1use std::collections::{BTreeMap, HashMap, HashSet};
66use std::path::{Path, PathBuf};
67
68use waratah_storage::{
69 CommitTs, EncodedQuad, EncodedTerm, GEO_HISTOGRAM_COARSE_FLOOR_LEVEL, GeoCellInterval,
70 GeoIndexPut, MAIN_REPOSITORY_ID, PartitionAxis, RocksDbTuning, Storage, StorageOp, StrHash,
71 TermReader, blob_store_dir, encode_term_bytes, geo_cell_level, geo_l11_bucket_range,
72 hexastore_data_dir,
73};
74
75use crate::error::DevError;
76
77struct TermVersions {
81 term: EncodedTerm,
82 quads: HashMap<[Vec<u8>; 3], (CommitTs, StorageOp)>,
84}
85
86fn quad_identity(quad: &waratah_storage::EncodedQuad) -> [Vec<u8>; 3] {
89 [
90 encode_term_bytes(&quad.subject),
91 encode_term_bytes(&quad.predicate),
92 encode_term_bytes(&quad.graph_name),
93 ]
94}
95
96fn geo_datatype_hashes() -> [StrHash; 2] {
100 [
101 StrHash::new(waratah_geo::GEO_WKT_LITERAL),
102 StrHash::new(waratah_geo::GEO_WKB_LITERAL),
103 ]
104}
105
106fn is_orphan_geo_typed_literal<'a>(
107 term: &'a EncodedTerm,
108 geo_hashes: &'a [StrHash; 2],
109) -> Option<&'a StrHash> {
110 let datatype_id = match term {
111 EncodedTerm::SmallTypedLiteral { datatype_id, .. }
112 | EncodedTerm::BigTypedLiteral { datatype_id, .. } => datatype_id,
113 _ => return None,
114 };
115 geo_hashes.iter().find(|geo| *geo == datatype_id)
116}
117
118pub fn rebuild(data_dir: &Path) -> Result<(), DevError> {
122 let blobs = waratah_registry::BlobStore::open(blob_store_dir(data_dir, MAIN_REPOSITORY_ID))?;
123 let registry = waratah_storage::Registry::open_rocksdb(
124 waratah_storage::registry_data_dir(data_dir, MAIN_REPOSITORY_ID),
125 waratah_storage::RocksDbTuning::registry_node(),
126 )?;
127 let tuning = RocksDbTuning::default();
137 let s = crate::import::open_hexastore(
138 hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, PartitionAxis::S),
139 PartitionAxis::S,
140 tuning,
141 true,
142 )?;
143 let p = crate::import::open_hexastore(
144 hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, PartitionAxis::P),
145 PartitionAxis::P,
146 tuning,
147 true,
148 )?;
149 let o = crate::import::open_hexastore(
150 hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, PartitionAxis::O),
151 PartitionAxis::O,
152 tuning,
153 true,
154 )?;
155 let geo_hashes = geo_datatype_hashes();
156 let mut terms: HashMap<StrHash, TermVersions> = HashMap::new();
163 let mut epoch = 0u64;
164 for permutation in waratah_storage::IndexPermutation::for_axis(PartitionAxis::O) {
165 o.visit_index_versions(permutation, |quad, ts, op| {
166 let is_orphan = is_orphan_geo_typed_literal(&quad.object, &geo_hashes).is_some();
170 if is_geo_term(&quad.object) || is_orphan {
171 let key = StrHash::from_bytes(&encode_term_bytes(&quad.object));
172 epoch = epoch.max(ts.0);
173 let entry = terms.entry(key).or_insert_with(|| TermVersions {
174 term: quad.object.clone(),
175 quads: HashMap::new(),
176 });
177 let identity = quad_identity(quad);
183 match entry.quads.get_mut(&identity) {
184 Some(latest) if ts > latest.0 => *latest = (ts, op),
185 Some(_) => {}
186 None => {
187 entry.quads.insert(identity, (ts, op));
188 }
189 }
190 }
191 Ok(())
192 })?;
193 }
194 status(format!(
195 "rebuilding geometry index for {} geo term(s) (coverer {:?})",
196 terms.len(),
197 waratah_geo::coverer_config()
198 ));
199
200 let deleted = o.wipe_geo_index()?;
211 let mut reindexed = 0u64;
212 let mut report = waratah_geo::RebuildReport::default();
213 let mut replace_pairs: Vec<waratah_storage::ReplacePair> = Vec::new();
219 let mut upgraded: HashMap<StrHash, EncodedTerm> = HashMap::new();
221 for versions in terms.values() {
222 let alive = versions.quads.values().any(|(_, op)| *op == StorageOp::Put);
226 if !alive {
227 continue;
228 }
229 if let Some(datatype_hash) = is_orphan_geo_typed_literal(&versions.term, &geo_hashes) {
230 let datatype_iri = if *datatype_hash == geo_hashes[0] {
233 waratah_geo::GEO_WKT_LITERAL
234 } else {
235 waratah_geo::GEO_WKB_LITERAL
236 };
237 let lexical = resolve_orphan_lexical(®istry, &versions.term)?;
238 let outcome = waratah_geo::upgrade_outcome(&versions.term, datatype_iri, &lexical);
239 let (new_term, upgrade_blobs) = match outcome {
240 waratah_geo::UpgradeOutcome::ToNative { new_term, blobs } => (new_term, blobs),
241 waratah_geo::UpgradeOutcome::Invalid { reason } => {
242 let identity = versions
243 .quads
244 .iter()
245 .filter(|(_, (_, op))| *op == StorageOp::Put)
246 .map(|(identity, _)| identity)
247 .min()
248 .ok_or_else(|| {
249 DevError::GeoRebuild(
250 "orphan cannot be indexed but has no live referencing quad"
251 .to_owned(),
252 )
253 })?;
254 let row = EncodedQuad::new(
255 decode_identity_slot(&identity[0])?,
256 decode_identity_slot(&identity[1])?,
257 versions.term.clone(),
258 decode_identity_slot(&identity[2])?,
259 );
260 return Err(DevError::GeoRebuild(format!(
261 "orphan cannot be indexed: {}",
262 format_orphan_error(&row, &lexical, &reason, |hash| {
263 registry.lookup(*hash).ok().flatten()
264 })
265 )));
266 }
267 };
268 for (blob_id, payload) in upgrade_blobs {
269 blobs.put(blob_id, &payload)?;
270 }
271 for identity in versions.quads.keys() {
272 replace_pairs.push(waratah_storage::ReplacePair {
273 subject: decode_identity_slot(&identity[0])?,
274 predicate: decode_identity_slot(&identity[1])?,
275 graph_name: decode_identity_slot(&identity[2])?,
276 old_object: versions.term.clone(),
277 new_object: new_term.clone(),
278 });
279 }
280 report.orphans_upgraded += 1;
281 upgraded.insert(
282 StrHash::from_bytes(&encode_term_bytes(&versions.term)),
283 new_term,
284 );
285 }
286 }
287 for chunk in replace_pairs.chunks(8_000) {
291 let commit_ts = CommitTs(epoch);
292 s.apply_replace_pairs(chunk, commit_ts)?;
293 p.apply_replace_pairs(chunk, commit_ts)?;
294 o.apply_replace_pairs(chunk, commit_ts)?;
295 }
296 for versions in terms.values() {
299 let alive = versions.quads.values().any(|(_, op)| *op == StorageOp::Put);
300 if !alive {
301 continue;
302 }
303 if let Some(datatype_hash) = is_orphan_geo_typed_literal(&versions.term, &geo_hashes) {
304 let hash = StrHash::from_bytes(&encode_term_bytes(&versions.term));
307 let Some(new_term) = upgraded.get(&hash) else {
308 return Err(DevError::GeoRebuild(format!(
309 "orphan (geo hash {datatype_hash:?}) has no native replacement"
310 )));
311 };
312 reindexed += reindex_term(&o, &blobs, new_term, CommitTs(epoch))?;
313 continue;
314 }
315 report.native_recovered += 1;
316 reindexed += reindex_term(&o, &blobs, &versions.term, CommitTs(epoch))?;
317 }
318 o.set_geo_index_epoch(epoch)?;
321 status(format!(
322 "geometry index rebuild done: {deleted} old posting(s) deleted, {reindexed} new posting(s) written, epoch {epoch}; {}",
323 report.summary()
324 ));
325 s.flush_memtables()?;
330 p.flush_memtables()?;
331 o.flush_memtables()?;
332 Ok(())
333}
334
335fn resolve_orphan_lexical(
338 registry: &waratah_storage::Registry,
339 term: &EncodedTerm,
340) -> Result<String, DevError> {
341 match term {
342 EncodedTerm::SmallTypedLiteral { value, .. } => Ok(value.as_str().to_owned()),
343 EncodedTerm::BigTypedLiteral { value_id, .. } => registry
344 .lookup(*value_id)
345 .map_err(|error| DevError::GeoRebuild(error.to_string()))?
346 .ok_or_else(|| {
347 DevError::GeoRebuild(format!(
348 "registry miss for orphan literal value {value_id:?}"
349 ))
350 }),
351 other => Err(DevError::GeoRebuild(format!(
352 "not a typed literal: {other:?}"
353 ))),
354 }
355}
356
357const ORPHAN_LEXICAL_PREVIEW_BYTES: usize = 256;
358
359pub(crate) fn format_orphan_error(
362 row: &EncodedQuad,
363 lexical: &str,
364 reason: &str,
365 mut resolve: impl FnMut(&StrHash) -> Option<String>,
366) -> String {
367 let lexical = if lexical.len() <= ORPHAN_LEXICAL_PREVIEW_BYTES {
368 lexical.to_owned()
369 } else {
370 let mut end = ORPHAN_LEXICAL_PREVIEW_BYTES;
371 while !lexical.is_char_boundary(end) {
372 end -= 1;
373 }
374 format!("{}… ({} bytes total)", &lexical[..end], lexical.len())
375 };
376 let mut render = |term: &EncodedTerm| match term {
377 EncodedTerm::NamedNode { iri_id } => resolve(iri_id)
378 .map(|iri| format!("<{iri}>"))
379 .unwrap_or_else(|| format!("{term:?}")),
380 EncodedTerm::SmallBlankNode(id) => format!("_:{}", id.as_str()),
381 EncodedTerm::BigBlankNode { id_id } => resolve(id_id)
382 .map(|id| format!("_:{id}"))
383 .unwrap_or_else(|| format!("{term:?}")),
384 EncodedTerm::DefaultGraph => "DefaultGraph".to_owned(),
385 other => format!("{other:?}"),
386 };
387 format!(
388 "subject={} predicate={} graph={} object={} lexical={lexical:?}: {reason}",
389 render(&row.subject),
390 render(&row.predicate),
391 render(&row.graph_name),
392 render(&row.object)
393 )
394}
395
396fn decode_identity_slot(bytes: &[u8]) -> Result<EncodedTerm, DevError> {
399 if bytes.is_empty() {
400 return Ok(EncodedTerm::DefaultGraph);
401 }
402 let mut cursor: &[u8] = bytes;
403 let term = cursor
404 .read_term()
405 .map_err(|error| DevError::GeoRebuild(error.to_string()))?;
406 debug_assert!(cursor.is_empty(), "identity slot is exactly one term");
407 Ok(term)
408}
409
410fn reindex_term(
413 o: &Storage,
414 blobs_reg: &waratah_registry::BlobStore,
415 term: &EncodedTerm,
416 commit_ts: CommitTs,
417) -> Result<u64, DevError> {
418 let blob_payload: Option<Vec<u8>> = match term {
419 EncodedTerm::LiteralGeometry { blob_id, .. } => {
420 let payloads = blobs_reg
421 .get(&[*blob_id])
422 .map_err(|error| DevError::GeoRebuild(error.to_string()))?;
423 Some(payloads.into_iter().flatten().next().ok_or_else(|| {
424 DevError::GeoRebuild(format!("blob {blob_id} missing for indexed geometry"))
425 })?)
426 }
427 _ => None,
428 };
429 let postings = waratah_geo::postings_for_geo_term(term, blob_payload.as_deref(), commit_ts)
430 .map_err(DevError::GeoRebuild)?;
431 o.apply_geo_puts(&postings)?;
432 Ok(postings.len() as u64)
433}
434
435fn is_geo_term(term: &EncodedTerm) -> bool {
436 matches!(
437 term,
438 EncodedTerm::LiteralPoint { .. } | EncodedTerm::LiteralGeometry { .. }
439 )
440}
441
442fn status(message: String) {
443 println!("waratah geo: {message}");
444}
445
446pub fn proj_data_dir() -> Option<PathBuf> {
448 if let Some(dir) = std::env::var_os("PROJ_DATA") {
449 return Some(dir.into());
450 }
451 let in_repo = Path::new(env!("CARGO_MANIFEST_DIR")).join("../waratah_geo/proj-data");
452 in_repo.join("proj.db").exists().then_some(in_repo)
453}
454
455pub fn configure_proj_env() {
462 if std::env::var_os("PROJ_DATA").is_none()
463 && let Some(dir) = proj_data_dir()
464 {
465 unsafe { std::env::set_var("PROJ_DATA", &dir) };
467 }
468 if std::env::var_os("PROJ_NETWORK").is_none() {
469 unsafe { std::env::set_var("PROJ_NETWORK", "OFF") };
471 }
472}
473
474#[derive(Debug, Default)]
476struct LevelTally {
477 puts: u64,
479 deletes: u64,
481 envelopes: u64,
484 incidences: u64,
488}
489
490#[derive(Debug, Default)]
497struct PostingCensus {
498 rows: u64,
500 logical: u64,
502 puts: u64,
504 deletes: u64,
506 malformed: u64,
509 coarse_puts: u64,
513 fine_incidences: u64,
515 levels: BTreeMap<u8, LevelTally>,
517 terms: HashSet<Vec<u8>>,
521 seen: HashSet<Vec<u8>>,
525 window: Option<WindowState>,
527}
528
529#[derive(Debug)]
534struct WindowState {
535 histogram: waratah_stats::GeoCellHistogram,
537 intervals: Vec<GeoCellInterval>,
541 hits: u64,
544 hit_terms: HashSet<Vec<u8>>,
547}
548
549impl WindowState {
550 fn new(intervals: Vec<GeoCellInterval>) -> Self {
551 Self {
552 histogram: waratah_stats::GeoCellHistogram::default(),
553 intervals,
554 hits: 0,
555 hit_terms: HashSet::new(),
556 }
557 }
558
559 fn hits_cell(&self, cell_id: u64) -> bool {
560 self.intervals
561 .iter()
562 .any(|iv| iv.min_cell_id <= cell_id && cell_id <= iv.max_cell_id)
563 }
564}
565
566impl PostingCensus {
567 fn consider(&mut self, posting: &GeoIndexPut) {
569 self.rows += 1;
570 let mut logical = posting.cell_id.to_be_bytes().to_vec();
571 logical.extend_from_slice(&posting.term);
572 if !self.seen.insert(logical) {
573 return;
574 }
575 self.logical += 1;
576 let Some(level) = geo_cell_level(posting.cell_id) else {
577 self.malformed += 1;
578 return;
579 };
580 let tally = self.levels.entry(level).or_default();
581 if posting.op == StorageOp::Put {
582 tally.puts += 1;
583 if posting.envelope.is_some() {
584 tally.envelopes += 1;
585 }
586 self.puts += 1;
587 self.terms.insert(posting.term.clone());
588 if level < GEO_HISTOGRAM_COARSE_FLOOR_LEVEL {
589 self.coarse_puts += 1;
590 } else {
591 let width = geo_l11_bucket_range(posting.cell_id)
594 .map(|(lo, hi)| u64::from(hi - lo + 1))
595 .unwrap_or(1);
596 tally.incidences += width;
597 self.fine_incidences += width;
598 }
599 if let Some(window) = &mut self.window {
600 window.histogram.observe_posting(posting.cell_id);
603 if window.hits_cell(posting.cell_id) {
606 window.hits += 1;
607 window.hit_terms.insert(posting.term.clone());
608 }
609 }
610 } else {
611 tally.deletes += 1;
612 self.deletes += 1;
613 }
614 }
615
616 fn report(&self, dir: &Path) {
619 let config = waratah_geo::coverer_config();
620 status(format!(
621 "posting census of {} (process coverer config: min_level={} max_level={} max_cells={} densify_step={}° (0 = off); the POSTINGS were built by the config live at ingest)",
622 dir.display(),
623 config.min_level,
624 config.max_level,
625 config.max_cells,
626 config.densify_step_deg
627 ));
628 status(format!(
629 "raw rows {} — distinct (cell,term) postings {} (puts {}, deletes {}, undecodable cell ids {})",
630 self.rows, self.logical, self.puts, self.deletes, self.malformed
631 ));
632 let avg = if self.terms.is_empty() {
633 0.0
634 } else {
635 self.puts as f64 / self.terms.len() as f64
636 };
637 status(format!(
638 "distinct live terms {} — {:.2} cells per live term on average (the drain's distinct seen-set collapses these per window)",
639 self.terms.len(),
640 avg
641 ));
642 status("level | puts | share | envelopes | L11-incidences".to_string());
643 for (level, tally) in &self.levels {
644 let share = if self.puts > 0 {
645 tally.puts as f64 * 100.0 / self.puts as f64
646 } else {
647 0.0
648 };
649 status(format!(
650 "{level:5} | {:#9} | {share:5.1}% | {:#9} | {:#9}",
651 tally.puts, tally.envelopes, tally.incidences
652 ));
653 }
654 status(format!(
655 "levels 0–8 (the histogram's native-id coarse map, count-once): {} puts",
656 self.coarse_puts
657 ));
658 status(format!(
659 "fine-map incidence mass (the stats histogram's summed bucket counts): {}",
660 self.fine_incidences
661 ));
662 }
663
664 fn report_window(
668 &self,
669 dir: &Path,
670 shape: &waratah_geo::WindowQueryShape,
671 window: &WindowState,
672 ) {
673 let config = waratah_geo::coverer_config();
674 status(format!(
675 "window census of {} (query coverer config: min_level={} max_level={} max_cells={} densify_step={}° (0 = off); the covering uses THIS config, the postings were built by the config live at ingest)",
676 dir.display(),
677 config.min_level,
678 config.max_level,
679 config.max_cells,
680 config.densify_step_deg
681 ));
682 let levels: Vec<u8> = shape
683 .covering
684 .iter()
685 .filter_map(|id| geo_cell_level(id.id()))
686 .collect();
687 let width: u64 = shape
688 .l11_ranges
689 .iter()
690 .map(|(lo, hi)| u64::from(hi - lo + 1))
691 .sum();
692 status(format!(
693 "window: {} covering cells (levels {}–{}), {} merged L11 ranges, {} bucket{} wide",
694 shape.covering.len(),
695 levels.iter().min().copied().unwrap_or(0),
696 levels.iter().max().copied().unwrap_or(0),
697 shape.l11_ranges.len(),
698 width,
699 if width == 1 { "" } else { "s" }
700 ));
701 let breakdown = window
702 .histogram
703 .estimate_ranges_breakdown(&shape.l11_ranges);
704 status(
705 "estimate ladder over the postings-exact histogram (every fine bucket exact — no wire trims, no remainder):"
706 .to_string(),
707 );
708 status(format!(
709 " fine buckets in-window: {} (exact posting mass {})",
710 breakdown.fine_buckets, breakdown.fine_mass
711 ));
712 status(format!(
713 " absent-run mass: {} (postings-exact: an absent bucket is genuinely empty)",
714 breakdown.absent_run_mass
715 ));
716 status(format!(
717 " coarse entries intersecting: {} (count-once mass {})",
718 breakdown.coarse_entries, breakdown.coarse_mass
719 ));
720 status(format!(
721 " estimate total: {}{} — the number the planner stamps on the geo scan when the profile histogram is exact",
722 breakdown.total,
723 if breakdown.clamped {
724 " (clamp-1 fired)"
725 } else {
726 ""
727 }
728 ));
729 status(format!(
730 "drain truth over the same intervals: {} candidate postings, {} distinct candidate terms (one geometry = one candidate, the estimate's target unit)",
731 window.hits,
732 window.hit_terms.len()
733 ));
734 if window.hit_terms.is_empty() {
735 status("window carries no live candidates — nothing to compare".to_string());
736 return;
737 }
738 status(format!(
739 " {:.2} candidate postings per term — the drain's boundary-cell over-return (AABB + relate retract these at fetch)",
740 window.hits as f64 / window.hit_terms.len() as f64
741 ));
742 status(format!(
743 " estimate / candidates: {:.2}x — the estimator's inflation on this window",
744 breakdown.total as f64 / window.hit_terms.len() as f64
745 ));
746 status(
747 "the engine's LIVE estimate instead reads the rolled-up (wire-trimmed, generation-mixed) profile histogram — compare this total against EXPLAIN to attribute the gap"
748 .to_string(),
749 );
750 }
751}
752
753pub fn census(data_dir: &Path, window: Option<&str>) -> Result<(), DevError> {
767 let o_dir = hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, PartitionAxis::O);
768 if !o_dir.exists() {
769 return Err(DevError::Io(std::io::Error::new(
770 std::io::ErrorKind::NotFound,
771 format!("no O-axis store at {} — import first", o_dir.display()),
772 )));
773 }
774 let shape = window
778 .map(waratah_geo::window_query_shape)
779 .transpose()
780 .map_err(|error| {
781 DevError::Io(std::io::Error::new(
782 std::io::ErrorKind::InvalidInput,
783 format!("window: {error}"),
784 ))
785 })?;
786 let o = crate::import::open_hexastore(
790 o_dir.clone(),
791 PartitionAxis::O,
792 RocksDbTuning::default(),
793 false,
794 )?;
795 let mut totals = PostingCensus {
796 window: shape
797 .as_ref()
798 .map(|s| WindowState::new(s.intervals.clone())),
799 ..PostingCensus::default()
800 };
801 o.visit_geo_postings(&mut |posting| {
802 totals.consider(posting);
803 Ok(())
804 })?;
805 match (shape.as_ref(), totals.window.as_ref()) {
806 (Some(shape), Some(window)) => totals.report_window(&o_dir, shape, window),
807 _ => totals.report(&o_dir),
808 }
809 Ok(())
810}
811
812#[cfg(test)]
813mod tests {
814 use tempfile::TempDir;
815 use waratah_storage::{
816 EncodedQuad, GeoCandidateState, GeoCellInterval, GeoEnvelope, GraphName, NamedNode, Quad,
817 SnapshotId, StorageBackendKind, VisibilityLabel, encode_quad, registry_data_dir,
818 };
819
820 use super::*;
821
822 fn census_level_cell(level: u8) -> u64 {
825 1u64 << (2 * (30 - u32::from(level)))
826 }
827
828 #[test]
834 fn census_folds_versions_levels_envelopes_and_incidence_mass() {
835 let mut rows = vec![
836 GeoIndexPut {
838 cell_id: census_level_cell(30),
839 term: vec![1],
840 commit_ts: CommitTs(1),
841 op: StorageOp::Put,
842 visibility: VisibilityLabel(7),
843 envelope: None,
844 },
845 GeoIndexPut {
846 cell_id: census_level_cell(30),
847 term: vec![2],
848 commit_ts: CommitTs(1),
849 op: StorageOp::Put,
850 visibility: VisibilityLabel(7),
851 envelope: None,
852 },
853 GeoIndexPut {
856 cell_id: census_level_cell(9),
857 term: vec![3],
858 commit_ts: CommitTs(9),
859 op: StorageOp::Put,
860 visibility: VisibilityLabel(7),
861 envelope: Some(GeoEnvelope {
862 min_lon: 150.0,
863 min_lat: -34.0,
864 max_lon: 151.0,
865 max_lat: -33.0,
866 }),
867 },
868 GeoIndexPut {
869 cell_id: census_level_cell(9),
870 term: vec![3],
871 commit_ts: CommitTs(4),
872 op: StorageOp::Put,
873 visibility: VisibilityLabel(7),
874 envelope: None,
875 },
876 GeoIndexPut {
878 cell_id: census_level_cell(11),
879 term: vec![4],
880 commit_ts: CommitTs(8),
881 op: StorageOp::Delete,
882 visibility: VisibilityLabel(7),
883 envelope: None,
884 },
885 ];
886 rows.sort_by_key(|put| put.encode_key());
889 let mut census = PostingCensus::default();
890 for put in &rows {
891 census.consider(put);
892 }
893 assert_eq!(census.rows, 5, "every raw version is walked");
894 assert_eq!(census.logical, 4, "versions collapse to their logical key");
895 assert_eq!(census.puts, 3);
896 assert_eq!(census.deletes, 1);
897 assert_eq!(census.terms.len(), 3, "one entry per live term");
898 assert_eq!(census.levels[&30].puts, 2);
899 assert_eq!(census.levels[&30].envelopes, 0);
900 assert_eq!(census.levels[&9].puts, 1);
901 assert_eq!(
902 census.levels[&9].envelopes, 1,
903 "the newest version's envelope"
904 );
905 assert_eq!(census.levels[&11].deletes, 1);
906 assert_eq!(
907 census.levels[&30].incidences, 2,
908 "level-30 leaves map to their single L11 ancestor bucket"
909 );
910 assert_eq!(
911 census.levels[&9].incidences, 16,
912 "a level-9 posting expands into its 16 L11 descendant buckets"
913 );
914 assert_eq!(census.fine_incidences, 18);
915 assert_eq!(census.coarse_puts, 0);
916 assert_eq!(census.malformed, 0);
917 }
918
919 #[test]
926 fn window_mode_builds_the_exact_histogram_and_counts_drain_truth() {
927 let w = census_level_cell(11);
931 let mut intervals = vec![GeoCellInterval {
932 min_cell_id: w | 1,
933 max_cell_id: w | ((1u64 << 38) - 1),
934 }];
935 for level in (0..11).rev() {
936 intervals.push(GeoCellInterval::exact(census_level_cell(level)));
937 }
938 let mut census = PostingCensus {
939 window: Some(WindowState::new(intervals)),
940 ..PostingCensus::default()
941 };
942 let mut rows = vec![
943 GeoIndexPut {
945 cell_id: w | (5 << 1) | 1,
946 term: vec![1],
947 commit_ts: CommitTs(5),
948 op: StorageOp::Put,
949 visibility: VisibilityLabel(7),
950 envelope: None,
951 },
952 GeoIndexPut {
953 cell_id: w | (5 << 1) | 1,
954 term: vec![1],
955 commit_ts: CommitTs(1),
956 op: StorageOp::Put,
957 visibility: VisibilityLabel(7),
958 envelope: None,
959 },
960 GeoIndexPut {
962 cell_id: w | (9 << 1) | 1,
963 term: vec![2],
964 commit_ts: CommitTs(9),
965 op: StorageOp::Delete,
966 visibility: VisibilityLabel(7),
967 envelope: None,
968 },
969 GeoIndexPut {
972 cell_id: (2u64 << 61) | (5 << 1) | 1,
973 term: vec![3],
974 commit_ts: CommitTs(1),
975 op: StorageOp::Put,
976 visibility: VisibilityLabel(7),
977 envelope: None,
978 },
979 GeoIndexPut {
982 cell_id: census_level_cell(9),
983 term: vec![4],
984 commit_ts: CommitTs(1),
985 op: StorageOp::Put,
986 visibility: VisibilityLabel(7),
987 envelope: None,
988 },
989 ];
990 rows.sort_by_key(|put| put.encode_key());
991 for put in &rows {
992 census.consider(put);
993 }
994 let window = census.window.as_ref().unwrap();
995 assert_eq!(window.hits, 2);
998 assert_eq!(window.hit_terms.len(), 2);
999 let mass: u64 = window.histogram.fine.values().map(|c| u64::from(*c)).sum();
1002 assert_eq!(mass, 18);
1003 let (lo, hi) = geo_l11_bucket_range(w).unwrap();
1007 let b = window.histogram.estimate_ranges_breakdown(&[(lo, hi)]);
1008 assert_eq!(b.fine_buckets, 1);
1009 assert_eq!(b.fine_mass, 2);
1010 assert_eq!(b.absent_run_mass, 0);
1011 assert_eq!(b.coarse_entries, 0);
1012 assert_eq!(b.total, 2);
1013 }
1014
1015 #[test]
1021 fn window_query_shape_derives_intervals_and_ranges_from_wkt() {
1022 let shape = waratah_geo::window_query_shape(
1023 "POLYGON((150.0 -34.0, 151.0 -34.0, 151.0 -33.0, 150.0 -33.0, 150.0 -34.0))",
1024 )
1025 .unwrap();
1026 assert!(!shape.covering.is_empty());
1027 assert!(!shape.l11_ranges.is_empty());
1028 for pair in shape.l11_ranges.windows(2) {
1029 assert!(
1030 pair[0].1 < pair[1].0,
1031 "merged ranges must be disjoint and sorted"
1032 );
1033 }
1034 for id in shape.covering.iter() {
1035 assert!(
1036 shape
1037 .intervals
1038 .iter()
1039 .any(|iv| iv.min_cell_id <= id.id() && id.id() <= iv.max_cell_id),
1040 "covering cell {:x} not walkable by the drain intervals",
1041 id.id()
1042 );
1043 }
1044 }
1045
1046 #[test]
1052 fn census_routes_level8_coarse_and_expands_level9() {
1053 let level8 = GeoIndexPut {
1054 cell_id: census_level_cell(8),
1055 term: vec![9],
1056 commit_ts: CommitTs(1),
1057 op: StorageOp::Put,
1058 visibility: VisibilityLabel(7),
1059 envelope: None,
1060 };
1061 let mut census = PostingCensus::default();
1062 census.consider(&level8);
1063 assert_eq!(census.puts, 1);
1064 assert_eq!(census.coarse_puts, 1);
1065 assert_eq!(census.levels[&8].incidences, 0);
1066 assert_eq!(census.fine_incidences, 0);
1067
1068 let level9 = GeoIndexPut {
1069 cell_id: census_level_cell(9),
1070 term: vec![8],
1071 commit_ts: CommitTs(1),
1072 op: StorageOp::Put,
1073 visibility: VisibilityLabel(7),
1074 envelope: None,
1075 };
1076 census.consider(&level9);
1077 assert_eq!(census.coarse_puts, 1, "level 9 stays on the fine side");
1078 assert_eq!(census.levels[&9].incidences, 16);
1079 assert_eq!(census.fine_incidences, 16);
1080 }
1081
1082 fn write_plugin() -> &'static dyn waratah_compute::plugin::WritePlugin {
1086 configure_proj_env();
1087 crate::test_support::install_composed();
1088 waratah_compute::plugin::process_plugins()
1089 .write_plugins()
1090 .next()
1091 .expect("geo write plugin registered")
1092 }
1093
1094 fn wkt_literal(wkt: &str) -> oxrdf::Literal {
1095 oxrdf::Literal::new_typed_literal(
1096 wkt,
1097 NamedNode::new_unchecked(waratah_geo::GEO_WKT_LITERAL),
1098 )
1099 }
1100
1101 fn wkt_quad(subject: &str, wkt: &str) -> Quad {
1102 Quad::new(
1103 NamedNode::new_unchecked(subject),
1104 NamedNode::new_unchecked("http://ex/hasLocation"),
1105 wkt_literal(wkt),
1106 GraphName::DefaultGraph,
1107 )
1108 }
1109
1110 #[test]
1111 fn orphan_error_resolves_row_identity_and_bounds_the_lexical() {
1112 let subject = NamedNode::new_unchecked("http://ex/s");
1113 let predicate = NamedNode::new_unchecked("http://ex/p");
1114 let object = wkt_literal("POINT EMPTY");
1115 let row = EncodedQuad::new(
1116 EncodedTerm::from(&subject),
1117 EncodedTerm::from(&predicate),
1118 EncodedTerm::from(&object),
1119 EncodedTerm::DefaultGraph,
1120 );
1121 let lexical = "x".repeat(ORPHAN_LEXICAL_PREVIEW_BYTES + 64);
1122 let message = format_orphan_error(&row, &lexical, "invalid geometry", |hash| {
1123 if *hash == StrHash::new(subject.as_str()) {
1124 Some(subject.as_str().to_owned())
1125 } else if *hash == StrHash::new(predicate.as_str()) {
1126 Some(predicate.as_str().to_owned())
1127 } else {
1128 None
1129 }
1130 });
1131 assert!(message.contains("subject=<http://ex/s>"), "{message}");
1132 assert!(message.contains("predicate=<http://ex/p>"), "{message}");
1133 assert!(message.contains("graph=DefaultGraph"), "{message}");
1134 assert!(message.contains("bytes total"), "{message}");
1135 assert!(!message.contains(&lexical), "lexical must be bounded");
1136 }
1137
1138 fn put_version(o: &Storage, encoded: &EncodedQuad, ts: u64, op: StorageOp) {
1140 o.insert_encoded_quad_version(encoded, CommitTs(ts), op, VisibilityLabel::default())
1141 .unwrap();
1142 }
1143
1144 fn point_candidates(o: &Storage, term: &EncodedTerm, snapshot: u64) -> Vec<EncodedTerm> {
1146 let EncodedTerm::LiteralPoint { x, y, .. } = term else {
1147 panic!("expected a literal point, got {term:?}");
1148 };
1149 let cell = waratah_geo::point_leaf_cell(*x, *y).id();
1150 candidate_scan(o, &[GeoCellInterval::exact(cell)], snapshot)
1151 .into_iter()
1152 .filter(|candidate| candidate == term)
1153 .collect()
1154 }
1155
1156 fn polygon_candidates(
1158 o: &Storage,
1159 payload: &[u8],
1160 term: &EncodedTerm,
1161 snapshot: u64,
1162 ) -> Vec<EncodedTerm> {
1163 let geometry = waratah_geo::geometry_from_crs84_ewkb(payload).unwrap();
1164 let covering = waratah_geo::geometry_covering(&geometry);
1165 candidate_scan(o, &waratah_geo::intervals_for_covering(&covering), snapshot)
1166 .into_iter()
1167 .filter(|candidate| candidate == term)
1168 .collect()
1169 }
1170
1171 fn candidate_scan(
1172 o: &Storage,
1173 intervals: &[GeoCellInterval],
1174 snapshot: u64,
1175 ) -> Vec<EncodedTerm> {
1176 let mut state = GeoCandidateState::default();
1177 let mut out = Vec::new();
1178 o.geo_scan_candidates(
1179 intervals,
1180 SnapshotId(snapshot),
1181 None,
1182 0,
1183 &mut state,
1184 |candidate| {
1185 out.push(candidate.clone());
1186 Ok(true)
1187 },
1188 )
1189 .unwrap();
1190 out
1191 }
1192
1193 const SEQ_POLY_WKT: &str =
1194 "POLYGON((152.5 -28.0, 153.5 -28.0, 153.5 -27.0, 152.5 -27.0, 152.5 -28.0))";
1195
1196 struct Seeded {
1216 dir: TempDir,
1217 point1: EncodedTerm,
1218 point2: EncodedTerm,
1219 point3: EncodedTerm,
1220 polygon: EncodedTerm,
1221 polygon_payload: std::sync::Arc<[u8]>,
1222 }
1223
1224 fn seed() -> Seeded {
1225 let plugin = write_plugin();
1226 let dir = tempfile::tempdir().unwrap();
1227 let blobs =
1228 waratah_registry::BlobStore::open(blob_store_dir(dir.path(), MAIN_REPOSITORY_ID))
1229 .unwrap();
1230 let o = Storage::open_with_backend(
1231 StorageBackendKind::RocksDb,
1232 hexastore_data_dir(dir.path(), MAIN_REPOSITORY_ID, PartitionAxis::O),
1233 PartitionAxis::O,
1234 )
1235 .unwrap();
1236
1237 let mut encoded: Vec<EncodedQuad> = Vec::new();
1240 let mut polygon_payload: Option<std::sync::Arc<[u8]>> = None;
1241 for quad in [
1242 wkt_quad("http://ex/a", "POINT(153.025 -27.47)"),
1243 wkt_quad("http://ex/b", "POINT(152.76 -27.61)"),
1244 wkt_quad("http://ex/c", "POINT(150.0 -30.0)"),
1245 wkt_quad("http://ex/seq", SEQ_POLY_WKT),
1246 Quad::new(
1249 NamedNode::new_unchecked("http://ex/typed"),
1250 NamedNode::new_unchecked("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
1251 wkt_literal("POINT(152.76 -27.61)"),
1252 GraphName::DefaultGraph,
1253 ),
1254 ] {
1255 let prepared = plugin
1256 .prepare_insert(std::slice::from_ref(&quad), CommitTs(0), StorageOp::Put)
1257 .unwrap();
1258 let mut encoded_quad = encode_quad(&quad).unwrap();
1259 for (_, term) in prepared.object_rewrites {
1260 encoded_quad.object = term;
1261 }
1262 for (blob_id, payload) in &prepared.blobs {
1263 blobs.put(*blob_id, payload).unwrap();
1264 if let oxrdf::Term::Literal(literal) = &quad.object
1265 && literal.value() == SEQ_POLY_WKT
1266 {
1267 polygon_payload = Some(std::sync::Arc::clone(payload));
1268 }
1269 }
1270 for put in &prepared.geo_puts {
1271 o.apply_geo_puts(std::slice::from_ref(put)).unwrap();
1272 }
1273 put_version(&o, &encoded_quad, 0, StorageOp::Put);
1274 encoded.push(encoded_quad.clone());
1275 }
1276 let point1 = encoded[0].object.clone();
1277 let point2 = encoded[1].object.clone();
1278 let point3 = encoded[2].object.clone();
1279 let polygon = encoded[3].object.clone();
1280 let typed_point2 = encoded[4].clone();
1281
1282 put_version(&o, &encoded[0], 5, StorageOp::Put);
1284 put_version(&o, &encoded[0], 8, StorageOp::Put);
1285 put_version(&o, &typed_point2, 10, StorageOp::Put);
1287 put_version(&o, &encoded[2], 12, StorageOp::Put);
1291 put_version(&o, &encoded[2], 14, StorageOp::Delete);
1292 put_version(&o, &encoded[3], 20, StorageOp::Put);
1294
1295 let orphan_quad = Quad::new(
1303 NamedNode::new_unchecked("http://ex/orphan"),
1304 NamedNode::new_unchecked("http://ex/hasLocation"),
1305 oxrdf::Term::from(wkt_literal("POINT(1 2)")),
1306 GraphName::DefaultGraph,
1307 );
1308 let orphan_encoded = encode_quad(&orphan_quad).unwrap();
1309 put_version(&o, &orphan_encoded, 9, StorageOp::Put);
1310
1311 Seeded {
1312 dir,
1313 point1,
1314 point2,
1315 point3,
1316 polygon,
1317 polygon_payload: polygon_payload.expect("polygon blob payload"),
1318 }
1319 }
1320
1321 #[test]
1322 fn rebuild_dedups_gcs_dead_terms_and_stamps_the_epoch() {
1323 let seeded = seed();
1324 let data_dir = seeded.dir.path();
1325
1326 rebuild(data_dir).unwrap();
1327
1328 for axis in [PartitionAxis::S, PartitionAxis::P, PartitionAxis::O] {
1334 let store = Storage::open_with_backend(
1335 StorageBackendKind::RocksDb,
1336 hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, axis),
1337 axis,
1338 )
1339 .unwrap();
1340 let puts: u64 = store
1341 .stats_property_blobs(waratah_stats::STATS_USER_PROPERTY_KEY)
1342 .unwrap()
1343 .iter()
1344 .map(|blob| waratah_stats::from_bytes(blob).unwrap().total_puts)
1345 .sum();
1346 assert!(
1347 puts > 0,
1348 "{axis:?} rebuild flush must stamp canonical stats blobs"
1349 );
1350 }
1351
1352 let o = Storage::open_with_backend(
1353 StorageBackendKind::RocksDb,
1354 hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, PartitionAxis::O),
1355 PartitionAxis::O,
1356 )
1357 .unwrap();
1358
1359 assert_eq!(o.geo_index_epoch().unwrap(), Some(20));
1361
1362 let blobs = o
1367 .stats_property_blobs(waratah_stats::STATS_USER_PROPERTY_KEY)
1368 .unwrap();
1369 let geo_mass: u64 = blobs
1370 .iter()
1371 .map(|blob| {
1372 waratah_stats::from_bytes(blob)
1373 .unwrap()
1374 .geo_cell_histogram
1375 .total_bucket_mass()
1376 })
1377 .sum();
1378 assert!(
1379 geo_mass > 0,
1380 "rebuild flush must stamp the geo histogram blob (found {} blob(s))",
1381 blobs.len()
1382 );
1383
1384 assert_eq!(
1386 o.delete_geo_term(&encode_term_bytes(&seeded.point3))
1387 .unwrap(),
1388 0
1389 );
1390
1391 assert_eq!(
1394 point_candidates(&o, &seeded.point1, 20),
1395 vec![seeded.point1.clone()]
1396 );
1397 assert!(point_candidates(&o, &seeded.point1, 19).is_empty());
1398 assert_eq!(
1399 point_candidates(&o, &seeded.point2, 20),
1400 vec![seeded.point2.clone()]
1401 );
1402 assert!(point_candidates(&o, &seeded.point2, 19).is_empty());
1403 assert_eq!(
1406 polygon_candidates(&o, &seeded.polygon_payload, &seeded.polygon, 20),
1407 vec![seeded.polygon.clone()]
1408 );
1409 assert!(polygon_candidates(&o, &seeded.polygon_payload, &seeded.polygon, 19).is_empty());
1410
1411 drop(o);
1412
1413 rebuild(data_dir).unwrap();
1415 let o = Storage::open_with_backend(
1416 StorageBackendKind::RocksDb,
1417 hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, PartitionAxis::O),
1418 PartitionAxis::O,
1419 )
1420 .unwrap();
1421 assert_eq!(o.geo_index_epoch().unwrap(), Some(20));
1422 assert_eq!(
1423 point_candidates(&o, &seeded.point1, 20),
1424 vec![seeded.point1.clone()]
1425 );
1426 assert!(point_candidates(&o, &seeded.point1, 19).is_empty());
1427 assert_eq!(
1428 point_candidates(&o, &seeded.point2, 20),
1429 vec![seeded.point2.clone()]
1430 );
1431 assert_eq!(
1432 polygon_candidates(&o, &seeded.polygon_payload, &seeded.polygon, 20),
1433 vec![seeded.polygon.clone()]
1434 );
1435 assert_eq!(
1436 o.delete_geo_term(&encode_term_bytes(&seeded.point3))
1437 .unwrap(),
1438 0
1439 );
1440 }
1441
1442 #[test]
1443 fn rebuild_rejects_an_unindexable_orphan_without_stamping() {
1444 let dir = tempfile::tempdir().unwrap();
1445 {
1446 let mut registry = waratah_storage::Registry::open_rocksdb(
1447 registry_data_dir(dir.path(), MAIN_REPOSITORY_ID),
1448 RocksDbTuning::registry_node(),
1449 )
1450 .unwrap();
1451 registry
1452 .register_entries(&[
1453 (
1454 StrHash::new("http://ex/broken"),
1455 "http://ex/broken".to_owned(),
1456 ),
1457 (
1458 StrHash::new("http://ex/hasLocation"),
1459 "http://ex/hasLocation".to_owned(),
1460 ),
1461 ])
1462 .unwrap();
1463 }
1464 let encoded = encode_quad(&wkt_quad("http://ex/broken", "POINT EMPTY")).unwrap();
1465 {
1466 let o = Storage::open_with_backend(
1467 StorageBackendKind::RocksDb,
1468 hexastore_data_dir(dir.path(), MAIN_REPOSITORY_ID, PartitionAxis::O),
1469 PartitionAxis::O,
1470 )
1471 .unwrap();
1472 put_version(&o, &encoded, 1, StorageOp::Put);
1473 }
1474
1475 let error = rebuild(dir.path()).unwrap_err();
1476 let message = error.to_string();
1477 assert!(
1478 message.contains("EMPTY geometry"),
1479 "rebuild must report the validation failure: {message}"
1480 );
1481 assert!(
1482 message.contains("subject=<http://ex/broken>"),
1483 "rebuild error must identify the subject: {message}"
1484 );
1485 assert!(
1486 message.contains("predicate=<http://ex/hasLocation>"),
1487 "rebuild error must identify the predicate: {message}"
1488 );
1489 assert!(
1490 message.contains("graph=DefaultGraph") && message.contains("POINT EMPTY"),
1491 "rebuild error must identify the graph and lexical: {message}"
1492 );
1493 let o = Storage::open_with_backend(
1494 StorageBackendKind::RocksDb,
1495 hexastore_data_dir(dir.path(), MAIN_REPOSITORY_ID, PartitionAxis::O),
1496 PartitionAxis::O,
1497 )
1498 .unwrap();
1499 assert_eq!(o.geo_index_epoch().unwrap(), None);
1500 }
1501
1502 #[test]
1504 fn rebuild_with_no_geo_terms_persists_epoch_zero() {
1505 let dir = tempfile::tempdir().unwrap();
1506 Storage::open_with_backend(
1507 StorageBackendKind::RocksDb,
1508 hexastore_data_dir(dir.path(), MAIN_REPOSITORY_ID, PartitionAxis::O),
1509 PartitionAxis::O,
1510 )
1511 .unwrap();
1512 rebuild(dir.path()).unwrap();
1513 let o = Storage::open_with_backend(
1514 StorageBackendKind::RocksDb,
1515 hexastore_data_dir(dir.path(), MAIN_REPOSITORY_ID, PartitionAxis::O),
1516 PartitionAxis::O,
1517 )
1518 .unwrap();
1519 assert_eq!(o.geo_index_epoch().unwrap(), Some(0));
1520 }
1521
1522 fn reopen(dir: &TempDir) -> Storage {
1525 Storage::open_with_backend(
1526 StorageBackendKind::RocksDb,
1527 hexastore_data_dir(dir.path(), MAIN_REPOSITORY_ID, PartitionAxis::O),
1528 PartitionAxis::O,
1529 )
1530 .unwrap()
1531 }
1532
1533 #[test]
1539 fn rebuild_keeps_a_shared_literal_until_its_last_quad_is_deleted() {
1540 let plugin = write_plugin();
1541 let dir = tempfile::tempdir().unwrap();
1542
1543 let mut encoded: Vec<EncodedQuad> = Vec::new();
1546 {
1547 let o = reopen(&dir);
1548 for subject in ["http://ex/one", "http://ex/two"] {
1549 let quad = wkt_quad(subject, "POINT(151.0 -29.0)");
1550 let prepared = plugin
1551 .prepare_insert(std::slice::from_ref(&quad), CommitTs(0), StorageOp::Put)
1552 .unwrap();
1553 let mut encoded_quad = encode_quad(&quad).unwrap();
1554 for (_, term) in prepared.object_rewrites {
1555 encoded_quad.object = term;
1556 }
1557 for put in &prepared.geo_puts {
1558 o.apply_geo_puts(std::slice::from_ref(put)).unwrap();
1559 }
1560 put_version(&o, &encoded_quad, 0, StorageOp::Put);
1561 encoded.push(encoded_quad);
1562 }
1563 }
1564 assert_eq!(
1565 encoded[0].object, encoded[1].object,
1566 "both quads share one literal"
1567 );
1568 let term = encoded[0].object.clone();
1569
1570 {
1573 let o = reopen(&dir);
1574 put_version(&o, &encoded[1], 5, StorageOp::Delete);
1575 }
1576
1577 rebuild(dir.path()).unwrap();
1579 {
1580 let o = reopen(&dir);
1581 assert_eq!(o.geo_index_epoch().unwrap(), Some(5));
1582 assert_eq!(point_candidates(&o, &term, 5), vec![term.clone()]);
1583 }
1584
1585 {
1588 let o = reopen(&dir);
1589 put_version(&o, &encoded[0], 6, StorageOp::Delete);
1590 }
1591 rebuild(dir.path()).unwrap();
1592 {
1593 let o = reopen(&dir);
1594 assert!(point_candidates(&o, &term, 6).is_empty());
1595 assert_eq!(o.delete_geo_term(&encode_term_bytes(&term)).unwrap(), 0);
1597 }
1598 }
1599}