Skip to main content

waratah_storage/
memory.rs

1//! In-memory storage backend for fast unit tests (always compiled).
2
3use std::collections::BTreeMap;
4
5use crate::encode::{
6    AxisHeadCountHit, COMMIT_TS_LEN, CatalogPut, CatalogRebuildStats, ComparisonMask,
7    DomainCountMode, DomainScanCountHit, DomainScanHit, EncodedQuad, EncodedTerm,
8    EncodedTriplePattern, GByteFilter, GEO_CELL_ID_LEN, GEO_INDEX_EPOCH_KEY,
9    GEO_INDEX_LIVENESS_KEY, GeoCandidateDecision, GeoCandidateState, GeoCellInterval, GeoEnvelope,
10    GeoIndexPut, GraphCatalogState, HeadVerdict, HexastorePut, HexastoreVersion, IndexPermutation,
11    IriOnlyMask, KeyRow, MERGE_NEXT_CHAIN_LIMIT, MERGE_TRIPLE_PREFIX_MAX, MatchDecision, QuadSlot,
12    RowMatcher, RunCounter, SnapshotScanState, TEMPORAL_INDEX_EPOCH_KEY, TEMPORAL_INDEX_ORIGIN_KEY,
13    TEMPORAL_KEY_LEN, TEMPORAL_ORIGIN_VERSION, TemporalCandidateDecision, TemporalCandidateState,
14    TemporalCellInterval, TemporalIndexPut, TemporalQueryPredicate, TermReader,
15    WRITTEN_TERM_MAX_SIZE, byte_successor, catalog_prefix, classify_g_window,
16    collect_dedup_visible_catalog_graphs, consider_axis_head_key, consider_head_key,
17    decode_catalog_value, decode_geo_epoch, decode_geo_liveness, decode_index_key,
18    decode_storage_value, decode_temporal_epoch, decode_temporal_origin,
19    decode_temporal_posting_value, decode_versioned_key, encode_geo_epoch, encode_geo_liveness,
20    encode_index_key, encode_quad, encode_temporal_epoch, encode_temporal_origin,
21    encode_term_bytes, graph_hops_after_head, head_prefix_resume_seek, head_resume_seek,
22    head_term_from_region, is_catalog_graph, prepare_constraints_sorted, prepare_head_prefixes,
23    prepare_hexastore_puts, record_first_put_graph, region_after_head, require_catalog_graph,
24    stage_catalog_puts, term_in_quad_slot, triple_prefix_len, versioned_key_term_prefix,
25};
26use crate::types::{
27    CommitTs, PartitionAxis, ReplacePair, ScanExhaustion, ScanPage, SnapshotId, StorageOp,
28    VisibilityLabel,
29};
30use crate::{Quad, StorageError};
31
32/// In-memory hexastore backend keyed like RocksDB (lexicographic BTree maps).
33#[derive(Debug)]
34pub struct MemoryStorage {
35    axis: PartitionAxis,
36    indexes: [BTreeMap<Vec<u8>, [u8; 5]>; 2],
37    /// S-axis MVCC named-graph catalog. `None` on P/O.
38    ///
39    /// A future G axis may hold a duplicate of this map for in-partition checks;
40    /// that replica is not a second source of truth and is not allocated here.
41    catalog: Option<BTreeMap<Vec<u8>, [u8; 1]>>,
42    /// O-axis geometry index (`geo_index`): same key/value byte layout as the
43    /// RocksDB CF, variable-length values (optional envelope). `None` on S/P.
44    geo: Option<BTreeMap<Vec<u8>, Vec<u8>>>,
45    /// O-axis geo-index metadata (`geo_index_meta`, single-key rebuild
46    /// epoch). `None` on S/P.
47    geo_meta: Option<BTreeMap<Vec<u8>, Vec<u8>>>,
48    /// O-axis temporal index (`temporal_index`): same key/value byte layout
49    /// as the RocksDB CF. `None` on S/P.
50    temporal: Option<BTreeMap<Vec<u8>, Vec<u8>>>,
51    /// O-axis temporal-index metadata (single-key rebuild epoch).
52    temporal_meta: Option<BTreeMap<Vec<u8>, Vec<u8>>>,
53}
54
55impl MemoryStorage {
56    /// Create an empty in-memory store for `axis`.
57    pub fn new(axis: PartitionAxis) -> Self {
58        Self {
59            axis,
60            indexes: [BTreeMap::new(), BTreeMap::new()],
61            catalog: (axis == PartitionAxis::S).then(BTreeMap::new),
62            geo: (axis == PartitionAxis::O).then(BTreeMap::new),
63            geo_meta: (axis == PartitionAxis::O).then(BTreeMap::new),
64            temporal: (axis == PartitionAxis::O).then(BTreeMap::new),
65            temporal_meta: (axis == PartitionAxis::O).then(BTreeMap::new),
66        }
67    }
68
69    /// Partition axis this store owns.
70    pub fn axis(&self) -> PartitionAxis {
71        self.axis
72    }
73
74    /// Insert a quad version into both axis-local indexes.
75    ///
76    /// Defaults (`commit_ts = 0`, `op = Put`, `visibility = 0`) keep existing
77    /// callers working until compute assigns real timestamps.
78    pub fn insert_quad(&mut self, quad: &Quad) -> Result<(), StorageError> {
79        self.insert_quad_version(
80            quad,
81            CommitTs::default(),
82            StorageOp::Put,
83            VisibilityLabel::default(),
84        )
85    }
86
87    /// Insert a versioned hexastore record (`Put` or `Delete`).
88    pub fn insert_quad_version(
89        &mut self,
90        quad: &Quad,
91        commit_ts: CommitTs,
92        op: StorageOp,
93        visibility: VisibilityLabel,
94    ) -> Result<(), StorageError> {
95        self.insert_encoded_quad_version(&encode_quad(quad)?, commit_ts, op, visibility)
96    }
97
98    /// Insert an already-encoded quad version (partition-service write path).
99    pub fn insert_encoded_quad_version(
100        &mut self,
101        encoded: &EncodedQuad,
102        commit_ts: CommitTs,
103        op: StorageOp,
104        visibility: VisibilityLabel,
105    ) -> Result<(), StorageError> {
106        let puts = prepare_hexastore_puts(
107            self.axis,
108            [HexastoreVersion {
109                quad: encoded,
110                commit_ts,
111                op,
112                visibility,
113            }],
114        );
115        let catalog = self.catalog_puts_for_encoded(encoded, commit_ts, op)?;
116        self.apply_prepared_puts_with_catalog(&puts, &catalog)
117    }
118
119    /// Apply pre-encoded index puts into the in-memory BTreeMaps.
120    ///
121    /// Empty `puts` is a no-op. Caller encodes keys via [`crate::prepare_hexastore_puts`].
122    /// Does not update the named-graph catalog; use
123    /// [`Self::apply_prepared_puts_with_catalog`] on the S-axis write path.
124    pub fn apply_prepared_puts(&mut self, puts: &[HexastorePut]) -> Result<(), StorageError> {
125        self.apply_prepared_puts_with_catalog(puts, &[])
126    }
127
128    /// Apply hexastore index puts and catalog puts together.
129    pub fn apply_prepared_puts_with_catalog(
130        &mut self,
131        puts: &[HexastorePut],
132        catalog: &[CatalogPut],
133    ) -> Result<(), StorageError> {
134        if !catalog.is_empty() && self.catalog.is_none() {
135            return Err(StorageError::CatalogNotOnAxis(self.axis));
136        }
137        for put in puts {
138            let index = self.indexes.get_mut(put.cf_index).ok_or_else(|| {
139                StorageError::Backend(format!(
140                    "hexastore put cf_index {} is not 0 or 1",
141                    put.cf_index
142                ))
143            })?;
144            index.insert(put.key.clone(), put.value);
145        }
146        if let Some(map) = &mut self.catalog {
147            for put in catalog {
148                map.insert(put.key.clone(), put.value);
149            }
150        }
151        Ok(())
152    }
153
154    /// Prefix-seek the catalog for each graph and stage `Present` when missing or Dropped.
155    pub fn catalog_puts_for_insert(
156        &self,
157        graphs: &[(EncodedTerm, CommitTs)],
158    ) -> Result<Vec<CatalogPut>, StorageError> {
159        if self.axis != PartitionAxis::S {
160            return Err(StorageError::CatalogNotOnAxis(self.axis));
161        }
162        stage_catalog_puts(graphs, |graph| self.catalog_newest_state(graph))
163    }
164
165    /// Insert an empty named graph (or recreate after Dropped) at `commit_ts`.
166    pub fn add_named_graph(
167        &mut self,
168        graph: &EncodedTerm,
169        commit_ts: CommitTs,
170    ) -> Result<(), StorageError> {
171        require_catalog_graph(graph)?;
172        let puts = self.catalog_puts_for_insert(&[(graph.clone(), commit_ts)])?;
173        self.apply_prepared_puts_with_catalog(&[], &puts)
174    }
175
176    /// Named graphs whose newest in-snapshot catalog version is `Present`.
177    ///
178    /// Includes empty graphs. Never includes the RDF default graph.
179    pub fn list_named_graphs(
180        &self,
181        snapshot: SnapshotId,
182    ) -> Result<Vec<EncodedTerm>, StorageError> {
183        let map = self.catalog_map()?;
184        collect_dedup_visible_catalog_graphs(
185            map.iter()
186                .map(|(key, value)| (key.as_slice(), value.as_slice())),
187            snapshot,
188        )
189    }
190
191    /// Rebuild the named-graph catalog from all SPOG versions (S axis only).
192    pub fn rebuild_named_graph_catalog(&mut self) -> Result<CatalogRebuildStats, StorageError> {
193        let _ = self.catalog_map()?;
194        let mut first_puts = Vec::new();
195        self.visit_index_versions(IndexPermutation::Spog, |quad, commit_ts, op| {
196            record_first_put_graph(&mut first_puts, &quad.graph_name, commit_ts, op);
197            Ok(())
198        })?;
199        let mut stats = CatalogRebuildStats::default();
200        let mut staged = Vec::new();
201        for (graph, commit_ts) in &first_puts {
202            if self.catalog_prefix_occupied(graph)? {
203                stats.graphs_skipped += 1;
204            } else {
205                staged.push(CatalogPut::new(
206                    graph,
207                    *commit_ts,
208                    GraphCatalogState::Present,
209                )?);
210                stats.graphs_inserted += 1;
211            }
212        }
213        self.apply_prepared_puts_with_catalog(&[], &staged)?;
214        Ok(stats)
215    }
216
217    /// Walk every versioned key in an axis-local index (no MVCC collapse).
218    pub fn visit_index_versions(
219        &self,
220        permutation: IndexPermutation,
221        mut visit: impl FnMut(&EncodedQuad, CommitTs, StorageOp) -> Result<(), StorageError>,
222    ) -> Result<(), StorageError> {
223        let index = self.index_for(permutation)?;
224        for (key, value) in index {
225            let (quad, commit_ts) = decode_versioned_key(permutation, key)?;
226            let (op, _visibility) = decode_storage_value(value)?;
227            visit(&quad, commit_ts, op)?;
228        }
229        Ok(())
230    }
231
232    /// Flush MemTables to SST — no-op for the in-memory backend.
233    pub fn flush_memtables(&self) -> Result<(), StorageError> {
234        Ok(())
235    }
236
237    /// Scan an encoded pattern as of `snapshot`.
238    ///
239    /// For each logical quad, returns the newest version with
240    /// `commit_ts <= snapshot` whose `op` is [`StorageOp::Put`].
241    /// Visibility labels are stored but not enforced yet.
242    pub fn scan_pattern(
243        &self,
244        pattern: &EncodedTriplePattern,
245        snapshot: SnapshotId,
246    ) -> Result<Vec<EncodedQuad>, StorageError> {
247        self.scan_pattern_in(pattern.best_permutation(self.axis), pattern, snapshot)
248    }
249
250    /// Scan `pattern` through an explicitly chosen axis-local index.
251    ///
252    /// Returns [`StorageError::PermutationNotOwned`] when `permutation` belongs
253    /// to another partition axis.
254    pub fn scan_pattern_in(
255        &self,
256        permutation: IndexPermutation,
257        pattern: &EncodedTriplePattern,
258        snapshot: SnapshotId,
259    ) -> Result<Vec<EncodedQuad>, StorageError> {
260        // Unlimited drain: the page's verdict is ExhaustedScan by
261        // construction and carries no information for this caller.
262        self.scan_pattern_page(
263            permutation,
264            pattern,
265            snapshot,
266            0,
267            None,
268            GByteFilter::Unconstrained,
269            false,
270            IriOnlyMask::NONE,
271        )
272        .map(|page| page.rows)
273    }
274
275    /// Prefix scan with the **full matcher semantics**: residual `graph_filter`
276    /// membership, `merge_default_graph` whole-triple collapse (rows return with G
277    /// rewritten to DefaultGraph), the exclusive `start_after` cursor, and
278    /// `iri_only` segment pushdown all run inside the RowMatcher on raw key
279    /// bytes. `limit` counts **post-filter** matches (`0` = unlimited) — one
280    /// continuous pass, no decoded pre-filter chunking.
281    #[allow(clippy::too_many_arguments)]
282    pub fn scan_pattern_page(
283        &self,
284        permutation: IndexPermutation,
285        pattern: &EncodedTriplePattern,
286        snapshot: SnapshotId,
287        limit: u64,
288        start_after: Option<&EncodedQuad>,
289        graph_filter: GByteFilter,
290        merge_default_graph: bool,
291        iri_only: IriOnlyMask,
292    ) -> Result<ScanPage, StorageError> {
293        self.scan_pattern_page_with_comparisons(
294            permutation,
295            pattern,
296            snapshot,
297            limit,
298            start_after,
299            graph_filter,
300            merge_default_graph,
301            iri_only,
302            &ComparisonMask::default(),
303        )
304    }
305
306    /// [`Self::scan_pattern_page`] with compiled slot comparisons applied
307    /// inside the walk, before a row reaches the page.
308    #[allow(clippy::too_many_arguments)]
309    pub fn scan_pattern_page_with_comparisons(
310        &self,
311        permutation: IndexPermutation,
312        pattern: &EncodedTriplePattern,
313        snapshot: SnapshotId,
314        limit: u64,
315        start_after: Option<&EncodedQuad>,
316        graph_filter: GByteFilter,
317        merge_default_graph: bool,
318        iri_only: IriOnlyMask,
319        mask: &ComparisonMask,
320    ) -> Result<ScanPage, StorageError> {
321        // The decoded adapter runs the same RowMatcher walk, decodes each
322        // emitted row, and enforces the post-filter limit; this callback only
323        // adds the merge-default G rewrite.
324        let mut out = Vec::new();
325        let exhausted = self.visit_pattern_quads(
326            permutation,
327            pattern,
328            snapshot,
329            limit,
330            start_after,
331            graph_filter,
332            merge_default_graph,
333            iri_only,
334            mask,
335            |mut quad| {
336                if merge_default_graph {
337                    quad = quad.into_merged_default();
338                }
339                out.push(quad);
340                Ok(true)
341            },
342        )?;
343        Ok(ScanPage {
344            rows: out,
345            exhausted: Some(exhausted),
346        })
347    }
348
349    /// Count matching rows with the **full matcher semantics** — same
350    /// `graph_filter` / `merge_default_graph` / cursor contract as
351    /// [`Self::scan_pattern_page`], counting raw [`KeyRow`]s without
352    /// decoding any term. `limit` counts post-filter matches (`0` = unlimited).
353    #[allow(clippy::too_many_arguments)]
354    pub fn count_pattern_impl(
355        &self,
356        permutation: IndexPermutation,
357        pattern: &EncodedTriplePattern,
358        snapshot: SnapshotId,
359        limit: u64,
360        graph_filter: GByteFilter,
361        merge_default_graph: bool,
362    ) -> Result<u64, StorageError> {
363        let mut count = 0u64;
364        self.visit_pattern_rows(
365            permutation,
366            pattern,
367            snapshot,
368            None,
369            graph_filter,
370            merge_default_graph,
371            IriOnlyMask::NONE,
372            &ComparisonMask::default(),
373            |_row| {
374                count += 1;
375                Ok(limit == 0 || count < limit)
376            },
377        )?;
378        Ok(count)
379    }
380
381    /// Count matching quads visible at `snapshot` without collecting rows.
382    ///
383    /// `limit` of `0` is unlimited; a positive limit stops the iterator once
384    /// that many matches have been counted.
385    pub fn count_pattern_best_permutation(
386        &self,
387        pattern: &EncodedTriplePattern,
388        snapshot: SnapshotId,
389        limit: u64,
390    ) -> Result<u64, StorageError> {
391        self.count_pattern_in(
392            pattern.best_permutation(self.axis),
393            pattern,
394            snapshot,
395            limit,
396        )
397    }
398
399    /// Count `pattern` through an explicitly chosen axis-local index.
400    ///
401    /// Returns [`StorageError::PermutationNotOwned`] when `permutation` belongs
402    /// to another partition axis. `limit` of `0` is unlimited.
403    pub fn count_pattern_in(
404        &self,
405        permutation: IndexPermutation,
406        pattern: &EncodedTriplePattern,
407        snapshot: SnapshotId,
408        limit: u64,
409    ) -> Result<u64, StorageError> {
410        // Counting never needs terms decoded: walk the raw rows directly.
411        let mut count = 0u64;
412        self.visit_pattern_rows(
413            permutation,
414            pattern,
415            snapshot,
416            None,
417            GByteFilter::Unconstrained,
418            false,
419            IriOnlyMask::NONE,
420            &ComparisonMask::default(),
421            |_row| {
422                count += 1;
423                Ok(limit == 0 || count < limit)
424            },
425        )?;
426        Ok(count)
427    }
428
429    /// Allow-list prefix scan with the **full matcher semantics** per tight
430    /// prefix: residual `graph_filter` membership and `merge_default_graph`
431    /// collapse (rows return with G rewritten to DefaultGraph) run inside
432    /// each prefix's matcher. `limit` counts post-filter matches
433    /// (`0` = unlimited). Returns `None` when `slot` does not extend
434    /// `permutation`.
435    #[allow(clippy::too_many_arguments)]
436    pub fn scan_pattern_page_allow_list(
437        &self,
438        permutation: IndexPermutation,
439        pattern: &EncodedTriplePattern,
440        snapshot: SnapshotId,
441        limit: u64,
442        start_after: Option<&EncodedQuad>,
443        allow_list_slot: QuadSlot,
444        allow_terms: &[EncodedTerm],
445        graph_filter: GByteFilter,
446        merge_default_graph: bool,
447        iri_only: IriOnlyMask,
448    ) -> Result<Option<ScanPage>, StorageError> {
449        self.scan_pattern_page_allow_list_with_comparisons(
450            permutation,
451            pattern,
452            snapshot,
453            limit,
454            start_after,
455            allow_list_slot,
456            allow_terms,
457            graph_filter,
458            merge_default_graph,
459            iri_only,
460            &ComparisonMask::default(),
461        )
462    }
463
464    /// [`Self::scan_pattern_page_allow_list`] with compiled slot comparisons
465    /// applied inside each tight prefix's walk.
466    #[allow(clippy::too_many_arguments)]
467    pub fn scan_pattern_page_allow_list_with_comparisons(
468        &self,
469        permutation: IndexPermutation,
470        pattern: &EncodedTriplePattern,
471        snapshot: SnapshotId,
472        limit: u64,
473        start_after: Option<&EncodedQuad>,
474        allow_list_slot: QuadSlot,
475        allow_terms: &[EncodedTerm],
476        graph_filter: GByteFilter,
477        merge_default_graph: bool,
478        iri_only: IriOnlyMask,
479        mask: &ComparisonMask,
480    ) -> Result<Option<ScanPage>, StorageError> {
481        let mut out = Vec::new();
482        let verdict = self.visit_allow_list_rows(
483            permutation,
484            pattern,
485            snapshot,
486            start_after,
487            allow_list_slot,
488            allow_terms,
489            graph_filter,
490            merge_default_graph,
491            iri_only,
492            mask,
493            |row| {
494                // EDGE-triggered limit (see the RocksDB twin): a row
495                // arriving AT the page limit proves more data exists
496                // (stop, `Limited`) but does not enter the page;
497                // when the data ends exactly at the limit this row never
498                // arrives and the walk completes with the terminal
499                // verdict.
500                if limit > 0 && (out.len() as u64) >= limit {
501                    return Ok(false);
502                }
503                let mut quad = decode_index_key(permutation, row.logical())?;
504                if merge_default_graph {
505                    quad = quad.into_merged_default();
506                }
507                out.push(quad);
508                Ok(true)
509            },
510        )?;
511        Ok(verdict.map(|exhausted| ScanPage {
512            rows: out,
513            exhausted: Some(exhausted),
514        }))
515    }
516
517    /// Domain scan: distinct slot-1 head terms under each slot-0 constraint
518    /// on `permutation`. Axis-local only. Twin of
519    /// [`crate::rocksdb::RocksDbStorage::scan_domain`]. `iri_only_head`
520    /// rejects non-NamedNode heads (FILTER(isIRI) pushdown).
521    #[allow(clippy::too_many_arguments)]
522    pub fn scan_domain(
523        &self,
524        permutation: IndexPermutation,
525        constraints: &[EncodedTerm],
526        snapshot: SnapshotId,
527        limit: u64,
528        start_after_constraint: Option<&EncodedTerm>,
529        start_after_term: Option<&EncodedTerm>,
530        graph_name: Option<&EncodedTerm>,
531        graph_filter_terms: &[EncodedTerm],
532        graph_filter_allow: bool,
533        iri_only_head: bool,
534    ) -> Result<Vec<DomainScanHit>, StorageError> {
535        let index = self.index_for(permutation)?;
536        // Sorted prep matches the RocksDB walkers' key-order visitation
537        // (see `prepare_constraints_sorted`): the memory backend is the
538        // reference semantics, so it must agree with the RocksDB modes'
539        // emission order, and the resume skip is only sound when
540        // constraints are visited in key order.
541        let prepared = prepare_constraints_sorted(permutation, constraints)?;
542        let g_window = classify_g_window(graph_name, graph_filter_terms, graph_filter_allow);
543        let mut hits = Vec::new();
544        for constraint in prepared {
545            if limit > 0 && hits.len() as u64 >= limit {
546                break;
547            }
548            let Some(seek) =
549                head_resume_seek(&constraint, start_after_constraint, start_after_term)
550            else {
551                continue;
552            };
553            let c_bytes = encode_term_bytes(&constraint);
554            let mut state = SnapshotScanState::default();
555            let mut start = std::ops::Bound::Included(seek);
556            loop {
557                if limit > 0 && hits.len() as u64 >= limit {
558                    break;
559                }
560                let Some((key, value)) = index
561                    .range((start.clone(), std::ops::Bound::Unbounded))
562                    .next()
563                else {
564                    break;
565                };
566                if !key.starts_with(&c_bytes) {
567                    break;
568                }
569                let head = match consider_head_key(
570                    &mut state,
571                    snapshot,
572                    key,
573                    value,
574                    c_bytes.len(),
575                    graph_hops_after_head(permutation, true),
576                    g_window,
577                    graph_name,
578                    graph_filter_terms,
579                    graph_filter_allow,
580                    iri_only_head,
581                )? {
582                    HeadVerdict::Candidate { head } => head,
583                    HeadVerdict::Skip => {
584                        start = std::ops::Bound::Excluded(key.clone());
585                        continue;
586                    }
587                };
588                // Skip-scan past the rest of this head term: the encoded
589                // bytes are already in the key — no decode, no re-encode.
590                let mut skip = c_bytes.clone();
591                skip.extend_from_slice(&key[head.clone()]);
592                let step = byte_successor(&skip);
593                hits.push(DomainScanHit {
594                    constraint: constraint.clone(),
595                    term: head_term_from_region(&key[head.clone()])?,
596                });
597                if limit > 0 && hits.len() as u64 >= limit {
598                    break;
599                }
600                match step {
601                    Some(next) => start = std::ops::Bound::Included(next),
602                    None => break,
603                }
604                state = SnapshotScanState::default();
605            }
606        }
607        Ok(hits)
608    }
609
610    /// Domain count scan: run lengths of slot-1 head terms under each
611    /// slot-0 constraint on `permutation`. Axis-local only. Twin of
612    /// [`crate::rocksdb::RocksDbStorage::scan_domain_counts`] and of
613    /// [`Self::scan_domain`] — same visibility semantics (per-logical-quad
614    /// MVCC collapse, `op == Put`, graph window, `iri_only_head`), but the
615    /// walk iterates every key of the constraint prefix instead of seeking
616    /// past runs. What one increment represents is `mode` — see
617    /// [`DomainCountMode`]. With `merge_default_graph` set the walk seeks
618    /// past extra G per counted triple, which makes `Rows` coincide with
619    /// `DistinctTerms`. Runs with zero visible rows are not emitted.
620    /// `limit` counts emitted triples (`0` = unlimited).
621    #[allow(clippy::too_many_arguments)]
622    pub fn scan_domain_counts(
623        &self,
624        permutation: IndexPermutation,
625        constraints: &[EncodedTerm],
626        snapshot: SnapshotId,
627        limit: u64,
628        start_after_constraint: Option<&EncodedTerm>,
629        start_after_term: Option<&EncodedTerm>,
630        graph_name: Option<&EncodedTerm>,
631        graph_filter_terms: &[EncodedTerm],
632        graph_filter_allow: bool,
633        iri_only_head: bool,
634        merge_default_graph: bool,
635        mode: DomainCountMode,
636    ) -> Result<Vec<DomainScanCountHit>, StorageError> {
637        // TSG refusal — same contract as the RocksDB entry point: the
638        // distinct modes' region arithmetic assumes a 4-slot layout; TSG's
639        // third component IS G. See
640        // [`StorageError::DistinctCountsNotOnTsg`]. Rows mode stays
641        // servable.
642        if permutation == IndexPermutation::Tsg && mode != DomainCountMode::Rows {
643            return Err(StorageError::DistinctCountsNotOnTsg);
644        }
645        let index = self.index_for(permutation)?;
646        // Sorted prep matches the RocksDB walkers' key-order visitation
647        // (see `prepare_constraints_sorted`): the memory backend is the
648        // reference semantics, so it must agree with the RocksDB modes'
649        // emission order, and the resume skip is only sound when
650        // constraints are visited in key order.
651        let prepared = prepare_constraints_sorted(permutation, constraints)?;
652        let g_window = classify_g_window(graph_name, graph_filter_terms, graph_filter_allow);
653        let mut hits = Vec::new();
654        for constraint in prepared {
655            if limit > 0 && hits.len() as u64 >= limit {
656                break;
657            }
658            let Some(seek) =
659                head_resume_seek(&constraint, start_after_constraint, start_after_term)
660            else {
661                continue;
662            };
663            let c_bytes = encode_term_bytes(&constraint);
664            let mut state = SnapshotScanState::default();
665            // The run currently being counted. The walk visits every key in
666            // order, so `state` dedupes version chains across the constraint;
667            // merge mode seeks past extra G of a counted triple and resets
668            // `state` the way a domain-scan head skip does.
669            let mut run_head = [0u8; WRITTEN_TERM_MAX_SIZE];
670            let mut run_len = 0usize;
671            let mut current: Option<RunCounter> = None;
672            let mut full = false;
673            let mut start = std::ops::Bound::Included(seek);
674            while let Some((key, value)) = index
675                .range((start.clone(), std::ops::Bound::Unbounded))
676                .next()
677            {
678                if !key.starts_with(&c_bytes) {
679                    break;
680                }
681                let head = match consider_head_key(
682                    &mut state,
683                    snapshot,
684                    key,
685                    value,
686                    c_bytes.len(),
687                    graph_hops_after_head(permutation, true),
688                    g_window,
689                    graph_name,
690                    graph_filter_terms,
691                    graph_filter_allow,
692                    iri_only_head,
693                )? {
694                    HeadVerdict::Candidate { head } => head,
695                    HeadVerdict::Skip => {
696                        start = std::ops::Bound::Excluded(key.clone());
697                        continue;
698                    }
699                };
700                let opens_new_run = current.is_none() || run_head[..run_len] != key[head.clone()];
701                if opens_new_run {
702                    if let Some(run) = current.take() {
703                        hits.push(DomainScanCountHit {
704                            constraint: constraint.clone(),
705                            term: head_term_from_region(&run_head[..run_len])?,
706                            count: run.total(),
707                        });
708                        if limit > 0 && hits.len() as u64 >= limit {
709                            full = true;
710                            break;
711                        }
712                    }
713                    run_head[..head.len()].copy_from_slice(&key[head.clone()]);
714                    run_len = head.len();
715                    current = Some(RunCounter::new(mode));
716                }
717                if let Some(run) = &mut current {
718                    match mode {
719                        DomainCountMode::Rows => run.observe_rows(),
720                        DomainCountMode::DistinctTerms => {
721                            let slot2 = region_after_head(key, head.end)?;
722                            run.observe_distinct_terms(key, &slot2);
723                        }
724                        DomainCountMode::DistinctGraphs => {
725                            let slot2 = region_after_head(key, head.end)?;
726                            let logical_end = key.len() - COMMIT_TS_LEN;
727                            run.observe_distinct_graphs(&key[slot2.end..logical_end]);
728                        }
729                    }
730                }
731                if merge_default_graph {
732                    // Merge semantics: the counted triple is unique across
733                    // graphs, so skip its remaining G-variants and older
734                    // versions. Advance one row at a time while the key
735                    // still shares the triple's S/P/O prefix — this backend
736                    // re-ranges per row anyway, so the gate (not the
737                    // advance) is what mirrors the RocksDB Next-chain —
738                    // and pay one positioned seek only for a chain longer
739                    // than MERGE_NEXT_CHAIN_LIMIT. The fallback seek resets
740                    // the MVCC state — but NOT the open run: the next key
741                    // can share the head, so the run continues across the
742                    // merge advance. The per-row advance must not reset
743                    // either: the next considered key has a different
744                    // S/P/O, so the stale handled-logical can never match.
745                    let mut stop_walk = false;
746                    let tp_len = {
747                        let logical = versioned_key_term_prefix(key)?;
748                        triple_prefix_len(logical)?
749                    };
750                    let mut prefix = [0u8; MERGE_TRIPLE_PREFIX_MAX];
751                    prefix[..tp_len].copy_from_slice(&key[..tp_len]);
752                    let mut cursor = key.clone();
753                    let mut chained = 0usize;
754                    loop {
755                        let Some((peek, _)) = index
756                            .range((
757                                std::ops::Bound::Excluded(cursor.clone()),
758                                std::ops::Bound::Unbounded,
759                            ))
760                            .next()
761                        else {
762                            // Range exhausted mid-chain; the outer loop's
763                            // re-query from `cursor` returns None and ends.
764                            start = std::ops::Bound::Excluded(cursor);
765                            break;
766                        };
767                        if !peek.starts_with(&prefix[..tp_len]) {
768                            // Next triple reached: leave `peek` for the
769                            // outer loop to consider.
770                            start = std::ops::Bound::Excluded(cursor);
771                            break;
772                        }
773                        chained += 1;
774                        if chained < MERGE_NEXT_CHAIN_LIMIT {
775                            cursor = peek.clone();
776                            continue;
777                        }
778                        // Bounded fallback: one positioned seek finishes
779                        // the chain.
780                        match byte_successor(&prefix[..tp_len]) {
781                            Some(next) => {
782                                start = std::ops::Bound::Included(next);
783                                state = SnapshotScanState::default();
784                            }
785                            None => stop_walk = true,
786                        }
787                        break;
788                    }
789                    if stop_walk {
790                        break;
791                    }
792                    continue;
793                }
794                start = std::ops::Bound::Excluded(key.clone());
795            }
796            // Flush the trailing run — unless the page filled mid-run, in
797            // which case the cursor resumes the client past the last emitted
798            // triple and this run is re-walked (and emitted) on the next page.
799            if !full && let Some(run) = current {
800                hits.push(DomainScanCountHit {
801                    constraint: constraint.clone(),
802                    term: head_term_from_region(&run_head[..run_len])?,
803                    count: run.total(),
804                });
805            }
806        }
807        Ok(hits)
808    }
809
810    /// Axis head scan: distinct slot-0 head terms of the whole `permutation`
811    /// CF. Axis-local only. Twin of
812    /// [`crate::rocksdb::RocksDbStorage::scan_axis_head`]. `iri_only_head`
813    /// rejects non-NamedNode heads (FILTER(isIRI) pushdown). With non-empty
814    /// `head_prefixes` the walk is a seek-union over those partial head-term
815    /// byte ranges (opaque bytes; see
816    /// [`prepare_head_prefixes`](crate::encode::head_scan::prepare_head_prefixes)
817    /// for normalization and resume semantics); empty means the unfiltered
818    /// whole-CF walk.
819    #[allow(clippy::too_many_arguments)]
820    pub fn scan_axis_head(
821        &self,
822        permutation: IndexPermutation,
823        snapshot: SnapshotId,
824        limit: u64,
825        start_after_term: Option<&EncodedTerm>,
826        graph_name: Option<&EncodedTerm>,
827        graph_filter_terms: &[EncodedTerm],
828        graph_filter_allow: bool,
829        iri_only_head: bool,
830        head_prefixes: &[Vec<u8>],
831    ) -> Result<Vec<EncodedTerm>, StorageError> {
832        let index = self.index_for(permutation)?;
833        let g_window = classify_g_window(graph_name, graph_filter_terms, graph_filter_allow);
834        let after_bytes = start_after_term.map(encode_term_bytes);
835        let prefixes = prepare_head_prefixes(head_prefixes);
836        let mut terms = Vec::new();
837        let mut state = SnapshotScanState::default();
838        if prefixes.is_empty() {
839            let mut start = match after_bytes.as_deref() {
840                Some(after) => match byte_successor(after) {
841                    Some(next) => std::ops::Bound::Included(next),
842                    None => return Ok(terms),
843                },
844                None => std::ops::Bound::Included(Vec::new()),
845            };
846            loop {
847                if limit > 0 && terms.len() as u64 >= limit {
848                    break;
849                }
850                let Some((key, value)) = index
851                    .range((start.clone(), std::ops::Bound::Unbounded))
852                    .next()
853                else {
854                    break;
855                };
856                let head = match consider_axis_head_key(
857                    permutation,
858                    &mut state,
859                    snapshot,
860                    key,
861                    value,
862                    g_window,
863                    graph_name,
864                    graph_filter_terms,
865                    graph_filter_allow,
866                    iri_only_head,
867                )? {
868                    HeadVerdict::Candidate { head } => head,
869                    HeadVerdict::Skip => {
870                        start = std::ops::Bound::Excluded(key.clone());
871                        continue;
872                    }
873                };
874                // Skip-scan past the rest of this head: the encoded bytes
875                // are the key's own prefix — no decode, no re-encode.
876                let step = byte_successor(&key[..head.end]);
877                terms.push(head_term_from_region(&key[head.clone()])?);
878                if limit > 0 && terms.len() as u64 >= limit {
879                    break;
880                }
881                match step {
882                    Some(next) => start = std::ops::Bound::Included(next),
883                    None => break,
884                }
885                state = SnapshotScanState::default();
886            }
887        } else {
888            // Seek-union twin of the RocksDB walk: visit only each
889            // normalized prefix's key range, in byte order. Keys outside a
890            // prefix's range are never decoded — the `starts_with` gate runs
891            // before any term work.
892            'prefix: for prefix in &prefixes {
893                let Some(seek) = head_prefix_resume_seek(prefix, after_bytes.as_deref()) else {
894                    continue;
895                };
896                let mut start = std::ops::Bound::Included(seek);
897                state = SnapshotScanState::default();
898                while let Some((key, value)) = index
899                    .range((start.clone(), std::ops::Bound::Unbounded))
900                    .next()
901                {
902                    if !key.starts_with(prefix) {
903                        break;
904                    }
905                    let head = match consider_axis_head_key(
906                        permutation,
907                        &mut state,
908                        snapshot,
909                        key,
910                        value,
911                        g_window,
912                        graph_name,
913                        graph_filter_terms,
914                        graph_filter_allow,
915                        iri_only_head,
916                    )? {
917                        HeadVerdict::Candidate { head } => head,
918                        HeadVerdict::Skip => {
919                            start = std::ops::Bound::Excluded(key.clone());
920                            continue;
921                        }
922                    };
923                    // Skip-scan past the rest of this head: the encoded
924                    // bytes are the key's own prefix — no decode, no
925                    // re-encode.
926                    let step = byte_successor(&key[..head.end]);
927                    terms.push(head_term_from_region(&key[head.clone()])?);
928                    if limit > 0 && terms.len() as u64 >= limit {
929                        break 'prefix;
930                    }
931                    match step {
932                        Some(next) => start = std::ops::Bound::Included(next),
933                        None => break,
934                    }
935                    state = SnapshotScanState::default();
936                }
937            }
938        }
939        Ok(terms)
940    }
941
942    /// Max commit_ts among the versioned keys whose slot-0 head term falls
943    /// under `head_prefixes` (normalized like [`Self::scan_axis_head`]). Twin
944    /// of [`crate::rocksdb::RocksDbStorage::max_commit_ts_under_prefixes`]:
945    /// pure suffix scan over the versioned keys, no liveness evaluation —
946    /// counting superseded/dead versions too only ever *overestimates* the
947    /// bound, which is safe (a larger swap ts still sorts ahead of every row
948    /// it deletes). `0` when no key matches.
949    pub fn max_commit_ts_under_prefixes(
950        &self,
951        permutation: IndexPermutation,
952        head_prefixes: &[Vec<u8>],
953    ) -> Result<u64, StorageError> {
954        let index = self.index_for(permutation)?;
955        let prefixes = prepare_head_prefixes(head_prefixes);
956        let mut max_ts = 0u64;
957        let visit = |key: &[u8], max_ts: &mut u64| {
958            if key.len() >= crate::encode::COMMIT_TS_LEN {
959                let ts = CommitTs::from_descending_be_bytes(
960                    key[key.len() - crate::encode::COMMIT_TS_LEN..]
961                        .try_into()
962                        .expect("slice length checked above"),
963                );
964                *max_ts = (*max_ts).max(ts.0);
965            }
966        };
967        if prefixes.is_empty() {
968            for (key, _) in index.iter() {
969                visit(key, &mut max_ts);
970            }
971        } else {
972            for prefix in &prefixes {
973                for (key, _) in index.range(prefix.clone()..) {
974                    if !key.starts_with(prefix) {
975                        break;
976                    }
977                    visit(key, &mut max_ts);
978                }
979            }
980        }
981        Ok(max_ts)
982    }
983
984    /// Axis head count, `TOTAL` mode. Twin of
985    /// [`crate::rocksdb::RocksDbStorage::count_axis_heads`].
986    #[allow(clippy::too_many_arguments)]
987    pub fn count_axis_heads(
988        &self,
989        permutation: IndexPermutation,
990        snapshot: SnapshotId,
991        graph_name: Option<&EncodedTerm>,
992        graph_filter_terms: &[EncodedTerm],
993        graph_filter_allow: bool,
994        iri_only_head: bool,
995    ) -> Result<u64, StorageError> {
996        let index = self.index_for(permutation)?;
997        let g_window = classify_g_window(graph_name, graph_filter_terms, graph_filter_allow);
998        let mut total = 0u64;
999        let mut start = std::ops::Bound::Included(Vec::new());
1000        let mut state = SnapshotScanState::default();
1001        while let Some((key, value)) = index
1002            .range((start.clone(), std::ops::Bound::Unbounded))
1003            .next()
1004        {
1005            let head = match consider_axis_head_key(
1006                permutation,
1007                &mut state,
1008                snapshot,
1009                key,
1010                value,
1011                g_window,
1012                graph_name,
1013                graph_filter_terms,
1014                graph_filter_allow,
1015                iri_only_head,
1016            )? {
1017                HeadVerdict::Candidate { head } => head,
1018                HeadVerdict::Skip => {
1019                    start = std::ops::Bound::Excluded(key.clone());
1020                    continue;
1021                }
1022            };
1023            total += 1;
1024            // Payload-validate the counted head — twin of the RocksDB
1025            // TOTAL walk's validation decode (corruption must surface as
1026            // `Corrupt` here too, not a silent under-count; one decode per
1027            // distinct head, not per row).
1028            let _ = head_term_from_region(&key[head.clone()])?;
1029            // TOTAL mode needs no term at all — the skip-seek is the key's
1030            // own prefix bytes.
1031            let step = byte_successor(&key[..head.end]);
1032            match step {
1033                Some(next) => start = std::ops::Bound::Included(next),
1034                None => break,
1035            }
1036            state = SnapshotScanState::default();
1037        }
1038        Ok(total)
1039    }
1040
1041    /// Axis head count, `PER_HEAD` mode. Twin of
1042    /// [`crate::rocksdb::RocksDbStorage::scan_axis_head_counts`].
1043    #[allow(clippy::too_many_arguments)]
1044    pub fn scan_axis_head_counts(
1045        &self,
1046        permutation: IndexPermutation,
1047        snapshot: SnapshotId,
1048        limit: u64,
1049        start_after_term: Option<&EncodedTerm>,
1050        graph_name: Option<&EncodedTerm>,
1051        graph_filter_terms: &[EncodedTerm],
1052        graph_filter_allow: bool,
1053        iri_only_head: bool,
1054    ) -> Result<Vec<AxisHeadCountHit>, StorageError> {
1055        let index = self.index_for(permutation)?;
1056        let g_window = classify_g_window(graph_name, graph_filter_terms, graph_filter_allow);
1057        let mut hits = Vec::new();
1058        let mut start = match start_after_term {
1059            Some(after) => match byte_successor(&encode_term_bytes(after)) {
1060                Some(next) => std::ops::Bound::Included(next),
1061                None => return Ok(hits),
1062            },
1063            None => std::ops::Bound::Included(Vec::new()),
1064        };
1065        let mut state = SnapshotScanState::default();
1066        // The head run being counted: the head term's encoded bytes
1067        // (`run_head[..run_len]`), the distinct slot-1 count, and the last
1068        // slot-1 region (slot-1 terms are contiguous under their head, so
1069        // boundary counting needs only the previous region — byte identity
1070        // is term identity).
1071        let mut run_head = [0u8; WRITTEN_TERM_MAX_SIZE];
1072        let mut run_len = 0usize;
1073        // Head run accumulator: distinct slot-1 count so far, plus the
1074        // previous row's slot-1 region as `(encoded bytes, used length)` —
1075        // byte identity is term identity.
1076        type Slot1RunAcc = (u64, Option<([u8; WRITTEN_TERM_MAX_SIZE], usize)>);
1077        let mut current: Option<Slot1RunAcc> = None;
1078        let mut full = false;
1079        while let Some((key, value)) = index
1080            .range((start.clone(), std::ops::Bound::Unbounded))
1081            .next()
1082        {
1083            let head = match consider_axis_head_key(
1084                permutation,
1085                &mut state,
1086                snapshot,
1087                key,
1088                value,
1089                g_window,
1090                graph_name,
1091                graph_filter_terms,
1092                graph_filter_allow,
1093                iri_only_head,
1094            )? {
1095                HeadVerdict::Candidate { head } => head,
1096                HeadVerdict::Skip => {
1097                    start = std::ops::Bound::Excluded(key.clone());
1098                    continue;
1099                }
1100            };
1101            // Slot 1 starts at the head's end; slot 1 is never G, so the
1102            // term is always present (never the empty default-graph case).
1103            let slot1 = region_after_head(key, head.end)?;
1104            let opens_new_run = current.is_none() || run_head[..run_len] != key[head.clone()];
1105            if opens_new_run {
1106                if let Some((count, _)) = current.take() {
1107                    hits.push(AxisHeadCountHit {
1108                        term: head_term_from_region(&run_head[..run_len])?,
1109                        count,
1110                    });
1111                    if limit > 0 && hits.len() as u64 >= limit {
1112                        full = true;
1113                        break;
1114                    }
1115                }
1116                // `head.len()`, not `head.end`: the buffer is indexed from
1117                // zero, and only the axis walks' hard-coded head offset of
1118                // zero makes the two equal. A future caller with a
1119                // non-zero head offset would corrupt the saved run head
1120                // (or panic on overflow past WRITTEN_TERM_MAX_SIZE).
1121                run_head[..head.len()].copy_from_slice(&key[head.clone()]);
1122                run_len = head.len();
1123                current = Some((0, None));
1124            }
1125            if let Some((count, last)) = &mut current {
1126                let changed = match last.as_ref() {
1127                    Some((prev, prev_len)) => prev[..*prev_len] != key[slot1.clone()],
1128                    None => true,
1129                };
1130                if changed {
1131                    *count += 1;
1132                    let mut saved = [0u8; WRITTEN_TERM_MAX_SIZE];
1133                    saved[..slot1.len()].copy_from_slice(&key[slot1.clone()]);
1134                    *last = Some((saved, slot1.len()));
1135                }
1136            }
1137            start = std::ops::Bound::Excluded(key.clone());
1138        }
1139        // Flush the trailing run — unless the page filled mid-run, in which
1140        // case the cursor resumes the client at the last emitted head and
1141        // this run is re-walked (and emitted) on the next page.
1142        if !full && let Some((count, _)) = current {
1143            hits.push(AxisHeadCountHit {
1144                term: head_term_from_region(&run_head[..run_len])?,
1145                count,
1146            });
1147        }
1148        Ok(hits)
1149    }
1150
1151    /// Count an allow-list scan with the **full matcher semantics** per tight
1152    /// prefix — residual `graph_filter` membership and `merge_default_graph`
1153    /// collapse inside each prefix's matcher, counting raw [`KeyRow`]s
1154    /// without decoding any term. `limit` counts post-filter matches
1155    /// (`0` = unlimited). Returns `None` when `slot` does not extend
1156    /// `permutation`.
1157    #[allow(clippy::too_many_arguments)]
1158    pub fn count_pattern_allow_list(
1159        &self,
1160        permutation: IndexPermutation,
1161        pattern: &EncodedTriplePattern,
1162        snapshot: SnapshotId,
1163        limit: u64,
1164        allow_list_slot: QuadSlot,
1165        allow_terms: &[EncodedTerm],
1166        graph_filter: GByteFilter,
1167        merge_default_graph: bool,
1168    ) -> Result<Option<u64>, StorageError> {
1169        let mut count = 0u64;
1170        let verdict = self.visit_allow_list_rows(
1171            permutation,
1172            pattern,
1173            snapshot,
1174            None,
1175            allow_list_slot,
1176            allow_terms,
1177            graph_filter,
1178            merge_default_graph,
1179            IriOnlyMask::NONE,
1180            &ComparisonMask::default(),
1181            |_row| {
1182                count += 1;
1183                Ok(limit == 0 || count < limit)
1184            },
1185        )?;
1186        Ok(verdict.map(|_| count))
1187    }
1188
1189    /// Per-term Rockdb prefix ranges in the same encoded order as RocksDB multi-seek.
1190    /// Wraps `visit_pattern_rows` in a loop, with prepared tight allow list prefix ranges
1191    /// Handles the resume cursor, start_after_prefix_bytes.
1192    #[allow(clippy::too_many_arguments)]
1193    pub(crate) fn visit_allow_list_rows(
1194        &self,
1195        permutation: IndexPermutation,
1196        pattern: &EncodedTriplePattern,
1197        snapshot: SnapshotId,
1198        start_after: Option<&EncodedQuad>,
1199        allow_list_slot: QuadSlot,
1200        allow_terms: &[EncodedTerm],
1201        graph_filter: GByteFilter,
1202        merge_default_graph: bool,
1203        iri_only: IriOnlyMask,
1204        mask: &ComparisonMask,
1205        mut on_match: impl FnMut(&KeyRow) -> Result<bool, StorageError>,
1206    ) -> Result<Option<ScanExhaustion>, StorageError> {
1207        let Some(prepared) =
1208            pattern.prepare_tight_allow_list(permutation, allow_list_slot, allow_terms)
1209        else {
1210            // `allow_list_slot` does not extend `permutation`.
1211            // So return `None`, the caller will use a different calling method
1212            return Ok(None);
1213        };
1214        let start_after_prefix_bytes = start_after.map(|after_quad| {
1215            let mut bound = pattern.clone();
1216            bound.bind_slot(
1217                allow_list_slot,
1218                term_in_quad_slot(after_quad, allow_list_slot).clone(),
1219            );
1220            bound.build_scan_prefix_bytes(permutation)
1221        });
1222        // Walk verdict: `Some(Limited)` once any prefix's walk is
1223        // stopped at the limit; completing every prefix is
1224        // `Some(ExhaustedFilterTerms)` — the walk never consults key
1225        // ranges outside its terms (see the RocksDB twin).
1226        let mut verdict = ScanExhaustion::ExhaustedFilterTerms;
1227        // Run `visit_pattern_rows` for each tight prefix.
1228        for (tight_prefix, term) in &prepared.terms {
1229            if start_after_prefix_bytes
1230                .as_ref()
1231                .is_some_and(|cursor| tight_prefix.as_slice() < cursor.as_slice())
1232            {
1233                continue;
1234            }
1235            let mut bound = pattern.clone();
1236            bound.bind_slot(allow_list_slot, term.clone());
1237            let resuming = start_after_prefix_bytes
1238                .as_ref()
1239                .is_some_and(|cursor| tight_prefix.as_slice() == cursor.as_slice());
1240            let term_after = if resuming { start_after } else { None };
1241            // Each tight prefix owns a fresh matcher: dedup collapse never
1242            // spans prefixes (the allow-listed slot is part of the triple,
1243            // so same-triple rows share one prefix).
1244            let mut stopped = false;
1245            let prefix_verdict = self.visit_pattern_rows(
1246                permutation,
1247                &bound,
1248                snapshot,
1249                term_after,
1250                graph_filter.clone(),
1251                merge_default_graph,
1252                iri_only,
1253                mask,
1254                |row| {
1255                    if !on_match(row)? {
1256                        stopped = true;
1257                        return Ok(false);
1258                    }
1259                    Ok(true)
1260                },
1261            )?;
1262            if stopped || prefix_verdict == ScanExhaustion::Limited {
1263                verdict = ScanExhaustion::Limited;
1264                break;
1265            }
1266        }
1267        Ok(Some(verdict))
1268    }
1269
1270    /// Stream every visible matching row to `emit` in one pass over the
1271    /// index range; `emit` returning `false` stops the walk early.
1272    ///
1273    /// Same visibility / cursor contract as [`Self::scan_pattern_page`] with
1274    /// `limit = 0` — the callback decides when to stop. A compiled
1275    /// [`RowMatcher`] applies bound slots, `graph_filter` membership,
1276    /// `merge_default_graph` whole-triple collapse, and the exclusive
1277    /// `start_after` cursor on raw key bytes — the RocksDB twin of this loop
1278    /// runs the identical matcher.
1279    #[allow(clippy::too_many_arguments)]
1280    pub(crate) fn visit_pattern_rows(
1281        &self,
1282        permutation: IndexPermutation,
1283        pattern: &EncodedTriplePattern,
1284        snapshot: SnapshotId,
1285        start_after: Option<&EncodedQuad>,
1286        graph_filter: GByteFilter,
1287        merge_default_graph: bool,
1288        iri_only: IriOnlyMask,
1289        mask: &ComparisonMask,
1290        mut on_match: impl FnMut(&KeyRow) -> Result<bool, StorageError>,
1291    ) -> Result<ScanExhaustion, StorageError> {
1292        let index = self.index_for(permutation)?;
1293        let prefix = pattern.build_scan_prefix_bytes(permutation);
1294        // Seek to the cursor's term prefix (not `term || 0xFF`): a variable-length
1295        // successor key can sort *before* the last versioned key of `start_after`.
1296        let range_start = match start_after {
1297            Some(quad) => {
1298                let key = encode_index_key(permutation, quad);
1299                if key.as_slice() >= prefix.as_slice() {
1300                    std::ops::Bound::Included(key)
1301                } else {
1302                    std::ops::Bound::Included(prefix.clone())
1303                }
1304            }
1305            None => std::ops::Bound::Included(prefix.clone()),
1306        };
1307
1308        let mut state = SnapshotScanState::default();
1309        let mut matcher = RowMatcher::compile(
1310            pattern,
1311            permutation,
1312            graph_filter,
1313            merge_default_graph,
1314            start_after,
1315            iri_only,
1316        );
1317        // The exclusive-cursor bound is fixed for the whole walk; encode it
1318        // once (see the RocksDB twin of this loop).
1319        let cursor_key = start_after.map(|quad| encode_index_key(permutation, quad));
1320        // Walk verdict (see the RocksDB twin): sink stop = Limited,
1321        // leaving the pattern's key range = ExhaustedScan. A sink error
1322        // also stops early; the error surfaces from `?` and the verdict
1323        // is discarded.
1324        let mut verdict = ScanExhaustion::ExhaustedScan;
1325        for (key, value) in index.range((range_start, std::ops::Bound::Unbounded)) {
1326            if !key.starts_with(&prefix) {
1327                break;
1328            }
1329            if let Some(cursor) = cursor_key.as_deref() {
1330                let logical = versioned_key_term_prefix(key)?;
1331                if logical <= cursor {
1332                    continue;
1333                }
1334            }
1335            match matcher.matches_row(key, value, snapshot, &mut state)? {
1336                MatchDecision::Skip => {}
1337                MatchDecision::Emit {
1338                    slot_starts,
1339                    commit_ts,
1340                } => {
1341                    let row = KeyRow {
1342                        key: key.as_slice(),
1343                        permutation,
1344                        seg_starts: slot_starts,
1345                        commit_ts,
1346                    };
1347                    // Slot comparison mask: a proven-false row never reaches
1348                    // the page and never counts toward the limit.
1349                    if !mask.keeps(row.logical(), &row.seg_starts) {
1350                        continue;
1351                    }
1352                    if !on_match(&row)? {
1353                        verdict = ScanExhaustion::Limited;
1354                        break;
1355                    }
1356                }
1357            }
1358        }
1359        Ok(verdict)
1360    }
1361
1362    #[allow(clippy::too_many_arguments)]
1363    pub(crate) fn visit_pattern_quads(
1364        &self,
1365        permutation: IndexPermutation,
1366        pattern: &EncodedTriplePattern,
1367        snapshot: SnapshotId,
1368        limit: u64,
1369        start_after: Option<&EncodedQuad>,
1370        graph_filter: GByteFilter,
1371        merge_default_graph: bool,
1372        iri_only: IriOnlyMask,
1373        mask: &ComparisonMask,
1374        // `true` = keep walking, `false` = the sink is done (guard reached,
1375        // consumer gone). An `Err` aborts with that error.
1376        mut on_match: impl FnMut(EncodedQuad) -> Result<bool, StorageError>,
1377    ) -> Result<ScanExhaustion, StorageError> {
1378        let mut error = None;
1379        let mut matched = 0u64;
1380        // Unary paths decode only rows that already passed the matcher.
1381        // The walk verdict passes through unchanged (see the RocksDB
1382        // twin's note): the adapter stops the walk only at the limit or
1383        // on an error, and an error discards the verdict.
1384        let verdict = self.visit_pattern_rows(
1385            permutation,
1386            pattern,
1387            snapshot,
1388            start_after,
1389            graph_filter,
1390            merge_default_graph,
1391            iri_only,
1392            mask,
1393            |row| {
1394                if error.is_some() {
1395                    return Ok(false);
1396                }
1397                match decode_index_key(permutation, row.logical()) {
1398                    Ok(quad) => {
1399                        // EDGE-triggered limit: a row arriving AT the page
1400                        // limit proves more data exists (stop,
1401                        // `Limited`) but is not delivered to the
1402                        // sink; when the data ends exactly at the limit
1403                        // this row never arrives and the walk completes
1404                        // with the terminal verdict.
1405                        if limit > 0 && matched >= limit {
1406                            return Ok(false);
1407                        }
1408                        match on_match(quad) {
1409                            Ok(keep_going) => {
1410                                matched += 1;
1411                                Ok(keep_going)
1412                            }
1413                            Err(e) => {
1414                                error = Some(e);
1415                                Ok(false)
1416                            }
1417                        }
1418                    }
1419                    Err(e) => {
1420                        error = Some(e);
1421                        Ok(false)
1422                    }
1423                }
1424            },
1425        )?;
1426        match error {
1427            Some(e) => Err(e),
1428            None => Ok(verdict),
1429        }
1430    }
1431
1432    fn index_for(
1433        &self,
1434        permutation: IndexPermutation,
1435    ) -> Result<&BTreeMap<Vec<u8>, [u8; 5]>, StorageError> {
1436        let indexes = IndexPermutation::for_axis(self.axis);
1437        if permutation == indexes[0] {
1438            Ok(&self.indexes[0])
1439        } else if permutation == indexes[1] {
1440            Ok(&self.indexes[1])
1441        } else {
1442            Err(StorageError::PermutationNotOwned {
1443                index: permutation.cf_name(),
1444                axis: self.axis,
1445            })
1446        }
1447    }
1448
1449    fn catalog_map(&self) -> Result<&BTreeMap<Vec<u8>, [u8; 1]>, StorageError> {
1450        self.catalog
1451            .as_ref()
1452            .ok_or(StorageError::CatalogNotOnAxis(self.axis))
1453    }
1454
1455    fn catalog_puts_for_encoded(
1456        &self,
1457        encoded: &EncodedQuad,
1458        commit_ts: CommitTs,
1459        op: StorageOp,
1460    ) -> Result<Vec<CatalogPut>, StorageError> {
1461        if self.axis != PartitionAxis::S
1462            || op != StorageOp::Put
1463            || !is_catalog_graph(&encoded.graph_name)
1464        {
1465            return Ok(Vec::new());
1466        }
1467        self.catalog_puts_for_insert(&[(encoded.graph_name.clone(), commit_ts)])
1468    }
1469
1470    fn catalog_newest_state(
1471        &self,
1472        graph: &EncodedTerm,
1473    ) -> Result<Option<GraphCatalogState>, StorageError> {
1474        let map = self.catalog_map()?;
1475        let prefix = catalog_prefix(graph)?;
1476        match map.range(prefix.clone()..).next() {
1477            Some((key, value)) if key.starts_with(&prefix) => decode_catalog_value(value).map(Some),
1478            _ => Ok(None),
1479        }
1480    }
1481
1482    fn catalog_prefix_occupied(&self, graph: &EncodedTerm) -> Result<bool, StorageError> {
1483        Ok(self.catalog_newest_state(graph)?.is_some())
1484    }
1485
1486    /// Apply geometry-index postings into the in-memory map (O axis only).
1487    pub fn apply_geo_puts(&mut self, puts: &[GeoIndexPut]) -> Result<(), StorageError> {
1488        if puts.is_empty() {
1489            return Ok(());
1490        }
1491        let Some(map) = &mut self.geo else {
1492            return Err(StorageError::GeoIndexNotOnAxis(self.axis));
1493        };
1494        for put in puts {
1495            map.insert(put.encode_key(), put.encode_value());
1496        }
1497        Ok(())
1498    }
1499
1500    /// Delete every versioned posting of one encoded geo term (rebuild).
1501    pub fn delete_geo_term(&mut self, term: &[u8]) -> Result<u64, StorageError> {
1502        let Some(map) = &mut self.geo else {
1503            return Err(StorageError::GeoIndexNotOnAxis(self.axis));
1504        };
1505        let victims: Vec<Vec<u8>> = map
1506            .keys()
1507            .filter(|key| {
1508                let logical_len = key.len().saturating_sub(crate::encode::COMMIT_TS_LEN);
1509                logical_len > GEO_CELL_ID_LEN && key[GEO_CELL_ID_LEN..logical_len] == *term
1510            })
1511            .cloned()
1512            .collect();
1513        for key in &victims {
1514            map.remove(key);
1515        }
1516        Ok(victims.len() as u64)
1517    }
1518
1519    /// Visit every posting row, decoded, in key order (read-only; the
1520    /// census/debug surface — see the RocksDb twin for the order contract:
1521    /// the `BTreeMap` iterates in the same cell-major, newest-version-first
1522    /// order as the CF).
1523    pub fn visit_geo_postings(
1524        &self,
1525        on_posting: &mut dyn FnMut(&GeoIndexPut) -> Result<(), StorageError>,
1526    ) -> Result<(), StorageError> {
1527        let Some(map) = &self.geo else {
1528            return Err(StorageError::GeoIndexNotOnAxis(self.axis));
1529        };
1530        for (key, value) in map {
1531            on_posting(&GeoIndexPut::decode(key, value)?)?;
1532        }
1533        Ok(())
1534    }
1535
1536    /// Rebuild epoch of the geometry index (O axis) — the TRUST decision.
1537    ///
1538    /// `Ok(None)` on S/P (no map) and when no epoch was ever stamped: every
1539    /// consumer treats a missing epoch as UNTRUSTED (the flip from the
1540    /// original missing-epoch-trusted default, because geography can be
1541    /// ingested plugin-less, so an empty index is not proof of an empty
1542    /// dataset). `None` also when the liveness marker is absent or disagrees
1543    /// with the epoch: the postings were wiped without the epoch being
1544    /// re-stamped, so the index is empty-but-"trusted" and must read
1545    /// untrusted instead. A malformed value also reads as `None`.
1546    pub fn geo_index_epoch(&self) -> Result<Option<u64>, StorageError> {
1547        let Some(map) = &self.geo_meta else {
1548            return Ok(None);
1549        };
1550        let epoch = decode_geo_epoch(map.get(GEO_INDEX_EPOCH_KEY).map(Vec::as_slice));
1551        let liveness = decode_geo_liveness(map.get(GEO_INDEX_LIVENESS_KEY).map(Vec::as_slice));
1552        Ok(match (epoch, liveness) {
1553            (Some(epoch), Some(live)) if epoch == live => Some(epoch),
1554            _ => None,
1555        })
1556    }
1557
1558    /// Stamp the rebuild epoch of the geometry index (O axis) together with
1559    /// its liveness marker.
1560    ///
1561    /// Called by `waratah geo rebuild-index` and by `finish_geo_rebuild`
1562    /// after the postings were rewritten: the epoch is the max `commit_ts`
1563    /// over the geo-contributing version rows the rebuild scanned, and
1564    /// postings stamped at the epoch become visible exactly when the planner
1565    /// starts trusting the index. Both keys are written together — an epoch
1566    /// without its marker is deliberately unreadable as a trust signal (see
1567    /// [`Self::geo_index_epoch`]).
1568    pub fn set_geo_index_epoch(&mut self, epoch: u64) -> Result<(), StorageError> {
1569        let Some(map) = &mut self.geo_meta else {
1570            return Err(StorageError::GeoIndexNotOnAxis(self.axis));
1571        };
1572        map.insert(GEO_INDEX_EPOCH_KEY.to_vec(), encode_geo_epoch(epoch));
1573        map.insert(GEO_INDEX_LIVENESS_KEY.to_vec(), encode_geo_liveness(epoch));
1574        Ok(())
1575    }
1576
1577    /// Raw stored epoch number, ignoring the liveness marker (`0` when absent
1578    /// or malformed, `0` on S/P). Twin of
1579    /// [`crate::rocksdb::RocksDbStorage::geo_index_epoch_number`]: unlike
1580    /// [`Self::geo_index_epoch`] this survives a wipe, so `finish_geo_rebuild`
1581    /// can floor the new epoch at the previously stamped one.
1582    pub fn geo_index_epoch_number(&self) -> Result<u64, StorageError> {
1583        let Some(map) = &self.geo_meta else {
1584            return Ok(0);
1585        };
1586        Ok(decode_geo_epoch(map.get(GEO_INDEX_EPOCH_KEY).map(Vec::as_slice)).unwrap_or(0))
1587    }
1588
1589    /// Skip-seek candidate scan over merged cell-id intervals (O axis).
1590    ///
1591    /// Twin of the RocksDB walk over a BTree range per interval; the
1592    /// caller-owned [`GeoCandidateState`] provides MVCC collapse, the
1593    /// per-stream DISTINCT, and the optional envelope AABB reject.
1594    pub fn geo_scan_candidates(
1595        &self,
1596        intervals: &[GeoCellInterval],
1597        snapshot: SnapshotId,
1598        query_envelope: Option<&GeoEnvelope>,
1599        limit: u64,
1600        state: &mut GeoCandidateState,
1601        mut emit: impl FnMut(&EncodedTerm) -> Result<bool, StorageError>,
1602    ) -> Result<(), StorageError> {
1603        let Some(map) = &self.geo else {
1604            return Err(StorageError::GeoIndexNotOnAxis(self.axis));
1605        };
1606        let mut emitted = 0u64;
1607        for interval in intervals {
1608            // Range over the fixed 8-byte cell-id prefix, bounded ABOVE by the
1609            // in-loop guard rather than by an exclusive end key — the same
1610            // reasoning as `temporal_scan_candidates`: `wrapping_add(1)` on
1611            // the maximum key wraps to zero, which sorts BELOW start and
1612            // makes `BTreeMap::range` panic on start > end. Reachability
1613            // differs (S2 never issues the top-face cell id `u64::MAX`), but
1614            // leaving a panic one bad interval away, on the strength of an
1615            // argument about cell-id numbering, is how the temporal twin got
1616            // into trouble — so the bound is open at the top here too.
1617            let start = interval.min_cell_id.to_be_bytes().to_vec();
1618            let range = if interval.max_cell_id == u64::MAX {
1619                map.range(start..)
1620            } else {
1621                map.range(start..interval.max_cell_id.wrapping_add(1).to_be_bytes().to_vec())
1622            };
1623            for (key, value) in range {
1624                if key[..GEO_CELL_ID_LEN] > interval.max_cell_id.to_be_bytes()[..] {
1625                    break;
1626                }
1627                let ts_at = key
1628                    .len()
1629                    .checked_sub(crate::encode::COMMIT_TS_LEN)
1630                    .ok_or_else(|| StorageError::Corrupt("geo index key too short".to_owned()))?;
1631                let commit_ts = CommitTs::from_descending_be_bytes(
1632                    key[ts_at..]
1633                        .try_into()
1634                        .map_err(|_| StorageError::Corrupt("geo commit_ts suffix".to_owned()))?,
1635                );
1636                let header = value
1637                    .get(..crate::encode::STORAGE_VALUE_LEN)
1638                    .ok_or_else(|| StorageError::Corrupt("truncated storage value".to_owned()))?;
1639                let (op, _visibility) = decode_storage_value(header)?;
1640                let stored_envelope = if query_envelope.is_some() && value.len() > 5 {
1641                    Some(GeoEnvelope::decode(&value[5..])?)
1642                } else {
1643                    None
1644                };
1645                let decision = state.consider_posting(
1646                    key,
1647                    commit_ts,
1648                    op,
1649                    snapshot,
1650                    stored_envelope.as_ref(),
1651                    query_envelope,
1652                )?;
1653                if decision == GeoCandidateDecision::Emit {
1654                    let term_len = key.len() - GEO_CELL_ID_LEN - crate::encode::COMMIT_TS_LEN;
1655                    let mut cursor = &key[GEO_CELL_ID_LEN..GEO_CELL_ID_LEN + term_len];
1656                    let term = cursor.read_term()?;
1657                    if !emit(&term)? {
1658                        return Ok(());
1659                    }
1660                    emitted += 1;
1661                    if limit > 0 && emitted >= limit {
1662                        return Ok(());
1663                    }
1664                }
1665            }
1666        }
1667        Ok(())
1668    }
1669
1670    /// Apply replace pairs as ONE in-memory batch on this axis (the
1671    /// RocksDB twin; see its doc).
1672    pub fn apply_replace_pairs(
1673        &mut self,
1674        pairs: &[ReplacePair],
1675        commit_ts: CommitTs,
1676    ) -> Result<u64, StorageError> {
1677        if pairs.is_empty() {
1678            return Ok(0);
1679        }
1680        let mut versions: Vec<HexastoreVersion<'_>> = Vec::with_capacity(pairs.len() * 2);
1681        let quads: Vec<(crate::encode::EncodedQuad, crate::encode::EncodedQuad)> = pairs
1682            .iter()
1683            .map(|pair| (pair.old_quad(), pair.new_quad()))
1684            .collect();
1685        for (old, new) in &quads {
1686            versions.push(HexastoreVersion {
1687                quad: old,
1688                commit_ts,
1689                op: StorageOp::Delete,
1690                visibility: VisibilityLabel::default(),
1691            });
1692            versions.push(HexastoreVersion {
1693                quad: new,
1694                commit_ts,
1695                op: StorageOp::Put,
1696                visibility: VisibilityLabel::default(),
1697            });
1698        }
1699        let puts = prepare_hexastore_puts(self.axis, versions);
1700        self.apply_prepared_puts(&puts)?;
1701        Ok(pairs.len() as u64)
1702    }
1703
1704    /// Wipe every geo-index posting (O axis; rebuild preamble).
1705    ///
1706    /// Also drops the LIVENESS marker and only that — the epoch key stays on
1707    /// disk, so `geo_index_epoch()` reads `None` (untrusted) for as long as
1708    /// the index is empty, and a rebuild that dies in its walk leaves the
1709    /// planner on the residual `geof:*` path instead of answering every
1710    /// rewrite from a trusted-but-empty index. `finish_geo_rebuild` (or
1711    /// `set_geo_index_epoch`) restores both together.
1712    pub fn wipe_geo_index(&mut self) -> Result<u64, StorageError> {
1713        let Some(map) = &mut self.geo else {
1714            return Err(StorageError::GeoIndexNotOnAxis(self.axis));
1715        };
1716        let deleted = map.len() as u64;
1717        map.clear();
1718        if let Some(meta) = &mut self.geo_meta {
1719            meta.remove(GEO_INDEX_LIVENESS_KEY);
1720        }
1721        Ok(deleted)
1722    }
1723
1724    /// Apply temporal-index postings into the in-memory map (O axis only).
1725    pub fn apply_temporal_puts(&mut self, puts: &[TemporalIndexPut]) -> Result<(), StorageError> {
1726        if puts.is_empty() {
1727            return Ok(());
1728        }
1729        let Some(map) = &mut self.temporal else {
1730            return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
1731        };
1732        for put in puts {
1733            map.insert(put.encode_key(), put.encode_value());
1734        }
1735        Ok(())
1736    }
1737
1738    /// Rebuild epoch of the temporal index (O axis) — the TRUST decision.
1739    ///
1740    /// `Ok(None)` on S/P (no map) and when no epoch was ever stamped (a
1741    /// missing epoch is UNTRUSTED here, unlike geo, because temporal
1742    /// literals predate the plugin and the auto-rebuild stamps before
1743    /// queries serve). `None` also when the tick-axis ORIGIN version beside
1744    /// the epoch disagrees with [`TEMPORAL_ORIGIN_VERSION`]: the origin moved
1745    /// (B56), so postings keyed under the old origin must not be trusted.
1746    pub fn temporal_index_epoch(&self) -> Result<Option<u64>, StorageError> {
1747        let Some(map) = &self.temporal_meta else {
1748            return Ok(None);
1749        };
1750        let epoch = decode_temporal_epoch(map.get(TEMPORAL_INDEX_EPOCH_KEY).map(Vec::as_slice));
1751        let origin = decode_temporal_origin(map.get(TEMPORAL_INDEX_ORIGIN_KEY).map(Vec::as_slice));
1752        Ok(match (epoch, origin) {
1753            (Some(epoch), Some(version)) if version == TEMPORAL_ORIGIN_VERSION => Some(epoch),
1754            _ => None,
1755        })
1756    }
1757
1758    /// Stamp the rebuild epoch of the temporal index (O axis) together with
1759    /// the tick-axis origin version, so the two cannot diverge: an epoch
1760    /// without a matching origin version is deliberately unreadable as a
1761    /// trust signal (see [`Self::temporal_index_epoch`]).
1762    pub fn set_temporal_index_epoch(&mut self, epoch: u64) -> Result<(), StorageError> {
1763        let Some(map) = &mut self.temporal_meta else {
1764            return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
1765        };
1766        map.insert(
1767            TEMPORAL_INDEX_EPOCH_KEY.to_vec(),
1768            encode_temporal_epoch(epoch),
1769        );
1770        map.insert(
1771            TEMPORAL_INDEX_ORIGIN_KEY.to_vec(),
1772            encode_temporal_origin(TEMPORAL_ORIGIN_VERSION),
1773        );
1774        Ok(())
1775    }
1776
1777    /// Wipe every temporal-index posting (O axis; rebuild preamble).
1778    pub fn wipe_temporal_index(&mut self) -> Result<(), StorageError> {
1779        let Some(map) = &mut self.temporal else {
1780            return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
1781        };
1782        map.clear();
1783        // Drop the trust state WITH the postings: a stamped epoch over an
1784        // empty index reads TRUSTED (the gate checks epoch + origin, never
1785        // a liveness marker), so a rebuild failing after the wipe would
1786        // leave temporal FILTERs silently answering zero rows. The GEO
1787        // index's meta state is not ours to touch.
1788        if let Some(meta) = &mut self.temporal_meta {
1789            meta.remove(TEMPORAL_INDEX_EPOCH_KEY);
1790            meta.remove(TEMPORAL_INDEX_ORIGIN_KEY);
1791        }
1792        Ok(())
1793    }
1794
1795    /// Collect the O-axis temporal terms for the rebuild walk.
1796    ///
1797    /// Twin of the RocksDB walk over the in-memory leading O-permutation
1798    /// map (same object-major byte order). See the RocksDB doc for the
1799    /// per-quad liveness contract (any quad referencing the term with its
1800    /// own-latest version = a visible `Put` keeps it) and the epoch source.
1801    pub fn temporal_rebuild_terms(&self) -> Result<(Vec<EncodedTerm>, CommitTs), StorageError> {
1802        if self.axis != PartitionAxis::O {
1803            return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
1804        }
1805        let mut epoch = CommitTs(0);
1806        // Current term run under aggregation: (term bytes, decoded term,
1807        // alive flag = any quad's latest version is a Put).
1808        let mut term_run: Option<(Vec<u8>, EncodedTerm, bool)> = None;
1809        // Current quad run inside the term run: (row key minus the
1810        // commit_ts suffix — identifies the quad, op of its FIRST row,
1811        // which is the quad's latest version in descending-ts order).
1812        let mut quad_run: Option<(Vec<u8>, StorageOp)> = None;
1813        let mut alive_terms: Vec<EncodedTerm> = Vec::new();
1814        for (key, value) in self.indexes[0].iter() {
1815            let mut cursor: &[u8] = key;
1816            let term = match cursor.read_term() {
1817                Ok(term) => term,
1818                Err(_) => continue,
1819            };
1820            let term_len = key.len() - cursor.len();
1821            if crate::encode::temporal_term_interval(&term).is_none() {
1822                // Non-temporal terms never carry postings: skip without
1823                // touching the aggregation. A temporal term's rows are
1824                // contiguous, so skipping cannot merge two term runs.
1825                continue;
1826            }
1827            let ts_at = key
1828                .len()
1829                .checked_sub(crate::encode::COMMIT_TS_LEN)
1830                .ok_or_else(|| StorageError::Corrupt("hexastore key too short".to_owned()))?;
1831            let commit_ts = CommitTs::from_descending_be_bytes(
1832                key[ts_at..]
1833                    .try_into()
1834                    .map_err(|_| StorageError::Corrupt("hexastore commit_ts".to_owned()))?,
1835            );
1836            let (op, _) = decode_storage_value(value)?;
1837            if commit_ts.0 > epoch.0 {
1838                epoch = commit_ts;
1839            }
1840            let quad_key = &key[..ts_at];
1841            let same_term = term_run
1842                .as_ref()
1843                .is_some_and(|(bytes, _, _)| bytes.as_slice() == &key[..term_len]);
1844            if !same_term {
1845                // Term boundary: the finished term's quad runs have already
1846                // folded into its alive flag; emit the term iff alive.
1847                Self::fold_quad_run(&mut quad_run, &mut term_run);
1848                if let Some((_, term, true)) = term_run.take() {
1849                    alive_terms.push(term);
1850                }
1851                term_run = Some((key[..term_len].to_vec(), term, false));
1852            }
1853            // Quad boundary inside the term (or its first row): the
1854            // finished quad's FIRST row — its latest version — folds into
1855            // the alive flag; older versions of the same quad are ignored.
1856            let same_quad = quad_run
1857                .as_ref()
1858                .is_some_and(|(prefix, _)| prefix.as_slice() == quad_key);
1859            if !same_quad {
1860                Self::fold_quad_run(&mut quad_run, &mut term_run);
1861                quad_run = Some((quad_key.to_vec(), op));
1862            }
1863        }
1864        // Tail flush: the last term run.
1865        Self::fold_quad_run(&mut quad_run, &mut term_run);
1866        if let Some((_, term, true)) = term_run.take() {
1867            alive_terms.push(term);
1868        }
1869        Ok((alive_terms, epoch))
1870    }
1871
1872    /// Fold a finished quad run's verdict into its term run's alive flag:
1873    /// a quad whose own-latest version (the op of its FIRST, newest row)
1874    /// is a `Put` keeps the term alive.
1875    fn fold_quad_run(
1876        quad_run: &mut Option<(Vec<u8>, StorageOp)>,
1877        term_run: &mut Option<(Vec<u8>, EncodedTerm, bool)>,
1878    ) {
1879        if let Some((_, quad_op)) = quad_run.take()
1880            && quad_op == StorageOp::Put
1881            && let Some((_, _, alive)) = term_run.as_mut()
1882        {
1883            *alive = true;
1884        }
1885    }
1886
1887    /// Skip-seek candidate scan over merged node-key intervals (O axis).
1888    ///
1889    /// Twin of the RocksDB walk over a BTree range per interval; the
1890    /// caller-owned [`TemporalCandidateState`] provides MVCC collapse, the
1891    /// per-stream DISTINCT, and the exact-interval reject.
1892    pub fn temporal_scan_candidates(
1893        &self,
1894        intervals: &[TemporalCellInterval],
1895        snapshot: SnapshotId,
1896        predicate: &TemporalQueryPredicate,
1897        limit: u64,
1898        state: &mut TemporalCandidateState,
1899        mut emit: impl FnMut(&EncodedTerm) -> Result<bool, StorageError>,
1900    ) -> Result<(), StorageError> {
1901        let Some(map) = &self.temporal else {
1902            return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
1903        };
1904        let mut emitted = 0u64;
1905        for interval in intervals {
1906            // Range over the fixed 16-byte node-key prefix, bounded ABOVE by
1907            // the in-loop guard rather than by an exclusive end key.
1908            //
1909            // An exclusive end bound cannot name a key past the axis top:
1910            // `u128::MAX + 1` wraps to zero, and all-zero big-endian bytes
1911            // sort BELOW `start` — so `map.range(start..end)` is then called
1912            // with start > end, which is a panic in `BTreeMap::range`
1913            // ("range start is greater than range end"), not an empty range.
1914            // A one-sided `?t >= const` comparison is exactly that shape: its
1915            // window runs to `i128::MAX`, which maps to `u128::MAX`, and the
1916            // last covering node of the tail interval carries it. So the
1917            // upper bound is left open at the top and the guard below stops
1918            // the walk — the same behaviour RocksDB gets for free, since it
1919            // only ever compares `key[..16] > max_key`.
1920            let start = interval.min_key.to_be_bytes().to_vec();
1921            let range = if interval.max_key == u128::MAX {
1922                map.range(start..)
1923            } else {
1924                map.range(start..interval.max_key.wrapping_add(1).to_be_bytes().to_vec())
1925            };
1926            for (key, value) in range {
1927                if key[..TEMPORAL_KEY_LEN] > interval.max_key.to_be_bytes()[..] {
1928                    break;
1929                }
1930                let ts_at = key
1931                    .len()
1932                    .checked_sub(crate::encode::COMMIT_TS_LEN)
1933                    .ok_or_else(|| {
1934                        StorageError::Corrupt("temporal index key too short".to_owned())
1935                    })?;
1936                let commit_ts =
1937                    CommitTs::from_descending_be_bytes(key[ts_at..].try_into().map_err(|_| {
1938                        StorageError::Corrupt("temporal commit_ts suffix".to_owned())
1939                    })?);
1940                let (op, _visibility, begin, end_tick) = decode_temporal_posting_value(value)?;
1941                let decision = state
1942                    .consider_posting(key, commit_ts, op, snapshot, begin, end_tick, predicate)?;
1943                if decision == TemporalCandidateDecision::Emit {
1944                    let term_len = key.len() - TEMPORAL_KEY_LEN - crate::encode::COMMIT_TS_LEN;
1945                    let mut cursor = &key[TEMPORAL_KEY_LEN..TEMPORAL_KEY_LEN + term_len];
1946                    let term = cursor.read_term()?;
1947                    if !emit(&term)? {
1948                        return Ok(());
1949                    }
1950                    emitted += 1;
1951                    if limit > 0 && emitted >= limit {
1952                        return Ok(());
1953                    }
1954                }
1955            }
1956        }
1957        Ok(())
1958    }
1959}
1960
1961#[cfg(test)]
1962mod tests {
1963    use super::*;
1964    use crate::encode::{EncodedTerm, RDF_TYPE, encode_storage_value, encode_versioned_key};
1965    use crate::test_util::{sample_quad, sample_quads};
1966    use crate::{Literal, NamedNode};
1967    use pretty_assertions::assert_eq;
1968
1969    #[test]
1970    fn insert_and_scan_empty_store() {
1971        let store = MemoryStorage::new(PartitionAxis::S);
1972        let pattern = EncodedTriplePattern::default();
1973        let rows = store.scan_pattern(&pattern, SnapshotId::default()).unwrap();
1974        assert!(rows.is_empty());
1975    }
1976
1977    #[test]
1978    fn insert_writes_both_axis_cfs_with_storage_value() {
1979        let mut store = MemoryStorage::new(PartitionAxis::S);
1980        let quad = sample_quad();
1981        store.insert_quad(&quad).unwrap();
1982        assert_eq!(store.indexes[0].len(), 1);
1983        assert_eq!(store.indexes[1].len(), 1);
1984
1985        let encoded = encode_quad(&quad).unwrap();
1986        let spog = encode_versioned_key(IndexPermutation::Spog, &encoded, CommitTs::default());
1987        let sopg = encode_versioned_key(IndexPermutation::Sopg, &encoded, CommitTs::default());
1988        let expected = encode_storage_value(StorageOp::Put, VisibilityLabel::default());
1989        assert_eq!(store.indexes[0].get(&spog), Some(&expected));
1990        assert_eq!(store.indexes[1].get(&sopg), Some(&expected));
1991    }
1992
1993    #[test]
1994    fn o_axis_writes_tsg_only_for_rdf_type() {
1995        let mut store = MemoryStorage::new(PartitionAxis::O);
1996        let typed = crate::Quad::new(
1997            NamedNode::new("http://ex/alice").unwrap(),
1998            NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap(),
1999            NamedNode::new("http://ex/Person").unwrap(),
2000            crate::GraphName::DefaultGraph,
2001        );
2002        let other = sample_quad();
2003        store.insert_quad(&typed).unwrap();
2004        store.insert_quad(&other).unwrap();
2005
2006        // OPSG (indexes[0]) gets both quads; TSG (indexes[1]) only the type quad.
2007        assert_eq!(store.indexes[0].len(), 2);
2008        assert_eq!(store.indexes[1].len(), 1);
2009
2010        let encoded = encode_quad(&typed).unwrap();
2011        let tsg = encode_versioned_key(IndexPermutation::Tsg, &encoded, CommitTs::default());
2012        assert!(store.indexes[1].contains_key(&tsg));
2013
2014        let pattern = EncodedTriplePattern {
2015            subject: None,
2016            predicate: Some(RDF_TYPE.clone()),
2017            object: Some(EncodedTerm::from(
2018                &NamedNode::new("http://ex/Person").unwrap(),
2019            )),
2020            graph_name: Some(EncodedTerm::DefaultGraph),
2021        };
2022        assert_eq!(
2023            pattern.best_permutation(PartitionAxis::O),
2024            IndexPermutation::Tsg
2025        );
2026        let rows = store
2027            .scan_pattern_in(IndexPermutation::Tsg, &pattern, SnapshotId::default())
2028            .unwrap();
2029        assert_eq!(rows.len(), 1);
2030        assert_eq!(rows[0].predicate, RDF_TYPE);
2031    }
2032
2033    #[test]
2034    fn scan_bound_predicate_on_p_axis() {
2035        let mut store = MemoryStorage::new(PartitionAxis::P);
2036        for quad in sample_quads() {
2037            store.insert_quad(&quad).unwrap();
2038        }
2039
2040        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
2041        let pattern = EncodedTriplePattern {
2042            subject: None,
2043            predicate: Some(p),
2044            object: None,
2045            graph_name: Some(EncodedTerm::DefaultGraph),
2046        };
2047        let rows = store.scan_pattern(&pattern, SnapshotId::default()).unwrap();
2048        assert_eq!(rows.len(), 2);
2049        assert!(rows.iter().all(|q| pattern.matches(q)));
2050    }
2051
2052    #[test]
2053    fn scan_bound_object_literal_on_o_axis() {
2054        let mut store = MemoryStorage::new(PartitionAxis::O);
2055        for quad in sample_quads() {
2056            store.insert_quad(&quad).unwrap();
2057        }
2058
2059        let sunny = EncodedTerm::from(&Literal::from("Sunny"));
2060        let pattern = EncodedTriplePattern {
2061            subject: None,
2062            predicate: None,
2063            object: Some(sunny),
2064            graph_name: Some(EncodedTerm::DefaultGraph),
2065        };
2066        let rows = store.scan_pattern(&pattern, SnapshotId::default()).unwrap();
2067        assert_eq!(rows.len(), 1);
2068        assert_eq!(
2069            rows[0].subject,
2070            EncodedTerm::from(&NamedNode::new("http://ex/brisbane").unwrap())
2071        );
2072    }
2073
2074    #[test]
2075    fn scan_returns_encoded_columns_not_strings() {
2076        let mut store = MemoryStorage::new(PartitionAxis::S);
2077        store.insert_quad(&sample_quad()).unwrap();
2078        let rows = store
2079            .scan_pattern(&EncodedTriplePattern::default(), SnapshotId::default())
2080            .unwrap();
2081        assert_eq!(rows.len(), 1);
2082        assert!(matches!(rows[0].subject, EncodedTerm::NamedNode { .. }));
2083        assert!(matches!(rows[0].predicate, EncodedTerm::NamedNode { .. }));
2084    }
2085
2086    #[test]
2087    fn snapshot_filter_sees_only_versions_at_or_before_snapshot() {
2088        let mut store = MemoryStorage::new(PartitionAxis::S);
2089        let quad = sample_quad();
2090        store
2091            .insert_quad_version(
2092                &quad,
2093                CommitTs(10),
2094                StorageOp::Put,
2095                VisibilityLabel::default(),
2096            )
2097            .unwrap();
2098        // Same logical quad at a later ts — still Put; snapshot 15 must see ts=10 only
2099        // once (newest visible). We insert a second distinct version by deleting then
2100        // re-putting would change op; here we only have one Put at 10 and one Put at 20
2101        // which would both be Puts — newest <= 15 is ts=10.
2102        store
2103            .insert_quad_version(&quad, CommitTs(20), StorageOp::Put, VisibilityLabel(7))
2104            .unwrap();
2105
2106        let at_15 = store
2107            .scan_pattern(&EncodedTriplePattern::default(), SnapshotId(15))
2108            .unwrap();
2109        assert_eq!(at_15.len(), 1);
2110
2111        let at_25 = store
2112            .scan_pattern(&EncodedTriplePattern::default(), SnapshotId(25))
2113            .unwrap();
2114        assert_eq!(at_25.len(), 1);
2115    }
2116
2117    #[test]
2118    fn delete_hides_put_for_later_snapshots() {
2119        let mut store = MemoryStorage::new(PartitionAxis::S);
2120        let quad = sample_quad();
2121        store
2122            .insert_quad_version(
2123                &quad,
2124                CommitTs(10),
2125                StorageOp::Put,
2126                VisibilityLabel::default(),
2127            )
2128            .unwrap();
2129        store
2130            .insert_quad_version(
2131                &quad,
2132                CommitTs(20),
2133                StorageOp::Delete,
2134                VisibilityLabel::default(),
2135            )
2136            .unwrap();
2137
2138        let before_delete = store
2139            .scan_pattern(&EncodedTriplePattern::default(), SnapshotId(15))
2140            .unwrap();
2141        assert_eq!(before_delete.len(), 1);
2142
2143        let after_delete = store
2144            .scan_pattern(&EncodedTriplePattern::default(), SnapshotId(25))
2145            .unwrap();
2146        assert!(after_delete.is_empty());
2147    }
2148
2149    #[test]
2150    fn scan_page_limit_and_exclusive_start_after() {
2151        let mut store = MemoryStorage::new(PartitionAxis::S);
2152        for quad in sample_quads() {
2153            store.insert_quad(&quad).unwrap();
2154        }
2155        let pattern = EncodedTriplePattern::default();
2156        let permutation = pattern.best_permutation(PartitionAxis::S);
2157        let all = store
2158            .scan_pattern_in(permutation, &pattern, SnapshotId::default())
2159            .unwrap();
2160        assert!(all.len() >= 3);
2161
2162        let first = store
2163            .scan_pattern_page(
2164                permutation,
2165                &pattern,
2166                SnapshotId::default(),
2167                1,
2168                None,
2169                GByteFilter::Unconstrained,
2170                false,
2171                IriOnlyMask::NONE,
2172            )
2173            .unwrap()
2174            .rows;
2175        assert_eq!(first.len(), 1);
2176        assert_eq!(first[0], all[0]);
2177
2178        let rest = store
2179            .scan_pattern_page(
2180                permutation,
2181                &pattern,
2182                SnapshotId::default(),
2183                0,
2184                Some(&first[0]),
2185                GByteFilter::Unconstrained,
2186                false,
2187                IriOnlyMask::NONE,
2188            )
2189            .unwrap()
2190            .rows;
2191        assert_eq!(rest, all[1..]);
2192        assert!(!rest.contains(&first[0]));
2193    }
2194
2195    #[test]
2196    fn start_after_skips_every_version_of_the_cursor_quad() {
2197        let mut store = MemoryStorage::new(PartitionAxis::S);
2198        let quads = sample_quads();
2199        store
2200            .insert_quad_version(
2201                &quads[0],
2202                CommitTs(10),
2203                StorageOp::Put,
2204                VisibilityLabel::default(),
2205            )
2206            .unwrap();
2207        store
2208            .insert_quad_version(
2209                &quads[0],
2210                CommitTs(20),
2211                StorageOp::Put,
2212                VisibilityLabel::default(),
2213            )
2214            .unwrap();
2215        for quad in &quads[1..] {
2216            store
2217                .insert_quad_version(
2218                    quad,
2219                    CommitTs(15),
2220                    StorageOp::Put,
2221                    VisibilityLabel::default(),
2222                )
2223                .unwrap();
2224        }
2225
2226        let pattern = EncodedTriplePattern::default();
2227        let permutation = pattern.best_permutation(PartitionAxis::S);
2228        let all = store
2229            .scan_pattern_page(
2230                permutation,
2231                &pattern,
2232                SnapshotId(30),
2233                0,
2234                None,
2235                GByteFilter::Unconstrained,
2236                false,
2237                IriOnlyMask::NONE,
2238            )
2239            .unwrap()
2240            .rows;
2241        assert!(all.len() >= 2);
2242        let cursor = &all[0];
2243        let page = store
2244            .scan_pattern_page(
2245                permutation,
2246                &pattern,
2247                SnapshotId(30),
2248                10,
2249                Some(cursor),
2250                GByteFilter::Unconstrained,
2251                false,
2252                IriOnlyMask::NONE,
2253            )
2254            .unwrap()
2255            .rows;
2256        assert!(!page.contains(cursor), "must not re-emit the cursor quad");
2257        assert_eq!(page, all[1..]);
2258    }
2259
2260    #[test]
2261    fn domain_counts_count_visible_rows_per_head() {
2262        let mut store = MemoryStorage::new(PartitionAxis::P);
2263        let s1 = NamedNode::new("http://ex/s1").unwrap();
2264        let s2 = NamedNode::new("http://ex/s2").unwrap();
2265        let p1 = NamedNode::new("http://ex/p1").unwrap();
2266        let o1 = NamedNode::new("http://ex/o1").unwrap();
2267        let o2 = NamedNode::new("http://ex/o2").unwrap();
2268        // (s1,p1,o1), (s2,p1,o1), (s1,p1,o2): runs o1=2, o2=1 under p1.
2269        store
2270            .insert_quad(&crate::Quad::new(
2271                s1.clone(),
2272                p1.clone(),
2273                o1.clone(),
2274                crate::GraphName::DefaultGraph,
2275            ))
2276            .unwrap();
2277        store
2278            .insert_quad(&crate::Quad::new(
2279                s2.clone(),
2280                p1.clone(),
2281                o1.clone(),
2282                crate::GraphName::DefaultGraph,
2283            ))
2284            .unwrap();
2285        store
2286            .insert_quad(&crate::Quad::new(
2287                s1.clone(),
2288                p1.clone(),
2289                o2.clone(),
2290                crate::GraphName::DefaultGraph,
2291            ))
2292            .unwrap();
2293
2294        let p1e = encode_quad(&crate::Quad::new(
2295            s1.clone(),
2296            p1.clone(),
2297            o1.clone(),
2298            crate::GraphName::DefaultGraph,
2299        ))
2300        .unwrap();
2301        let hits = store
2302            .scan_domain_counts(
2303                IndexPermutation::Posg,
2304                std::slice::from_ref(&p1e.predicate),
2305                SnapshotId::default(),
2306                0,
2307                None,
2308                None,
2309                None,
2310                &[],
2311                false,
2312                false,
2313                false,
2314                DomainCountMode::Rows,
2315            )
2316            .unwrap();
2317        let got: Vec<(String, u64)> = hits
2318            .iter()
2319            .map(|h| (format!("{:?}", h.term), h.count))
2320            .collect();
2321        assert_eq!(got.len(), 2, "two distinct objects: {got:?}");
2322        let total: u64 = hits.iter().map(|h| h.count).sum();
2323        assert_eq!(total, 3, "three visible rows across both runs");
2324    }
2325
2326    #[test]
2327    fn domain_counts_apply_mvcc_and_graph_window_per_row() {
2328        let mut store = MemoryStorage::new(PartitionAxis::P);
2329        let s1 = NamedNode::new("http://ex/s1").unwrap();
2330        let p1 = NamedNode::new("http://ex/p1").unwrap();
2331        let o1 = NamedNode::new("http://ex/o1").unwrap();
2332        let g1 = crate::GraphName::NamedNode(NamedNode::new("http://ex/g1").unwrap());
2333        let g2 = crate::GraphName::NamedNode(NamedNode::new("http://ex/g2").unwrap());
2334
2335        // Same (s1,p1,o1) in g1 and g2: per-row G semantics count 2.
2336        store
2337            .insert_quad_version(
2338                &crate::Quad::new(s1.clone(), p1.clone(), o1.clone(), g1.clone()),
2339                CommitTs(1),
2340                StorageOp::Put,
2341                VisibilityLabel::default(),
2342            )
2343            .unwrap();
2344        store
2345            .insert_quad_version(
2346                &crate::Quad::new(s1.clone(), p1.clone(), o1.clone(), g2.clone()),
2347                CommitTs(2),
2348                StorageOp::Put,
2349                VisibilityLabel::default(),
2350            )
2351            .unwrap();
2352        // A later Delete of the g2 copy: per-row window + MVCC collapse -> 1.
2353        store
2354            .insert_quad_version(
2355                &crate::Quad::new(s1.clone(), p1.clone(), o1.clone(), g2.clone()),
2356                CommitTs(3),
2357                StorageOp::Delete,
2358                VisibilityLabel::default(),
2359            )
2360            .unwrap();
2361
2362        let p1e = encode_quad(&crate::Quad::new(s1.clone(), p1.clone(), o1.clone(), g1)).unwrap();
2363        // Unconstrained window: both graph copies are visible rows before the
2364        // delete; after ts=3 the g2 copy is deleted -> count 1.
2365        let at3 = store
2366            .scan_domain_counts(
2367                IndexPermutation::Posg,
2368                std::slice::from_ref(&p1e.predicate),
2369                SnapshotId(3),
2370                0,
2371                None,
2372                None,
2373                None,
2374                &[],
2375                false,
2376                false,
2377                false,
2378                DomainCountMode::Rows,
2379            )
2380            .unwrap();
2381        let total: u64 = at3.iter().map(|h| h.count).sum();
2382        assert_eq!(total, 1, "deleted copy must not count");
2383        // Allow-list restricted to g2: the surviving g2 copy is deleted, so
2384        // nothing counts and no hit is emitted.
2385        let g2_term = encode_quad(&crate::Quad::new(s1.clone(), p1.clone(), o1.clone(), g2))
2386            .unwrap()
2387            .graph_name;
2388        let empty = store
2389            .scan_domain_counts(
2390                IndexPermutation::Posg,
2391                std::slice::from_ref(&p1e.predicate),
2392                SnapshotId(3),
2393                0,
2394                None,
2395                None,
2396                None,
2397                std::slice::from_ref(&g2_term),
2398                true,
2399                false,
2400                false,
2401                DomainCountMode::Rows,
2402            )
2403            .unwrap();
2404        assert!(empty.is_empty(), "zero-count runs must not be emitted");
2405    }
2406
2407    #[test]
2408    fn domain_counts_cursor_resumes_at_run_boundaries() {
2409        let mut store = MemoryStorage::new(PartitionAxis::P);
2410        let s1 = NamedNode::new("http://ex/s1").unwrap();
2411        let p1 = NamedNode::new("http://ex/p1").unwrap();
2412        let o1 = NamedNode::new("http://ex/o1").unwrap();
2413        let o2 = NamedNode::new("http://ex/o2").unwrap();
2414        let s2 = NamedNode::new("http://ex/s2").unwrap();
2415        // Two rows under o1 (distinct subjects — identical quads would share
2416        // one key) and one under o2. Key order is by encoded O bytes: the
2417        // test below must not assume IRI lexical order.
2418        store
2419            .insert_quad(&crate::Quad::new(
2420                s1.clone(),
2421                p1.clone(),
2422                o1.clone(),
2423                crate::GraphName::DefaultGraph,
2424            ))
2425            .unwrap();
2426        store
2427            .insert_quad(&crate::Quad::new(
2428                s2,
2429                p1.clone(),
2430                o1.clone(),
2431                crate::GraphName::DefaultGraph,
2432            ))
2433            .unwrap();
2434        store
2435            .insert_quad(&crate::Quad::new(
2436                s1.clone(),
2437                p1.clone(),
2438                o2.clone(),
2439                crate::GraphName::DefaultGraph,
2440            ))
2441            .unwrap();
2442
2443        let p1e = encode_quad(&crate::Quad::new(
2444            s1.clone(),
2445            p1.clone(),
2446            o1.clone(),
2447            crate::GraphName::DefaultGraph,
2448        ))
2449        .unwrap();
2450        // Page 1: one pair (limit=1) — whichever run sorts first, with its
2451        // full run length.
2452        let page1 = store
2453            .scan_domain_counts(
2454                IndexPermutation::Posg,
2455                std::slice::from_ref(&p1e.predicate),
2456                SnapshotId::default(),
2457                1,
2458                None,
2459                None,
2460                None,
2461                &[],
2462                false,
2463                false,
2464                false,
2465                DomainCountMode::Rows,
2466            )
2467            .unwrap();
2468        assert_eq!(page1.len(), 1);
2469        // Resume past it: only the o2 run remains, count 1.
2470        let page2 = store
2471            .scan_domain_counts(
2472                IndexPermutation::Posg,
2473                std::slice::from_ref(&p1e.predicate),
2474                SnapshotId::default(),
2475                0,
2476                Some(&page1[0].constraint),
2477                Some(&page1[0].term),
2478                None,
2479                &[],
2480                false,
2481                false,
2482                false,
2483                DomainCountMode::Rows,
2484            )
2485            .unwrap();
2486        assert_eq!(page2.len(), 1);
2487        // The two pages partition the two runs: one run has both subjects
2488        // (count 2), the other the single o2 row (count 1).
2489        let (first, second) = if page1[0].term == EncodedTerm::from(&o1) {
2490            (page1[0].count, page2[0].count)
2491        } else {
2492            (page2[0].count, page1[0].count)
2493        };
2494        assert_eq!((first, second), (2, 1));
2495    }
2496
2497    fn named_spo(s: &str, o: &str, g: &str) -> crate::Quad {
2498        crate::Quad::new(
2499            NamedNode::new(format!("http://ex/{s}")).unwrap(),
2500            NamedNode::new("http://ex/p").unwrap(),
2501            NamedNode::new(format!("http://ex/{o}")).unwrap(),
2502            crate::GraphName::NamedNode(NamedNode::new(format!("http://ex/{g}")).unwrap()),
2503        )
2504    }
2505
2506    fn put_named(store: &mut MemoryStorage, quad: &crate::Quad, ts: u64, op: StorageOp) {
2507        store
2508            .insert_quad_version(quad, CommitTs(ts), op, VisibilityLabel::default())
2509            .unwrap();
2510    }
2511
2512    fn count_posg(
2513        store: &MemoryStorage,
2514        predicate: &EncodedTerm,
2515        snapshot: u64,
2516        allow: &[EncodedTerm],
2517        allow_on: bool,
2518        merge: bool,
2519    ) -> u64 {
2520        store
2521            .scan_domain_counts(
2522                IndexPermutation::Posg,
2523                std::slice::from_ref(predicate),
2524                SnapshotId(snapshot),
2525                0,
2526                None,
2527                None,
2528                None,
2529                allow,
2530                allow_on,
2531                false,
2532                merge,
2533                DomainCountMode::Rows,
2534            )
2535            .unwrap()
2536            .iter()
2537            .map(|hit| hit.count)
2538            .sum()
2539    }
2540
2541    /// RDF-merge counts distinct S/P/O prefixes. Bag counts still add one per
2542    /// visible G row. A Delete does not seek; the next graph's Put still counts.
2543    #[test]
2544    fn domain_counts_merge_uniques_spo_not_heads() {
2545        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
2546        let g1 = encode_quad(&named_spo("s", "o", "g1")).unwrap().graph_name;
2547        let g2 = encode_quad(&named_spo("s", "o", "g2")).unwrap().graph_name;
2548
2549        let mut same = MemoryStorage::new(PartitionAxis::P);
2550        put_named(&mut same, &named_spo("s", "o", "g1"), 1, StorageOp::Put);
2551        put_named(&mut same, &named_spo("s", "o", "g2"), 2, StorageOp::Put);
2552        assert_eq!(count_posg(&same, &p, 9, &[], false, true), 1);
2553        assert_eq!(count_posg(&same, &p, 9, &[], false, false), 2);
2554        assert_eq!(
2555            count_posg(&same, &p, 9, &[g1.clone(), g2.clone()], true, true),
2556            1
2557        );
2558
2559        let mut two_subjects = MemoryStorage::new(PartitionAxis::P);
2560        put_named(
2561            &mut two_subjects,
2562            &named_spo("s1", "o", "g1"),
2563            1,
2564            StorageOp::Put,
2565        );
2566        put_named(
2567            &mut two_subjects,
2568            &named_spo("s1", "o", "g2"),
2569            2,
2570            StorageOp::Put,
2571        );
2572        put_named(
2573            &mut two_subjects,
2574            &named_spo("s2", "o", "g1"),
2575            3,
2576            StorageOp::Put,
2577        );
2578        put_named(
2579            &mut two_subjects,
2580            &named_spo("s2", "o", "g2"),
2581            4,
2582            StorageOp::Put,
2583        );
2584        assert_eq!(count_posg(&two_subjects, &p, 9, &[], false, true), 2);
2585
2586        // `a` sorts before `b`. The Delete must not seek past the later Put.
2587        let mut deleted = MemoryStorage::new(PartitionAxis::P);
2588        put_named(&mut deleted, &named_spo("s", "o", "a"), 1, StorageOp::Put);
2589        put_named(
2590            &mut deleted,
2591            &named_spo("s", "o", "a"),
2592            2,
2593            StorageOp::Delete,
2594        );
2595        put_named(&mut deleted, &named_spo("s", "o", "b"), 3, StorageOp::Put);
2596        let gone = encode_quad(&named_spo("s", "o", "a")).unwrap().graph_name;
2597        assert_eq!(count_posg(&deleted, &p, 9, &[], false, true), 1);
2598        assert_eq!(count_posg(&deleted, &p, 9, &[gone], true, true), 0);
2599    }
2600
2601    fn scan_posg_runs(
2602        store: &MemoryStorage,
2603        predicate: &EncodedTerm,
2604        snapshot: u64,
2605        allow: &[EncodedTerm],
2606        allow_on: bool,
2607        merge: bool,
2608        mode: DomainCountMode,
2609    ) -> Vec<DomainScanCountHit> {
2610        store
2611            .scan_domain_counts(
2612                IndexPermutation::Posg,
2613                std::slice::from_ref(predicate),
2614                SnapshotId(snapshot),
2615                0,
2616                None,
2617                None,
2618                None,
2619                allow,
2620                allow_on,
2621                false,
2622                merge,
2623                mode,
2624            )
2625            .unwrap()
2626    }
2627
2628    fn head_count(hits: &[DomainScanCountHit], head: &EncodedTerm) -> u64 {
2629        hits.iter()
2630            .find(|h| h.term == *head)
2631            .unwrap_or_else(|| panic!("no hit for head {head:?}"))
2632            .count
2633    }
2634
2635    /// Mode matrix: Rows = bag of `(slot-2, G)` rows, DistinctTerms collapses
2636    /// graph multiplicity, DistinctGraphs counts graph terms per head. MVCC
2637    /// applies per row in every mode: the delete hides the `s1/g2` copy.
2638    #[test]
2639    fn domain_counts_modes_select_counting_dimension() {
2640        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
2641        let mut store = MemoryStorage::new(PartitionAxis::P);
2642        // s1 typed o in g1+g2 (deleted at ts=5), s2 typed o in g1, s3 typed
2643        // o2 in g1.
2644        put_named(&mut store, &named_spo("s1", "o", "g1"), 1, StorageOp::Put);
2645        put_named(&mut store, &named_spo("s1", "o", "g2"), 2, StorageOp::Put);
2646        put_named(&mut store, &named_spo("s2", "o", "g1"), 3, StorageOp::Put);
2647        put_named(&mut store, &named_spo("s3", "o2", "g1"), 4, StorageOp::Put);
2648        put_named(
2649            &mut store,
2650            &named_spo("s1", "o", "g2"),
2651            5,
2652            StorageOp::Delete,
2653        );
2654
2655        let o_head = encode_quad(&named_spo("s1", "o", "g1")).unwrap().object;
2656        let o2_head = encode_quad(&named_spo("s3", "o2", "g1")).unwrap().object;
2657        let runs = |snapshot: u64, mode: DomainCountMode| {
2658            scan_posg_runs(&store, &p, snapshot, &[], false, false, mode)
2659        };
2660
2661        // Before the delete: o run = (s1,g1) (s1,g2) (s2,g1).
2662        let at4 = runs(4, DomainCountMode::Rows);
2663        assert_eq!(head_count(&at4, &o_head), 3);
2664        assert_eq!(head_count(&at4, &o2_head), 1);
2665        // Distinct slot-2 terms: s1 and s2 under o; graph multiplicity gone.
2666        let terms = runs(4, DomainCountMode::DistinctTerms);
2667        assert_eq!(head_count(&terms, &o_head), 2);
2668        assert_eq!(head_count(&terms, &o2_head), 1);
2669        // Distinct graphs under o: g1 and g2.
2670        let graphs = runs(4, DomainCountMode::DistinctGraphs);
2671        assert_eq!(head_count(&graphs, &o_head), 2);
2672        assert_eq!(head_count(&graphs, &o2_head), 1);
2673
2674        // After the delete the s1/g2 copy is invisible in every mode.
2675        assert_eq!(head_count(&runs(9, DomainCountMode::Rows), &o_head), 2);
2676        assert_eq!(
2677            head_count(&runs(9, DomainCountMode::DistinctTerms), &o_head),
2678            2
2679        );
2680        assert_eq!(
2681            head_count(&runs(9, DomainCountMode::DistinctGraphs), &o_head),
2682            1
2683        );
2684        assert_eq!(
2685            head_count(&runs(9, DomainCountMode::DistinctGraphs), &o2_head),
2686            1
2687        );
2688    }
2689
2690    /// DistinctGraphs respects the graph window per row: only graphs with a
2691    /// visible `Put` inside the window contribute.
2692    #[test]
2693    fn domain_counts_distinct_graphs_respects_graph_window() {
2694        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
2695        let mut store = MemoryStorage::new(PartitionAxis::P);
2696        put_named(&mut store, &named_spo("s", "o", "g1"), 1, StorageOp::Put);
2697        put_named(&mut store, &named_spo("s", "o", "g2"), 2, StorageOp::Put);
2698        put_named(&mut store, &named_spo("s", "o", "g3"), 3, StorageOp::Put);
2699        let o_head = encode_quad(&named_spo("s", "o", "g1")).unwrap().object;
2700        let g1 = encode_quad(&named_spo("s", "o", "g1")).unwrap().graph_name;
2701        let g3 = encode_quad(&named_spo("s", "o", "g3")).unwrap().graph_name;
2702
2703        let all = scan_posg_runs(
2704            &store,
2705            &p,
2706            9,
2707            &[],
2708            false,
2709            false,
2710            DomainCountMode::DistinctGraphs,
2711        );
2712        assert_eq!(head_count(&all, &o_head), 3);
2713        let allowed = scan_posg_runs(
2714            &store,
2715            &p,
2716            9,
2717            std::slice::from_ref(&g1),
2718            true,
2719            false,
2720            DomainCountMode::DistinctGraphs,
2721        );
2722        assert_eq!(head_count(&allowed, &o_head), 1);
2723        // Block-list excluding g3.
2724        let blocked = scan_posg_runs(
2725            &store,
2726            &p,
2727            9,
2728            std::slice::from_ref(&g3),
2729            false,
2730            false,
2731            DomainCountMode::DistinctGraphs,
2732        );
2733        assert_eq!(head_count(&blocked, &o_head), 2);
2734    }
2735
2736    /// Under `merge_default_graph` the walk seeks past extra G per triple, so
2737    /// Rows already counts distinct slot-2 terms — the two modes coincide.
2738    #[test]
2739    fn domain_counts_merge_makes_rows_equal_distinct_terms() {
2740        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
2741        let mut store = MemoryStorage::new(PartitionAxis::P);
2742        put_named(&mut store, &named_spo("s1", "o", "g1"), 1, StorageOp::Put);
2743        put_named(&mut store, &named_spo("s1", "o", "g2"), 2, StorageOp::Put);
2744        put_named(&mut store, &named_spo("s2", "o", "g1"), 3, StorageOp::Put);
2745        let o_head = encode_quad(&named_spo("s1", "o", "g1")).unwrap().object;
2746        assert_eq!(
2747            head_count(
2748                &scan_posg_runs(&store, &p, 9, &[], false, true, DomainCountMode::Rows),
2749                &o_head
2750            ),
2751            2
2752        );
2753        assert_eq!(
2754            head_count(
2755                &scan_posg_runs(
2756                    &store,
2757                    &p,
2758                    9,
2759                    &[],
2760                    false,
2761                    false,
2762                    DomainCountMode::DistinctTerms
2763                ),
2764                &o_head
2765            ),
2766            2
2767        );
2768    }
2769
2770    /// A run filled mid-page is re-walked on the next page and emitted with
2771    /// its full distinct count.
2772    #[test]
2773    fn domain_counts_distinct_terms_cursor_resumes_at_run_boundaries() {
2774        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
2775        let mut store = MemoryStorage::new(PartitionAxis::P);
2776        put_named(&mut store, &named_spo("s1", "o", "g1"), 1, StorageOp::Put);
2777        put_named(&mut store, &named_spo("s2", "o", "g1"), 2, StorageOp::Put);
2778        put_named(&mut store, &named_spo("s3", "o2", "g1"), 3, StorageOp::Put);
2779        let o_head = encode_quad(&named_spo("s1", "o", "g1")).unwrap().object;
2780        let o2_head = encode_quad(&named_spo("s3", "o2", "g1")).unwrap().object;
2781
2782        let page1 = store
2783            .scan_domain_counts(
2784                IndexPermutation::Posg,
2785                std::slice::from_ref(&p),
2786                SnapshotId(9),
2787                1,
2788                None,
2789                None,
2790                None,
2791                &[],
2792                false,
2793                false,
2794                false,
2795                DomainCountMode::DistinctTerms,
2796            )
2797            .unwrap();
2798        assert_eq!(page1.len(), 1);
2799
2800        let page2 = store
2801            .scan_domain_counts(
2802                IndexPermutation::Posg,
2803                std::slice::from_ref(&p),
2804                SnapshotId(9),
2805                0,
2806                Some(&page1[0].constraint),
2807                Some(&page1[0].term),
2808                None,
2809                &[],
2810                false,
2811                false,
2812                false,
2813                DomainCountMode::DistinctTerms,
2814            )
2815            .unwrap();
2816        assert_eq!(page2.len(), 1);
2817        assert_ne!(page1[0].term, page2[0].term);
2818        // Head order follows encoded bytes, not the IRI text.
2819        let (first, second) = if page1[0].term == o_head {
2820            (&page1[0], &page2[0])
2821        } else {
2822            (&page2[0], &page1[0])
2823        };
2824        assert_eq!(first.term, o_head);
2825        assert_eq!(first.count, 2);
2826        assert_eq!(second.term, o2_head);
2827        assert_eq!(second.count, 1);
2828    }
2829
2830    fn put_type_quad(
2831        store: &mut MemoryStorage,
2832        s: &str,
2833        cls: &str,
2834        g: &str,
2835        ts: u64,
2836        op: StorageOp,
2837    ) {
2838        let quad = crate::Quad::new(
2839            NamedNode::new(format!("http://ex/{s}")).unwrap(),
2840            NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap(),
2841            NamedNode::new(format!("http://ex/{cls}")).unwrap(),
2842            crate::GraphName::NamedNode(NamedNode::new(format!("http://ex/{g}")).unwrap()),
2843        );
2844        store
2845            .insert_quad_version(&quad, CommitTs(ts), op, VisibilityLabel::default())
2846            .unwrap();
2847    }
2848
2849    fn type_graph(_store: &MemoryStorage) -> EncodedTerm {
2850        encode_quad(&crate::Quad::new(
2851            NamedNode::new("http://ex/s1").unwrap(),
2852            NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap(),
2853            NamedNode::new("http://ex/cls1").unwrap(),
2854            crate::GraphName::NamedNode(NamedNode::new("http://ex/g1").unwrap()),
2855        ))
2856        .unwrap()
2857        .graph_name
2858    }
2859
2860    /// Axis head counts: TOTAL counts distinct heads; PER_HEAD counts
2861    /// distinct slot-1 (subject) terms per head, MVCC- and window-aware.
2862    #[test]
2863    fn axis_head_counts_total_and_per_head() {
2864        let mut store = MemoryStorage::new(PartitionAxis::O);
2865        // cls1: s1 in g1+g2 (g2 deleted at ts=5), s2 in g1; cls2: s3 in g1.
2866        put_type_quad(&mut store, "s1", "cls1", "g1", 1, StorageOp::Put);
2867        put_type_quad(&mut store, "s1", "cls1", "g2", 2, StorageOp::Put);
2868        put_type_quad(&mut store, "s2", "cls1", "g1", 3, StorageOp::Put);
2869        put_type_quad(&mut store, "s3", "cls2", "g1", 4, StorageOp::Put);
2870        put_type_quad(&mut store, "s1", "cls1", "g2", 5, StorageOp::Delete);
2871
2872        let total = store
2873            .count_axis_heads(
2874                IndexPermutation::Tsg,
2875                SnapshotId(9),
2876                None,
2877                &[],
2878                false,
2879                false,
2880            )
2881            .unwrap();
2882        assert_eq!(total, 2, "two distinct classes");
2883
2884        let hits = store
2885            .scan_axis_head_counts(
2886                IndexPermutation::Tsg,
2887                SnapshotId(9),
2888                0,
2889                None,
2890                None,
2891                &[],
2892                false,
2893                false,
2894            )
2895            .unwrap();
2896        assert_eq!(hits.len(), 2);
2897        let counts: Vec<u64> = hits.iter().map(|h| h.count).collect();
2898        assert!(
2899            counts.contains(&2),
2900            "cls1 has two distinct subjects: {hits:?}"
2901        );
2902        assert!(counts.contains(&1), "cls2 has one subject: {hits:?}");
2903
2904        // Window restricted to g2: the surviving rows are gone.
2905        let g2 = encode_quad(&crate::Quad::new(
2906            NamedNode::new("http://ex/s1").unwrap(),
2907            NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap(),
2908            NamedNode::new("http://ex/cls1").unwrap(),
2909            crate::GraphName::NamedNode(NamedNode::new("http://ex/g2").unwrap()),
2910        ))
2911        .unwrap()
2912        .graph_name;
2913        let total_g2 = store
2914            .count_axis_heads(
2915                IndexPermutation::Tsg,
2916                SnapshotId(9),
2917                None,
2918                std::slice::from_ref(&g2),
2919                true,
2920                false,
2921            )
2922            .unwrap();
2923        assert_eq!(total_g2, 0, "the g2 copy was deleted");
2924        let at4 = store
2925            .count_axis_heads(
2926                IndexPermutation::Tsg,
2927                SnapshotId(4),
2928                None,
2929                std::slice::from_ref(&g2),
2930                true,
2931                false,
2932            )
2933            .unwrap();
2934        assert_eq!(at4, 1, "one class visible in g2 before the delete");
2935
2936        // Paging: limit 1 emits the first head's run complete; the cursor
2937        // resumes at the next head.
2938        let page1 = store
2939            .scan_axis_head_counts(
2940                IndexPermutation::Tsg,
2941                SnapshotId(9),
2942                1,
2943                None,
2944                None,
2945                &[],
2946                false,
2947                false,
2948            )
2949            .unwrap();
2950        assert_eq!(page1.len(), 1);
2951        let page2 = store
2952            .scan_axis_head_counts(
2953                IndexPermutation::Tsg,
2954                SnapshotId(9),
2955                0,
2956                Some(&page1[0].term),
2957                None,
2958                &[],
2959                false,
2960                false,
2961            )
2962            .unwrap();
2963        assert_eq!(page2.len(), 1);
2964        assert_ne!(page1[0].term, page2[0].term);
2965        let _ = type_graph(&store);
2966    }
2967
2968    /// The rebuild epoch round-trips on O and is rejected on axes without
2969    /// the metadata map.
2970    #[test]
2971    fn geo_index_epoch_round_trips_on_o_only() {
2972        let mut store = MemoryStorage::new(PartitionAxis::O);
2973        assert_eq!(store.geo_index_epoch().unwrap(), None);
2974        store.set_geo_index_epoch(7).unwrap();
2975        assert_eq!(store.geo_index_epoch().unwrap(), Some(7));
2976
2977        let mut subject_axis = MemoryStorage::new(PartitionAxis::S);
2978        assert_eq!(subject_axis.geo_index_epoch().unwrap(), None);
2979        assert!(matches!(
2980            subject_axis.set_geo_index_epoch(1),
2981            Err(crate::StorageError::GeoIndexNotOnAxis(_))
2982        ));
2983    }
2984
2985    fn temporal_event_quad(subject: &str, when: &str) -> Quad {
2986        Quad::new(
2987            NamedNode::new(format!("http://ex/{subject}")).unwrap(),
2988            NamedNode::new("http://ex/observedAt").unwrap(),
2989            Literal::new_typed_literal(
2990                when,
2991                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#dateTime"),
2992            ),
2993            crate::GraphName::DefaultGraph,
2994        )
2995    }
2996
2997    /// Per-quad liveness (shared-literal delete bug): one temporal literal
2998    /// referenced by two quads stays collectable while ANY referencing
2999    /// quad's own-latest version is a Put; the epoch covers either op.
3000    /// Twin of the RocksDB case.
3001    #[test]
3002    fn temporal_rebuild_terms_liveness_is_per_quad() {
3003        let mut store = MemoryStorage::new(PartitionAxis::O);
3004        let a = encode_quad(&temporal_event_quad("a", "2020-01-01T00:00:00Z")).unwrap();
3005        let b = encode_quad(&temporal_event_quad("b", "2020-01-01T00:00:00Z")).unwrap();
3006        let term = a.object.clone();
3007
3008        // Both quads live: the term is collected once, epoch = ts 2.
3009        store
3010            .insert_encoded_quad_version(
3011                &a,
3012                CommitTs(1),
3013                StorageOp::Put,
3014                VisibilityLabel::default(),
3015            )
3016            .unwrap();
3017        store
3018            .insert_encoded_quad_version(
3019                &b,
3020                CommitTs(2),
3021                StorageOp::Put,
3022                VisibilityLabel::default(),
3023            )
3024            .unwrap();
3025        let (terms, epoch) = store.temporal_rebuild_terms().unwrap();
3026        assert_eq!(terms, vec![term.clone()]);
3027        assert_eq!(epoch, CommitTs(2));
3028
3029        // Delete ONE quad: the term must survive (the old per-term max-ts
3030        // verdict retracted it — the shared-literal delete bug).
3031        store
3032            .insert_encoded_quad_version(
3033                &b,
3034                CommitTs(3),
3035                StorageOp::Delete,
3036                VisibilityLabel::default(),
3037            )
3038            .unwrap();
3039        let (terms, epoch) = store.temporal_rebuild_terms().unwrap();
3040        assert_eq!(terms, vec![term.clone()]);
3041        assert_eq!(epoch, CommitTs(3));
3042
3043        // Delete the second quad too: now dead.
3044        store
3045            .insert_encoded_quad_version(
3046                &a,
3047                CommitTs(4),
3048                StorageOp::Delete,
3049                VisibilityLabel::default(),
3050            )
3051            .unwrap();
3052        let (terms, epoch) = store.temporal_rebuild_terms().unwrap();
3053        assert!(terms.is_empty());
3054        assert_eq!(epoch, CommitTs(4));
3055
3056        // Reinsert one quad: alive again.
3057        store
3058            .insert_encoded_quad_version(
3059                &b,
3060                CommitTs(5),
3061                StorageOp::Put,
3062                VisibilityLabel::default(),
3063            )
3064            .unwrap();
3065        let (terms, epoch) = store.temporal_rebuild_terms().unwrap();
3066        assert_eq!(terms, vec![term.clone()]);
3067        assert_eq!(epoch, CommitTs(5));
3068    }
3069
3070    /// Memory-backend twin: the origin version gates the trust decision, so a
3071    /// store stamped under a DIFFERENT axis origin (B56 moved the calendar
3072    /// families 306 days onto the stored `dateTime` origin) reads UNTRUSTED
3073    /// rather than trusting postings keyed where no query looks.
3074    #[test]
3075    fn temporal_origin_version_gates_the_epoch_trust_decision() {
3076        let mut store = MemoryStorage::new(PartitionAxis::O);
3077        assert_eq!(store.temporal_index_epoch().unwrap(), None, "fresh store");
3078
3079        // A stamp under the current origin is trusted.
3080        store.set_temporal_index_epoch(42).unwrap();
3081        assert_eq!(
3082            store.temporal_index_epoch().unwrap(),
3083            Some(42),
3084            "stamped under the current origin"
3085        );
3086
3087        // Simulate a pre-B56 store: its epoch key survives but was stamped
3088        // under a different origin version.
3089        let map = store
3090            .temporal_meta
3091            .as_mut()
3092            .expect("O axis has the meta map");
3093        map.insert(
3094            TEMPORAL_INDEX_ORIGIN_KEY.to_vec(),
3095            encode_temporal_origin(0),
3096        );
3097        assert_eq!(
3098            store.temporal_index_epoch().unwrap(),
3099            None,
3100            "an epoch stamped under a different origin must read untrusted"
3101        );
3102
3103        // Re-stamping (what a rebuild's finish does) restores trust.
3104        store.set_temporal_index_epoch(43).unwrap();
3105        assert_eq!(
3106            store.temporal_index_epoch().unwrap(),
3107            Some(43),
3108            "re-stamped"
3109        );
3110
3111        // Off the O axis there is no meta map at all, which reads untrusted.
3112        let s = MemoryStorage::new(PartitionAxis::S);
3113        assert_eq!(s.temporal_index_epoch().unwrap(), None);
3114    }
3115
3116    /// Memory-backend twin of the RocksDB liveness test: a wipe clears the
3117    /// marker but not the epoch, so the trust decision flips to untrusted
3118    /// until an epoch is stamped again.
3119    #[test]
3120    fn geo_index_liveness_gates_the_epoch_across_a_wipe() {
3121        let mut store = MemoryStorage::new(PartitionAxis::O);
3122        assert_eq!(store.geo_index_epoch().unwrap(), None, "fresh store");
3123        store.set_geo_index_epoch(42).unwrap();
3124        assert_eq!(store.geo_index_epoch().unwrap(), Some(42), "stamped");
3125        store.wipe_geo_index().unwrap();
3126        assert_eq!(
3127            store.geo_index_epoch().unwrap(),
3128            None,
3129            "a wiped index with a surviving epoch must read untrusted"
3130        );
3131        store.set_geo_index_epoch(43).unwrap();
3132        assert_eq!(store.geo_index_epoch().unwrap(), Some(43), "re-stamped");
3133
3134        // Off the O axis there is no meta map at all, which reads untrusted
3135        // rather than erroring.
3136        let s = MemoryStorage::new(PartitionAxis::S);
3137        assert_eq!(s.geo_index_epoch().unwrap(), None);
3138    }
3139
3140    /// Memory-backend twin of the RocksDB wipe fix: the temporal wipe must
3141    /// clear the trust state with the postings — a stamped epoch over an
3142    /// emptied index reads trusted, so a failed rebuild would answer zero
3143    /// rows from every rewritten temporal FILTER.
3144    #[test]
3145    fn temporal_wipe_untrusts_temporal() {
3146        let mut store = MemoryStorage::new(PartitionAxis::O);
3147        store.set_temporal_index_epoch(9).unwrap();
3148        assert_eq!(store.temporal_index_epoch().unwrap(), Some(9), "stamped");
3149
3150        store.wipe_temporal_index().unwrap();
3151        assert_eq!(
3152            store.temporal_index_epoch().unwrap(),
3153            None,
3154            "a wiped index must read untrusted"
3155        );
3156
3157        store.set_temporal_index_epoch(10).unwrap();
3158        assert_eq!(
3159            store.temporal_index_epoch().unwrap(),
3160            Some(10),
3161            "re-stamped"
3162        );
3163    }
3164}