Skip to main content

waratah_storage/
storage.rs

1//! Top-level [`Storage`] enum dispatching memory vs RocksDB backends.
2
3use std::path::Path;
4use std::sync::RwLock;
5
6use crate::Quad;
7use crate::StrHash;
8use crate::encode::{
9    AxisHeadCountHit, CatalogPut, CatalogRebuildStats, ComparisonMask, DomainCountMode,
10    DomainScanCountHit, DomainScanHit, EncodedQuad, EncodedTerm, EncodedTriplePattern, GByteFilter,
11    GeoCandidateState, GeoCellInterval, GeoEnvelope, GeoIndexPut, HexastorePut, IndexPermutation,
12    IriOnlyMask, KeyRow, QuadSlot, SlotComparison, TemporalCandidateState, TemporalCellInterval,
13    TemporalIndexPut, TemporalQueryPredicate,
14};
15use crate::error::StorageError;
16use crate::memory::MemoryStorage;
17use crate::rocksdb::{RocksDbOptionsHooks, RocksDbStorage};
18use crate::types::{
19    CommitTs, PartitionAxis, ReplacePair, ScanExhaustion, ScanPage, SnapshotId, StorageOp,
20    VisibilityLabel,
21};
22
23/// Environment variable selecting the storage backend at runtime.
24///
25/// - unset / `rocksdb` (default) → RocksDB
26/// - `memory` → in-memory backend (fast tests / local prototyping)
27pub const STORAGE_BACKEND_ENV: &str = "WARATAH_STORAGE_BACKEND";
28
29/// Maximum encoded versions applied in one RocksDB `WriteBatch`.
30///
31/// Coordinators send 8192 quads per RPC; this cap is for a larger direct apply.
32pub const WRITE_BATCH_MAX_QUADS: usize = 16384;
33
34/// Which physical backend to open.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum StorageBackendKind {
37    /// RocksDB hexastore (production default).
38    #[default]
39    RocksDb,
40    /// In-memory hexastore for tests and lightweight local runs.
41    Memory,
42}
43
44impl StorageBackendKind {
45    /// Parse `WARATAH_STORAGE_BACKEND` (`memory` or `rocksdb`; default RocksDB).
46    pub fn from_env() -> Self {
47        match std::env::var(STORAGE_BACKEND_ENV).as_deref() {
48            Ok("memory") | Ok("MEMORY") => Self::Memory,
49            Ok("rocksdb") | Ok("ROCKSDB") | Ok("") | Err(_) => Self::RocksDb,
50            Ok(other) => {
51                eprintln!("warning: unknown {STORAGE_BACKEND_ENV}={other:?}; using RocksDB");
52                Self::RocksDb
53            }
54        }
55    }
56}
57
58/// Single-partition hexastore storage brick.
59///
60/// Both backends are always compiled. RocksDB is the production path; the
61/// in-memory backend is selected explicitly or via [`STORAGE_BACKEND_ENV`].
62#[derive(Debug)]
63pub enum Storage {
64    /// In-memory backend for fast unit tests and local prototyping.
65    ///
66    /// Behind an `RwLock`: unlike RocksDB, the BTreeMaps have no internal
67    /// concurrency, so every [`Storage`] access takes a lock. Scans hold a
68    /// **shared** read guard for the whole walk, so concurrent readers on
69    /// one partition (e.g. a probe stream while a driver walk is parked on
70    /// backpressure) proceed together; writes take the write guard and
71    /// exclude readers for their duration. The walk's guard spans the
72    /// caller's callback: the text subject resolve emits frames from inside
73    /// it and blocks when the consumer is behind, so a slow consumer stalls
74    /// writers to this partition for the length of the stream. RocksDB reads
75    /// a snapshot iterator and takes no such lock; this is a memory-backend
76    /// limitation, accepted for its test/prototyping role (a real fix needs
77    /// a resumable batched walk or a persistent snapshot store). `axis` sits
78    /// outside the lock: it is immutable metadata, not store state.
79    Memory {
80        /// Immutable partition axis (metadata, not store state).
81        axis: PartitionAxis,
82        /// BTreeMap state, guarded because it has no internal concurrency.
83        store: RwLock<MemoryStorage>,
84    },
85    /// RocksDB-backed hexastore.
86    RocksDb(RocksDbStorage),
87}
88
89impl Storage {
90    /// Open an empty in-memory store for `axis`.
91    pub fn memory(axis: PartitionAxis) -> Self {
92        Self::Memory {
93            axis,
94            store: RwLock::new(MemoryStorage::new(axis)),
95        }
96    }
97
98    /// Open a RocksDB store at `path` for `axis`.
99    ///
100    /// Creates the directory and axis-local column families if missing.
101    pub fn open_rocksdb(path: impl AsRef<Path>, axis: PartitionAxis) -> Result<Self, StorageError> {
102        Self::open_rocksdb_with_hooks(path, axis, RocksDbOptionsHooks::default())
103    }
104
105    /// Open RocksDB with optional collector / listener hooks.
106    pub fn open_rocksdb_with_hooks(
107        path: impl AsRef<Path>,
108        axis: PartitionAxis,
109        hooks: RocksDbOptionsHooks<'_>,
110    ) -> Result<Self, StorageError> {
111        Ok(Self::RocksDb(RocksDbStorage::open_with_hooks(
112            path.as_ref(),
113            axis,
114            hooks,
115        )?))
116    }
117
118    /// Open a store using `kind` (RocksDB uses `path`; memory ignores it).
119    pub fn open_with_backend(
120        kind: StorageBackendKind,
121        path: impl AsRef<Path>,
122        axis: PartitionAxis,
123    ) -> Result<Self, StorageError> {
124        match kind {
125            StorageBackendKind::Memory => Ok(Self::memory(axis)),
126            StorageBackendKind::RocksDb => Self::open_rocksdb(path, axis),
127        }
128    }
129
130    /// Open using [`StorageBackendKind::from_env`] (default RocksDB).
131    pub fn open_from_env(
132        path: impl AsRef<Path>,
133        axis: PartitionAxis,
134    ) -> Result<Self, StorageError> {
135        Self::open_with_backend(StorageBackendKind::from_env(), path, axis)
136    }
137
138    /// Backend kind of this instance.
139    pub fn backend_kind(&self) -> StorageBackendKind {
140        match self {
141            Self::Memory { .. } => StorageBackendKind::Memory,
142            Self::RocksDb(_) => StorageBackendKind::RocksDb,
143        }
144    }
145
146    /// Partition axis this store owns.
147    pub fn axis(&self) -> PartitionAxis {
148        match self {
149            Self::Memory { axis, .. } => *axis,
150            Self::RocksDb(store) => store.axis(),
151        }
152    }
153
154    /// Where the text plugin's Tantivy directory belongs, or `None` when the
155    /// backend has no persistent home.
156    ///
157    /// The location follows the storage backend, not the process mode: a
158    /// RocksDB partition keeps the index beside its hexastore directory so a
159    /// delete of the data dir removes both, and the memory backend keeps the
160    /// index in RAM where it vanishes with the store it mirrors.
161    pub fn text_index_dir(&self) -> Option<std::path::PathBuf> {
162        match self {
163            Self::Memory { .. } => None,
164            Self::RocksDb(store) => crate::layout::text_index_dir_beside(store.data_path()),
165        }
166    }
167
168    /// RocksDB LSM counters (`None` on the memory backend).
169    pub fn lsm_metrics(&self) -> Option<crate::LsmMetrics> {
170        match self {
171            Self::Memory { .. } => None,
172            Self::RocksDb(store) => Some(store.lsm_metrics()),
173        }
174    }
175
176    /// Process-wide block cache bytes: `(capacity, charged usage)`.
177    /// `None` on the memory backend.
178    pub fn block_cache_bytes(&self) -> Option<(u64, u64)> {
179        match self {
180            Self::Memory { .. } => None,
181            Self::RocksDb(store) => store.block_cache_bytes(),
182        }
183    }
184
185    /// L0 SST files on the two hexastore column families.
186    ///
187    /// `None` on the memory backend. A flush with auto-compaction off leaves
188    /// files here; a finished full-range compact moves them to a lower level.
189    pub fn hexastore_level0_files(&self) -> Option<u64> {
190        match self {
191            Self::Memory { .. } => None,
192            Self::RocksDb(store) => store.hexastore_level0_files(),
193        }
194    }
195
196    /// Insert a quad as a `Put` at `commit_ts = 0`, `visibility = 0`.
197    pub fn insert_quad(&self, quad: &Quad) -> Result<(), StorageError> {
198        self.insert_quad_version(
199            quad,
200            CommitTs::default(),
201            StorageOp::Put,
202            VisibilityLabel::default(),
203        )
204    }
205
206    /// Insert a versioned hexastore record (`Put` or `Delete`).
207    pub fn insert_quad_version(
208        &self,
209        quad: &Quad,
210        commit_ts: CommitTs,
211        op: StorageOp,
212        visibility: VisibilityLabel,
213    ) -> Result<(), StorageError> {
214        match self {
215            Self::Memory { store, .. } => store
216                .write()
217                .map_err(|_| StorageError::LockPoisoned)?
218                .insert_quad_version(quad, commit_ts, op, visibility),
219            Self::RocksDb(store) => store.insert_quad_version(quad, commit_ts, op, visibility),
220        }
221    }
222
223    /// Insert an already-encoded quad version.
224    ///
225    /// This is the partition-service write path: compute encodes a quad once
226    /// and fans the encoded form out to S, P, and O, so raw strings never reach
227    /// a hexastore node.
228    pub fn insert_encoded_quad_version(
229        &self,
230        encoded: &EncodedQuad,
231        commit_ts: CommitTs,
232        op: StorageOp,
233        visibility: VisibilityLabel,
234    ) -> Result<(), StorageError> {
235        match self {
236            Self::Memory { store, .. } => {
237                let mut store = store.write().map_err(|_| StorageError::LockPoisoned)?;
238                store.insert_encoded_quad_version(encoded, commit_ts, op, visibility)
239            }
240            Self::RocksDb(store) => {
241                store.insert_encoded_quad_version(encoded, commit_ts, op, visibility)
242            }
243        }
244    }
245
246    /// Apply pre-encoded axis-local index puts.
247    ///
248    /// RocksDB commits them in one `WriteBatch`. Memory inserts into the
249    /// BTreeMaps. Empty `puts` is a no-op. Does not update the named-graph catalog.
250    pub fn apply_prepared_puts(&self, puts: &[HexastorePut]) -> Result<(), StorageError> {
251        match self {
252            Self::Memory { store, .. } => store
253                .write()
254                .map_err(|_| StorageError::LockPoisoned)?
255                .apply_prepared_puts(puts),
256            Self::RocksDb(store) => store.apply_prepared_puts(puts),
257        }
258    }
259
260    /// Apply hexastore index puts and named-graph catalog puts together.
261    ///
262    /// Catalog puts require the S axis. Empty `puts` and empty `catalog` is a no-op.
263    pub fn apply_prepared_puts_with_catalog(
264        &self,
265        puts: &[HexastorePut],
266        catalog: &[CatalogPut],
267    ) -> Result<(), StorageError> {
268        match self {
269            Self::Memory { store, .. } => store
270                .write()
271                .map_err(|_| StorageError::LockPoisoned)?
272                .apply_prepared_puts_with_catalog(puts, catalog),
273            Self::RocksDb(store) => store.apply_prepared_puts_with_catalog(puts, catalog),
274        }
275    }
276
277    /// Prefix-seek the S-axis catalog and stage `Present` when missing or Dropped.
278    pub fn catalog_puts_for_insert(
279        &self,
280        graphs: &[(EncodedTerm, CommitTs)],
281    ) -> Result<Vec<CatalogPut>, StorageError> {
282        match self {
283            Self::Memory { store, .. } => store
284                .write()
285                .map_err(|_| StorageError::LockPoisoned)?
286                .catalog_puts_for_insert(graphs),
287            Self::RocksDb(store) => store.catalog_puts_for_insert(graphs),
288        }
289    }
290
291    /// Insert an empty named graph (or recreate after Dropped) at `commit_ts`.
292    ///
293    /// S-axis only. No-op if the newest catalog version is already `Present`.
294    pub fn add_named_graph(
295        &self,
296        graph: &EncodedTerm,
297        commit_ts: CommitTs,
298    ) -> Result<(), StorageError> {
299        match self {
300            Self::Memory { store, .. } => store
301                .write()
302                .map_err(|_| StorageError::LockPoisoned)?
303                .add_named_graph(graph, commit_ts),
304            Self::RocksDb(store) => store.add_named_graph(graph, commit_ts),
305        }
306    }
307
308    /// Named graphs whose newest in-snapshot catalog version is `Present`.
309    ///
310    /// Includes empty graphs. Never includes the RDF default graph. S-axis only.
311    pub fn list_named_graphs(
312        &self,
313        snapshot: SnapshotId,
314    ) -> Result<Vec<EncodedTerm>, StorageError> {
315        match self {
316            Self::Memory { store, .. } => store
317                .read()
318                .map_err(|_| StorageError::LockPoisoned)?
319                .list_named_graphs(snapshot),
320            Self::RocksDb(store) => store.list_named_graphs(snapshot),
321        }
322    }
323
324    /// Rebuild `named_graphs_catalog` from all SPOG versions (S axis only).
325    pub fn rebuild_named_graph_catalog(&self) -> Result<CatalogRebuildStats, StorageError> {
326        match self {
327            Self::Memory { store, .. } => store
328                .write()
329                .map_err(|_| StorageError::LockPoisoned)?
330                .rebuild_named_graph_catalog(),
331            Self::RocksDb(store) => store.rebuild_named_graph_catalog(),
332        }
333    }
334
335    /// Walk every versioned key in an axis-local index (no MVCC collapse).
336    pub fn visit_index_versions(
337        &self,
338        permutation: IndexPermutation,
339        visit: impl FnMut(&EncodedQuad, CommitTs, StorageOp) -> Result<(), StorageError>,
340    ) -> Result<(), StorageError> {
341        match self {
342            Self::Memory { store, .. } => store
343                .read()
344                .map_err(|_| StorageError::LockPoisoned)?
345                .visit_index_versions(permutation, visit),
346            Self::RocksDb(store) => store.visit_index_versions(permutation, visit),
347        }
348    }
349
350    // ---------------------------------------------------------------------
351    // Scan/count family. Naming grammar for everything below and for the
352    // per-backend twins in `rocksdb.rs` / `memory.rs`:
353    //
354    //   [scan|count]_pattern[_page][_filtered][_allow_list]
355    //
356    // - `scan_` returns `Vec<EncodedQuad>`; `count_` returns `u64`;
357    //   `visit_*` streams raw [`KeyRow`] key slices to a callback
358    //   (crate-internal plumbing — the only places that touch an iterator).
359    // - `_filtered` (plain family only) → the caller supplies a
360    //   [`GByteFilter`] window and a `merge_default_graph` flag, both
361    //   enforced inside the RowMatcher on raw key bytes; `limit` counts
362    //   post-filter, post-collapse matches.
363    // - `_allow_list` → broadcast shape: `slot` + `terms` are seeked as
364    //   sorted tight prefixes. Without it the walk is a single contiguous
365    //   prefix. Allow-list scans always take the window and flag directly —
366    //   there is no unfiltered twin.
367    // - `scan_pattern` / `scan_pattern_in` / `scan_pattern_page` conveniences
368    //   encode their knobs in the signature: `_in` takes an explicit
369    //   [`IndexPermutation`] instead of `best_permutation`; `_page` adds
370    //   `limit` + the exclusive `start_after` cursor.
371    //
372    // Every concrete method has exactly one implementation: the
373    // `scan_pattern_page` delegates to a raw `visit_*` walk. Counts never
374    // decode terms; scans decode only emitted rows.
375    // ---------------------------------------------------------------------
376
377    /// Apply geometry-index postings (O axis only; apply-only, verbatim).
378    pub fn apply_geo_puts(&self, puts: &[GeoIndexPut]) -> Result<(), StorageError> {
379        match self {
380            Self::Memory { store, .. } => store
381                .write()
382                .map_err(|_| StorageError::LockPoisoned)?
383                .apply_geo_puts(puts),
384            Self::RocksDb(store) => store.apply_geo_puts(puts),
385        }
386    }
387
388    /// Delete every posting of one encoded geo term (O axis; rebuild).
389    pub fn delete_geo_term(&self, term: &[u8]) -> Result<u64, StorageError> {
390        match self {
391            Self::Memory { store, .. } => store
392                .write()
393                .map_err(|_| StorageError::LockPoisoned)?
394                .delete_geo_term(term),
395            Self::RocksDb(store) => store.delete_geo_term(term),
396        }
397    }
398
399    /// Visit every geometry-index posting, decoded, in key order (O axis;
400    /// read-only census/debug surface).
401    pub fn visit_geo_postings(
402        &self,
403        on_posting: &mut dyn FnMut(&GeoIndexPut) -> Result<(), StorageError>,
404    ) -> Result<(), StorageError> {
405        match self {
406            Self::Memory { store, .. } => store
407                .read()
408                .map_err(|_| StorageError::LockPoisoned)?
409                .visit_geo_postings(on_posting),
410            Self::RocksDb(store) => store.visit_geo_postings(on_posting),
411        }
412    }
413
414    /// Rebuild epoch of the O-axis geometry index.
415    ///
416    /// `Ok(None)` on S/P and when no epoch was ever stamped; every consumer
417    /// treats a missing epoch as "index trusted from store creation".
418    pub fn geo_index_epoch(&self) -> Result<Option<u64>, StorageError> {
419        match self {
420            Self::Memory { store, .. } => store
421                .read()
422                .map_err(|_| StorageError::LockPoisoned)?
423                .geo_index_epoch(),
424            Self::RocksDb(store) => store.geo_index_epoch(),
425        }
426    }
427
428    /// Stamp the rebuild epoch of the O-axis geometry index.
429    ///
430    /// Errors with [`StorageError::GeoIndexNotOnAxis`] on S/P.
431    pub fn set_geo_index_epoch(&self, epoch: u64) -> Result<(), StorageError> {
432        match self {
433            Self::Memory { store, .. } => store
434                .write()
435                .map_err(|_| StorageError::LockPoisoned)?
436                .set_geo_index_epoch(epoch),
437            Self::RocksDb(store) => store.set_geo_index_epoch(epoch),
438        }
439    }
440
441    /// Raw stored geo epoch number, ignoring the liveness marker (`0` when
442    /// absent, `0` on S/P). Survives a wipe, so the rebuild finish can floor
443    /// the new epoch at the previously stamped one.
444    pub fn geo_index_epoch_number(&self) -> Result<u64, StorageError> {
445        match self {
446            Self::Memory { store, .. } => store
447                .read()
448                .map_err(|_| StorageError::LockPoisoned)?
449                .geo_index_epoch_number(),
450            Self::RocksDb(store) => store.geo_index_epoch_number(),
451        }
452    }
453
454    /// Max commit_ts among the versioned keys whose slot-0 head term falls
455    /// under `head_prefixes` (geo upgrade stage 1: the swap-timestamp bound,
456    /// derived from the walked data itself).
457    pub fn max_commit_ts_under_prefixes(
458        &self,
459        permutation: IndexPermutation,
460        head_prefixes: &[Vec<u8>],
461    ) -> Result<u64, StorageError> {
462        match self {
463            Self::Memory { store, .. } => store
464                .read()
465                .map_err(|_| StorageError::LockPoisoned)?
466                .max_commit_ts_under_prefixes(permutation, head_prefixes),
467            Self::RocksDb(store) => store.max_commit_ts_under_prefixes(permutation, head_prefixes),
468        }
469    }
470
471    /// Apply replace pairs as ONE batch on this axis (see the backend
472    /// docs; served by every axis partition).
473    pub fn apply_replace_pairs(
474        &self,
475        pairs: &[ReplacePair],
476        commit_ts: CommitTs,
477    ) -> Result<u64, StorageError> {
478        match self {
479            Self::Memory { store, .. } => store
480                .write()
481                .map_err(|_| StorageError::LockPoisoned)?
482                .apply_replace_pairs(pairs, commit_ts),
483            Self::RocksDb(store) => store.apply_replace_pairs(pairs, commit_ts),
484        }
485    }
486
487    /// Wipe every geo-index posting (O axis; rebuild preamble). ONE scan,
488    /// ONE atomic batch — the posting deletes and the LIVENESS-marker drop
489    /// commit together, so an interrupted rebuild after this point reads
490    /// UNTRUSTED instead of trusted-with-a-partial-index. Returns the
491    /// number of posting rows deleted.
492    pub fn wipe_geo_index(&self) -> Result<u64, StorageError> {
493        match self {
494            Self::Memory { store, .. } => store
495                .write()
496                .map_err(|_| StorageError::LockPoisoned)?
497                .wipe_geo_index(),
498            Self::RocksDb(store) => store.wipe_geo_index(),
499        }
500    }
501
502    /// Apply temporal-index postings (O axis only; apply-only, verbatim).
503    pub fn apply_temporal_puts(&self, puts: &[TemporalIndexPut]) -> Result<(), StorageError> {
504        match self {
505            Self::Memory { store, .. } => store
506                .write()
507                .map_err(|_| StorageError::LockPoisoned)?
508                .apply_temporal_puts(puts),
509            Self::RocksDb(store) => store.apply_temporal_puts(puts),
510        }
511    }
512
513    /// Rebuild epoch of the O-axis temporal index (`None` = untrusted).
514    pub fn temporal_index_epoch(&self) -> Result<Option<u64>, StorageError> {
515        match self {
516            Self::Memory { store, .. } => store
517                .read()
518                .map_err(|_| StorageError::LockPoisoned)?
519                .temporal_index_epoch(),
520            Self::RocksDb(store) => store.temporal_index_epoch(),
521        }
522    }
523
524    /// Stamp the rebuild epoch of the O-axis temporal index.
525    ///
526    /// Errors with [`StorageError::TemporalIndexNotOnAxis`] on S/P.
527    pub fn set_temporal_index_epoch(&self, epoch: u64) -> Result<(), StorageError> {
528        match self {
529            Self::Memory { store, .. } => store
530                .write()
531                .map_err(|_| StorageError::LockPoisoned)?
532                .set_temporal_index_epoch(epoch),
533            Self::RocksDb(store) => store.set_temporal_index_epoch(epoch),
534        }
535    }
536
537    /// Wipe every temporal-index posting (O axis; rebuild preamble).
538    pub fn wipe_temporal_index(&self) -> Result<(), StorageError> {
539        match self {
540            Self::Memory { store, .. } => store
541                .write()
542                .map_err(|_| StorageError::LockPoisoned)?
543                .wipe_temporal_index(),
544            Self::RocksDb(store) => store.wipe_temporal_index(),
545        }
546    }
547
548    /// Collect the O-axis temporal terms for the rebuild walk (see the
549    /// backend docs for the per-quad liveness contract).
550    pub fn temporal_rebuild_terms(&self) -> Result<(Vec<EncodedTerm>, CommitTs), StorageError> {
551        match self {
552            Self::Memory { store, .. } => store
553                .read()
554                .map_err(|_| StorageError::LockPoisoned)?
555                .temporal_rebuild_terms(),
556            Self::RocksDb(store) => store.temporal_rebuild_terms(),
557        }
558    }
559
560    /// Skip-seek candidate scan over merged node-key intervals (O axis).
561    #[allow(clippy::too_many_arguments)]
562    pub fn temporal_scan_candidates(
563        &self,
564        intervals: &[TemporalCellInterval],
565        snapshot: SnapshotId,
566        predicate: &TemporalQueryPredicate,
567        limit: u64,
568        state: &mut TemporalCandidateState,
569        emit: impl FnMut(&EncodedTerm) -> Result<bool, StorageError>,
570    ) -> Result<(), StorageError> {
571        match self {
572            Self::Memory { store, .. } => store
573                .read()
574                .map_err(|_| StorageError::LockPoisoned)?
575                .temporal_scan_candidates(intervals, snapshot, predicate, limit, state, emit),
576            Self::RocksDb(store) => {
577                store.temporal_scan_candidates(intervals, snapshot, predicate, limit, state, emit)
578            }
579        }
580    }
581
582    /// Skip-seek candidate scan over merged cell-id intervals (O axis).
583    pub fn geo_scan_candidates(
584        &self,
585        intervals: &[GeoCellInterval],
586        snapshot: SnapshotId,
587        query_envelope: Option<&GeoEnvelope>,
588        limit: u64,
589        state: &mut GeoCandidateState,
590        emit: impl FnMut(&EncodedTerm) -> Result<bool, StorageError>,
591    ) -> Result<(), StorageError> {
592        match self {
593            Self::Memory { store, .. } => store
594                .read()
595                .map_err(|_| StorageError::LockPoisoned)?
596                .geo_scan_candidates(intervals, snapshot, query_envelope, limit, state, emit),
597            Self::RocksDb(store) => {
598                store.geo_scan_candidates(intervals, snapshot, query_envelope, limit, state, emit)
599            }
600        }
601    }
602
603    /// Prefix/range scan returning encoded quads visible at `snapshot`.
604    ///
605    /// Newest version with `commit_ts <= snapshot` and `op == Put` wins per
606    /// logical quad. Visibility labels are not enforced yet.
607    pub fn scan_pattern(
608        &self,
609        pattern: &EncodedTriplePattern,
610        snapshot: SnapshotId,
611    ) -> Result<Vec<EncodedQuad>, StorageError> {
612        match self {
613            Self::Memory { store, .. } => store
614                .read()
615                .map_err(|_| StorageError::LockPoisoned)?
616                .scan_pattern(pattern, snapshot),
617            Self::RocksDb(store) => store.scan_pattern(pattern, snapshot),
618        }
619    }
620
621    /// Scan through an explicitly chosen axis-local index.
622    ///
623    /// Returns [`StorageError::PermutationNotOwned`] when `permutation` belongs
624    /// to another partition axis, so a partition service can reject a
625    /// mis-routed request instead of panicking.
626    pub fn scan_pattern_in(
627        &self,
628        permutation: IndexPermutation,
629        pattern: &EncodedTriplePattern,
630        snapshot: SnapshotId,
631    ) -> Result<Vec<EncodedQuad>, StorageError> {
632        // Unlimited drain: the page's verdict is ExhaustedScan by
633        // construction and carries no information for this caller.
634        self.scan_pattern_page(
635            permutation,
636            pattern,
637            snapshot,
638            0,
639            None,
640            GByteFilter::Unconstrained,
641            false,
642            IriOnlyMask::NONE,
643        )
644        .map(|page| page.rows)
645    }
646
647    /// [`Self::scan_pattern`] with slot comparisons on the best
648    /// permutation for `pattern`.
649    pub fn scan_pattern_with_comparisons(
650        &self,
651        pattern: &EncodedTriplePattern,
652        snapshot: SnapshotId,
653        comparisons: &[SlotComparison],
654    ) -> Result<Vec<EncodedQuad>, StorageError> {
655        let permutation = pattern.best_permutation(self.axis());
656        self.scan_pattern_in_with_comparisons(permutation, pattern, snapshot, comparisons)
657    }
658
659    /// [`Self::scan_pattern_in`] with slot comparisons.
660    pub fn scan_pattern_in_with_comparisons(
661        &self,
662        permutation: IndexPermutation,
663        pattern: &EncodedTriplePattern,
664        snapshot: SnapshotId,
665        comparisons: &[SlotComparison],
666    ) -> Result<Vec<EncodedQuad>, StorageError> {
667        self.scan_pattern_page_with_comparisons(
668            permutation,
669            pattern,
670            snapshot,
671            0,
672            None,
673            GByteFilter::Unconstrained,
674            false,
675            IriOnlyMask::NONE,
676            comparisons,
677        )
678        .map(|page| page.rows)
679    }
680
681    /// Allow-list prefix scan with the **full matcher semantics** per tight
682    /// prefix: residual `graph_filter` membership and `merge_default_graph`
683    /// collapse (rows return with G rewritten to DefaultGraph) run inside
684    /// each prefix's RowMatcher on raw key bytes. `limit` counts
685    /// post-filter matches (`0` = unlimited). Returns `None` when `slot`
686    /// does not extend `permutation`; otherwise the page plus the walk's
687    /// own [`ScanExhaustion`] verdict.
688    #[allow(clippy::too_many_arguments)]
689    pub fn scan_pattern_page_allow_list(
690        &self,
691        permutation: IndexPermutation,
692        pattern: &EncodedTriplePattern,
693        snapshot: SnapshotId,
694        limit: u64,
695        start_after: Option<&EncodedQuad>,
696        allow_list_slot: QuadSlot,
697        allow_terms: &[EncodedTerm],
698        graph_filter: GByteFilter,
699        merge_default_graph: bool,
700        iri_only: IriOnlyMask,
701    ) -> Result<Option<ScanPage>, StorageError> {
702        match self {
703            Self::Memory { store, .. } => store
704                .read()
705                .map_err(|_| StorageError::LockPoisoned)?
706                .scan_pattern_page_allow_list(
707                    permutation,
708                    pattern,
709                    snapshot,
710                    limit,
711                    start_after,
712                    allow_list_slot,
713                    allow_terms,
714                    graph_filter,
715                    merge_default_graph,
716                    iri_only,
717                ),
718            Self::RocksDb(store) => store.scan_pattern_page_allow_list(
719                permutation,
720                pattern,
721                snapshot,
722                limit,
723                start_after,
724                allow_list_slot,
725                allow_terms,
726                graph_filter,
727                merge_default_graph,
728                iri_only,
729            ),
730        }
731    }
732
733    /// Count an allow-list scan with the **full matcher semantics** per tight
734    /// prefix: residual `graph_filter` membership and `merge_default_graph`
735    /// collapse run inside each prefix's RowMatcher, counting raw [`KeyRow`]s
736    /// without decoding any term. `limit` counts post-filter matches
737    /// (`0` = unlimited). Returns `None` when `slot` does not extend
738    /// `permutation`.
739    #[allow(clippy::too_many_arguments)]
740    pub fn count_pattern_allow_list(
741        &self,
742        permutation: IndexPermutation,
743        pattern: &EncodedTriplePattern,
744        snapshot: SnapshotId,
745        limit: u64,
746        allow_list_slot: QuadSlot,
747        allow_terms: &[EncodedTerm],
748        graph_filter: GByteFilter,
749        merge_default_graph: bool,
750    ) -> Result<Option<u64>, StorageError> {
751        match self {
752            Self::Memory { store, .. } => store
753                .read()
754                .map_err(|_| StorageError::LockPoisoned)?
755                .count_pattern_allow_list(
756                    permutation,
757                    pattern,
758                    snapshot,
759                    limit,
760                    allow_list_slot,
761                    allow_terms,
762                    graph_filter,
763                    merge_default_graph,
764                ),
765            Self::RocksDb(store) => store.count_pattern_allow_list(
766                permutation,
767                pattern,
768                snapshot,
769                limit,
770                allow_list_slot,
771                allow_terms,
772                graph_filter,
773                merge_default_graph,
774            ),
775        }
776    }
777
778    /// Stream every visible matching row of an allow-list scan as raw
779    /// [`KeyRow`] key slices; `on_match` returning `false` stops the walk
780    /// early (the caller owns the stop reason — including any `limit`,
781    /// which counts post-filter, post-collapse matches). Full matcher
782    /// semantics per tight prefix: residual `graph_filter` membership,
783    /// `merge_default_graph` collapse, and `iri_only` pushdown run inside
784    /// each prefix's RowMatcher on raw key bytes. Returns `Ok(None)` when
785    /// `slot` does not extend `permutation` (caller should bind each term
786    /// instead); `Ok(Some(verdict))` otherwise — `Limited` when the
787    /// callback stopped the walk at the limit,
788    /// `ExhaustedFilterTerms` when every term's prefix was served.
789    #[allow(clippy::too_many_arguments)]
790    pub fn visit_allow_list_rows(
791        &self,
792        permutation: IndexPermutation,
793        pattern: &EncodedTriplePattern,
794        snapshot: SnapshotId,
795        start_after: Option<&EncodedQuad>,
796        allow_list_slot: QuadSlot,
797        allow_terms: &[EncodedTerm],
798        graph_filter: GByteFilter,
799        merge_default_graph: bool,
800        iri_only: IriOnlyMask,
801        on_match: impl FnMut(&KeyRow) -> Result<bool, StorageError>,
802    ) -> Result<Option<ScanExhaustion>, StorageError> {
803        self.visit_allow_list_rows_with_comparisons(
804            permutation,
805            pattern,
806            snapshot,
807            start_after,
808            allow_list_slot,
809            allow_terms,
810            graph_filter,
811            merge_default_graph,
812            iri_only,
813            &[],
814            on_match,
815        )
816    }
817
818    /// [`Self::visit_allow_list_rows`] with slot comparisons compiled inside
819    /// this call. An emptied mask returns `ExhaustedScan` without opening an
820    /// iterator.
821    #[allow(clippy::too_many_arguments)]
822    pub fn visit_allow_list_rows_with_comparisons(
823        &self,
824        permutation: IndexPermutation,
825        pattern: &EncodedTriplePattern,
826        snapshot: SnapshotId,
827        start_after: Option<&EncodedQuad>,
828        allow_list_slot: QuadSlot,
829        allow_terms: &[EncodedTerm],
830        graph_filter: GByteFilter,
831        merge_default_graph: bool,
832        iri_only: IriOnlyMask,
833        comparisons: &[SlotComparison],
834        on_match: impl FnMut(&KeyRow) -> Result<bool, StorageError>,
835    ) -> Result<Option<ScanExhaustion>, StorageError> {
836        let mask = ComparisonMask::compile(pattern, permutation, comparisons);
837        if mask.is_empty() {
838            return Ok(Some(ScanExhaustion::ExhaustedScan));
839        }
840        match self {
841            Self::Memory { store, .. } => store
842                .read()
843                .map_err(|_| StorageError::LockPoisoned)?
844                .visit_allow_list_rows(
845                    permutation,
846                    pattern,
847                    snapshot,
848                    start_after,
849                    allow_list_slot,
850                    allow_terms,
851                    graph_filter,
852                    merge_default_graph,
853                    iri_only,
854                    &mask,
855                    on_match,
856                ),
857            Self::RocksDb(store) => store.visit_allow_list_rows(
858                permutation,
859                pattern,
860                snapshot,
861                start_after,
862                allow_list_slot,
863                allow_terms,
864                graph_filter,
865                merge_default_graph,
866                iri_only,
867                &mask,
868                on_match,
869            ),
870        }
871    }
872
873    /// Domain scan: distinct slot-1 head terms under each slot-0 constraint
874    /// on `permutation` (POSG predicates→objects, SPOG subjects→predicates,
875    /// SOPG subjects→objects, OPSG objects→predicates).
876    ///
877    /// Returns [`StorageError::PermutationNotOwned`] when `permutation`
878    /// belongs to another partition axis. `limit` counts emitted pairs
879    /// (`0` = unlimited).
880    #[allow(clippy::too_many_arguments)]
881    pub fn scan_domain(
882        &self,
883        permutation: IndexPermutation,
884        constraints: &[EncodedTerm],
885        snapshot: SnapshotId,
886        limit: u64,
887        start_after_constraint: Option<&EncodedTerm>,
888        start_after_term: Option<&EncodedTerm>,
889        graph_name: Option<&EncodedTerm>,
890        graph_filter_terms: &[EncodedTerm],
891        graph_filter_allow: bool,
892        iri_only_head: bool,
893    ) -> Result<Vec<DomainScanHit>, StorageError> {
894        match self {
895            Self::Memory { store, .. } => store
896                .read()
897                .map_err(|_| StorageError::LockPoisoned)?
898                .scan_domain(
899                    permutation,
900                    constraints,
901                    snapshot,
902                    limit,
903                    start_after_constraint,
904                    start_after_term,
905                    graph_name,
906                    graph_filter_terms,
907                    graph_filter_allow,
908                    iri_only_head,
909                ),
910            Self::RocksDb(store) => store.scan_domain(
911                permutation,
912                constraints,
913                snapshot,
914                limit,
915                start_after_constraint,
916                start_after_term,
917                graph_name,
918                graph_filter_terms,
919                graph_filter_allow,
920                iri_only_head,
921            ),
922        }
923    }
924
925    /// Domain count scan: run lengths of slot-1 head terms under each
926    /// slot-0 constraint on `permutation` (twin of [`Self::scan_domain`]).
927    ///
928    /// Returns [`StorageError::PermutationNotOwned`] when `permutation`
929    /// belongs to another partition axis. `limit` counts emitted triples
930    /// (`0` = unlimited). `mode` selects what one run-count increment
931    /// represents — see [`DomainCountMode`].
932    #[allow(clippy::too_many_arguments)]
933    pub fn scan_domain_counts(
934        &self,
935        permutation: IndexPermutation,
936        constraints: &[EncodedTerm],
937        snapshot: SnapshotId,
938        limit: u64,
939        start_after_constraint: Option<&EncodedTerm>,
940        start_after_term: Option<&EncodedTerm>,
941        graph_name: Option<&EncodedTerm>,
942        graph_filter_terms: &[EncodedTerm],
943        graph_filter_allow: bool,
944        iri_only_head: bool,
945        merge_default_graph: bool,
946        mode: DomainCountMode,
947    ) -> Result<Vec<DomainScanCountHit>, StorageError> {
948        match self {
949            Self::Memory { store, .. } => store
950                .read()
951                .map_err(|_| StorageError::LockPoisoned)?
952                .scan_domain_counts(
953                    permutation,
954                    constraints,
955                    snapshot,
956                    limit,
957                    start_after_constraint,
958                    start_after_term,
959                    graph_name,
960                    graph_filter_terms,
961                    graph_filter_allow,
962                    iri_only_head,
963                    merge_default_graph,
964                    mode,
965                ),
966            Self::RocksDb(store) => store.scan_domain_counts(
967                permutation,
968                constraints,
969                snapshot,
970                limit,
971                start_after_constraint,
972                start_after_term,
973                graph_name,
974                graph_filter_terms,
975                graph_filter_allow,
976                iri_only_head,
977                merge_default_graph,
978                mode,
979            ),
980        }
981    }
982
983    /// Axis head count, `TOTAL` mode: distinct slot-0 head terms of the
984    /// whole CF. Twin of [`Self::scan_axis_head`].
985    #[allow(clippy::too_many_arguments)]
986    pub fn count_axis_heads(
987        &self,
988        permutation: IndexPermutation,
989        snapshot: SnapshotId,
990        graph_name: Option<&EncodedTerm>,
991        graph_filter_terms: &[EncodedTerm],
992        graph_filter_allow: bool,
993        iri_only_head: bool,
994    ) -> Result<u64, StorageError> {
995        match self {
996            Self::Memory { store, .. } => store
997                .read()
998                .map_err(|_| StorageError::LockPoisoned)?
999                .count_axis_heads(
1000                    permutation,
1001                    snapshot,
1002                    graph_name,
1003                    graph_filter_terms,
1004                    graph_filter_allow,
1005                    iri_only_head,
1006                ),
1007            Self::RocksDb(store) => store.count_axis_heads(
1008                permutation,
1009                snapshot,
1010                graph_name,
1011                graph_filter_terms,
1012                graph_filter_allow,
1013                iri_only_head,
1014            ),
1015        }
1016    }
1017
1018    /// Axis head count, `PER_HEAD` mode: per-head distinct slot-1 counts.
1019    #[allow(clippy::too_many_arguments)]
1020    pub fn scan_axis_head_counts(
1021        &self,
1022        permutation: IndexPermutation,
1023        snapshot: SnapshotId,
1024        limit: u64,
1025        start_after_term: Option<&EncodedTerm>,
1026        graph_name: Option<&EncodedTerm>,
1027        graph_filter_terms: &[EncodedTerm],
1028        graph_filter_allow: bool,
1029        iri_only_head: bool,
1030    ) -> Result<Vec<AxisHeadCountHit>, StorageError> {
1031        match self {
1032            Self::Memory { store, .. } => store
1033                .read()
1034                .map_err(|_| StorageError::LockPoisoned)?
1035                .scan_axis_head_counts(
1036                    permutation,
1037                    snapshot,
1038                    limit,
1039                    start_after_term,
1040                    graph_name,
1041                    graph_filter_terms,
1042                    graph_filter_allow,
1043                    iri_only_head,
1044                ),
1045            Self::RocksDb(store) => store.scan_axis_head_counts(
1046                permutation,
1047                snapshot,
1048                limit,
1049                start_after_term,
1050                graph_name,
1051                graph_filter_terms,
1052                graph_filter_allow,
1053                iri_only_head,
1054            ),
1055        }
1056    }
1057
1058    /// Axis head scan: distinct slot-0 head terms of the whole `permutation`
1059    /// CF (SPOG subjects, PSOG predicates, OPSG objects, TSG classes).
1060    ///
1061    /// Returns [`StorageError::PermutationNotOwned`] when `permutation`
1062    /// belongs to another partition axis. `limit` counts emitted terms
1063    /// (`0` = unlimited). With non-empty `head_prefixes` the walk is a
1064    /// seek-union over those partial head-term byte ranges; empty means the
1065    /// unfiltered whole-CF walk.
1066    #[allow(clippy::too_many_arguments)]
1067    pub fn scan_axis_head(
1068        &self,
1069        permutation: IndexPermutation,
1070        snapshot: SnapshotId,
1071        limit: u64,
1072        start_after_term: Option<&EncodedTerm>,
1073        graph_name: Option<&EncodedTerm>,
1074        graph_filter_terms: &[EncodedTerm],
1075        graph_filter_allow: bool,
1076        iri_only_head: bool,
1077        head_prefixes: &[Vec<u8>],
1078    ) -> Result<Vec<EncodedTerm>, StorageError> {
1079        match self {
1080            Self::Memory { store, .. } => store
1081                .read()
1082                .map_err(|_| StorageError::LockPoisoned)?
1083                .scan_axis_head(
1084                    permutation,
1085                    snapshot,
1086                    limit,
1087                    start_after_term,
1088                    graph_name,
1089                    graph_filter_terms,
1090                    graph_filter_allow,
1091                    iri_only_head,
1092                    head_prefixes,
1093                ),
1094            Self::RocksDb(store) => store.scan_axis_head(
1095                permutation,
1096                snapshot,
1097                limit,
1098                start_after_term,
1099                graph_name,
1100                graph_filter_terms,
1101                graph_filter_allow,
1102                iri_only_head,
1103                head_prefixes,
1104            ),
1105        }
1106    }
1107
1108    /// Distinct objects per predicate (POSG skip-scan). P-axis only.
1109    #[allow(clippy::too_many_arguments)]
1110    pub fn scan_predicate_domain(
1111        &self,
1112        predicates: &[EncodedTerm],
1113        snapshot: SnapshotId,
1114        limit: u64,
1115        start_after_predicate: Option<&EncodedTerm>,
1116        start_after_object: Option<&EncodedTerm>,
1117        graph_name: Option<&EncodedTerm>,
1118        graph_filter_terms: &[EncodedTerm],
1119        graph_filter_allow: bool,
1120    ) -> Result<Vec<DomainScanHit>, StorageError> {
1121        self.scan_domain(
1122            IndexPermutation::Posg,
1123            predicates,
1124            snapshot,
1125            limit,
1126            start_after_predicate,
1127            start_after_object,
1128            graph_name,
1129            graph_filter_terms,
1130            graph_filter_allow,
1131            false,
1132        )
1133    }
1134
1135    /// Distinct predicates per subject (SPOG skip-scan). S-axis only.
1136    #[allow(clippy::too_many_arguments)]
1137    pub fn scan_subject_preds(
1138        &self,
1139        subjects: &[EncodedTerm],
1140        snapshot: SnapshotId,
1141        limit: u64,
1142        start_after_subject: Option<&EncodedTerm>,
1143        start_after_predicate: Option<&EncodedTerm>,
1144        graph_name: Option<&EncodedTerm>,
1145        graph_filter_terms: &[EncodedTerm],
1146        graph_filter_allow: bool,
1147    ) -> Result<Vec<DomainScanHit>, StorageError> {
1148        self.scan_domain(
1149            IndexPermutation::Spog,
1150            subjects,
1151            snapshot,
1152            limit,
1153            start_after_subject,
1154            start_after_predicate,
1155            graph_name,
1156            graph_filter_terms,
1157            graph_filter_allow,
1158            false,
1159        )
1160    }
1161
1162    /// Distinct objects per subject (SOPG skip-scan). S-axis only.
1163    #[allow(clippy::too_many_arguments)]
1164    pub fn scan_subject_domain(
1165        &self,
1166        subjects: &[EncodedTerm],
1167        snapshot: SnapshotId,
1168        limit: u64,
1169        start_after_subject: Option<&EncodedTerm>,
1170        start_after_object: Option<&EncodedTerm>,
1171        graph_name: Option<&EncodedTerm>,
1172        graph_filter_terms: &[EncodedTerm],
1173        graph_filter_allow: bool,
1174    ) -> Result<Vec<DomainScanHit>, StorageError> {
1175        self.scan_domain(
1176            IndexPermutation::Sopg,
1177            subjects,
1178            snapshot,
1179            limit,
1180            start_after_subject,
1181            start_after_object,
1182            graph_name,
1183            graph_filter_terms,
1184            graph_filter_allow,
1185            false,
1186        )
1187    }
1188
1189    /// Distinct predicates per object (OPSG skip-scan). O-axis only.
1190    #[allow(clippy::too_many_arguments)]
1191    pub fn scan_object_preds(
1192        &self,
1193        objects: &[EncodedTerm],
1194        snapshot: SnapshotId,
1195        limit: u64,
1196        start_after_object: Option<&EncodedTerm>,
1197        start_after_predicate: Option<&EncodedTerm>,
1198        graph_name: Option<&EncodedTerm>,
1199        graph_filter_terms: &[EncodedTerm],
1200        graph_filter_allow: bool,
1201    ) -> Result<Vec<DomainScanHit>, StorageError> {
1202        self.scan_domain(
1203            IndexPermutation::Opsg,
1204            objects,
1205            snapshot,
1206            limit,
1207            start_after_object,
1208            start_after_predicate,
1209            graph_name,
1210            graph_filter_terms,
1211            graph_filter_allow,
1212            false,
1213        )
1214    }
1215
1216    /// Distinct subjects of the whole SPOG index. S-axis only.
1217    #[allow(clippy::too_many_arguments)]
1218    pub fn scan_subjects(
1219        &self,
1220        snapshot: SnapshotId,
1221        limit: u64,
1222        start_after_term: Option<&EncodedTerm>,
1223        graph_name: Option<&EncodedTerm>,
1224        graph_filter_terms: &[EncodedTerm],
1225        graph_filter_allow: bool,
1226    ) -> Result<Vec<EncodedTerm>, StorageError> {
1227        self.scan_axis_head(
1228            IndexPermutation::Spog,
1229            snapshot,
1230            limit,
1231            start_after_term,
1232            graph_name,
1233            graph_filter_terms,
1234            graph_filter_allow,
1235            false,
1236            &[],
1237        )
1238    }
1239
1240    /// Distinct predicates of the whole PSOG index. P-axis only.
1241    #[allow(clippy::too_many_arguments)]
1242    pub fn scan_predicates(
1243        &self,
1244        snapshot: SnapshotId,
1245        limit: u64,
1246        start_after_term: Option<&EncodedTerm>,
1247        graph_name: Option<&EncodedTerm>,
1248        graph_filter_terms: &[EncodedTerm],
1249        graph_filter_allow: bool,
1250    ) -> Result<Vec<EncodedTerm>, StorageError> {
1251        self.scan_axis_head(
1252            IndexPermutation::Psog,
1253            snapshot,
1254            limit,
1255            start_after_term,
1256            graph_name,
1257            graph_filter_terms,
1258            graph_filter_allow,
1259            false,
1260            &[],
1261        )
1262    }
1263
1264    /// Distinct objects of the whole OPSG index. O-axis only.
1265    #[allow(clippy::too_many_arguments)]
1266    pub fn scan_objects(
1267        &self,
1268        snapshot: SnapshotId,
1269        limit: u64,
1270        start_after_term: Option<&EncodedTerm>,
1271        graph_name: Option<&EncodedTerm>,
1272        graph_filter_terms: &[EncodedTerm],
1273        graph_filter_allow: bool,
1274    ) -> Result<Vec<EncodedTerm>, StorageError> {
1275        self.scan_axis_head(
1276            IndexPermutation::Opsg,
1277            snapshot,
1278            limit,
1279            start_after_term,
1280            graph_name,
1281            graph_filter_terms,
1282            graph_filter_allow,
1283            false,
1284            &[],
1285        )
1286    }
1287
1288    /// Distinct classes of the whole TSG index (`rdf:type` objects).
1289    /// O-axis only.
1290    #[allow(clippy::too_many_arguments)]
1291    pub fn scan_classes(
1292        &self,
1293        snapshot: SnapshotId,
1294        limit: u64,
1295        start_after_term: Option<&EncodedTerm>,
1296        graph_name: Option<&EncodedTerm>,
1297        graph_filter_terms: &[EncodedTerm],
1298        graph_filter_allow: bool,
1299    ) -> Result<Vec<EncodedTerm>, StorageError> {
1300        self.scan_axis_head(
1301            IndexPermutation::Tsg,
1302            snapshot,
1303            limit,
1304            start_after_term,
1305            graph_name,
1306            graph_filter_terms,
1307            graph_filter_allow,
1308            false,
1309            &[],
1310        )
1311    }
1312
1313    /// Count matching quads visible at `snapshot` without collecting rows.
1314    ///
1315    /// `limit` of `0` is unlimited.
1316    pub fn count_pattern_best_permutation(
1317        &self,
1318        pattern: &EncodedTriplePattern,
1319        snapshot: SnapshotId,
1320        limit: u64,
1321    ) -> Result<u64, StorageError> {
1322        match self {
1323            Self::Memory { store, .. } => store
1324                .read()
1325                .map_err(|_| StorageError::LockPoisoned)?
1326                .count_pattern_best_permutation(pattern, snapshot, limit),
1327            Self::RocksDb(store) => store.count_pattern_best_permutation(pattern, snapshot, limit),
1328        }
1329    }
1330
1331    /// Count through an explicitly chosen axis-local index.
1332    ///
1333    /// Returns [`StorageError::PermutationNotOwned`] when `permutation` belongs
1334    /// to another partition axis. `limit` of `0` is unlimited.
1335    pub fn count_pattern_in(
1336        &self,
1337        permutation: IndexPermutation,
1338        pattern: &EncodedTriplePattern,
1339        snapshot: SnapshotId,
1340        limit: u64,
1341    ) -> Result<u64, StorageError> {
1342        match self {
1343            Self::Memory { store, .. } => store
1344                .read()
1345                .map_err(|_| StorageError::LockPoisoned)?
1346                .count_pattern_in(permutation, pattern, snapshot, limit),
1347            Self::RocksDb(store) => store.count_pattern_in(permutation, pattern, snapshot, limit),
1348        }
1349    }
1350
1351    /// Prefix scan with the **full matcher semantics**: residual `graph_filter`
1352    /// membership, `merge_default_graph` whole-triple collapse (rows return with G
1353    /// rewritten to DefaultGraph), the exclusive `start_after` cursor, and
1354    /// `iri_only` segment pushdown all run inside the RowMatcher on raw key
1355    /// bytes. `limit` counts **post-filter** matches (`0` = unlimited) — one
1356    /// continuous walk, no decoded pre-filter chunking. Returns the page
1357    /// plus the walk's own [`ScanExhaustion`] verdict.
1358    #[allow(clippy::too_many_arguments)]
1359    pub fn scan_pattern_page(
1360        &self,
1361        permutation: IndexPermutation,
1362        pattern: &EncodedTriplePattern,
1363        snapshot: SnapshotId,
1364        limit: u64,
1365        start_after: Option<&EncodedQuad>,
1366        graph_filter: GByteFilter,
1367        merge_default_graph: bool,
1368        iri_only: IriOnlyMask,
1369    ) -> Result<ScanPage, StorageError> {
1370        match self {
1371            Self::Memory { store, .. } => store
1372                .read()
1373                .map_err(|_| StorageError::LockPoisoned)?
1374                .scan_pattern_page(
1375                    permutation,
1376                    pattern,
1377                    snapshot,
1378                    limit,
1379                    start_after,
1380                    graph_filter,
1381                    merge_default_graph,
1382                    iri_only,
1383                ),
1384            Self::RocksDb(store) => store.scan_pattern_page(
1385                permutation,
1386                pattern,
1387                snapshot,
1388                limit,
1389                start_after,
1390                graph_filter,
1391                merge_default_graph,
1392                iri_only,
1393            ),
1394        }
1395    }
1396
1397    /// Streaming variant of [`Self::scan_pattern_page`]: the callback receives
1398    /// each visible quad as it is decoded and returns `false` to stop the
1399    /// walk. `limit` counts post-filter matches (`0` = unlimited) and is
1400    /// edge-triggered exactly like the page API's, so a caller with its own
1401    /// stopping rule passes `0` and uses the callback's return value.
1402    ///
1403    /// The verdict is the walker's [`ScanExhaustion`]; a callback stop is not
1404    /// distinguished there, so the callback's own `false` is the signal.
1405    #[allow(clippy::too_many_arguments)]
1406    pub fn visit_pattern_quads(
1407        &self,
1408        permutation: IndexPermutation,
1409        pattern: &EncodedTriplePattern,
1410        snapshot: SnapshotId,
1411        limit: u64,
1412        start_after: Option<&EncodedQuad>,
1413        graph_filter: GByteFilter,
1414        merge_default_graph: bool,
1415        iri_only: IriOnlyMask,
1416        on_match: impl FnMut(EncodedQuad) -> Result<bool, StorageError>,
1417    ) -> Result<ScanExhaustion, StorageError> {
1418        let mask = ComparisonMask::default();
1419        match self {
1420            Self::Memory { store, .. } => store
1421                .read()
1422                .map_err(|_| StorageError::LockPoisoned)?
1423                .visit_pattern_quads(
1424                    permutation,
1425                    pattern,
1426                    snapshot,
1427                    limit,
1428                    start_after,
1429                    graph_filter,
1430                    merge_default_graph,
1431                    iri_only,
1432                    &mask,
1433                    on_match,
1434                ),
1435            Self::RocksDb(store) => store.visit_pattern_quads(
1436                permutation,
1437                pattern,
1438                snapshot,
1439                limit,
1440                start_after,
1441                graph_filter,
1442                merge_default_graph,
1443                iri_only,
1444                &mask,
1445                on_match,
1446            ),
1447        }
1448    }
1449
1450    /// Resolve `(object, predicate)` rows to their subjects through the O
1451    /// axis's OPSG index.
1452    ///
1453    /// `objects` are the resolved literals the candidate drain produced. They
1454    /// arrive in ascending encoded-term order — OPSG is `O‖P‖S‖G`, so that
1455    /// is also RocksDB key order, which the shared iterator below requires
1456    /// (it only steps forward). The whole list is ONE allow-list walk: a
1457    /// single iterator over the CF, `seek`ed once per object to its prefix.
1458    /// Recreating an iterator per object costs several microseconds each —
1459    /// several seconds over a broad match set — so the allow-list road is
1460    /// the point of this method.
1461    ///
1462    /// An object's prefix covers every predicate it appears under; the
1463    /// `predicates` set is therefore an in-memory membership test, not part
1464    /// of the key prefix (an empty list restricts nothing). A literal is
1465    /// usually stored under one of the named predicates, so a walk per
1466    /// `(object, predicate)` would seek twice more per object to prefixes
1467    /// that cannot hold a row.
1468    ///
1469    /// Rows are the raw `(subject, graph)` pairs: a subject reached through
1470    /// several objects or predicates repeats, and the caller dedups (and
1471    /// enforces its own distinct-subject budget). Visibility and graph
1472    /// semantics are [`Self::scan_pattern_page`]'s — a `Delete` newer than
1473    /// `snapshot` hides its row, and `graph_filter` / `merge_default_graph`
1474    /// apply exactly as they do to a `ScanPattern` request. `visit` returns
1475    /// `false` to stop early (a caller's budget reached).
1476    ///
1477    /// O axis only: OPSG is the permutation this store owns.
1478    #[allow(clippy::too_many_arguments)]
1479    pub fn visit_object_subjects(
1480        &self,
1481        objects: &[EncodedTerm],
1482        predicates: &[EncodedTerm],
1483        snapshot: SnapshotId,
1484        graph_name: Option<&EncodedTerm>,
1485        graph_filter: &GByteFilter,
1486        merge_default_graph: bool,
1487        mut visit: impl FnMut(&EncodedTerm, &EncodedTerm) -> Result<bool, StorageError>,
1488    ) -> Result<(), StorageError> {
1489        // The object slot leads OPSG, so the tight allow-list extends the
1490        // (empty) shared prefix: one scan_prefix iterator, one seek per
1491        // object. `visit_allow_list_rows` sorts the terms itself, so the
1492        // forward-only iterator is safe even if a caller's list is not.
1493        let pattern = EncodedTriplePattern {
1494            subject: None,
1495            predicate: None,
1496            object: None,
1497            graph_name: graph_name.cloned(),
1498        };
1499        let mut stopped = false;
1500        let verdict = self.visit_allow_list_rows(
1501            IndexPermutation::Opsg,
1502            &pattern,
1503            snapshot,
1504            None,
1505            QuadSlot::Object,
1506            objects,
1507            graph_filter.clone(),
1508            merge_default_graph,
1509            IriOnlyMask::NONE,
1510            |row| {
1511                let mut quad =
1512                    crate::encode::decode_index_key(IndexPermutation::Opsg, row.logical())?;
1513                // The page API rewrote the merged-default graph before
1514                // exposing the row; keep the same visible row.
1515                if merge_default_graph {
1516                    quad = quad.into_merged_default();
1517                }
1518                if !predicates.is_empty()
1519                    && !predicates
1520                        .iter()
1521                        .any(|predicate| predicate == &quad.predicate)
1522                {
1523                    return Ok(true);
1524                }
1525                let keep_going = visit(&quad.subject, &quad.graph_name)?;
1526                if !keep_going {
1527                    stopped = true;
1528                }
1529                Ok(keep_going)
1530            },
1531        )?;
1532        if verdict.is_some() {
1533            return Ok(());
1534        }
1535        // The allow-list slot did not extend the permutation, which cannot
1536        // happen for OPSG's leading object slot. Honour the allow-list
1537        // contract's fallback ("bind each term instead") rather than
1538        // returning an empty answer if a future permutation changes that.
1539        for object in objects {
1540            let pattern = EncodedTriplePattern {
1541                subject: None,
1542                predicate: None,
1543                object: Some(object.clone()),
1544                graph_name: graph_name.cloned(),
1545            };
1546            self.visit_pattern_quads(
1547                IndexPermutation::Opsg,
1548                &pattern,
1549                snapshot,
1550                0,
1551                None,
1552                graph_filter.clone(),
1553                merge_default_graph,
1554                IriOnlyMask::NONE,
1555                |mut quad| {
1556                    if !predicates.is_empty()
1557                        && !predicates
1558                            .iter()
1559                            .any(|predicate| predicate == &quad.predicate)
1560                    {
1561                        return Ok(true);
1562                    }
1563                    if merge_default_graph {
1564                        quad = quad.into_merged_default();
1565                    }
1566                    let keep_going = visit(&quad.subject, &quad.graph_name)?;
1567                    if !keep_going {
1568                        stopped = true;
1569                    }
1570                    Ok(keep_going)
1571                },
1572            )?;
1573            if stopped {
1574                return Ok(());
1575            }
1576        }
1577        Ok(())
1578    }
1579
1580    /// Prefix scan with the **full matcher semantics** and slot comparisons
1581    /// applied inside the walk. `comparisons` is compiled once for this
1582    /// permutation; a predicate storage cannot decide keeps the row, so the
1583    /// compute-side copy remains authoritative.
1584    #[allow(clippy::too_many_arguments)]
1585    pub fn scan_pattern_page_with_comparisons(
1586        &self,
1587        permutation: IndexPermutation,
1588        pattern: &EncodedTriplePattern,
1589        snapshot: SnapshotId,
1590        limit: u64,
1591        start_after: Option<&EncodedQuad>,
1592        graph_filter: GByteFilter,
1593        merge_default_graph: bool,
1594        iri_only: IriOnlyMask,
1595        comparisons: &[SlotComparison],
1596    ) -> Result<ScanPage, StorageError> {
1597        let mask = ComparisonMask::compile(pattern, permutation, comparisons);
1598        if mask.is_empty() {
1599            return Ok(ScanPage {
1600                rows: Vec::new(),
1601                exhausted: Some(ScanExhaustion::ExhaustedScan),
1602            });
1603        }
1604        match self {
1605            Self::Memory { store, .. } => store
1606                .read()
1607                .map_err(|_| StorageError::LockPoisoned)?
1608                .scan_pattern_page_with_comparisons(
1609                    permutation,
1610                    pattern,
1611                    snapshot,
1612                    limit,
1613                    start_after,
1614                    graph_filter,
1615                    merge_default_graph,
1616                    iri_only,
1617                    &mask,
1618                ),
1619            Self::RocksDb(store) => store.scan_pattern_page_with_comparisons(
1620                permutation,
1621                pattern,
1622                snapshot,
1623                limit,
1624                start_after,
1625                graph_filter,
1626                merge_default_graph,
1627                iri_only,
1628                &mask,
1629            ),
1630        }
1631    }
1632
1633    /// Allow-list prefix scan with slot comparisons applied inside each
1634    /// tight prefix's walk.
1635    #[allow(clippy::too_many_arguments)]
1636    pub fn scan_pattern_page_allow_list_with_comparisons(
1637        &self,
1638        permutation: IndexPermutation,
1639        pattern: &EncodedTriplePattern,
1640        snapshot: SnapshotId,
1641        limit: u64,
1642        start_after: Option<&EncodedQuad>,
1643        allow_list_slot: QuadSlot,
1644        allow_terms: &[EncodedTerm],
1645        graph_filter: GByteFilter,
1646        merge_default_graph: bool,
1647        iri_only: IriOnlyMask,
1648        comparisons: &[SlotComparison],
1649    ) -> Result<Option<ScanPage>, StorageError> {
1650        let mask = ComparisonMask::compile(pattern, permutation, comparisons);
1651        if mask.is_empty() {
1652            return Ok(Some(ScanPage {
1653                rows: Vec::new(),
1654                exhausted: Some(ScanExhaustion::ExhaustedScan),
1655            }));
1656        }
1657        match self {
1658            Self::Memory { store, .. } => store
1659                .read()
1660                .map_err(|_| StorageError::LockPoisoned)?
1661                .scan_pattern_page_allow_list_with_comparisons(
1662                    permutation,
1663                    pattern,
1664                    snapshot,
1665                    limit,
1666                    start_after,
1667                    allow_list_slot,
1668                    allow_terms,
1669                    graph_filter,
1670                    merge_default_graph,
1671                    iri_only,
1672                    &mask,
1673                ),
1674            Self::RocksDb(store) => store.scan_pattern_page_allow_list_with_comparisons(
1675                permutation,
1676                pattern,
1677                snapshot,
1678                limit,
1679                start_after,
1680                allow_list_slot,
1681                allow_terms,
1682                graph_filter,
1683                merge_default_graph,
1684                iri_only,
1685                &mask,
1686            ),
1687        }
1688    }
1689
1690    /// Count matching rows with the **full matcher semantics** — residual
1691    /// `graph_filter` membership and `merge_default_graph` collapse inside the
1692    /// RowMatcher, counting raw [`KeyRow`]s without decoding any term.
1693    /// `limit` counts post-filter matches (`0` = unlimited). Counts are not
1694    /// resumable: there is no cursor.
1695    #[allow(clippy::too_many_arguments)]
1696    pub fn count_pattern_impl(
1697        &self,
1698        permutation: IndexPermutation,
1699        pattern: &EncodedTriplePattern,
1700        snapshot: SnapshotId,
1701        limit: u64,
1702        graph_filter: GByteFilter,
1703        merge_default_graph: bool,
1704    ) -> Result<u64, StorageError> {
1705        match self {
1706            Self::Memory { store, .. } => store
1707                .read()
1708                .map_err(|_| StorageError::LockPoisoned)?
1709                .count_pattern_impl(
1710                    permutation,
1711                    pattern,
1712                    snapshot,
1713                    limit,
1714                    graph_filter,
1715                    merge_default_graph,
1716                ),
1717            Self::RocksDb(store) => store.count_pattern_impl(
1718                permutation,
1719                pattern,
1720                snapshot,
1721                limit,
1722                graph_filter,
1723                merge_default_graph,
1724            ),
1725        }
1726    }
1727
1728    /// [`Self::count_pattern_impl`] with advisory TSG class totals for the
1729    /// sliced full-axis count. The memory backend has no walks and ignores
1730    /// the hint; the RocksDB backend uses it only for the TSG full-axis
1731    /// shape (see `RocksDbStorage::count_pattern_impl_with_class_totals`).
1732    #[allow(clippy::too_many_arguments)]
1733    pub fn count_pattern_impl_with_class_totals(
1734        &self,
1735        permutation: IndexPermutation,
1736        pattern: &EncodedTriplePattern,
1737        snapshot: SnapshotId,
1738        limit: u64,
1739        graph_filter: GByteFilter,
1740        merge_default_graph: bool,
1741        class_totals: &[(StrHash, u64)],
1742        force_serial: bool,
1743    ) -> Result<u64, StorageError> {
1744        match self {
1745            // The memory backend has no walks and is always the serial
1746            // reference, so `force_serial` is a no-op here.
1747            Self::Memory { store, .. } => store
1748                .read()
1749                .map_err(|_| StorageError::LockPoisoned)?
1750                .count_pattern_impl(
1751                    permutation,
1752                    pattern,
1753                    snapshot,
1754                    limit,
1755                    graph_filter,
1756                    merge_default_graph,
1757                ),
1758            Self::RocksDb(store) => store.count_pattern_impl_with_class_totals(
1759                permutation,
1760                pattern,
1761                snapshot,
1762                limit,
1763                graph_filter,
1764                merge_default_graph,
1765                class_totals,
1766                force_serial,
1767            ),
1768        }
1769    }
1770
1771    /// Flush MemTables to SST files (RocksDB); no-op for the memory backend.
1772    pub fn flush_memtables(&self) -> Result<(), StorageError> {
1773        match self {
1774            Self::Memory { store, .. } => store
1775                .read()
1776                .map_err(|_| StorageError::LockPoisoned)?
1777                .flush_memtables(),
1778            Self::RocksDb(store) => store.flush_memtables(),
1779        }
1780    }
1781
1782    /// Compact both axis-local CFs (RocksDB); no-op for the memory backend.
1783    ///
1784    /// Bottommost compaction is forced, so a trivial move is rewritten and
1785    /// collectors run even when the flushed file had no `waratah.stats`.
1786    pub fn compact_range(&self) {
1787        match self {
1788            Self::Memory { .. } => {}
1789            Self::RocksDb(store) => store.compact_range(),
1790        }
1791    }
1792
1793    /// Warm this partition's block cache (see
1794    /// [`RocksDbStorage::warm_block_cache`]). No-op on the memory backend:
1795    /// there is no block cache, so the stats come back zeroed.
1796    pub fn warm_block_cache(
1797        &self,
1798        fill_fraction: f64,
1799    ) -> Result<crate::WarmBlockCacheStats, StorageError> {
1800        match self {
1801            Self::Memory { .. } => Ok(crate::WarmBlockCacheStats::noop()),
1802            Self::RocksDb(store) => store.warm_block_cache(fill_fraction),
1803        }
1804    }
1805
1806    /// Compact the same column families as [`Self::compact_range`] without
1807    /// rewriting the bottommost level.
1808    ///
1809    /// The L0 merge still runs. A file RocksDB only trivial-moves keeps the
1810    /// `waratah.stats` blob written when it was flushed. No-op for the memory
1811    /// backend.
1812    pub fn compact_range_skip_bottommost(&self) {
1813        match self {
1814            Self::Memory { .. } => {}
1815            Self::RocksDb(store) => store.compact_range_skip_bottommost(),
1816        }
1817    }
1818
1819    /// SST `user_collected_properties` blobs for `key` on the canonical stats CF
1820    /// and the S-axis named-graph catalog CF.
1821    ///
1822    /// Empty for the memory backend.
1823    pub fn stats_property_blobs(&self, key: &[u8]) -> Result<Vec<Vec<u8>>, StorageError> {
1824        match self {
1825            Self::Memory { .. } => Ok(Vec::new()),
1826            Self::RocksDb(store) => store.stats_property_blobs(key),
1827        }
1828    }
1829    /// Stream every visible matching row to `emit` in one index walk; `emit`
1830    /// returning `false` stops the walk early (the caller owns the stop
1831    /// reason). Rows arrive as raw [`KeyRow`] key slices — callers decode or
1832    /// copy out what they need. `graph_filter` is the residual graph
1833    /// membership window; `merge_default_graph` collapses same-triple rows
1834    /// (G last in every index) to the first visible one. Same visibility /
1835    /// cursor contract as [`Self::scan_pattern_page`] with `limit = 0`.
1836    /// `iri_only` rejects non-NamedNode S/O segments per the planner's
1837    /// `FILTER(isIRI(?x))` pushdown. Returns the walk's
1838    /// [`ScanExhaustion`] verdict: `Limited` when the callback
1839    /// stopped it at the limit, `ExhaustedScan` when it left the
1840    /// pattern's key range.
1841    #[allow(clippy::too_many_arguments)]
1842    pub fn visit_pattern_rows(
1843        &self,
1844        permutation: IndexPermutation,
1845        pattern: &EncodedTriplePattern,
1846        snapshot: SnapshotId,
1847        start_after: Option<&EncodedQuad>,
1848        graph_filter: GByteFilter,
1849        merge_default_graph: bool,
1850        iri_only: IriOnlyMask,
1851        on_match: impl FnMut(&KeyRow) -> Result<bool, StorageError>,
1852    ) -> Result<ScanExhaustion, StorageError> {
1853        self.visit_pattern_rows_with_comparisons(
1854            permutation,
1855            pattern,
1856            snapshot,
1857            start_after,
1858            graph_filter,
1859            merge_default_graph,
1860            iri_only,
1861            &[],
1862            on_match,
1863        )
1864    }
1865
1866    /// [`Self::visit_pattern_rows`] with slot comparisons compiled inside this
1867    /// call. An emptied mask returns `ExhaustedScan` without opening an
1868    /// iterator.
1869    #[allow(clippy::too_many_arguments)]
1870    pub fn visit_pattern_rows_with_comparisons(
1871        &self,
1872        permutation: IndexPermutation,
1873        pattern: &EncodedTriplePattern,
1874        snapshot: SnapshotId,
1875        start_after: Option<&EncodedQuad>,
1876        graph_filter: GByteFilter,
1877        merge_default_graph: bool,
1878        iri_only: IriOnlyMask,
1879        comparisons: &[SlotComparison],
1880        on_match: impl FnMut(&KeyRow) -> Result<bool, StorageError>,
1881    ) -> Result<ScanExhaustion, StorageError> {
1882        let mask = ComparisonMask::compile(pattern, permutation, comparisons);
1883        if mask.is_empty() {
1884            return Ok(ScanExhaustion::ExhaustedScan);
1885        }
1886        match self {
1887            Self::Memory { store, .. } => store
1888                .read()
1889                .map_err(|_| StorageError::LockPoisoned)?
1890                .visit_pattern_rows(
1891                    permutation,
1892                    pattern,
1893                    snapshot,
1894                    start_after,
1895                    graph_filter,
1896                    merge_default_graph,
1897                    iri_only,
1898                    &mask,
1899                    on_match,
1900                ),
1901            Self::RocksDb(store) => store.visit_pattern_rows(
1902                permutation,
1903                pattern,
1904                snapshot,
1905                start_after,
1906                graph_filter,
1907                merge_default_graph,
1908                iri_only,
1909                &mask,
1910                on_match,
1911            ),
1912        }
1913    }
1914}
1915
1916#[cfg(test)]
1917mod tests {
1918    use super::*;
1919    use crate::encode::{
1920        CatalogPut, CompareOp, CrsId, EncodedTerm, GeoDatatype, GeomKind, HexastoreVersion,
1921        IndexPermutation, QuadSlot, SlotComparison, SmallString, StrHash, encode_quad,
1922        encode_term_bytes, prepare_hexastore_puts,
1923    };
1924    use crate::rocksdb::{RocksDbOptionsHooks, RocksDbTuning};
1925    use crate::test_util::{sample_quad, sample_quads};
1926    use crate::{GraphName, Literal, NamedNode, Quad};
1927    use pretty_assertions::assert_eq;
1928
1929    fn populate(store: &Storage) {
1930        for quad in sample_quads() {
1931            store.insert_quad(&quad).unwrap();
1932        }
1933    }
1934
1935    fn assert_shared_fixture_behaviour(store: &Storage) {
1936        populate(store);
1937
1938        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
1939        let pattern_p = EncodedTriplePattern {
1940            subject: None,
1941            predicate: Some(p),
1942            object: None,
1943            graph_name: Some(EncodedTerm::DefaultGraph),
1944        };
1945        let rows_p = store
1946            .scan_pattern(&pattern_p, SnapshotId::default())
1947            .unwrap();
1948        assert_eq!(rows_p.len(), 2);
1949        assert_eq!(
1950            store
1951                .count_pattern_best_permutation(&pattern_p, SnapshotId::default(), 0)
1952                .unwrap(),
1953            rows_p.len() as u64
1954        );
1955
1956        let sunny = EncodedTerm::from(&Literal::from("Sunny"));
1957        let pattern_o = EncodedTriplePattern {
1958            subject: None,
1959            predicate: None,
1960            object: Some(sunny),
1961            graph_name: Some(EncodedTerm::DefaultGraph),
1962        };
1963        let rows_o = store
1964            .scan_pattern(&pattern_o, SnapshotId::default())
1965            .unwrap();
1966        assert_eq!(rows_o.len(), 1);
1967        assert_eq!(
1968            store
1969                .count_pattern_best_permutation(&pattern_o, SnapshotId::default(), 0)
1970                .unwrap(),
1971            1
1972        );
1973        assert_eq!(
1974            store
1975                .count_pattern_best_permutation(&pattern_p, SnapshotId::default(), 1)
1976                .unwrap(),
1977            1,
1978            "positive limit must stop after that many matches"
1979        );
1980
1981        let permutation = pattern_p.best_permutation(store.axis());
1982        let page1 = store
1983            .scan_pattern_page(
1984                permutation,
1985                &pattern_p,
1986                SnapshotId::default(),
1987                1,
1988                None,
1989                GByteFilter::Unconstrained,
1990                false,
1991                IriOnlyMask::NONE,
1992            )
1993            .unwrap()
1994            .rows;
1995        assert_eq!(page1.len(), 1);
1996        let page2 = store
1997            .scan_pattern_page(
1998                permutation,
1999                &pattern_p,
2000                SnapshotId::default(),
2001                1,
2002                Some(&page1[0]),
2003                GByteFilter::Unconstrained,
2004                false,
2005                IriOnlyMask::NONE,
2006            )
2007            .unwrap()
2008            .rows;
2009        assert_eq!(page2.len(), 1);
2010        assert_ne!(page1[0], page2[0], "start_after is exclusive");
2011        let past_end = store
2012            .scan_pattern_page(
2013                permutation,
2014                &pattern_p,
2015                SnapshotId::default(),
2016                1,
2017                Some(&page2[0]),
2018                GByteFilter::Unconstrained,
2019                false,
2020                IriOnlyMask::NONE,
2021            )
2022            .unwrap();
2023        assert!(past_end.rows.is_empty());
2024    }
2025
2026    fn assert_versioned_parity(store: &mut Storage) {
2027        let quad = sample_quad();
2028        store
2029            .insert_quad_version(
2030                &quad,
2031                CommitTs(10),
2032                StorageOp::Put,
2033                VisibilityLabel::default(),
2034            )
2035            .unwrap();
2036        store
2037            .insert_quad_version(
2038                &quad,
2039                CommitTs(20),
2040                StorageOp::Delete,
2041                VisibilityLabel::default(),
2042            )
2043            .unwrap();
2044
2045        assert_eq!(
2046            store
2047                .scan_pattern(&EncodedTriplePattern::default(), SnapshotId(15))
2048                .unwrap()
2049                .len(),
2050            1
2051        );
2052        assert_eq!(
2053            store
2054                .count_pattern_best_permutation(&EncodedTriplePattern::default(), SnapshotId(15), 0)
2055                .unwrap(),
2056            1
2057        );
2058        assert!(
2059            store
2060                .scan_pattern(&EncodedTriplePattern::default(), SnapshotId(25))
2061                .unwrap()
2062                .is_empty()
2063        );
2064        assert_eq!(
2065            store
2066                .count_pattern_best_permutation(&EncodedTriplePattern::default(), SnapshotId(25), 0)
2067                .unwrap(),
2068            0
2069        );
2070    }
2071
2072    #[test]
2073    fn memory_backend_shared_fixture() {
2074        let store = Storage::memory(PartitionAxis::O);
2075        assert_eq!(store.axis(), PartitionAxis::O);
2076        assert_eq!(store.backend_kind(), StorageBackendKind::Memory);
2077        assert_shared_fixture_behaviour(&store);
2078    }
2079
2080    #[test]
2081    fn warm_block_cache_is_a_noop_on_memory() {
2082        let store = Storage::memory(PartitionAxis::S);
2083        let stats = store.warm_block_cache(0.5).unwrap();
2084        assert!(stats.is_noop());
2085    }
2086
2087    #[test]
2088    fn rocksdb_backend_shared_fixture() {
2089        let dir = tempfile::tempdir().unwrap();
2090        let store = Storage::open_rocksdb(dir.path().join("parity"), PartitionAxis::O).unwrap();
2091        assert_eq!(store.axis(), PartitionAxis::O);
2092        assert_eq!(store.backend_kind(), StorageBackendKind::RocksDb);
2093        assert_shared_fixture_behaviour(&store);
2094    }
2095
2096    #[test]
2097    fn memory_and_rocksdb_honour_versioned_layout() {
2098        let mut mem = Storage::memory(PartitionAxis::S);
2099        assert_versioned_parity(&mut mem);
2100
2101        let dir = tempfile::tempdir().unwrap();
2102        let mut rocks =
2103            Storage::open_rocksdb(dir.path().join("versioned"), PartitionAxis::S).unwrap();
2104        assert_versioned_parity(&mut rocks);
2105    }
2106
2107    #[test]
2108    fn block_cache_bytes_reports_rocksdb_and_none_on_memory() {
2109        // Memory backend: no block cache exists.
2110        let mem = Storage::memory(PartitionAxis::S);
2111        assert!(mem.block_cache_bytes().is_none());
2112
2113        // RocksDB backend: capacity flows from tuning; usage climbs once a
2114        // flushed block is read back through the cache.
2115        let dir = tempfile::tempdir().unwrap();
2116        let store = Storage::open_rocksdb(dir.path().join("cache"), PartitionAxis::P).unwrap();
2117        let (capacity, usage_before) = store.block_cache_bytes().expect("rocksdb has a cache");
2118        assert!(capacity > 0);
2119        store
2120            .insert_quad_version(
2121                &store_sample_quad(1),
2122                CommitTs(1),
2123                StorageOp::Put,
2124                VisibilityLabel::default(),
2125            )
2126            .unwrap();
2127        store.flush_memtables().unwrap();
2128        let (capacity_after, usage_after) = store.block_cache_bytes().expect("rocksdb cache");
2129        assert_eq!(capacity_after, capacity, "capacity is fixed at open");
2130        assert!(usage_after >= usage_before);
2131        assert!(usage_after > 0, "a flush must charge at least one block");
2132    }
2133
2134    /// One quad for the cache-counters test (keeps the encode imports local).
2135    fn store_sample_quad(index: u8) -> Quad {
2136        Quad::new(
2137            NamedNode::new(format!("http://ex/s{index}")).unwrap(),
2138            NamedNode::new("http://ex/p").unwrap(),
2139            NamedNode::new(format!("http://ex/o{index}")).unwrap(),
2140            GraphName::DefaultGraph,
2141        )
2142    }
2143
2144    #[test]
2145    fn slot_comparisons_filter_both_backends_and_keep_the_page_contract() {
2146        let dir = tempfile::tempdir().unwrap();
2147        let stores = [
2148            Storage::memory(PartitionAxis::P),
2149            Storage::open_rocksdb(dir.path().join("slot-comparisons"), PartitionAxis::P).unwrap(),
2150        ];
2151        let year = NamedNode::new("http://ex/year").unwrap();
2152        for store in &stores {
2153            for (index, value) in [1966i64, 1967, 1971, 1972].into_iter().enumerate() {
2154                store
2155                    .insert_quad(&Quad::new(
2156                        NamedNode::new(format!("http://ex/s{index}")).unwrap(),
2157                        year.clone(),
2158                        Literal::from(value),
2159                        GraphName::DefaultGraph,
2160                    ))
2161                    .unwrap();
2162            }
2163        }
2164        let pattern = EncodedTriplePattern {
2165            subject: None,
2166            predicate: Some(EncodedTerm::from(&year)),
2167            object: None,
2168            graph_name: Some(EncodedTerm::DefaultGraph),
2169        };
2170        let comparisons = [SlotComparison {
2171            slot: QuadSlot::Object,
2172            op: CompareOp::Ge,
2173            term: EncodedTerm::from(&Literal::from(1967i64)),
2174        }];
2175        let expected = [1967i64, 1971, 1972].map(|value| EncodedTerm::from(&Literal::from(value)));
2176        for store in &stores {
2177            let rows = store
2178                .scan_pattern_with_comparisons(&pattern, SnapshotId::default(), &comparisons)
2179                .unwrap();
2180            assert_eq!(rows.len(), 3, "1967..=1972 matches");
2181            for row in &rows {
2182                assert!(expected.contains(&row.object), "{:?}", row.object);
2183            }
2184
2185            // The page limit counts post-filter matches, and the verdict
2186            // reports the third match beyond the two-row page.
2187            let page = store
2188                .scan_pattern_page_with_comparisons(
2189                    pattern.best_permutation(store.axis()),
2190                    &pattern,
2191                    SnapshotId::default(),
2192                    2,
2193                    None,
2194                    GByteFilter::Unconstrained,
2195                    false,
2196                    IriOnlyMask::NONE,
2197                    &comparisons,
2198                )
2199                .unwrap();
2200            assert_eq!(page.rows.len(), 2);
2201            assert_eq!(page.exhausted, Some(ScanExhaustion::Limited));
2202
2203            // A predicate that matches nothing is an empty, terminal page.
2204            let none = [SlotComparison {
2205                slot: QuadSlot::Object,
2206                op: CompareOp::Gt,
2207                term: EncodedTerm::from(&Literal::from(9_999i64)),
2208            }];
2209            let page = store
2210                .scan_pattern_page_with_comparisons(
2211                    pattern.best_permutation(store.axis()),
2212                    &pattern,
2213                    SnapshotId::default(),
2214                    0,
2215                    None,
2216                    GByteFilter::Unconstrained,
2217                    false,
2218                    IriOnlyMask::NONE,
2219                    &none,
2220                )
2221                .unwrap();
2222            assert!(page.rows.is_empty());
2223            assert_eq!(page.exhausted, Some(ScanExhaustion::ExhaustedScan));
2224        }
2225    }
2226
2227    #[test]
2228    fn slot_comparisons_cover_operators_predicate_slot_and_allow_list() {
2229        let dir = tempfile::tempdir().unwrap();
2230        let stores = [
2231            Storage::memory(PartitionAxis::P),
2232            Storage::open_rocksdb(dir.path().join("slot-comparison-ops"), PartitionAxis::P)
2233                .unwrap(),
2234        ];
2235        let year = NamedNode::new("http://ex/year").unwrap();
2236        for store in &stores {
2237            for (index, value) in [1966i64, 1967, 1971, 1972].into_iter().enumerate() {
2238                store
2239                    .insert_quad(&Quad::new(
2240                        NamedNode::new(format!("http://ex/s{index}")).unwrap(),
2241                        year.clone(),
2242                        Literal::from(value),
2243                        GraphName::DefaultGraph,
2244                    ))
2245                    .unwrap();
2246            }
2247        }
2248        let pattern = EncodedTriplePattern {
2249            subject: None,
2250            predicate: Some(EncodedTerm::from(&year)),
2251            object: None,
2252            graph_name: Some(EncodedTerm::DefaultGraph),
2253        };
2254        let int = |value: i64| EncodedTerm::from(&Literal::from(value));
2255        let object_cmp = |op: CompareOp, value: i64| {
2256            [SlotComparison {
2257                slot: QuadSlot::Object,
2258                op,
2259                term: int(value),
2260            }]
2261        };
2262
2263        for store in &stores {
2264            // Every operator, not just Ge.
2265            for (op, value, expected) in [
2266                (CompareOp::Ne, 1967, vec![1966, 1971, 1972]),
2267                (CompareOp::Lt, 1971, vec![1966, 1967]),
2268                (CompareOp::Le, 1971, vec![1966, 1967, 1971]),
2269                (CompareOp::Gt, 1967, vec![1971, 1972]),
2270            ] {
2271                let rows = store
2272                    .scan_pattern_with_comparisons(
2273                        &pattern,
2274                        SnapshotId::default(),
2275                        &object_cmp(op, value),
2276                    )
2277                    .unwrap();
2278                let want: Vec<EncodedTerm> = expected.into_iter().map(int).collect();
2279                assert_eq!(rows.len(), want.len(), "{op:?} {value}");
2280                for row in &rows {
2281                    assert!(
2282                        want.contains(&row.object),
2283                        "{op:?} {value}: {:?}",
2284                        row.object
2285                    );
2286                }
2287            }
2288
2289            // A comparison on the predicate slot of an unbound pattern.
2290            let all = EncodedTriplePattern {
2291                subject: None,
2292                predicate: None,
2293                object: None,
2294                graph_name: Some(EncodedTerm::DefaultGraph),
2295            };
2296            let pred_cmp = [SlotComparison {
2297                slot: QuadSlot::Predicate,
2298                op: CompareOp::Eq,
2299                term: EncodedTerm::from(&year),
2300            }];
2301            let rows = store
2302                .scan_pattern_with_comparisons(&all, SnapshotId::default(), &pred_cmp)
2303                .unwrap();
2304            assert_eq!(rows.len(), 4, "predicate-slot Eq");
2305
2306            // Allow-list + comparison: {1967, 1971} then >= 1971. Posg puts
2307            // the object immediately after the bound predicate, so the
2308            // allow-list slot extends the key prefix.
2309            let page = store
2310                .scan_pattern_page_allow_list_with_comparisons(
2311                    IndexPermutation::Posg,
2312                    &pattern,
2313                    SnapshotId::default(),
2314                    0,
2315                    None,
2316                    QuadSlot::Object,
2317                    &[int(1967), int(1971)],
2318                    GByteFilter::Unconstrained,
2319                    false,
2320                    IriOnlyMask::NONE,
2321                    &object_cmp(CompareOp::Ge, 1971),
2322                )
2323                .unwrap()
2324                .expect("tight allow-list");
2325            assert_eq!(page.rows.len(), 1);
2326            assert_eq!(page.rows[0].object, int(1971));
2327
2328            // A cursor pointing at a row the comparison drops: the walk
2329            // resumes after it, unaffected by the mask.
2330            let dropped = encode_quad(&Quad::new(
2331                NamedNode::new("http://ex/s0").unwrap(),
2332                year.clone(),
2333                Literal::from(1966i64),
2334                GraphName::DefaultGraph,
2335            ))
2336            .unwrap();
2337            let page = store
2338                .scan_pattern_page_with_comparisons(
2339                    pattern.best_permutation(store.axis()),
2340                    &pattern,
2341                    SnapshotId::default(),
2342                    0,
2343                    Some(&dropped),
2344                    GByteFilter::Unconstrained,
2345                    false,
2346                    IriOnlyMask::NONE,
2347                    &object_cmp(CompareOp::Ge, 1967),
2348                )
2349                .unwrap();
2350            assert_eq!(page.rows.len(), 3, "cursor before the first match");
2351
2352            // A bound-slot contradiction empties the mask and short-circuits
2353            // the walk with a terminal verdict.
2354            let bound = EncodedTriplePattern {
2355                subject: None,
2356                predicate: Some(EncodedTerm::from(&year)),
2357                object: Some(int(1967)),
2358                graph_name: Some(EncodedTerm::DefaultGraph),
2359            };
2360            let page = store
2361                .scan_pattern_page_with_comparisons(
2362                    pattern.best_permutation(store.axis()),
2363                    &bound,
2364                    SnapshotId::default(),
2365                    0,
2366                    None,
2367                    GByteFilter::Unconstrained,
2368                    false,
2369                    IriOnlyMask::NONE,
2370                    &object_cmp(CompareOp::Ne, 1967),
2371                )
2372                .unwrap();
2373            assert!(page.rows.is_empty());
2374            assert_eq!(page.exhausted, Some(ScanExhaustion::ExhaustedScan));
2375        }
2376    }
2377
2378    #[test]
2379    fn slot_comparisons_keep_merge_default_and_undecidable_strings() {
2380        let dir = tempfile::tempdir().unwrap();
2381        let stores = [
2382            Storage::memory(PartitionAxis::P),
2383            Storage::open_rocksdb(dir.path().join("slot-comparison-merge"), PartitionAxis::P)
2384                .unwrap(),
2385        ];
2386        let predicate = NamedNode::new("http://ex/value").unwrap();
2387        for store in &stores {
2388            // A hashed string: ordering needs the registry, so the mask keeps
2389            // it for the compute side.
2390            store
2391                .insert_quad(&Quad::new(
2392                    NamedNode::new("http://ex/big").unwrap(),
2393                    predicate.clone(),
2394                    Literal::from("aaaaaaaaaaaaaaaa"),
2395                    GraphName::DefaultGraph,
2396                ))
2397                .unwrap();
2398            // A small string that passes the same `Lt "b"` comparison, in a
2399            // named graph so `merge_default_graph` has something to collapse.
2400            store
2401                .insert_quad(&Quad::new(
2402                    NamedNode::new("http://ex/small").unwrap(),
2403                    predicate.clone(),
2404                    Literal::from("aaa"),
2405                    GraphName::NamedNode(NamedNode::new("http://ex/g").unwrap()),
2406                ))
2407                .unwrap();
2408        }
2409        let pattern = EncodedTriplePattern {
2410            subject: None,
2411            predicate: Some(EncodedTerm::from(&predicate)),
2412            object: None,
2413            graph_name: None,
2414        };
2415        let lt = [SlotComparison {
2416            slot: QuadSlot::Object,
2417            op: CompareOp::Lt,
2418            term: EncodedTerm::from(&Literal::new_simple_literal("b")),
2419        }];
2420        for store in &stores {
2421            let page = store
2422                .scan_pattern_page_with_comparisons(
2423                    pattern.best_permutation(store.axis()),
2424                    &pattern,
2425                    SnapshotId::default(),
2426                    0,
2427                    None,
2428                    GByteFilter::Unconstrained,
2429                    true, // merge_default_graph
2430                    IriOnlyMask::NONE,
2431                    &lt,
2432                )
2433                .unwrap();
2434            assert_eq!(
2435                page.rows.len(),
2436                2,
2437                "hashed string kept as undecidable; small string passes"
2438            );
2439            assert!(
2440                page.rows
2441                    .iter()
2442                    .all(|row| row.graph_name == EncodedTerm::DefaultGraph),
2443                "merge_default_graph rewrites every row"
2444            );
2445        }
2446    }
2447
2448    #[test]
2449    fn scan_in_foreign_permutation_is_typed_error_on_both_backends() {
2450        let dir = tempfile::tempdir().unwrap();
2451        let stores = [
2452            Storage::memory(PartitionAxis::S),
2453            Storage::open_rocksdb(dir.path().join("isolation"), PartitionAxis::S).unwrap(),
2454        ];
2455        for store in &stores {
2456            // The S axis owns SPOG/SOPG only; TSG belongs to the O partition.
2457            let error = store
2458                .scan_pattern_in(
2459                    IndexPermutation::Tsg,
2460                    &EncodedTriplePattern::default(),
2461                    SnapshotId::default(),
2462                )
2463                .unwrap_err();
2464            assert!(matches!(
2465                error,
2466                StorageError::PermutationNotOwned {
2467                    index: "tsg",
2468                    axis: PartitionAxis::S
2469                }
2470            ));
2471
2472            let count_error = store
2473                .count_pattern_in(
2474                    IndexPermutation::Tsg,
2475                    &EncodedTriplePattern::default(),
2476                    SnapshotId::default(),
2477                    0,
2478                )
2479                .unwrap_err();
2480            assert!(matches!(
2481                count_error,
2482                StorageError::PermutationNotOwned {
2483                    index: "tsg",
2484                    axis: PartitionAxis::S
2485                }
2486            ));
2487
2488            assert_eq!(
2489                store
2490                    .scan_pattern_in(
2491                        IndexPermutation::Spog,
2492                        &EncodedTriplePattern::default(),
2493                        SnapshotId::default()
2494                    )
2495                    .unwrap()
2496                    .len(),
2497                0
2498            );
2499            assert_eq!(
2500                store
2501                    .count_pattern_in(
2502                        IndexPermutation::Spog,
2503                        &EncodedTriplePattern::default(),
2504                        SnapshotId::default(),
2505                        0
2506                    )
2507                    .unwrap(),
2508                0
2509            );
2510        }
2511    }
2512
2513    #[test]
2514    fn count_matches_scan_and_drops_named_graph_on_default_graph_pattern() {
2515        let dir = tempfile::tempdir().unwrap();
2516        let stores = [
2517            Storage::memory(PartitionAxis::S),
2518            Storage::open_rocksdb(dir.path().join("count-graph"), PartitionAxis::S).unwrap(),
2519        ];
2520        let default_quad = sample_quad();
2521        let named_quad = Quad::new(
2522            NamedNode::new("http://ex/alice").unwrap(),
2523            NamedNode::new("http://ex/livesIn").unwrap(),
2524            NamedNode::new("http://ex/brisbane").unwrap(),
2525            GraphName::NamedNode(NamedNode::new("http://ex/g").unwrap()),
2526        );
2527        for store in stores {
2528            store.insert_quad(&default_quad).unwrap();
2529            store.insert_quad(&named_quad).unwrap();
2530
2531            let default_graph = EncodedTriplePattern {
2532                subject: None,
2533                predicate: None,
2534                object: None,
2535                graph_name: Some(EncodedTerm::DefaultGraph),
2536            };
2537            let any_graph = EncodedTriplePattern::default();
2538            assert_eq!(
2539                store
2540                    .scan_pattern(&default_graph, SnapshotId::default())
2541                    .unwrap()
2542                    .len() as u64,
2543                store
2544                    .count_pattern_best_permutation(&default_graph, SnapshotId::default(), 0)
2545                    .unwrap()
2546            );
2547            assert_eq!(
2548                store
2549                    .count_pattern_best_permutation(&default_graph, SnapshotId::default(), 0)
2550                    .unwrap(),
2551                1
2552            );
2553            assert_eq!(
2554                store
2555                    .count_pattern_best_permutation(&any_graph, SnapshotId::default(), 0)
2556                    .unwrap(),
2557                2
2558            );
2559        }
2560    }
2561
2562    #[test]
2563    fn open_with_backend_memory_ignores_path() {
2564        let store = Storage::open_with_backend(
2565            StorageBackendKind::Memory,
2566            "/unused/path",
2567            PartitionAxis::S,
2568        )
2569        .unwrap();
2570        assert_eq!(store.backend_kind(), StorageBackendKind::Memory);
2571    }
2572
2573    #[test]
2574    fn memory_flush_memtables_is_a_noop() {
2575        let store = Storage::memory(PartitionAxis::S);
2576        store.flush_memtables().unwrap();
2577    }
2578
2579    #[test]
2580    fn rocksdb_flush_memtables_writes_sst_files() {
2581        let dir = tempfile::tempdir().unwrap();
2582        let path = dir.path().join("flush");
2583        let store = Storage::open_rocksdb(&path, PartitionAxis::S).unwrap();
2584        populate(&store);
2585        store.flush_memtables().unwrap();
2586
2587        let sst_count = std::fs::read_dir(&path)
2588            .unwrap()
2589            .filter_map(Result::ok)
2590            .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "sst"))
2591            .count();
2592        assert!(
2593            sst_count > 0,
2594            "expected at least one .sst after flush_memtables under {path:?}"
2595        );
2596
2597        let rows = store
2598            .scan_pattern(&EncodedTriplePattern::default(), SnapshotId::default())
2599            .unwrap();
2600        assert_eq!(rows.len(), sample_quads().len());
2601    }
2602
2603    #[test]
2604    fn prepared_batch_puts_are_visible_on_both_backends() {
2605        let quads = sample_quads();
2606        assert!(quads.len() > 1);
2607        let encoded: Vec<_> = quads
2608            .iter()
2609            .map(|quad| encode_quad(quad).unwrap())
2610            .collect();
2611        let puts = prepare_hexastore_puts(
2612            PartitionAxis::S,
2613            encoded.iter().map(|quad| HexastoreVersion {
2614                quad,
2615                commit_ts: CommitTs(1),
2616                op: StorageOp::Put,
2617                visibility: VisibilityLabel::default(),
2618            }),
2619        );
2620        assert_eq!(puts.len(), encoded.len() * 2);
2621
2622        let dir = tempfile::tempdir().unwrap();
2623        let mut stores = [
2624            Storage::memory(PartitionAxis::S),
2625            Storage::open_rocksdb(dir.path().join("batch"), PartitionAxis::S).unwrap(),
2626        ];
2627        for store in &mut stores {
2628            store.apply_prepared_puts(&puts).unwrap();
2629            let rows = store
2630                .scan_pattern(&EncodedTriplePattern::default(), SnapshotId::latest())
2631                .unwrap();
2632            assert_eq!(rows.len(), quads.len());
2633        }
2634    }
2635
2636    #[test]
2637    fn rocksdb_bulk_tuning_roundtrips_a_scan() {
2638        let dir = tempfile::tempdir().unwrap();
2639        let store = Storage::open_rocksdb_with_hooks(
2640            dir.path().join("bulk"),
2641            PartitionAxis::S,
2642            RocksDbOptionsHooks {
2643                tuning: RocksDbTuning::bulk_ingest(true),
2644                ..Default::default()
2645            },
2646        )
2647        .unwrap();
2648        populate(&store);
2649        let rows = store
2650            .scan_pattern(&EncodedTriplePattern::default(), SnapshotId::default())
2651            .unwrap();
2652        assert_eq!(rows.len(), sample_quads().len());
2653    }
2654
2655    fn named_graph_quad() -> Quad {
2656        Quad::new(
2657            NamedNode::new("http://ex/alice").unwrap(),
2658            NamedNode::new("http://ex/livesIn").unwrap(),
2659            NamedNode::new("http://ex/brisbane").unwrap(),
2660            GraphName::NamedNode(NamedNode::new("http://ex/g1").unwrap()),
2661        )
2662    }
2663
2664    fn named_term(iri: &str) -> EncodedTerm {
2665        EncodedTerm::from(&NamedNode::new(iri).unwrap())
2666    }
2667
2668    fn assert_named_graph_catalog(store: &mut Storage) {
2669        store.insert_quad(&sample_quad()).unwrap();
2670        store
2671            .insert_quad_version(
2672                &named_graph_quad(),
2673                CommitTs(10),
2674                StorageOp::Put,
2675                VisibilityLabel::default(),
2676            )
2677            .unwrap();
2678        let listed = store.list_named_graphs(SnapshotId::latest()).unwrap();
2679        assert_eq!(listed, vec![named_term("http://ex/g1")]);
2680        assert!(
2681            !listed.contains(&EncodedTerm::DefaultGraph),
2682            "RDF default graph must never appear in the catalog"
2683        );
2684
2685        store
2686            .insert_quad_version(
2687                &named_graph_quad(),
2688                CommitTs(20),
2689                StorageOp::Put,
2690                VisibilityLabel::default(),
2691            )
2692            .unwrap();
2693        let again = store.list_named_graphs(SnapshotId::latest()).unwrap();
2694        assert_eq!(again, vec![named_term("http://ex/g1")]);
2695        let redundant = store
2696            .catalog_puts_for_insert(&[(named_term("http://ex/g1"), CommitTs(30))])
2697            .unwrap();
2698        assert!(
2699            redundant.is_empty(),
2700            "already-Present graphs must not stage another catalog version"
2701        );
2702
2703        let empty = named_term("http://ex/empty");
2704        store.add_named_graph(&empty, CommitTs(10)).unwrap();
2705        let after_add = store.list_named_graphs(SnapshotId::latest()).unwrap();
2706        assert!(after_add.contains(&named_term("http://ex/g1")));
2707        assert!(after_add.contains(&empty));
2708        let matching_spog = store
2709            .scan_pattern(
2710                &EncodedTriplePattern {
2711                    subject: None,
2712                    predicate: None,
2713                    object: None,
2714                    graph_name: Some(empty.clone()),
2715                },
2716                SnapshotId::latest(),
2717            )
2718            .unwrap();
2719        assert!(
2720            matching_spog.is_empty(),
2721            "AddNamedGraph must not insert hexastore quads"
2722        );
2723
2724        assert!(
2725            store.list_named_graphs(SnapshotId(5)).unwrap().is_empty(),
2726            "Present at ts=10 must be invisible at snapshot 5"
2727        );
2728        let at_ten = store.list_named_graphs(SnapshotId(10)).unwrap();
2729        assert!(at_ten.contains(&named_term("http://ex/g1")));
2730        assert!(at_ten.contains(&empty));
2731
2732        store
2733            .add_named_graph(&EncodedTerm::DefaultGraph, CommitTs(1))
2734            .unwrap_err();
2735
2736        let dropped = CatalogPut::new(
2737            &named_term("http://ex/recreated"),
2738            CommitTs(5),
2739            crate::GraphCatalogState::Dropped,
2740        )
2741        .unwrap();
2742        store
2743            .apply_prepared_puts_with_catalog(&[], &[dropped])
2744            .unwrap();
2745        assert!(
2746            !store
2747                .list_named_graphs(SnapshotId::latest())
2748                .unwrap()
2749                .contains(&named_term("http://ex/recreated"))
2750        );
2751        store
2752            .add_named_graph(&named_term("http://ex/recreated"), CommitTs(15))
2753            .unwrap();
2754        assert!(
2755            store
2756                .list_named_graphs(SnapshotId::latest())
2757                .unwrap()
2758                .contains(&named_term("http://ex/recreated"))
2759        );
2760    }
2761
2762    fn allow_list_label_pattern() -> EncodedTriplePattern {
2763        EncodedTriplePattern {
2764            subject: None,
2765            predicate: Some(named_term("http://ex/label")),
2766            object: None,
2767            graph_name: Some(EncodedTerm::DefaultGraph),
2768        }
2769    }
2770
2771    fn put_label(store: &mut Storage, subject: &str, object: &str) {
2772        let quad = Quad::new(
2773            NamedNode::new(subject).unwrap(),
2774            NamedNode::new("http://ex/label").unwrap(),
2775            NamedNode::new(object).unwrap(),
2776            GraphName::DefaultGraph,
2777        );
2778        store.insert_quad(&quad).unwrap();
2779    }
2780
2781    fn assert_allow_list_multi_seek(store: &mut Storage) {
2782        put_label(store, "http://ex/s1", "http://ex/o1a");
2783        put_label(store, "http://ex/s1", "http://ex/o1b");
2784        put_label(store, "http://ex/s2", "http://ex/o2");
2785        put_label(store, "http://ex/s3", "http://ex/o3");
2786        let pattern = allow_list_label_pattern();
2787        let permutation = IndexPermutation::Psog;
2788        let s1 = named_term("http://ex/s1");
2789        let s2 = named_term("http://ex/s2");
2790        let s3 = named_term("http://ex/s3");
2791        let missing = named_term("http://ex/missing");
2792
2793        let skip_middle = store
2794            .scan_pattern_page_allow_list(
2795                permutation,
2796                &pattern,
2797                SnapshotId::latest(),
2798                0,
2799                None,
2800                QuadSlot::Subject,
2801                &[s3.clone(), s1.clone(), missing.clone()],
2802                GByteFilter::Unconstrained,
2803                false,
2804                IriOnlyMask::NONE,
2805            )
2806            .unwrap()
2807            .expect("PSOG subject filter extends P");
2808        let skip_middle = skip_middle.rows;
2809        assert_eq!(
2810            skip_middle.len(),
2811            3,
2812            "s1 has two labels, s3 one, s2 skipped"
2813        );
2814        assert!(skip_middle.iter().all(|q| q.subject != s2));
2815        assert!(skip_middle.iter().any(|q| q.subject == s1));
2816        assert!(skip_middle.iter().any(|q| q.subject == s3));
2817
2818        let count = store
2819            .count_pattern_allow_list(
2820                permutation,
2821                &pattern,
2822                SnapshotId::latest(),
2823                0,
2824                QuadSlot::Subject,
2825                &[s3.clone(), s1.clone()],
2826                GByteFilter::Unconstrained,
2827                false,
2828            )
2829            .unwrap()
2830            .expect("count uses the same prefix-extend check");
2831        assert_eq!(count, 3);
2832
2833        let page1 = store
2834            .scan_pattern_page_allow_list(
2835                permutation,
2836                &pattern,
2837                SnapshotId::latest(),
2838                1,
2839                None,
2840                QuadSlot::Subject,
2841                &[s1.clone(), s3.clone()],
2842                GByteFilter::Unconstrained,
2843                false,
2844                IriOnlyMask::NONE,
2845            )
2846            .unwrap()
2847            .unwrap()
2848            .rows;
2849        assert_eq!(page1.len(), 1);
2850        let page2 = store
2851            .scan_pattern_page_allow_list(
2852                permutation,
2853                &pattern,
2854                SnapshotId::latest(),
2855                10,
2856                page1.last(),
2857                QuadSlot::Subject,
2858                &[s3.clone(), s1.clone()],
2859                GByteFilter::Unconstrained,
2860                false,
2861                IriOnlyMask::NONE,
2862            )
2863            .unwrap()
2864            .unwrap()
2865            .rows;
2866        assert_eq!(page2.len(), 2);
2867        let mut paged = page1.clone();
2868        paged.extend(page2);
2869        let all = store
2870            .scan_pattern_page_allow_list(
2871                permutation,
2872                &pattern,
2873                SnapshotId::latest(),
2874                0,
2875                None,
2876                QuadSlot::Subject,
2877                &[s1.clone(), s3.clone()],
2878                GByteFilter::Unconstrained,
2879                false,
2880                IriOnlyMask::NONE,
2881            )
2882            .unwrap()
2883            .unwrap()
2884            .rows;
2885        assert_eq!(paged, all);
2886
2887        let fallback = store
2888            .scan_pattern_page_allow_list(
2889                IndexPermutation::Posg,
2890                &pattern,
2891                SnapshotId::latest(),
2892                0,
2893                None,
2894                QuadSlot::Subject,
2895                &[s1, s3],
2896                GByteFilter::Unconstrained,
2897                false,
2898                IriOnlyMask::NONE,
2899            )
2900            .unwrap();
2901        assert!(
2902            fallback.is_none(),
2903            "POSG + unbound O cannot Seek on S as the next prefix slot"
2904        );
2905    }
2906
2907    #[test]
2908    fn memory_and_rocksdb_allow_list_multi_seek() {
2909        let dir = tempfile::tempdir().unwrap();
2910        let mut stores = [
2911            Storage::memory(PartitionAxis::P),
2912            Storage::open_rocksdb(dir.path().join("p"), PartitionAxis::P).unwrap(),
2913        ];
2914        for store in &mut stores {
2915            assert_allow_list_multi_seek(store);
2916        }
2917    }
2918
2919    /// The walk's own [`ScanExhaustion`] verdict at the three boundary
2920    /// shapes, both walks (allow-list and plain prefix), both backends:
2921    /// the server-side fact that replaces the client's short-page
2922    /// inference. The load-bearing case is the EXACT boundary — a full
2923    /// page that is also final must report the terminal verdict, not the
2924    /// conservative "maybe more" a row count alone would force.
2925    #[test]
2926    fn memory_and_rocksdb_page_verdict_boundaries() {
2927        let dir = tempfile::tempdir().unwrap();
2928        let mut stores = [
2929            Storage::memory(PartitionAxis::P),
2930            Storage::open_rocksdb(dir.path().join("p"), PartitionAxis::P).unwrap(),
2931        ];
2932        for store in &mut stores {
2933            put_label(store, "http://ex/s1", "http://ex/o1a");
2934            put_label(store, "http://ex/s1", "http://ex/o1b");
2935            put_label(store, "http://ex/s3", "http://ex/o3");
2936            let pattern = allow_list_label_pattern();
2937            let s1 = named_term("http://ex/s1");
2938            let s3 = named_term("http://ex/s3");
2939
2940            // Allow-list walk: 3 matching rows under [s1, s3].
2941            // Exact boundary — a full page that is ALSO final: the sinks
2942            // are edge-triggered (a row arriving AT the limit stops the
2943            // walk; a limit reached by data ending does not), so the walk
2944            // completed and reports the terminal verdict. This is the case
2945            // a row-count inference cannot make.
2946            let exact = store
2947                .scan_pattern_page_allow_list(
2948                    IndexPermutation::Psog,
2949                    &pattern,
2950                    SnapshotId::latest(),
2951                    3,
2952                    None,
2953                    QuadSlot::Subject,
2954                    &[s1.clone(), s3.clone()],
2955                    GByteFilter::Unconstrained,
2956                    false,
2957                    IriOnlyMask::NONE,
2958                )
2959                .unwrap()
2960                .expect("PSOG subject filter extends P");
2961            assert_eq!(exact.rows.len(), 3);
2962            assert_eq!(exact.exhausted, Some(ScanExhaustion::ExhaustedFilterTerms));
2963
2964            // Under the total: stopped at the limit, more remain.
2965            let partial = store
2966                .scan_pattern_page_allow_list(
2967                    IndexPermutation::Psog,
2968                    &pattern,
2969                    SnapshotId::latest(),
2970                    2,
2971                    None,
2972                    QuadSlot::Subject,
2973                    &[s1.clone(), s3.clone()],
2974                    GByteFilter::Unconstrained,
2975                    false,
2976                    IriOnlyMask::NONE,
2977                )
2978                .unwrap()
2979                .expect("PSOG subject filter extends P");
2980            assert_eq!(partial.rows.len(), 2);
2981            assert_eq!(partial.exhausted, Some(ScanExhaustion::Limited));
2982
2983            // Over the total: short page, list fully served.
2984            let over = store
2985                .scan_pattern_page_allow_list(
2986                    IndexPermutation::Psog,
2987                    &pattern,
2988                    SnapshotId::latest(),
2989                    10,
2990                    None,
2991                    QuadSlot::Subject,
2992                    &[s1.clone(), s3.clone()],
2993                    GByteFilter::Unconstrained,
2994                    false,
2995                    IriOnlyMask::NONE,
2996                )
2997                .unwrap()
2998                .expect("PSOG subject filter extends P");
2999            assert_eq!(over.rows.len(), 3);
3000            assert_eq!(over.exhausted, Some(ScanExhaustion::ExhaustedFilterTerms));
3001
3002            // Plain prefix walk (no allow-list): the whole pattern matches
3003            // exactly the 3 seeded rows. Exact boundary again — the
3004            // edge-triggered sink lets the walk complete, so the terminal
3005            // verdict (the walk left the key range; it never had wire
3006            // filter terms).
3007            let plain_exact = store
3008                .scan_pattern_page(
3009                    pattern.best_permutation(store.axis()),
3010                    &pattern,
3011                    SnapshotId::latest(),
3012                    3,
3013                    None,
3014                    GByteFilter::Unconstrained,
3015                    false,
3016                    IriOnlyMask::NONE,
3017                )
3018                .unwrap();
3019            assert_eq!(plain_exact.rows.len(), 3);
3020            assert_eq!(plain_exact.exhausted, Some(ScanExhaustion::ExhaustedScan));
3021
3022            let plain_partial = store
3023                .scan_pattern_page(
3024                    pattern.best_permutation(store.axis()),
3025                    &pattern,
3026                    SnapshotId::latest(),
3027                    2,
3028                    None,
3029                    GByteFilter::Unconstrained,
3030                    false,
3031                    IriOnlyMask::NONE,
3032                )
3033                .unwrap();
3034            assert_eq!(plain_partial.rows.len(), 2);
3035            assert_eq!(plain_partial.exhausted, Some(ScanExhaustion::Limited));
3036        }
3037    }
3038
3039    #[test]
3040    fn memory_and_rocksdb_named_graph_catalog() {
3041        let dir = tempfile::tempdir().unwrap();
3042        let mut stores = [
3043            Storage::memory(PartitionAxis::S),
3044            Storage::open_rocksdb(dir.path().join("catalog"), PartitionAxis::S).unwrap(),
3045        ];
3046        for store in &mut stores {
3047            assert_named_graph_catalog(store);
3048        }
3049    }
3050
3051    #[test]
3052    fn named_graph_catalog_is_s_axis_only() {
3053        let dir = tempfile::tempdir().unwrap();
3054        for axis in [PartitionAxis::P, PartitionAxis::O] {
3055            let stores = [
3056                Storage::memory(axis),
3057                Storage::open_rocksdb(dir.path().join(axis.as_str()), axis).unwrap(),
3058            ];
3059            for store in stores {
3060                let list_err = store.list_named_graphs(SnapshotId::latest()).unwrap_err();
3061                assert!(matches!(
3062                    list_err,
3063                    StorageError::CatalogNotOnAxis(a) if a == axis
3064                ));
3065                let add_err = store
3066                    .add_named_graph(&named_term("http://ex/g"), CommitTs(1))
3067                    .unwrap_err();
3068                assert!(matches!(
3069                    add_err,
3070                    StorageError::CatalogNotOnAxis(a) if a == axis
3071                ));
3072            }
3073        }
3074    }
3075
3076    #[test]
3077    fn rebuild_catalog_from_spog_skips_default_graph_and_is_idempotent() {
3078        let dir = tempfile::tempdir().unwrap();
3079        let mut stores = [
3080            Storage::memory(PartitionAxis::S),
3081            Storage::open_rocksdb(dir.path().join("rebuild"), PartitionAxis::S).unwrap(),
3082        ];
3083        let encoded_named = encode_quad(&named_graph_quad()).unwrap();
3084        let encoded_default = encode_quad(&sample_quad()).unwrap();
3085        let puts = prepare_hexastore_puts(
3086            PartitionAxis::S,
3087            [
3088                HexastoreVersion {
3089                    quad: &encoded_named,
3090                    commit_ts: CommitTs(7),
3091                    op: StorageOp::Put,
3092                    visibility: VisibilityLabel::default(),
3093                },
3094                HexastoreVersion {
3095                    quad: &encoded_default,
3096                    commit_ts: CommitTs(7),
3097                    op: StorageOp::Put,
3098                    visibility: VisibilityLabel::default(),
3099                },
3100            ],
3101        );
3102        for store in &mut stores {
3103            store.apply_prepared_puts(&puts).unwrap();
3104            assert!(
3105                store
3106                    .list_named_graphs(SnapshotId::latest())
3107                    .unwrap()
3108                    .is_empty(),
3109                "apply_prepared_puts must not populate the catalog"
3110            );
3111            let first = store.rebuild_named_graph_catalog().unwrap();
3112            assert_eq!(first.graphs_inserted, 1);
3113            assert_eq!(first.graphs_skipped, 0);
3114            assert_eq!(
3115                store.list_named_graphs(SnapshotId::latest()).unwrap(),
3116                vec![named_term("http://ex/g1")]
3117            );
3118            let second = store.rebuild_named_graph_catalog().unwrap();
3119            assert_eq!(second.graphs_inserted, 0);
3120            assert_eq!(second.graphs_skipped, 1);
3121        }
3122    }
3123
3124    // ---- PredicateDomain (POSG skip-scan) --------------------------------
3125
3126    /// Domain tests run on both backends: two predicates, three objects each,
3127    /// plus a named-graph and an MVCC versioning batch.
3128    fn domain_fixture(store: &mut Storage) {
3129        let put = |store: &mut Storage, quad: &Quad| {
3130            store.insert_quad(quad).unwrap();
3131        };
3132        for predicate in ["p1", "p2"] {
3133            for i in 0..3 {
3134                put(
3135                    store,
3136                    &Quad::new(
3137                        NamedNode::new(format!("http://ex/s{i}")).unwrap(),
3138                        NamedNode::new(format!("http://ex/{predicate}")).unwrap(),
3139                        Literal::from(format!("o{i}")),
3140                        GraphName::DefaultGraph,
3141                    ),
3142                );
3143            }
3144        }
3145        // Named-graph duplicate of (p1, o0): unconstrained scans must still
3146        // emit that object.
3147        put(
3148            store,
3149            &Quad::new(
3150                NamedNode::new("http://ex/s0").unwrap(),
3151                NamedNode::new("http://ex/p1").unwrap(),
3152                Literal::from("o0"),
3153                GraphName::from(NamedNode::new("http://ex/g1").unwrap()),
3154            ),
3155        );
3156    }
3157
3158    fn iri(local: &str) -> EncodedTerm {
3159        EncodedTerm::from(&NamedNode::new(format!("http://ex/{local}")).unwrap())
3160    }
3161
3162    fn literal(text: &str) -> EncodedTerm {
3163        EncodedTerm::from(&Literal::from(text))
3164    }
3165
3166    fn predicate() -> EncodedTerm {
3167        iri("p")
3168    }
3169
3170    fn hits_for(store: &Storage, predicates: &[EncodedTerm]) -> Vec<DomainScanHit> {
3171        store
3172            .scan_predicate_domain(
3173                predicates,
3174                SnapshotId::default(),
3175                0,
3176                None,
3177                None,
3178                None,
3179                &[],
3180                false,
3181            )
3182            .unwrap()
3183    }
3184
3185    fn by_encoded_bytes(terms: &mut [EncodedTerm]) {
3186        terms.sort_by_cached_key(crate::encode_term_bytes);
3187    }
3188
3189    #[test]
3190    fn object_subject_resolve_walks_opsg_with_scan_visibility_and_scope() {
3191        // s1 has "alpha" under two predicates (the per-predicate split), s3's
3192        // "alpha" row is deleted at 20, and s4's "beta" lives in a named
3193        // graph. At snapshot 25 in the default-graph window the resolve must
3194        // return s1 once (deduped across predicates) and s2 — never s3 (the
3195        // delete) or s4 (the wrong graph).
3196        let dir = tempfile::tempdir().unwrap();
3197        let stores = vec![
3198            Storage::memory(PartitionAxis::O),
3199            Storage::open_rocksdb(dir.path().join("subject-resolve"), PartitionAxis::O).unwrap(),
3200        ];
3201        let quad = |s: &str, p: &str, o: &str, graph: GraphName| {
3202            Quad::new(
3203                NamedNode::new(format!("http://ex/{s}")).unwrap(),
3204                NamedNode::new(format!("http://ex/{p}")).unwrap(),
3205                Literal::from(o),
3206                graph,
3207            )
3208        };
3209        let named = GraphName::from(NamedNode::new("http://ex/gx").unwrap());
3210        for store in &stores {
3211            let put = |s: &str, p: &str, o: &str, graph: GraphName, ts: u64, op: StorageOp| {
3212                store
3213                    .insert_quad_version(
3214                        &quad(s, p, o, graph),
3215                        CommitTs(ts),
3216                        op,
3217                        VisibilityLabel::default(),
3218                    )
3219                    .unwrap();
3220            };
3221            put(
3222                "s1",
3223                "p1",
3224                "alpha",
3225                GraphName::DefaultGraph,
3226                10,
3227                StorageOp::Put,
3228            );
3229            put(
3230                "s1",
3231                "p2",
3232                "alpha",
3233                GraphName::DefaultGraph,
3234                10,
3235                StorageOp::Put,
3236            );
3237            put(
3238                "s2",
3239                "p1",
3240                "beta",
3241                GraphName::DefaultGraph,
3242                10,
3243                StorageOp::Put,
3244            );
3245            put(
3246                "s3",
3247                "p1",
3248                "alpha",
3249                GraphName::DefaultGraph,
3250                10,
3251                StorageOp::Put,
3252            );
3253            put("s4", "p1", "beta", named.clone(), 10, StorageOp::Put);
3254            put(
3255                "s5",
3256                "p3",
3257                "alpha",
3258                GraphName::DefaultGraph,
3259                10,
3260                StorageOp::Put,
3261            );
3262            put(
3263                "s3",
3264                "p1",
3265                "alpha",
3266                GraphName::DefaultGraph,
3267                20,
3268                StorageOp::Delete,
3269            );
3270
3271            let mut objects = vec![literal("alpha"), literal("beta")];
3272            by_encoded_bytes(&mut objects);
3273            let mut predicates = vec![iri("p1"), iri("p2")];
3274            by_encoded_bytes(&mut predicates);
3275
3276            let collect = |graph_name: Option<&EncodedTerm>, predicates: &[EncodedTerm]| {
3277                let mut rows: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
3278                store
3279                    .visit_object_subjects(
3280                        &objects,
3281                        predicates,
3282                        SnapshotId(25),
3283                        graph_name,
3284                        &GByteFilter::Unconstrained,
3285                        false,
3286                        |subject, graph| {
3287                            rows.push((
3288                                crate::encode_term_bytes(subject),
3289                                crate::encode_term_bytes(graph),
3290                            ));
3291                            Ok(true)
3292                        },
3293                    )
3294                    .unwrap();
3295                rows
3296            };
3297
3298            // Default-graph window: s1 via both predicates (two raw rows) and
3299            // s2 via p1; s3 is deleted, s4 is in another graph.
3300            let rows = collect(Some(&EncodedTerm::DefaultGraph), &predicates);
3301            assert_eq!(rows.len(), 3, "s1 via p1 and p2, s2 via p1");
3302            let distinct: std::collections::BTreeSet<_> = rows.into_iter().collect();
3303            let expected: std::collections::BTreeSet<_> = [
3304                (iri("s1"), EncodedTerm::DefaultGraph),
3305                (iri("s2"), EncodedTerm::DefaultGraph),
3306            ]
3307            .iter()
3308            .map(|(subject, graph)| {
3309                (
3310                    crate::encode_term_bytes(subject),
3311                    crate::encode_term_bytes(graph),
3312                )
3313            })
3314            .collect();
3315            assert_eq!(distinct, expected);
3316
3317            // The per-predicate split: p1 alone drops s1's p2 row.
3318            let only_p1 = collect(Some(&EncodedTerm::DefaultGraph), &[iri("p1")]);
3319            assert_eq!(only_p1.len(), 2, "s1 via p1 and s2, not s1's p2 row");
3320
3321            // No predicate filter: the object's whole OPSG range, so s5's p3
3322            // row is included while the explicit {p1, p2} list excluded it.
3323            let unfiltered = collect(Some(&EncodedTerm::DefaultGraph), &[]);
3324            assert_eq!(unfiltered.len(), 4, "s1 twice, s2, and s5 via p3");
3325
3326            // An unconstrained graph scope also resolves s4's named-graph row.
3327            let all_graphs = collect(None, &predicates);
3328            assert!(
3329                all_graphs
3330                    .iter()
3331                    .any(|(subject, _)| *subject == crate::encode_term_bytes(&iri("s4"))),
3332                "the named-graph row is visible without the default-graph window"
3333            );
3334
3335            // A merge-default walk rewrites the graph column to DefaultGraph,
3336            // exactly as the page API did before this became a streaming walk.
3337            let mut merged: Vec<Vec<u8>> = Vec::new();
3338            store
3339                .visit_object_subjects(
3340                    &objects,
3341                    &predicates,
3342                    SnapshotId(25),
3343                    None,
3344                    &GByteFilter::Unconstrained,
3345                    true,
3346                    |subject, graph| {
3347                        if subject == &iri("s4") {
3348                            merged.push(crate::encode_term_bytes(graph));
3349                        }
3350                        Ok(true)
3351                    },
3352                )
3353                .unwrap();
3354            assert_eq!(
3355                merged,
3356                vec![crate::encode_term_bytes(&EncodedTerm::DefaultGraph)],
3357                "a merge-default walk rewrites the graph column"
3358            );
3359
3360            // Before the delete, s3 is visible too.
3361            let mut before: Vec<Vec<u8>> = Vec::new();
3362            store
3363                .visit_object_subjects(
3364                    &objects,
3365                    &predicates,
3366                    SnapshotId(15),
3367                    Some(&EncodedTerm::DefaultGraph),
3368                    &GByteFilter::Unconstrained,
3369                    false,
3370                    |subject, _graph| {
3371                        before.push(crate::encode_term_bytes(subject));
3372                        Ok(true)
3373                    },
3374                )
3375                .unwrap();
3376            assert!(before.contains(&crate::encode_term_bytes(&iri("s3"))));
3377
3378            // Early stop: the closure's false ends the walk after one row.
3379            let mut seen = 0usize;
3380            store
3381                .visit_object_subjects(
3382                    &objects,
3383                    &predicates,
3384                    SnapshotId(25),
3385                    Some(&EncodedTerm::DefaultGraph),
3386                    &GByteFilter::Unconstrained,
3387                    false,
3388                    |_subject, _graph| {
3389                        seen += 1;
3390                        Ok(false)
3391                    },
3392                )
3393                .unwrap();
3394            assert_eq!(seen, 1);
3395        }
3396    }
3397
3398    #[test]
3399    fn domain_scan_two_predicates_paging_and_resume() {
3400        for axis in [PartitionAxis::P] {
3401            let dir = tempfile::tempdir().unwrap();
3402            let rocks = Storage::open_rocksdb(dir.path().join("domain"), axis).unwrap();
3403            let mut stores = [Storage::memory(axis), rocks];
3404            for store in &mut stores {
3405                domain_fixture(store);
3406                let p1 = iri("p1");
3407                let p2 = iri("p2");
3408                let hits = hits_for(store, &[p1.clone(), p2.clone()]);
3409                assert_eq!(hits.len(), 6);
3410                // Emission order is key order in every mode and backend
3411                // (StrHash order puts p2's prefix *before* p1's — see the
3412                // resume case below). Assert the content per constraint;
3413                // the rocksdb suite pins the exact order.
3414                for constraint in [&p1, &p2] {
3415                    let mut terms: Vec<EncodedTerm> = hits
3416                        .iter()
3417                        .filter(|hit| &hit.constraint == constraint)
3418                        .map(|hit| hit.term.clone())
3419                        .collect();
3420                    terms.sort_by_key(encode_term_bytes);
3421                    assert_eq!(terms, vec![literal("o0"), literal("o1"), literal("o2")]);
3422                }
3423                // Resume after (p1, o1): only p1/o2. Encoded StrHash order
3424                // puts p2's prefix *before* p1's, and the walk visits
3425                // constraints in key order, so p2 was fully emitted before
3426                // the cursor — skipping it is sound.
3427                let hits = store
3428                    .scan_predicate_domain(
3429                        &[p1.clone(), p2.clone()],
3430                        SnapshotId::default(),
3431                        0,
3432                        Some(&p1),
3433                        Some(&literal("o1")),
3434                        None,
3435                        &[],
3436                        false,
3437                    )
3438                    .unwrap();
3439                assert_eq!(hits.len(), 1);
3440                assert_eq!(hits[0].constraint, p1);
3441                assert_eq!(hits[0].term, literal("o2"));
3442                // Limit across the predicate list.
3443                let hits = store
3444                    .scan_predicate_domain(
3445                        &[p1, p2],
3446                        SnapshotId::default(),
3447                        4,
3448                        None,
3449                        None,
3450                        None,
3451                        &[],
3452                        false,
3453                    )
3454                    .unwrap();
3455                assert_eq!(hits.len(), 4);
3456            }
3457        }
3458    }
3459
3460    #[test]
3461    fn domain_scan_named_graph_unconstrained_vs_default_graph() {
3462        let dir = tempfile::tempdir().unwrap();
3463        let mut stores = vec![Storage::memory(PartitionAxis::P)];
3464        stores.push(Storage::open_rocksdb(dir.path().join("domain"), PartitionAxis::P).unwrap());
3465        for store in &mut stores {
3466            let p = iri("p");
3467            let g = iri("g");
3468            let put = |store: &mut Storage, object: &str, graph: GraphName| {
3469                store
3470                    .insert_quad(&Quad::new(
3471                        NamedNode::new("http://ex/s").unwrap(),
3472                        NamedNode::new("http://ex/p").unwrap(),
3473                        Literal::from(object),
3474                        graph,
3475                    ))
3476                    .unwrap();
3477            };
3478            // o-default in the default graph; o-named only in the named graph.
3479            put(store, "o-default", GraphName::DefaultGraph);
3480            put(
3481                store,
3482                "o-named",
3483                GraphName::from(NamedNode::new("http://ex/g").unwrap()),
3484            );
3485
3486            // Path 1: unconstrained (empty block-list, graph_name unset) —
3487            // both objects emit; G is never decoded or membership-checked.
3488            assert_eq!(hits_for(store, std::slice::from_ref(&p)).len(), 2);
3489
3490            // Path 2: bound DefaultGraph — existence loop, only the default
3491            // graph's object.
3492            let hits = store
3493                .scan_predicate_domain(
3494                    std::slice::from_ref(&p),
3495                    SnapshotId::default(),
3496                    0,
3497                    None,
3498                    None,
3499                    Some(&EncodedTerm::DefaultGraph),
3500                    &[],
3501                    false,
3502                )
3503                .unwrap();
3504            assert_eq!(hits.len(), 1);
3505            assert_eq!(hits[0].term, literal("o-default"));
3506
3507            // Path 2: `FROM <g>` — only the named graph's object.
3508            let hits = store
3509                .scan_predicate_domain(
3510                    std::slice::from_ref(&p),
3511                    SnapshotId::default(),
3512                    0,
3513                    None,
3514                    None,
3515                    Some(&g),
3516                    &[],
3517                    false,
3518                )
3519                .unwrap();
3520            assert_eq!(hits.len(), 1);
3521            assert_eq!(hits[0].term, literal("o-named"));
3522
3523            // Path 2: empty allow-list allows nothing.
3524            let hits = store
3525                .scan_predicate_domain(&[p], SnapshotId::default(), 0, None, None, None, &[], true)
3526                .unwrap();
3527            assert!(hits.is_empty());
3528        }
3529    }
3530
3531    #[test]
3532    fn domain_scan_mvcc_delete_shadows_put_but_not_sibling_subjects() {
3533        let dir = tempfile::tempdir().unwrap();
3534        let mut stores = vec![Storage::memory(PartitionAxis::P)];
3535        stores.push(Storage::open_rocksdb(dir.path().join("domain"), PartitionAxis::P).unwrap());
3536        let p = predicate();
3537        for store in &mut stores {
3538            let quad = |s: &str, o: &str| {
3539                Quad::new(
3540                    NamedNode::new(format!("http://ex/{s}")).unwrap(),
3541                    NamedNode::new("http://ex/p").unwrap(),
3542                    Literal::from(o),
3543                    GraphName::DefaultGraph,
3544                )
3545            };
3546            store
3547                .insert_quad_version(
3548                    &quad("a", "o1"),
3549                    CommitTs(10),
3550                    StorageOp::Put,
3551                    VisibilityLabel::default(),
3552                )
3553                .unwrap();
3554            store
3555                .insert_quad_version(
3556                    &quad("b", "o2"),
3557                    CommitTs(10),
3558                    StorageOp::Put,
3559                    VisibilityLabel::default(),
3560                )
3561                .unwrap();
3562            // Delete (a, p, o1) at 20, re-put (b, p, o2) at 20.
3563            store
3564                .insert_quad_version(
3565                    &quad("a", "o1"),
3566                    CommitTs(20),
3567                    StorageOp::Delete,
3568                    VisibilityLabel::default(),
3569                )
3570                .unwrap();
3571            store
3572                .insert_quad_version(
3573                    &quad("b", "o2"),
3574                    CommitTs(20),
3575                    StorageOp::Delete,
3576                    VisibilityLabel::default(),
3577                )
3578                .unwrap();
3579            store
3580                .insert_quad_version(
3581                    &quad("b", "o2"),
3582                    CommitTs(30),
3583                    StorageOp::Put,
3584                    VisibilityLabel::default(),
3585                )
3586                .unwrap();
3587
3588            // Snapshot 15: both objects visible.
3589            let hits = store
3590                .scan_predicate_domain(
3591                    std::slice::from_ref(&p),
3592                    SnapshotId(15),
3593                    0,
3594                    None,
3595                    None,
3596                    None,
3597                    &[],
3598                    false,
3599                )
3600                .unwrap();
3601            assert_eq!(hits.len(), 2);
3602            // Snapshot 25: o1 deleted, o2 hidden by its Delete at 20.
3603            let hits = store
3604                .scan_predicate_domain(
3605                    std::slice::from_ref(&p),
3606                    SnapshotId(25),
3607                    0,
3608                    None,
3609                    None,
3610                    None,
3611                    &[],
3612                    false,
3613                )
3614                .unwrap();
3615            assert!(hits.is_empty());
3616            // Snapshot 35: o2 re-Put visible, o1 still deleted.
3617            let hits = store
3618                .scan_predicate_domain(
3619                    std::slice::from_ref(&p),
3620                    SnapshotId(35),
3621                    0,
3622                    None,
3623                    None,
3624                    None,
3625                    &[],
3626                    false,
3627                )
3628                .unwrap();
3629            assert_eq!(hits.len(), 1);
3630            assert_eq!(hits[0].term, literal("o2"));
3631        }
3632    }
3633
3634    #[test]
3635    fn domain_scan_byte_successor_overflow_and_named_node_predicates() {
3636        // Trailing 0xFF carries into the prefix ([0x01,0xFF] -> [0x02,0x00]).
3637        assert_eq!(crate::byte_successor(&[0x01, 0xFF]), Some(vec![0x02, 0x00]));
3638        assert_eq!(crate::byte_successor(&[0xFF, 0xFF]), None);
3639
3640        let store = Storage::memory(PartitionAxis::P);
3641        // Non-NamedNode predicates are rejected before any scan.
3642        let error = store
3643            .scan_predicate_domain(
3644                &[literal("not-an-iri")],
3645                SnapshotId::default(),
3646                0,
3647                None,
3648                None,
3649                None,
3650                &[],
3651                false,
3652            )
3653            .unwrap_err();
3654        assert!(matches!(error, StorageError::Corrupt(_)));
3655        // Empty predicate list is trivially empty hits.
3656        assert!(hits_for(&store, &[]).is_empty());
3657    }
3658
3659    // ---- Axis head scans (bare) + generalized domain scans ---------------
3660    /// A quad with a subject, predicate, and object, and a default graph name.
3661    /// Used for testing only, for testing the TSG index.
3662    fn rdf_type_quad(subject: &str, class: &str) -> Quad {
3663        Quad::new(
3664            NamedNode::new(format!("http://ex/{subject}")).unwrap(),
3665            NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap(),
3666            NamedNode::new(format!("http://ex/{class}")).unwrap(),
3667            GraphName::DefaultGraph,
3668        )
3669    }
3670
3671    /// Distinct-count helper: maps terms 1:1 (length is preserved) so tests
3672    /// can count distinct heads without depending on term ordering.
3673    /// Used for testing only.
3674    fn term_set(terms: Vec<EncodedTerm>) -> Vec<String> {
3675        terms.iter().map(|t| format!("{t:?}")).collect()
3676    }
3677
3678    #[test]
3679    fn axis_head_scans_return_distinct_heads_per_index() {
3680        // S axis: subjects / per-subject predicates / per-subject objects.
3681        let dir = tempfile::tempdir().unwrap();
3682        let mut stores = vec![Storage::memory(PartitionAxis::S)];
3683        stores.push(Storage::open_rocksdb(dir.path().join("heads_s"), PartitionAxis::S).unwrap());
3684        for store in &mut stores {
3685            for (s, p, o) in [("s1", "p1", "o1"), ("s1", "p1", "o2"), ("s2", "p2", "o1")] {
3686                store
3687                    .insert_quad(&Quad::new(
3688                        NamedNode::new(format!("http://ex/{s}")).unwrap(),
3689                        NamedNode::new(format!("http://ex/{p}")).unwrap(),
3690                        Literal::from(o),
3691                        GraphName::DefaultGraph,
3692                    ))
3693                    .unwrap();
3694            }
3695            // Long IRI (> 15 bytes) is hash-reduced; still one distinct head.
3696            store
3697                .insert_quad(&Quad::new(
3698                    NamedNode::new("http://ex/very-long-subject-identifier").unwrap(),
3699                    NamedNode::new("http://ex/p1").unwrap(),
3700                    Literal::from("o1"),
3701                    GraphName::DefaultGraph,
3702                ))
3703                .unwrap();
3704
3705            let subjects = store
3706                .scan_subjects(SnapshotId::default(), 0, None, None, &[], false)
3707                .unwrap();
3708            assert_eq!(term_set(subjects).len(), 3, "three distinct subjects");
3709
3710            let preds = store
3711                .scan_subject_preds(
3712                    &[iri("s1")],
3713                    SnapshotId::default(),
3714                    0,
3715                    None,
3716                    None,
3717                    None,
3718                    &[],
3719                    false,
3720                )
3721                .unwrap();
3722            assert_eq!(preds.len(), 1);
3723            assert_eq!(preds[0].constraint, iri("s1"));
3724            assert_eq!(preds[0].term, iri("p1"));
3725
3726            let both = store
3727                .scan_subject_preds(
3728                    &[iri("s1"), iri("s2"), iri("s1")],
3729                    SnapshotId::default(),
3730                    0,
3731                    None,
3732                    None,
3733                    None,
3734                    &[],
3735                    false,
3736                )
3737                .unwrap();
3738            // Duplicate constraint is deduped; s2 contributes p2.
3739            assert_eq!(both.len(), 2);
3740            let terms: Vec<&EncodedTerm> = both.iter().map(|h| &h.term).collect();
3741            assert!(terms.contains(&&iri("p1")));
3742            assert!(terms.contains(&&iri("p2")));
3743
3744            let objects = store
3745                .scan_subject_domain(
3746                    &[iri("s1")],
3747                    SnapshotId::default(),
3748                    0,
3749                    None,
3750                    None,
3751                    None,
3752                    &[],
3753                    false,
3754                )
3755                .unwrap();
3756            assert_eq!(objects.len(), 2, "s1 has two distinct objects");
3757        }
3758
3759        // P axis: distinct predicates of the whole PSOG index.
3760        let dir = tempfile::tempdir().unwrap();
3761        let mut stores = vec![Storage::memory(PartitionAxis::P)];
3762        stores.push(Storage::open_rocksdb(dir.path().join("heads_p"), PartitionAxis::P).unwrap());
3763        for store in &mut stores {
3764            for (p, o) in [("p1", "o1"), ("p2", "o2"), ("p1", "o2")] {
3765                store
3766                    .insert_quad(&Quad::new(
3767                        NamedNode::new("http://ex/s").unwrap(),
3768                        NamedNode::new(format!("http://ex/{p}")).unwrap(),
3769                        Literal::from(o),
3770                        GraphName::DefaultGraph,
3771                    ))
3772                    .unwrap();
3773            }
3774            let preds = store
3775                .scan_predicates(SnapshotId::default(), 0, None, None, &[], false)
3776                .unwrap();
3777            assert_eq!(preds.len(), 2);
3778        }
3779
3780        // O axis: distinct objects (OPSG) and distinct classes (TSG).
3781        let dir = tempfile::tempdir().unwrap();
3782        let mut stores = vec![Storage::memory(PartitionAxis::O)];
3783        stores.push(Storage::open_rocksdb(dir.path().join("heads_o"), PartitionAxis::O).unwrap());
3784        for store in &mut stores {
3785            for (s, o) in [("i1", "C1"), ("i2", "C1"), ("i3", "C2")] {
3786                store.insert_quad(&rdf_type_quad(s, o)).unwrap();
3787            }
3788            store
3789                .insert_quad(&Quad::new(
3790                    NamedNode::new("http://ex/i1").unwrap(),
3791                    NamedNode::new("http://ex/label").unwrap(),
3792                    Literal::from("text"),
3793                    GraphName::DefaultGraph,
3794                ))
3795                .unwrap();
3796
3797            let objects = store
3798                .scan_objects(SnapshotId::default(), 0, None, None, &[], false)
3799                .unwrap();
3800            // C1, C2 (typed) + the label literal.
3801            assert_eq!(objects.len(), 3);
3802
3803            let classes = store
3804                .scan_classes(SnapshotId::default(), 0, None, None, &[], false)
3805                .unwrap();
3806            assert_eq!(classes.len(), 2, "TSG walks only rdf:type objects");
3807            assert_eq!(term_set(classes).len(), 2);
3808
3809            let preds = store
3810                .scan_object_preds(
3811                    &[EncodedTerm::from(&NamedNode::new("http://ex/C1").unwrap())],
3812                    SnapshotId::default(),
3813                    0,
3814                    None,
3815                    None,
3816                    None,
3817                    &[],
3818                    false,
3819                )
3820                .unwrap();
3821            assert_eq!(preds.len(), 1);
3822            let rdf_type = EncodedTerm::from(
3823                &NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap(),
3824            );
3825            assert_eq!(preds[0].term, rdf_type, "only rdf:type points at C1");
3826        }
3827    }
3828
3829    #[test]
3830    fn axis_head_scan_paging_and_resume() {
3831        let dir = tempfile::tempdir().unwrap();
3832        let mut stores = vec![Storage::memory(PartitionAxis::S)];
3833        stores.push(Storage::open_rocksdb(dir.path().join("head_page"), PartitionAxis::S).unwrap());
3834        for store in &mut stores {
3835            for s in ["a", "b", "c"] {
3836                store
3837                    .insert_quad(&Quad::new(
3838                        NamedNode::new(format!("http://ex/{s}")).unwrap(),
3839                        NamedNode::new("http://ex/p").unwrap(),
3840                        Literal::from("o"),
3841                        GraphName::DefaultGraph,
3842                    ))
3843                    .unwrap();
3844            }
3845            // Page of two, then resume past the last emitted term.
3846            let page = store
3847                .scan_subjects(SnapshotId::default(), 2, None, None, &[], false)
3848                .unwrap();
3849            assert_eq!(page.len(), 2);
3850            let rest = store
3851                .scan_subjects(SnapshotId::default(), 0, page.last(), None, &[], false)
3852                .unwrap();
3853            assert_eq!(rest.len(), 1);
3854
3855            // Domain resume: (subject, predicate) exclusive cursor skips the
3856            // pair itself and everything before it.
3857            let page = store
3858                .scan_subject_preds(
3859                    &[iri("a"), iri("b")],
3860                    SnapshotId::default(),
3861                    1,
3862                    None,
3863                    None,
3864                    None,
3865                    &[],
3866                    false,
3867                )
3868                .unwrap();
3869            assert_eq!(page.len(), 1);
3870            let rest = store
3871                .scan_subject_preds(
3872                    &[iri("a"), iri("b")],
3873                    SnapshotId::default(),
3874                    0,
3875                    Some(&page[0].constraint),
3876                    Some(&page[0].term),
3877                    None,
3878                    &[],
3879                    false,
3880                )
3881                .unwrap();
3882            assert_eq!(rest.len(), 1);
3883            assert_ne!(
3884                rest[0].constraint, page[0].constraint,
3885                "the cursor pair's constraint is fully drained"
3886            );
3887        }
3888    }
3889
3890    #[test]
3891    fn axis_head_scan_named_graph_windows() {
3892        let dir = tempfile::tempdir().unwrap();
3893        let mut stores = vec![Storage::memory(PartitionAxis::S)];
3894        stores.push(Storage::open_rocksdb(dir.path().join("head_g"), PartitionAxis::S).unwrap());
3895        for store in &mut stores {
3896            // s-default in the default graph; s-named only in a named graph.
3897            store
3898                .insert_quad(&Quad::new(
3899                    NamedNode::new("http://ex/s-default").unwrap(),
3900                    NamedNode::new("http://ex/p").unwrap(),
3901                    Literal::from("o"),
3902                    GraphName::DefaultGraph,
3903                ))
3904                .unwrap();
3905            store
3906                .insert_quad(&Quad::new(
3907                    NamedNode::new("http://ex/s-named").unwrap(),
3908                    NamedNode::new("http://ex/p").unwrap(),
3909                    Literal::from("o"),
3910                    GraphName::from(NamedNode::new("http://ex/g").unwrap()),
3911                ))
3912                .unwrap();
3913
3914            // Unconstrained: any graph owns the head term.
3915            let all = store
3916                .scan_subjects(SnapshotId::default(), 0, None, None, &[], false)
3917                .unwrap();
3918            assert_eq!(all.len(), 2);
3919            // Bound default graph.
3920            let default_only = store
3921                .scan_subjects(
3922                    SnapshotId::default(),
3923                    0,
3924                    None,
3925                    Some(&EncodedTerm::DefaultGraph),
3926                    &[],
3927                    false,
3928                )
3929                .unwrap();
3930            assert_eq!(default_only.len(), 1);
3931            // `FROM <g>`: bound graph_name over an empty block-list.
3932            let named_only = store
3933                .scan_subjects(SnapshotId::default(), 0, None, Some(&iri("g")), &[], false)
3934                .unwrap();
3935            assert_eq!(named_only.len(), 1);
3936            let none = store
3937                .scan_subjects(SnapshotId::default(), 0, None, None, &[], true)
3938                .unwrap();
3939            assert!(none.is_empty());
3940
3941            // Domain scans take the same window.
3942            let constrained = store
3943                .scan_subject_domain(
3944                    &[iri("s-default"), iri("s-named")],
3945                    SnapshotId::default(),
3946                    0,
3947                    None,
3948                    None,
3949                    Some(&EncodedTerm::DefaultGraph),
3950                    &[],
3951                    false,
3952                )
3953                .unwrap();
3954            assert_eq!(constrained.len(), 1);
3955            assert_eq!(constrained[0].constraint, iri("s-default"));
3956        }
3957    }
3958
3959    #[test]
3960    fn axis_head_scan_mvcc_delete_shadows_heads() {
3961        let dir = tempfile::tempdir().unwrap();
3962        let mut stores = vec![Storage::memory(PartitionAxis::S)];
3963        stores.push(Storage::open_rocksdb(dir.path().join("head_mvcc"), PartitionAxis::S).unwrap());
3964        for store in &mut stores {
3965            let quad = |s: &str| {
3966                Quad::new(
3967                    NamedNode::new(format!("http://ex/{s}")).unwrap(),
3968                    NamedNode::new("http://ex/p").unwrap(),
3969                    Literal::from("o"),
3970                    GraphName::DefaultGraph,
3971                )
3972            };
3973            store
3974                .insert_quad_version(
3975                    &quad("a"),
3976                    CommitTs(10),
3977                    StorageOp::Put,
3978                    VisibilityLabel::default(),
3979                )
3980                .unwrap();
3981            store
3982                .insert_quad_version(
3983                    &quad("b"),
3984                    CommitTs(10),
3985                    StorageOp::Put,
3986                    VisibilityLabel::default(),
3987                )
3988                .unwrap();
3989            store
3990                .insert_quad_version(
3991                    &quad("a"),
3992                    CommitTs(20),
3993                    StorageOp::Delete,
3994                    VisibilityLabel::default(),
3995                )
3996                .unwrap();
3997            store
3998                .insert_quad_version(
3999                    &quad("b"),
4000                    CommitTs(20),
4001                    StorageOp::Delete,
4002                    VisibilityLabel::default(),
4003                )
4004                .unwrap();
4005            store
4006                .insert_quad_version(
4007                    &quad("b"),
4008                    CommitTs(30),
4009                    StorageOp::Put,
4010                    VisibilityLabel::default(),
4011                )
4012                .unwrap();
4013
4014            let subjects_at = |snapshot: SnapshotId| {
4015                store
4016                    .scan_subjects(snapshot, 0, None, None, &[], false)
4017                    .unwrap()
4018                    .len()
4019            };
4020            assert_eq!(subjects_at(SnapshotId(15)), 2);
4021            // Snapshot 25: both visible candidates are Deletes — no subject.
4022            assert_eq!(subjects_at(SnapshotId(25)), 0);
4023            assert_eq!(subjects_at(SnapshotId(35)), 1);
4024
4025            // Domain side: a's only quad is deleted at 25, b's is back at 35.
4026            let preds = store
4027                .scan_subject_preds(
4028                    &[iri("a"), iri("b")],
4029                    SnapshotId(25),
4030                    0,
4031                    None,
4032                    None,
4033                    None,
4034                    &[],
4035                    false,
4036                )
4037                .unwrap();
4038            assert!(preds.is_empty());
4039            let preds = store
4040                .scan_subject_preds(
4041                    &[iri("a"), iri("b")],
4042                    SnapshotId(35),
4043                    0,
4044                    None,
4045                    None,
4046                    None,
4047                    &[],
4048                    false,
4049                )
4050                .unwrap();
4051            assert_eq!(preds.len(), 1);
4052            assert_eq!(preds[0].constraint, iri("b"));
4053        }
4054    }
4055
4056    #[test]
4057    fn axis_head_scan_empty_prefix_list_matches_unfiltered_walk() {
4058        let dir = tempfile::tempdir().unwrap();
4059        let mut stores = vec![Storage::memory(PartitionAxis::O)];
4060        stores.push(Storage::open_rocksdb(dir.path().join("head_pfx0"), PartitionAxis::O).unwrap());
4061        for store in &mut stores {
4062            store
4063                .insert_quad(&Quad::new(
4064                    NamedNode::new("http://ex/s").unwrap(),
4065                    NamedNode::new("http://ex/p").unwrap(),
4066                    Literal::from("text"),
4067                    GraphName::DefaultGraph,
4068                ))
4069                .unwrap();
4070            let snapshot = SnapshotId::default();
4071            let unfiltered = store
4072                .scan_objects(snapshot, 0, None, None, &[], false)
4073                .unwrap();
4074            let via_empty_list = store
4075                .scan_axis_head(
4076                    IndexPermutation::Opsg,
4077                    snapshot,
4078                    0,
4079                    None,
4080                    None,
4081                    &[],
4082                    false,
4083                    false,
4084                    &[],
4085                )
4086                .unwrap();
4087            assert_eq!(via_empty_list, unfiltered);
4088            assert_eq!(via_empty_list.len(), 1);
4089
4090            // A list of only-empty prefix bytes is dropped defensively: an
4091            // empty prefix would match every key, so the walk stays
4092            // unfiltered, same as the empty list.
4093            let only_empty = store
4094                .scan_axis_head(
4095                    IndexPermutation::Opsg,
4096                    snapshot,
4097                    0,
4098                    None,
4099                    None,
4100                    &[],
4101                    false,
4102                    false,
4103                    &[Vec::new()],
4104                )
4105                .unwrap();
4106            assert_eq!(only_empty, unfiltered);
4107        }
4108    }
4109
4110    #[test]
4111    fn max_commit_ts_under_prefixes_bounds_the_walked_range() {
4112        // Stage 1 of the geo upgrade: the swap ts must dominate the newest
4113        // version of every upgradeable row. A multi-version chain (assert,
4114        // retract, re-assert) is bounded by its newest version; unrelated
4115        // rows outside the prefixes must not leak into the bound.
4116        let dir = tempfile::tempdir().unwrap();
4117        let mut stores = vec![Storage::memory(PartitionAxis::O)];
4118        stores.push(Storage::open_rocksdb(dir.path().join("head_max"), PartitionAxis::O).unwrap());
4119        for store in &mut stores {
4120            let quad_with = |object: EncodedTerm| EncodedQuad {
4121                subject: EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap()),
4122                predicate: EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap()),
4123                object,
4124                graph_name: EncodedTerm::DefaultGraph,
4125            };
4126            let typed = |text: &str| EncodedTerm::SmallTypedLiteral {
4127                value: SmallString::try_from(text).unwrap(),
4128                datatype_id: StrHash::new("http://www.opengis.net/ont/geosparql#wktLiteral"),
4129            };
4130            store
4131                .insert_encoded_quad_version(
4132                    &quad_with(typed("POINT(1 2)")),
4133                    CommitTs(10),
4134                    StorageOp::Put,
4135                    VisibilityLabel::default(),
4136                )
4137                .unwrap();
4138            store
4139                .insert_encoded_quad_version(
4140                    &quad_with(typed("POINT(1 2)")),
4141                    CommitTs(15),
4142                    StorageOp::Delete,
4143                    VisibilityLabel::default(),
4144                )
4145                .unwrap();
4146            store
4147                .insert_encoded_quad_version(
4148                    &quad_with(typed("POINT(1 2)")),
4149                    CommitTs(25),
4150                    StorageOp::Put,
4151                    VisibilityLabel::default(),
4152                )
4153                .unwrap();
4154            // An unrelated NamedNode object at 99 — outside every geo prefix.
4155            store
4156                .insert_encoded_quad_version(
4157                    &quad_with(iri("o")),
4158                    CommitTs(99),
4159                    StorageOp::Put,
4160                    VisibilityLabel::default(),
4161                )
4162                .unwrap();
4163
4164            // Bare type-byte prefix [24]: sees the typed chain's newest
4165            // version (25), not the NamedNode row at 99.
4166            assert_eq!(
4167                store
4168                    .max_commit_ts_under_prefixes(IndexPermutation::Opsg, &[vec![24]])
4169                    .unwrap(),
4170                25
4171            );
4172            // Empty list = unfiltered whole-CF walk: everything counts.
4173            assert_eq!(
4174                store
4175                    .max_commit_ts_under_prefixes(IndexPermutation::Opsg, &[])
4176                    .unwrap(),
4177                99
4178            );
4179            // No key under an unmatched prefix.
4180            assert_eq!(
4181                store
4182                    .max_commit_ts_under_prefixes(IndexPermutation::Opsg, &[vec![99]])
4183                    .unwrap(),
4184                0
4185            );
4186        }
4187        let _ = std::fs::remove_dir_all(dir.path());
4188    }
4189
4190    #[test]
4191    fn axis_head_scan_prefix_filter_seek_union_liveness_and_resume() {
4192        // O-axis heads are objects: a mixed population of plain literals,
4193        // native geo terms, and typed literals sharing one datatype-IRI hash
4194        // (the orphaned-geo-literal shape). Prefixes stay opaque bytes here —
4195        // the walk only compares and seeks them.
4196        let dir = tempfile::tempdir().unwrap();
4197        let mut stores = vec![Storage::memory(PartitionAxis::O)];
4198        stores.push(Storage::open_rocksdb(dir.path().join("head_pfx"), PartitionAxis::O).unwrap());
4199        for store in &mut stores {
4200            // Variant marker bytes of the encoded-term format
4201            // (encode/binary.rs): 26 = LiteralPoint, 27 = LiteralGeometry,
4202            // 24 = SmallTypedLiteral, 25 = BigTypedLiteral.
4203            const POINT_BYTE: u8 = 26;
4204            const GEOMETRY_BYTE: u8 = 27;
4205            const SMALL_TYPED_BYTE: u8 = 24;
4206            const BIG_TYPED_BYTE: u8 = 25;
4207
4208            let quad_with = |object: EncodedTerm| EncodedQuad {
4209                subject: EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap()),
4210                predicate: EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap()),
4211                object,
4212                graph_name: EncodedTerm::DefaultGraph,
4213            };
4214            let put = |store: &Storage, object: &EncodedTerm, commit_ts: CommitTs| {
4215                store
4216                    .insert_encoded_quad_version(
4217                        &quad_with(object.clone()),
4218                        commit_ts,
4219                        StorageOp::Put,
4220                        VisibilityLabel::default(),
4221                    )
4222                    .unwrap();
4223            };
4224
4225            let point = |x: f64, y: f64| EncodedTerm::LiteralPoint {
4226                x,
4227                y,
4228                crs: CrsId::Crs84,
4229                geo_datatype: GeoDatatype::WktLiteral,
4230            };
4231            let points: Vec<EncodedTerm> = vec![point(1.0, 2.0), point(3.0, 4.0), point(5.0, 6.0)];
4232            let geometry = EncodedTerm::LiteralGeometry {
4233                geom_kind: GeomKind::Polygon,
4234                crs: CrsId::Crs84,
4235                geo_datatype: GeoDatatype::WkbLiteral,
4236                blob_id: StrHash::from_bytes(&[0xAB_u8; 32]),
4237                requires_spike_reduction: false,
4238            };
4239            let geo_datatype_id = StrHash::new("http://www.opengis.net/ont/geosparql#wktLiteral");
4240            let orphan_small = EncodedTerm::SmallTypedLiteral {
4241                value: SmallString::try_from("POINT(1 2)").unwrap(),
4242                datatype_id: geo_datatype_id,
4243            };
4244            let other_small = EncodedTerm::SmallTypedLiteral {
4245                value: SmallString::try_from("other").unwrap(),
4246                datatype_id: StrHash::new("http://ex/other"),
4247            };
4248            let orphan_big = EncodedTerm::BigTypedLiteral {
4249                value_id: StrHash::new("POLYGON((0 0, 1 0, 1 1, 0 0))"),
4250                datatype_id: geo_datatype_id,
4251            };
4252
4253            for term in &points {
4254                put(store, term, CommitTs::default());
4255            }
4256            put(store, &geometry, CommitTs::default());
4257            put(store, &orphan_small, CommitTs::default());
4258            put(store, &other_small, CommitTs::default());
4259            put(store, &orphan_big, CommitTs::default());
4260            // Plain objects outside every geo prefix: a string literal and a
4261            // named node (via rdf:type, which also lands in TSG).
4262            store
4263                .insert_quad(&Quad::new(
4264                    NamedNode::new("http://ex/plain").unwrap(),
4265                    NamedNode::new("http://ex/p").unwrap(),
4266                    Literal::from("text"),
4267                    GraphName::DefaultGraph,
4268                ))
4269                .unwrap();
4270            store.insert_quad(&rdf_type_quad("plain", "C1")).unwrap();
4271            // A fourth point whose only row is a Delete at snapshot 25.
4272            let doomed = point(7.0, 8.0);
4273            put(store, &doomed, CommitTs(10));
4274            store
4275                .insert_encoded_quad_version(
4276                    &quad_with(doomed.clone()),
4277                    CommitTs(20),
4278                    StorageOp::Delete,
4279                    VisibilityLabel::default(),
4280                )
4281                .unwrap();
4282
4283            let sort_bytes = |terms: &[EncodedTerm]| -> Vec<Vec<u8>> {
4284                let mut bytes: Vec<Vec<u8>> = terms.iter().map(encode_term_bytes).collect();
4285                bytes.sort();
4286                bytes
4287            };
4288            let scan = |snapshot: SnapshotId,
4289                        limit: u64,
4290                        cursor: Option<&EncodedTerm>,
4291                        prefixes: &[Vec<u8>]| {
4292                store
4293                    .scan_axis_head(
4294                        IndexPermutation::Opsg,
4295                        snapshot,
4296                        limit,
4297                        cursor,
4298                        None,
4299                        &[],
4300                        false,
4301                        false,
4302                        prefixes,
4303                    )
4304                    .unwrap()
4305            };
4306
4307            let late = SnapshotId(25);
4308            let point_prefixes = vec![vec![POINT_BYTE]];
4309            let geo_prefixes = vec![vec![POINT_BYTE], vec![GEOMETRY_BYTE]];
4310            let mut small_typed_prefix = vec![SMALL_TYPED_BYTE];
4311            small_typed_prefix.extend_from_slice(&geo_datatype_id.to_be_bytes());
4312            let mut big_typed_prefix = vec![BIG_TYPED_BYTE];
4313            big_typed_prefix.extend_from_slice(&geo_datatype_id.to_be_bytes());
4314
4315            // Unfiltered sees everything live at snapshot 25 (the deleted
4316            // point is shadowed): 3 points + geometry + 3 typed orphans +
4317            // string literal + class node = 9 heads.
4318            let unfiltered = scan(late, 0, None, &[]);
4319            assert_eq!(unfiltered.len(), 9);
4320
4321            // (a) Point prefix: exactly the live points, byte-ordered; the
4322            // deleted point is never emitted at snapshot 25 but is visible at
4323            // snapshot 15 (liveness, not type, decides).
4324            let hit = scan(late, 0, None, &point_prefixes);
4325            assert_eq!(sort_bytes(&hit), sort_bytes(&points));
4326            let early = SnapshotId(15);
4327            let hit_early = scan(early, 0, None, &point_prefixes);
4328            assert_eq!(hit_early.len(), 4);
4329            assert!(hit_early.contains(&doomed));
4330
4331            // (b) Point + geometry union: both prefix ranges, nothing else.
4332            let hit = scan(late, 0, None, &geo_prefixes);
4333            let mut expected = points.clone();
4334            expected.push(geometry.clone());
4335            assert_eq!(sort_bytes(&hit), sort_bytes(&expected));
4336
4337            // (c) Typed-literal prefixes: type byte + the 16-byte datatype
4338            // hash. Same-hash orphans are found, the other-hash literal and
4339            // every non-typed head stay out.
4340            let hit = scan(late, 0, None, &[small_typed_prefix.clone()]);
4341            assert_eq!(
4342                sort_bytes(&hit),
4343                sort_bytes(std::slice::from_ref(&orphan_small))
4344            );
4345            let hit = scan(late, 0, None, &[big_typed_prefix]);
4346            assert_eq!(
4347                sort_bytes(&hit),
4348                sort_bytes(std::slice::from_ref(&orphan_big))
4349            );
4350
4351            // (d) A prefix matching nothing returns empty.
4352            assert!(scan(late, 0, None, &[vec![0xEE]]).is_empty());
4353
4354            // (e) A nested prefix extending a kept shorter one is subsumed:
4355            // the full byte encoding of one point under the bare type byte
4356            // must not double-emit that point.
4357            let nested = encode_term_bytes(&points[0]);
4358            let hit = scan(late, 0, None, &[vec![POINT_BYTE], nested]);
4359            assert_eq!(sort_bytes(&hit), sort_bytes(&points));
4360
4361            // (f) Resume composes across prefix boundaries: paging with the
4362            // last emitted term as the exclusive cursor must yield every
4363            // matching head exactly once, whatever the page size.
4364            for page_size in [1u64, 2, 3] {
4365                let mut paged: Vec<EncodedTerm> = Vec::new();
4366                let mut cursor: Option<EncodedTerm> = None;
4367                loop {
4368                    let page = scan(late, page_size, cursor.as_ref(), &geo_prefixes);
4369                    assert!(
4370                        paged.len() + page.len() <= expected.len(),
4371                        "prefix paging emitted past the end"
4372                    );
4373                    if page.is_empty() {
4374                        break;
4375                    }
4376                    cursor = Some(page.last().unwrap().clone());
4377                    paged.extend(page);
4378                }
4379                assert_eq!(sort_bytes(&paged), sort_bytes(&expected));
4380            }
4381
4382            // Page boundary exactly at the prefix transition: page 1 fills up
4383            // on the last point head, page 2 resumes into the geometry range.
4384            let page = scan(late, points.len() as u64, None, &geo_prefixes);
4385            assert_eq!(sort_bytes(&page), sort_bytes(&points));
4386            let rest = scan(late, 0, Some(points.last().unwrap()), &geo_prefixes);
4387            assert_eq!(
4388                sort_bytes(&rest),
4389                sort_bytes(std::slice::from_ref(&geometry))
4390            );
4391
4392            // Resume with a cursor from outside every prefix: prefixes below
4393            // the cursor are drained and skipped, the rest start fresh.
4394            let rest = scan(late, 0, Some(&unfiltered[0]), &geo_prefixes);
4395            let expected_rest: Vec<EncodedTerm> = expected
4396                .iter()
4397                .filter(|t| encode_term_bytes(t) > encode_term_bytes(&unfiltered[0]))
4398                .cloned()
4399                .collect();
4400            assert_eq!(sort_bytes(&rest), sort_bytes(&expected_rest));
4401        }
4402    }
4403
4404    #[test]
4405    fn head_and_domain_scans_reject_foreign_permutations() {
4406        // S axis owns SPOG/SOPG only: PSOG / OPSG / TSG heads are not served.
4407        let store = Storage::memory(PartitionAxis::S);
4408        assert!(matches!(
4409            store
4410                .scan_predicates(SnapshotId::default(), 0, None, None, &[], false)
4411                .unwrap_err(),
4412            StorageError::PermutationNotOwned { .. }
4413        ));
4414        assert!(matches!(
4415            store
4416                .scan_classes(SnapshotId::default(), 0, None, None, &[], false)
4417                .unwrap_err(),
4418            StorageError::PermutationNotOwned { .. }
4419        ));
4420        assert!(matches!(
4421            store
4422                .scan_object_preds(&[], SnapshotId::default(), 0, None, None, None, &[], false)
4423                .unwrap_err(),
4424            StorageError::PermutationNotOwned { .. }
4425        ));
4426        // O axis does not serve subject heads.
4427        let store = Storage::memory(PartitionAxis::O);
4428        assert!(matches!(
4429            store
4430                .scan_subjects(SnapshotId::default(), 0, None, None, &[], false)
4431                .unwrap_err(),
4432            StorageError::PermutationNotOwned { .. }
4433        ));
4434    }
4435
4436    #[test]
4437    fn iri_only_mask_filters_pattern_scans() {
4438        let p = NamedNode::new("http://ex/p").unwrap();
4439        let quads = vec![
4440            Quad::new(
4441                NamedNode::new("http://ex/s1").unwrap(),
4442                p.clone(),
4443                NamedNode::new("http://ex/o1").unwrap(),
4444                GraphName::DefaultGraph,
4445            ),
4446            Quad::new(
4447                crate::BlankNode::new("b1").unwrap(),
4448                p.clone(),
4449                NamedNode::new("http://ex/o2").unwrap(),
4450                GraphName::DefaultGraph,
4451            ),
4452            Quad::new(
4453                NamedNode::new("http://ex/s2").unwrap(),
4454                p.clone(),
4455                Literal::from("lit"),
4456                GraphName::DefaultGraph,
4457            ),
4458            Quad::new(
4459                NamedNode::new("http://ex/s3").unwrap(),
4460                p,
4461                crate::BlankNode::new("b2").unwrap(),
4462                GraphName::DefaultGraph,
4463            ),
4464        ];
4465        let mut stores = vec![Storage::memory(PartitionAxis::S)];
4466        let dir = tempfile::tempdir().unwrap();
4467        stores.push(Storage::open_rocksdb(dir.path().join("s"), PartitionAxis::S).unwrap());
4468        for store in &stores {
4469            for quad in &quads {
4470                store.insert_quad(quad).unwrap();
4471            }
4472            let pattern = EncodedTriplePattern {
4473                subject: None,
4474                predicate: Some(EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap())),
4475                object: None,
4476                graph_name: Some(EncodedTerm::DefaultGraph),
4477            };
4478            let snapshot = SnapshotId::default();
4479            let rows = |iri_only| {
4480                store
4481                    .scan_pattern_page(
4482                        IndexPermutation::Spog,
4483                        &pattern,
4484                        snapshot,
4485                        0,
4486                        None,
4487                        GByteFilter::Unconstrained,
4488                        false,
4489                        iri_only,
4490                    )
4491                    .unwrap()
4492                    .rows
4493            };
4494            assert_eq!(rows(IriOnlyMask::NONE).len(), 4);
4495            assert_eq!(
4496                rows(IriOnlyMask {
4497                    subject: true,
4498                    object: false
4499                })
4500                .len(),
4501                3,
4502                "BNode subject dropped"
4503            );
4504            assert_eq!(
4505                rows(IriOnlyMask {
4506                    subject: false,
4507                    object: true
4508                })
4509                .len(),
4510                2,
4511                "literal and BNode objects dropped"
4512            );
4513            assert_eq!(
4514                rows(IriOnlyMask {
4515                    subject: true,
4516                    object: true
4517                })
4518                .len(),
4519                1,
4520                "only the all-IRI quad survives both masks"
4521            );
4522            // A bound slot is prefix-enforced: the mask must not reject the
4523            // exact row the pattern already pins.
4524            let bound = EncodedTriplePattern {
4525                subject: Some(EncodedTerm::from(&NamedNode::new("http://ex/s1").unwrap())),
4526                predicate: Some(EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap())),
4527                object: None,
4528                graph_name: Some(EncodedTerm::DefaultGraph),
4529            };
4530            let pinned = store
4531                .scan_pattern_page(
4532                    IndexPermutation::Spog,
4533                    &bound,
4534                    snapshot,
4535                    0,
4536                    None,
4537                    GByteFilter::Unconstrained,
4538                    false,
4539                    IriOnlyMask {
4540                        subject: true,
4541                        object: true,
4542                    },
4543                )
4544                .unwrap()
4545                .rows;
4546            assert_eq!(pinned.len(), 1);
4547        }
4548    }
4549
4550    #[test]
4551    fn iri_only_head_filters_axis_head_and_domain_scans() {
4552        let class = |s: &str| EncodedTerm::from(&NamedNode::new(s).unwrap());
4553        let quads = vec![
4554            Quad::new(
4555                NamedNode::new("http://ex/i1").unwrap(),
4556                NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap(),
4557                NamedNode::new("http://ex/C1").unwrap(),
4558                GraphName::DefaultGraph,
4559            ),
4560            Quad::new(
4561                NamedNode::new("http://ex/i2").unwrap(),
4562                NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap(),
4563                crate::BlankNode::new("c").unwrap(),
4564                GraphName::DefaultGraph,
4565            ),
4566            Quad::new(
4567                NamedNode::new("http://ex/i3").unwrap(),
4568                NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap(),
4569                Literal::from("not-a-class"),
4570                GraphName::DefaultGraph,
4571            ),
4572        ];
4573        let dir = tempfile::tempdir().unwrap();
4574        let o_stores = vec![
4575            Storage::memory(PartitionAxis::O),
4576            Storage::open_rocksdb(dir.path().join("o"), PartitionAxis::O).unwrap(),
4577        ];
4578        let p_stores = vec![
4579            Storage::memory(PartitionAxis::P),
4580            Storage::open_rocksdb(dir.path().join("p"), PartitionAxis::P).unwrap(),
4581        ];
4582        for store in o_stores.iter().chain(p_stores.iter()) {
4583            for quad in &quads {
4584                store.insert_quad(quad).unwrap();
4585            }
4586        }
4587        for store in &o_stores {
4588            let snapshot = SnapshotId::default();
4589            let unmasked = store
4590                .scan_axis_head(
4591                    IndexPermutation::Tsg,
4592                    snapshot,
4593                    0,
4594                    None,
4595                    None,
4596                    &[],
4597                    false,
4598                    false,
4599                    &[],
4600                )
4601                .unwrap();
4602            assert_eq!(
4603                unmasked.len(),
4604                3,
4605                "TSG stores BNode and literal classes too"
4606            );
4607            let masked = store
4608                .scan_axis_head(
4609                    IndexPermutation::Tsg,
4610                    snapshot,
4611                    0,
4612                    None,
4613                    None,
4614                    &[],
4615                    false,
4616                    true,
4617                    &[],
4618                )
4619                .unwrap();
4620            assert_eq!(masked, vec![class("http://ex/C1")]);
4621        }
4622
4623        // POSG PredicateDomain under the grounded rdf:type predicate (P axis):
4624        // the head (object) mask skips the BNode and literal heads.
4625        for store in &p_stores {
4626            let snapshot = SnapshotId::default();
4627            let rdf_type = class("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
4628            let unmasked_hits = store
4629                .scan_domain(
4630                    IndexPermutation::Posg,
4631                    std::slice::from_ref(&rdf_type),
4632                    snapshot,
4633                    0,
4634                    None,
4635                    None,
4636                    None,
4637                    &[],
4638                    false,
4639                    false,
4640                )
4641                .unwrap();
4642            assert_eq!(unmasked_hits.len(), 3);
4643            let masked_hits = store
4644                .scan_domain(
4645                    IndexPermutation::Posg,
4646                    &[rdf_type],
4647                    snapshot,
4648                    0,
4649                    None,
4650                    None,
4651                    None,
4652                    &[],
4653                    false,
4654                    true,
4655                )
4656                .unwrap();
4657            assert_eq!(masked_hits.len(), 1);
4658            assert_eq!(masked_hits[0].term, class("http://ex/C1"));
4659        }
4660    }
4661
4662    #[test]
4663    fn filtered_scan_and_count_apply_window_and_dedup() {
4664        // Same triple in three graphs (dedup collapses to one row with G
4665        // rewritten to DefaultGraph); a graph that only carries excluded
4666        // triples disappears under the block-list window.
4667        let g1 = GraphName::from(NamedNode::new("http://ex/g1").unwrap());
4668        let g2 = GraphName::from(NamedNode::new("http://ex/g2").unwrap());
4669        let quad = |s: &str, o: &str, g: GraphName| {
4670            Quad::new(
4671                NamedNode::new(format!("http://ex/{s}")).unwrap(),
4672                NamedNode::new("http://ex/p").unwrap(),
4673                Literal::from(o),
4674                g,
4675            )
4676        };
4677        let pattern = EncodedTriplePattern::default();
4678        let block_g2 = GByteFilter::compile(
4679            &[EncodedTerm::from(&NamedNode::new("http://ex/g2").unwrap())],
4680            false,
4681        );
4682        for store in [
4683            Storage::memory(PartitionAxis::S),
4684            Storage::open_rocksdb(
4685                tempfile::tempdir().unwrap().keep().join("filtered"),
4686                PartitionAxis::S,
4687            )
4688            .unwrap(),
4689        ] {
4690            store.insert_quad(&quad("a", "x", g1.clone())).unwrap();
4691            store.insert_quad(&quad("a", "x", g2.clone())).unwrap();
4692            store
4693                .insert_quad(&quad("a", "x", GraphName::DefaultGraph))
4694                .unwrap();
4695            store.insert_quad(&quad("b", "y", g2.clone())).unwrap();
4696            store
4697                .insert_quad(&quad("c", "z", GraphName::DefaultGraph))
4698                .unwrap();
4699
4700            // dedup + block-list: t(ax) collapses to one DefaultGraph row,
4701            // t(cz) survives, t(by) lives only in the excluded graph.
4702            let rows = store
4703                .scan_pattern_page(
4704                    IndexPermutation::Spog,
4705                    &pattern,
4706                    SnapshotId::default(),
4707                    0,
4708                    None,
4709                    block_g2.clone(),
4710                    true,
4711                    IriOnlyMask::NONE,
4712                )
4713                .unwrap()
4714                .rows;
4715            assert_eq!(rows.len(), 2, "{rows:?}");
4716            for row in &rows {
4717                assert_eq!(row.graph_name, EncodedTerm::DefaultGraph);
4718            }
4719
4720            // The count twin counts the same set without materializing rows.
4721            let count = store
4722                .count_pattern_impl(
4723                    IndexPermutation::Spog,
4724                    &pattern,
4725                    SnapshotId::default(),
4726                    0,
4727                    block_g2.clone(),
4728                    true,
4729                )
4730                .unwrap();
4731            assert_eq!(count, 2);
4732
4733            // Resume with a rewritten-DefaultGraph cursor: the walk skips the
4734            // cursor's whole triple (any G) and yields exactly the other one.
4735            let page1 = store
4736                .scan_pattern_page(
4737                    IndexPermutation::Spog,
4738                    &pattern,
4739                    SnapshotId::default(),
4740                    1,
4741                    None,
4742                    block_g2.clone(),
4743                    true,
4744                    IriOnlyMask::NONE,
4745                )
4746                .unwrap()
4747                .rows;
4748            assert_eq!(page1.len(), 1);
4749            let rest = store
4750                .scan_pattern_page(
4751                    IndexPermutation::Spog,
4752                    &pattern,
4753                    SnapshotId::default(),
4754                    0,
4755                    page1.last(),
4756                    block_g2.clone(),
4757                    true,
4758                    IriOnlyMask::NONE,
4759                )
4760                .unwrap()
4761                .rows;
4762            assert_eq!(rest.len(), 1);
4763            assert!(
4764                !rest[0].same_triple(&page1[0]),
4765                "the cursor's whole triple must be skipped"
4766            );
4767
4768            // No dedup: t(ax) surfaces once per remaining graph (g1 + default).
4769            let rows = store
4770                .scan_pattern_page(
4771                    IndexPermutation::Spog,
4772                    &pattern,
4773                    SnapshotId::default(),
4774                    0,
4775                    None,
4776                    block_g2.clone(),
4777                    false,
4778                    IriOnlyMask::NONE,
4779                )
4780                .unwrap()
4781                .rows;
4782            assert_eq!(rows.len(), 3, "{rows:?}");
4783        }
4784    }
4785
4786    #[test]
4787    fn allow_list_dedup_cursor_skips_whole_triple() {
4788        // Same triple in the default graph and a named graph; the dedup
4789        // cursor is the REWRITTEN (DefaultGraph) row the previous page
4790        // emitted. The resumed allow-list scan must skip the cursor's whole
4791        // triple — including the named-graph copy that sorts after the
4792        // rewritten cursor key — not just the exact cursor quad.
4793        // S and P bound so the O allow-list is contiguous on SPOG (the same
4794        // shape `resolve_broadcast_permutation` produces for
4795        // `?s <p> ?o` with an object filter on POSG).
4796        let pattern = EncodedTriplePattern {
4797            subject: Some(EncodedTerm::from(&NamedNode::new("http://ex/a").unwrap())),
4798            predicate: Some(EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap())),
4799            object: None,
4800            graph_name: None,
4801        };
4802        let cursor = EncodedQuad::new(
4803            EncodedTerm::from(&NamedNode::new("http://ex/a").unwrap()),
4804            EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap()),
4805            EncodedTerm::from(&Literal::from("x")),
4806            EncodedTerm::DefaultGraph,
4807        );
4808        for (kind, store) in [
4809            ("memory", Storage::memory(PartitionAxis::S)),
4810            (
4811                "rocksdb",
4812                Storage::open_rocksdb(
4813                    tempfile::tempdir()
4814                        .unwrap()
4815                        .keep()
4816                        .join("allow_dedup_cursor"),
4817                    PartitionAxis::S,
4818                )
4819                .unwrap(),
4820            ),
4821        ] {
4822            store
4823                .insert_quad(&Quad::new(
4824                    NamedNode::new("http://ex/a").unwrap(),
4825                    NamedNode::new("http://ex/p").unwrap(),
4826                    Literal::from("x"),
4827                    GraphName::DefaultGraph,
4828                ))
4829                .unwrap();
4830            store
4831                .insert_quad(&Quad::new(
4832                    NamedNode::new("http://ex/a").unwrap(),
4833                    NamedNode::new("http://ex/p").unwrap(),
4834                    Literal::from("x"),
4835                    GraphName::from(NamedNode::new("http://ex/g1").unwrap()),
4836                ))
4837                .unwrap();
4838
4839            // Dedup resume: the cursor's whole triple is skipped in every G.
4840            let rows = store
4841                .scan_pattern_page_allow_list(
4842                    IndexPermutation::Spog,
4843                    &pattern,
4844                    SnapshotId::default(),
4845                    0,
4846                    Some(&cursor),
4847                    QuadSlot::Object,
4848                    &[EncodedTerm::from(&Literal::from("x"))],
4849                    GByteFilter::Unconstrained,
4850                    true,
4851                    IriOnlyMask::NONE,
4852                )
4853                .unwrap()
4854                .expect("object extends the bound S+P prefix on SPOG");
4855            let rows = rows.rows;
4856            assert!(
4857                rows.is_empty(),
4858                "{kind}: cursor triple must not resurface: {rows:?}"
4859            );
4860
4861            // Without dedup the named-graph copy is a distinct quad and stays.
4862            let rows = store
4863                .scan_pattern_page_allow_list(
4864                    IndexPermutation::Spog,
4865                    &pattern,
4866                    SnapshotId::default(),
4867                    0,
4868                    Some(&cursor),
4869                    QuadSlot::Object,
4870                    &[EncodedTerm::from(&Literal::from("x"))],
4871                    GByteFilter::Unconstrained,
4872                    false,
4873                    IriOnlyMask::NONE,
4874                )
4875                .unwrap()
4876                .expect("prefix-extending");
4877            let rows = rows.rows;
4878            assert_eq!(rows.len(), 1, "{rows:?}");
4879            assert!(
4880                rest_is_g1(&rows[0]),
4881                "the default-graph cursor copy must be skipped; the g1 copy is a distinct quad"
4882            );
4883        }
4884
4885        fn rest_is_g1(row: &EncodedQuad) -> bool {
4886            matches!(&row.graph_name, EncodedTerm::NamedNode { .. })
4887        }
4888    }
4889
4890    /// Backend parity for the temporal candidate scan over a window that
4891    /// runs to the axis top.
4892    ///
4893    /// A one-sided `FILTER(?t >= const)` leaves the window's upper bound at
4894    /// `i128::MAX`, which maps to the key-space `u128::MAX`; the tail
4895    /// covering node then carries `max_key == u128::MAX` with `min_key > 0`.
4896    /// The memory backend derived that interval's exclusive end bound with
4897    /// `wrapping_add(1)`, which wraps to zero, sorts BELOW start, and made
4898    /// `BTreeMap::range` panic ("range start is greater than range end")
4899    /// instead of draining to EOF. RocksDB never built such a bound and was
4900    /// already correct — this pins both backends to the same answer.
4901    #[test]
4902    fn temporal_candidate_scan_axis_top_matches_between_backends() {
4903        let dir = tempfile::tempdir().unwrap();
4904        let mut stores = vec![Storage::memory(PartitionAxis::O)];
4905        stores.push(
4906            Storage::open_rocksdb(dir.path().join("temporal_top"), PartitionAxis::O).unwrap(),
4907        );
4908        let config = crate::DyadicCovererConfig::default();
4909        let gyear = |text: &str| EncodedTerm::GYearLiteral(text.parse().unwrap());
4910        // 2024 sits below the window floor: its postings are addressed and
4911        // then rejected on the exact interval. 2025 and 2030 must be emitted.
4912        let stored = [gyear("2024"), gyear("2025"), gyear("2030")];
4913        let begin = crate::temporal_term_interval(&gyear("2025")).unwrap().begin;
4914        let window = TemporalQueryPredicate::Overlaps {
4915            begin,
4916            end: i128::MAX,
4917        };
4918        // The planner's own construction: cover the window, then merge into
4919        // probe intervals (descendant ranges ∪ exact ancestor keys).
4920        let nodes = crate::cover_axis_range(
4921            crate::tick_to_key_u128(begin),
4922            crate::tick_to_key_u128(i128::MAX),
4923            &config,
4924        );
4925        let intervals = crate::intervals_for_nodes(&nodes);
4926        assert!(
4927            intervals
4928                .iter()
4929                .any(|interval| interval.max_key == u128::MAX && interval.min_key > 0),
4930            "the planner's tail interval must reach the axis top over a nonzero floor — \
4931             that is the interval whose wrapped end bound panicked the memory backend"
4932        );
4933
4934        for store in &mut stores {
4935            store
4936                .set_temporal_index_epoch(1)
4937                .expect("an O-axis store stamps an epoch");
4938            let mut puts = Vec::new();
4939            for term in &stored {
4940                puts.extend(crate::postings_for_term(term, CommitTs(1), &config));
4941            }
4942            store.apply_temporal_puts(&puts).expect("postings apply");
4943            let mut state = TemporalCandidateState::default();
4944            let mut found: Vec<Vec<u8>> = Vec::new();
4945            store
4946                .temporal_scan_candidates(
4947                    &intervals,
4948                    SnapshotId::latest(),
4949                    &window,
4950                    0,
4951                    &mut state,
4952                    |term| {
4953                        found.push(encode_term_bytes(term));
4954                        Ok(true)
4955                    },
4956                )
4957                .expect("the axis-top scan must not panic");
4958            let mut expected: Vec<Vec<u8>> = [gyear("2025"), gyear("2030")]
4959                .iter()
4960                .map(encode_term_bytes)
4961                .collect();
4962            found.sort();
4963            expected.sort();
4964            assert_eq!(
4965                found, expected,
4966                "axis-top scan must emit exactly the in-window terms"
4967            );
4968        }
4969    }
4970}