Skip to main content

waratah/
geo.rs

1//! `waratah geo rebuild-index`: recompute O-axis S2 postings from blobs.
2//!
3//! Same class as `waratah catalog rebuild` but a different algorithm: the
4//! old covering must be **wiped** (Delete every posting of each term), not
5//! merged — catalog rebuild only inserts missing Present rows and is the
6//! wrong template for that part. Points are re-emitted at the same leaf
7//! cell (no blob); geometries re-cover under the **current** process coverer
8//! config. The O partition never runs the coverer and never opens blobs —
9//! this command is compute/offline-side by construction.
10//!
11//! # Rebuild contract
12//!
13//! - **Term collection** is a [`HashMap`] keyed by the hash of the canonical
14//!   term bytes (the same term identity [`waratah_storage::geo_lexical_key`]
15//!   uses). Only the **object slot** is inspected: on the O axis, predicates
16//!   are always IRIs and literals can never be subjects or graph names, so
17//!   the other three slot checks can never match a geo term.
18//! - **Per-quad liveness:** inside each term's entry the walk records the
19//!   newest version row per REFERENCING QUAD (versions of one logical quad
20//!   arrive contiguous in descending-`commit_ts` order in the scan, so the
21//!   max-ts row is the quad's latest version; keeping the max-ts entry is
22//!   order-robust across permutations, which duplicate `rdf:type` quads at
23//!   equal timestamps). A term is re-indexed when ANY quad referencing it
24//!   has its own-latest version = a `Put` — deleting one quad that shares a
25//!   literal with other live quads must not retract the term. **The whole
26//!   postings CF is wiped in ONE pass** (`wipe_geo_index`) and only the
27//!   live terms re-posted: the write path never mirrors deletes to the
28//!   postings (`waratah_compute/src/fanout.rs` sends none on delete
29//!   batches — the index stays a conservative superset at every snapshot),
30//!   so a fully-dead term can still carry stale Put postings and this
31//!   rebuild IS the garbage collector over them — including postings whose
32//!   term no longer appears in the hexastore at all, which the per-term
33//!   wipe this replaced could never see.
34//! - **Epoch stamping:** every rebuilt posting is stamped with
35//!   `commit_ts = epoch`, where `epoch = max commit_ts over the
36//!   geo-contributing version rows seen by the scan` — **equal, never +1**.
37//!   The epoch derives from the data being indexed, never from the existing
38//!   index (which is absent on first rebuild and untrusted afterwards).
39//!   Zero geo terms found → epoch 0: the index is empty and incrementally
40//!   maintained from then on, valid for every snapshot. Postings stamped at
41//!   the epoch become visible exactly when the planner starts trusting the
42//!   index (`waratah_geo/src/plan.rs` rewrites the `geof:*` FILTER only for
43//!   snapshots ≥ the persisted epoch).
44//! - **Persistence:** the epoch is stored on the O partition
45//!   (`Storage::set_geo_index_epoch`, `geo_index_meta` CF) together with its
46//!   LIVENESS marker, and both reach compute through the hexastore
47//!   `Describe` payload. This CLI stamps via the same setter the cluster
48//!   rebuild's finish uses, so the two cannot diverge.
49//!
50//! Caveat: deriving the epoch from scanned data timestamps means a
51//! future-pinned `import --timestamp` above the wall clock can stamp an
52//! epoch above later online writes, so rebuilt postings sit below the
53//! planner trust gate (residual custom-fn answers) until the data clock
54//! catches up. The systemic fix (a
55//! monotonic cluster ts watermark) is out of scope here and is a
56//! pre-existing gap for all offline writes.
57//!
58//! Remaining exposure: none from the wipe — this CLI wipes the whole
59//! postings CF in ONE pass (`wipe_geo_index`, the same primitive the
60//! cluster rebuild's `begin_geo_rebuild` uses), and the LIVENESS marker
61//! drops in that same atomic batch, so an interrupted run reads UNTRUSTED
62//! instead of trusted-with-a-partial-index (the pre-2026-10-27 hole, when
63//! the CLI wiped per term and the marker survived).
64
65use 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
77/// Per-term aggregation for the rebuild walk: the canonical term plus the
78/// newest version row seen for each referencing quad. The term is alive iff
79/// ANY of those per-quad latest versions is a `Put`.
80struct TermVersions {
81    term: EncodedTerm,
82    /// Quad identity → `(newest ts, its op)`.
83    quads: HashMap<[Vec<u8>; 3], (CommitTs, StorageOp)>,
84}
85
86/// Quad identity inside one term's aggregation: the encoded subject,
87/// predicate, and graph bytes (the object IS the aggregated term).
88fn 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
96/// The two geo datatype hashes (the orphan-typed-literal discovery set —
97/// the same literals the write plugin would have encoded natively had it
98/// been enabled at ingest).
99fn 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
118/// Wipe and rebuild every geo posting under the current coverer config,
119/// upgrading orphaned typed literals (ingested while the plugin was
120/// disabled) to native terms across all three axis stores.
121pub 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    // All three axis opens attach the stats collectors (the offline
128    // importer's `open_hexastore` discipline: canonical on every axis,
129    // catalog on S, temporal + geo on O). The orphan-upgrade replaces and
130    // the re-applied geo postings flush at the end of this function; without
131    // collectors those SSTs would carry no `waratah.stats` blobs (the geo
132    // histogram empty until a collector-attached compaction, the hexastore
133    // row stats stale by the replaced rows). Reads are unaffected — the
134    // collectors run per flushed/compacted output file, and a zero-orphan
135    // rebuild writes no hexastore rows, so S/P never spin one up.
136    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    // Scan the hexastore for geo-typed terms (OPSG objects are the common
157    // case; any slot if a quad indexed it). One entry per term; inside it
158    // one entry per referencing quad keeps that quad's newest version row.
159    // Liveness is per-QUAD: any quad whose own-latest version is a Put
160    // keeps the term alive — deleting one quad that references a shared
161    // literal must not retract the term other quads still need.
162    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            // Predicates are IRIs and literals can never be subjects or
167            // graph names, so on the O axis only the object slot can hold
168            // a native geo term.
169            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                // Versions of one logical quad arrive contiguous in
178                // descending-ts order; the max-ts row is the quad's
179                // latest version. The same quad surfaces in both OPSG and
180                // TSG when its predicate is `rdf:type` — at equal ts with
181                // the same op, so the dedup is consistent.
182                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    // One-pass wipe: a single scan-and-batch over
201    // the whole postings CF replaces the per-term `delete_geo_term` walks
202    // (one full-CF scan PER TERM — quadratic in terms × postings; the 10m
203    // corpus paid ~7.3 × 10¹¹ row visits). The LIVENESS marker drops in
204    // the same atomic batch, so an interrupted rebuild reads UNTRUSTED
205    // instead of trusted-with-a-partial-index (the documented exposure,
206    // closed). The wipe also GCs postings whose term no longer appears in
207    // the hexastore at all — the per-term loop could never see those. The
208    // liveness marker stays down until `set_geo_index_epoch` re-stamps it
209    // below, so the trust gate reads untrusted for the whole rebuild.
210    let deleted = o.wipe_geo_index()?;
211    let mut reindexed = 0u64;
212    let mut report = waratah_geo::RebuildReport::default();
213    // The upgrade pass replaces orphaned typed literals with their native
214    // terms across ALL THREE axes; replacements then re-cover like any
215    // native term. Batches flush on accumulated pair count (byte-framing is
216    // the RPC shell's job; here one batch per store call is fine — the
217    // offline path owns the stores exclusively).
218    let mut replace_pairs: Vec<waratah_storage::ReplacePair> = Vec::new();
219    // Old orphan term hash → its minted native term (re-covered below).
220    let mut upgraded: HashMap<StrHash, EncodedTerm> = HashMap::new();
221    for versions in terms.values() {
222        // Delete every old posting (leftover Puts with no Deletes would
223        // be stale covering cells): already done by the one-pass wipe
224        // above.
225        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            // Orphan upgrade: resolve the lexical, plan, apply blob puts,
231            // queue the Replace pairs for every live referencing quad.
232            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(&registry, &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    // Apply the replaces in byte-ish-bounded batches on all three axes at
288    // the shared epoch ts (MVCC-atomic per batch: no snapshot sees both
289    // rows or neither).
290    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    // Re-cover every live term: natives as-is, upgraded terms under their
297    // NEW native encoding.
298    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            // Upgraded above: cover the NEW native term (its blob was put
305            // in the upgrade pass).
306            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    // Zero geo terms → epoch 0: an empty, incrementally-maintained index is
319    // valid for every snapshot.
320    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    // Flush all three axes so every SST this rebuild produces carries its
326    // `waratah.stats` blob (zero-orphan rebuilds wrote no hexastore rows;
327    // the S/P flushes no-op). Without these, the S/P replace rows would wait
328    // in the WAL for the next collector-attached process to count them.
329    s.flush_memtables()?;
330    p.flush_memtables()?;
331    o.flush_memtables()?;
332    Ok(())
333}
334
335/// Resolve an orphaned typed literal's lexical form (inline for
336/// `SmallTypedLiteral`, the string registry for `BigTypedLiteral`).
337fn 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
359/// Format a rebuild failure with enough information to locate the offending
360/// quad without embedding an arbitrarily large literal in the error.
361pub(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
396/// Decode one encoded-term byte run from a quad identity triple. The
397/// default graph encodes to ZERO bytes (as in the storage keys).
398fn 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
410/// Rebuild postings for one NATIVE term via the shared core; geometries
411/// read their canonical CRS84 EWKB from the blob store.
412fn 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
446/// Where the vendored `proj-data` tree lives next to the binary / in-repo.
447pub 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
455/// Point PROJ at the vendored data tree and disable the network.
456///
457/// Called before any geo transform runs (compute startup, import, rebuild).
458/// Ingest and tests must never hit the PROJ CDN; without the vendored tree
459/// the geo plugin still loads — only datum transforms (GDA/NZGD/ATRF) fail
460/// closed at encode time and fall back to typed literals.
461pub fn configure_proj_env() {
462    if std::env::var_os("PROJ_DATA").is_none()
463        && let Some(dir) = proj_data_dir()
464    {
465        // SAFETY: startup, before transform threads spawn.
466        unsafe { std::env::set_var("PROJ_DATA", &dir) };
467    }
468    if std::env::var_os("PROJ_NETWORK").is_none() {
469        // SAFETY: same startup window.
470        unsafe { std::env::set_var("PROJ_NETWORK", "OFF") };
471    }
472}
473
474/// Per-level tallies of the [`census`] walk.
475#[derive(Debug, Default)]
476struct LevelTally {
477    /// Distinct `(cell, term)` postings whose newest version is a Put.
478    puts: u64,
479    /// Distinct postings whose newest version is a Delete.
480    deletes: u64,
481    /// Put postings whose value carries a CRS84 envelope — the population
482    /// the storage-side AABB skip can remove before emission.
483    envelopes: u64,
484    /// L11 bucket incidences this level's Put postings contribute to the
485    /// stats histogram's fine map (`observe_posting`'s expansion: 1 per
486    /// level-≥11 posting, `4^(11−level)` per level 9–10 posting).
487    incidences: u64,
488}
489
490/// Read-only census of one O-axis geo posting store, folded from decoded
491/// rows in walk (key) order. Answers the window-estimate decomposition
492/// questions at the source: which S2 levels the coverer actually produced,
493/// how much L9–L10 expansion mass the stats histogram carries, how large
494/// the envelope-bearing (AABB-skippable) population is, and the
495/// cells-per-term multiplicity the drain's distinct seen-set collapses.
496#[derive(Debug, Default)]
497struct PostingCensus {
498    /// Raw rows walked, all versions.
499    rows: u64,
500    /// Distinct `(cell, term)` logical keys (versions collapse).
501    logical: u64,
502    /// Logical keys whose newest version is a Put.
503    puts: u64,
504    /// Logical keys whose newest version is a Delete.
505    deletes: u64,
506    /// Distinct cell ids `geo_cell_level` could not decode (the stats
507    /// collector ignores these rows the same way).
508    malformed: u64,
509    /// Levels 0–8 Put postings — the histogram's native-id coarse map
510    /// (the count-once rung; the floor is
511    /// `GEO_HISTOGRAM_COARSE_FLOOR_LEVEL`).
512    coarse_puts: u64,
513    /// The fine map's total bucket incidences.
514    fine_incidences: u64,
515    /// Per-level tallies (levels with at least one logical key).
516    levels: BTreeMap<u8, LevelTally>,
517    /// Distinct encoded terms among Put postings — the drain's distinct
518    /// candidate analog (one geometry files under many cells but emits
519    /// once per window).
520    terms: HashSet<Vec<u8>>,
521    /// Logical keys already counted. Rows arrive newest-version-first in
522    /// key order on both backends, so the first sight of a key carries its
523    /// newest op.
524    seen: HashSet<Vec<u8>>,
525    /// `--window` state: absent outside the window mode.
526    window: Option<WindowState>,
527}
528
529/// `--window` mode state: the postings-derived histogram (exact — the
530/// collector's own `observe_posting` classification, no wire trims and no
531/// remainder) plus the drain-truth accounting against the window's
532/// cell-id intervals.
533#[derive(Debug)]
534struct WindowState {
535    /// What the stats histogram would carry if every SST blob were exact.
536    histogram: waratah_stats::GeoCellHistogram,
537    /// The window's drain view: a live posting is fetched iff its cell
538    /// falls in one of these inclusive ranges (descendant ranges plus
539    /// exact ancestors — the storage scan's walk set).
540    intervals: Vec<GeoCellInterval>,
541    /// Posting rows the drain would fetch (the scan's pre-AABB fetch
542    /// volume).
543    hits: u64,
544    /// Distinct terms among `hits` — the true candidate set (one geometry
545    /// = one candidate, the estimate's target unit).
546    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    /// Fold one decoded row. Feed in walk (key) order.
568    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                // The same expansion `observe_posting` applies: the whole
592                // L11 descendant run counts (width 1 for level ≥ 11).
593                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                // The collector's own classification — what the stats
601                // histogram would carry if every SST blob were exact.
602                window.histogram.observe_posting(posting.cell_id);
603                // Drain truth: a live posting is fetched iff its cell
604                // falls in one of the window's intervals.
605                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    /// Print the report: one line per occupied level plus the populations
617    /// the stats histogram derives from them.
618    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    /// `--window` report: the estimator's ladder decomposition over the
665    /// postings-exact histogram and the drain truth over the same
666    /// intervals — the two numbers whose gap IS the window over-count.
667    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
753/// `waratah geo census`: read-only per-level census of the O-axis S2
754/// posting store (`{data_dir}/main/o`). The diagnostic behind geo window
755/// estimate over-counting: the level distribution the coverer actually
756/// produced, the L9–L10 expansion mass (the only expanding levels since
757/// the 2026-10 floor move — L8 and below ride the count-once coarse map),
758/// the envelope-bearing population,
759/// and cells-per-term multiplicity — all from the postings themselves, not
760/// the rolled-up profile.
761///
762/// With `window` set (WKT), the walk additionally builds the
763/// postings-exact histogram and the drain-truth candidate set for that
764/// window, and reports the estimator's ladder decomposition next to what
765/// the storage scan would actually fetch.
766pub 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    // The window's query shape derives under the process coverer config
775    // (applied by the CLI dispatch) — the same config the planner would
776    // run under for a `geof:*` conjunct over this WKT.
777    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    // Read-only walk, no stats collectors attached (nothing will flush or
787    // compact; the open itself still takes the RocksDB lock, so a running
788    // cluster on the same dir fails here loudly).
789    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    /// A face-0 cell id at `level` (zero digits, sentinel at the level
823    /// position) — the covering tests' construction.
824    fn census_level_cell(level: u8) -> u64 {
825        1u64 << (2 * (30 - u32::from(level)))
826    }
827
828    /// The census folds raw rows into per-level tallies: versions of one
829    /// logical `(cell, term)` key collapse to the newest (Put wins while a
830    /// Delete supersedes), L9 postings expand to 16 L11 incidences, level-30
831    /// leaves stay at 1, and the envelope count tracks only Put postings
832    /// that carry one.
833    #[test]
834    fn census_folds_versions_levels_envelopes_and_incidence_mass() {
835        let mut rows = vec![
836            // Two points at their level-30 leaves.
837            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            // A geometry posting at level 9 WITH an envelope — two versions
854            // of one logical key (newest first in key order).
855            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            // A superseded posting: the newest version is the Delete.
877            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        // Feed in walk order (key order) — the contract `consider` relies
887        // on for newest-version-first.
888        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    /// The window mode's accounting: a live Put feeds BOTH the
920    /// postings-exact histogram (the collector's classification) and —
921    /// when its cell falls in a window interval — the drain truth (hits
922    /// and distinct candidate terms). Versions collapse before any of it:
923    /// a dead point counts on neither side, and an out-of-window point
924    /// carries histogram mass but no drain truth.
925    #[test]
926    fn window_mode_builds_the_exact_histogram_and_counts_drain_truth() {
927        // The window: one level-11 cell on face 0, covered the way
928        // `intervals_for_covering` emits — the cell's descendant range
929        // plus the exact proper ancestors.
930        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            // Live point inside the window's L11 cell (newest version Put).
944            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            // Dead point (its only version is a Delete) — no hit, no mass.
961            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            // Live point outside the window (face-2 leaf): histogram mass,
970            // no drain truth.
971            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            // Live L9 polygon whose cell is an exact proper ancestor of
980            // the window — the coarse-posted huge-geometry fetch.
981            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        // Drain truth: the in-window point and the ancestor polygon fetch;
996        // the dead point and the face-2 point fetch nothing.
997        assert_eq!(window.hits, 2);
998        assert_eq!(window.hit_terms.len(), 2);
999        // Postings-exact histogram = the live global mass: the in-window
1000        // leaf (1) + the face-2 leaf (1) + the L9 expansion (16).
1001        let mass: u64 = window.histogram.fine.values().map(|c| u64::from(*c)).sum();
1002        assert_eq!(mass, 18);
1003        // The estimate over the window's own bucket: the leaf's bucket
1004        // carries the leaf (1) plus the polygon's expansion (1) = 2 exact
1005        // — equal to the drain truth, inflation 1.0 on this toy window.
1006        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    /// The window shape derivation end-to-end: the WKT parses through the
1016    /// ingest encode path, and the covering, drain intervals, and
1017    /// estimator ranges all derive from that one covering — intervals
1018    /// carry every covering cell (exact or via its descendant range),
1019    /// ranges are merged and disjoint.
1020    #[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    /// The coarse floor is count-once INCLUSIVE at level 8: an L8 posting
1047    /// rides the native-id coarse map (one entry), while level 9 is the
1048    /// first expanding level (16 L11 buckets). The census follows
1049    /// `GEO_HISTOGRAM_COARSE_FLOOR_LEVEL`, so this test pins the census
1050    /// against the floor's current meaning.
1051    #[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    /// The geo write plugin from the process registry (first install wins;
1083    /// the composed test host registers geo first, so it is the first write
1084    /// plugin).
1085    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    /// Seed one quad version directly on the O partition.
1139    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    /// Candidates visible at `snapshot` under one point's leaf-cell interval.
1145    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    /// Candidates visible at `snapshot` over a polygon's covering intervals.
1157    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    /// Seeded store layout (all under `http://ex/`):
1197    ///
1198    /// - `point1`: two Put versions of one logical key (ts 5, ts 8) — the
1199    ///   older row must not duplicate the term.
1200    /// - `point2`: object of an `rdf:type` quad (ts 10) — indexed in BOTH
1201    ///   OPSG and TSG, so the term arrives duplicated across permutations.
1202    /// - `point3`: Put at ts 12, Delete at ts 14 — its one quad is dead;
1203    ///   the rebuild must wipe its stale postings without re-posting.
1204    /// - `polygon`: blob-backed geometry Put at ts 20 (with its plugin-derived
1205    ///   postings seeded at ts 0 for the wipe to remove).
1206    ///
1207    /// Every seed term also carries stale ts-0 postings from the write
1208    /// plugin — deletes are never mirrored to postings, so point3's stale
1209    /// postings remain until the rebuild wipes them. One ORPHAN quad (a
1210    /// plugin-less typed literal, ts 9) exercises the upgrade path: the
1211    /// rebuild rewrites its referencing quad on all three axes via
1212    /// ReplacePairs. Expected rebuild: 4 live terms re-posted (the orphan
1213    /// under its upgraded native form), point3 GC'd, 1 orphan upgraded,
1214    /// epoch = 20 (max ts over geo-object version rows).
1215    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        // Encode all four geo quads through the write plugin once: native
1238        // terms, registry blobs, and O-axis postings come back together.
1239        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            // rdf:type predicate: the O partition indexes this quad in BOTH
1247            // OPSG and TSG, duplicating the point2 term across permutations.
1248            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        // point1: duplicated version rows of one logical key.
1283        put_version(&o, &encoded[0], 5, StorageOp::Put);
1284        put_version(&o, &encoded[0], 8, StorageOp::Put);
1285        // point2 via the rdf:type quad (both permutations).
1286        put_version(&o, &typed_point2, 10, StorageOp::Put);
1287        // point3: Put then Delete on its one quad → dead. Its stale ts-0
1288        // postings stay (the write path never mirrors deletes to
1289        // postings); the rebuild must wipe them without re-posting.
1290        put_version(&o, &encoded[2], 12, StorageOp::Put);
1291        put_version(&o, &encoded[2], 14, StorageOp::Delete);
1292        // polygon: live at ts 20, the highest geo-object row ts.
1293        put_version(&o, &encoded[3], 20, StorageOp::Put);
1294
1295        // The ORPHAN: a plain typed-literal object that never went through
1296        // the write plugin (the plugin-less ingest shape), live at ts 9 —
1297        // below the epoch, so the stamp is unchanged. The WKT stays ≤ 15
1298        // bytes so it encodes as a SmallTypedLiteral (inline value, no
1299        // registry entry needed). The rebuild upgrades it to a native term
1300        // via ReplacePairs on ALL three axes, which is the write shape the
1301        // canonical-stats fix pins.
1302        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        // The rebuild's axis opens attach the stats collectors, so the
1329        // orphan-upgrade replace rows flush WITH `waratah.stats` blobs on
1330        // every axis (pre-fix, S/P rows waited in the WAL for the next
1331        // collector-attached process and O's hexastore rows flushed
1332        // blobless).
1333        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        // Epoch persisted, equal to the max ts over geo-object rows.
1360        assert_eq!(o.geo_index_epoch().unwrap(), Some(20));
1361
1362        // The rebuild's collector attachment: the final flush stamped a
1363        // `waratah.stats` blob carrying the geo cell-count histogram for the
1364        // re-applied postings (the pre-fix open attached no collectors, so
1365        // rebuilt SSTs flushed blobless).
1366        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        // The dead term was GC'd: wiped by the rebuild, never re-posted.
1385        assert_eq!(
1386            o.delete_geo_term(&encode_term_bytes(&seeded.point3))
1387                .unwrap(),
1388            0
1389        );
1390
1391        // Surviving postings carry the epoch stamp: visible at the epoch,
1392        // invisible below it.
1393        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        // Blob-backed polygon: wiped (stale ts-0 postings) and re-covered
1404        // under the current config, stamped at the epoch.
1405        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        // A second rebuild is idempotent: same epoch, postings intact.
1414        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    /// Zero geo terms → epoch 0, no wipe/reindex work, index empty.
1503    #[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    /// Fresh O-partition handle for the data dir. Handles are scoped by the
1523    /// caller so the rebuild command can open its own (single-writer lock).
1524    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    /// The shared-literal delete bug, end to end on the O partition: one
1534    /// WKT point literal referenced by two subjects stays candidate-visible
1535    /// after ONE referencing quad is deleted (deletes are never mirrored to
1536    /// postings), and the rebuild's per-quad liveness keeps it posted until
1537    /// the LAST referencing quad goes — then wipes it entirely.
1538    #[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        // Seed both quads through the write plugin: native term + ts-0
1544        // postings, hexastore Put at ts 0.
1545        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        // Delete ONE quad's hexastore version (ts 5). No posting delete is
1571        // sent by the write path any more — the stale posting stays.
1572        {
1573            let o = reopen(&dir);
1574            put_version(&o, &encoded[1], 5, StorageOp::Delete);
1575        }
1576
1577        // The rebuild keeps the term posted: the other quad is still live.
1578        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        // Delete the second quad; the rebuild must now wipe the term
1586        // entirely (the rebuild IS the garbage collector).
1587        {
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            // Wiped: no posting rows remain for the dead term.
1596            assert_eq!(o.delete_geo_term(&encode_term_bytes(&term)).unwrap(), 0);
1597        }
1598    }
1599}