Skip to main content

waratah_storage/
rocksdb.rs

1//! RocksDB hexastore backend via `waratah-rocksdb-sys`.
2
3use std::fmt;
4use std::path::{Path, PathBuf};
5
6use crate::encode::{
7    AxisHeadCountHit, CATALOG_MIN_PREFIX_SIZE, COMMIT_TS_LEN, CatalogPut, CatalogRebuildStats,
8    ComparisonMask, DomainCountMode, DomainScanCountHit, DomainScanHit, EncodedQuad, EncodedTerm,
9    EncodedTriplePattern, GByteFilter, GEO_CELL_ID_LEN, GEO_INDEX_CF, GEO_INDEX_EPOCH_KEY,
10    GEO_INDEX_LIVENESS_KEY, GEO_INDEX_META_CF, GWindowKind, GeoCandidateDecision,
11    GeoCandidateState, GeoCellInterval, GeoEnvelope, GeoIndexPut, GraphCatalogState, HeadVerdict,
12    HexastorePut, HexastoreVersion, IndexPermutation, IriOnlyMask, KeyRow, MERGE_NEXT_CHAIN_LIMIT,
13    MERGE_TRIPLE_PREFIX_MAX, MatchDecision, NAMED_GRAPHS_CATALOG_CF, QuadSlot, RowMatcher,
14    RunCounter, SnapshotScanState, TEMPORAL_INDEX_CF, TEMPORAL_INDEX_EPOCH_KEY,
15    TEMPORAL_INDEX_META_CF, TEMPORAL_INDEX_ORIGIN_KEY, TEMPORAL_KEY_LEN, TEMPORAL_ORIGIN_VERSION,
16    TemporalCandidateDecision, TemporalCandidateState, TemporalCellInterval, TemporalIndexPut,
17    TemporalQueryPredicate, TermReader, WRITTEN_TERM_MAX_SIZE, byte_successor, catalog_prefix,
18    classify_g_window, collect_dedup_visible_catalog_graphs, consider_axis_head_key,
19    consider_head_key, decode_catalog_value, decode_geo_epoch, decode_geo_liveness,
20    decode_index_key, decode_storage_value, decode_temporal_epoch, decode_temporal_origin,
21    decode_temporal_posting_value, decode_versioned_key, encode_geo_epoch, encode_geo_liveness,
22    encode_index_key, encode_quad, encode_temporal_epoch, encode_temporal_origin,
23    encode_term_bytes, graph_hops_after_head, head_prefix_resume_seek, head_resume_seek,
24    head_term_from_region, is_catalog_graph, prepare_constraints_sorted, prepare_head_prefixes,
25    prepare_hexastore_puts, record_first_put_graph, region_after_head, require_catalog_graph,
26    stage_catalog_puts, term_in_quad_slot, triple_prefix_len, versioned_key_term_prefix,
27};
28use crate::rocksdb_db::{
29    BottommostLevelCompaction, ColumnFamily, ColumnFamilyDefinition, Db, warm_walk,
30};
31
32use crate::types::{
33    CommitTs, PartitionAxis, ReplacePair, ScanExhaustion, ScanPage, SnapshotId, StorageOp,
34    VisibilityLabel,
35};
36use crate::worker_pool::{self, PoolUnit, UnitOutcome};
37use crate::{Quad, StorageError, StrHash};
38
39use std::sync::Arc;
40use std::sync::OnceLock;
41use std::sync::atomic::{AtomicUsize, Ordering};
42
43pub use crate::rocksdb_db::{
44    BULK_MAX_WRITE_BUFFER_NUMBER, BULK_WRITE_BUFFER_BYTES, COMPACTION_READAHEAD_BYTES,
45    DEFAULT_BLOCK_SIZE_BYTES, DEFAULT_ITERATOR_READAHEAD_BYTES, DEFAULT_MAX_WRITE_BUFFER_NUMBER,
46    DEFAULT_WRITE_BUFFER_BYTES, PREFIX_FILTER_BITS_PER_KEY, REGISTRY_BLOCK_SIZE_BYTES,
47    RocksDbOptionsHooks, RocksDbTuning, TICKER_BLOCK_CACHE_FILTER_HIT,
48    TICKER_BLOCK_CACHE_FILTER_MISS, TICKER_BLOOM_FILTER_PREFIX_CHECKED,
49    TICKER_BLOOM_FILTER_PREFIX_USEFUL, TICKER_SEEK_FILTER_MATCH, TICKER_SEEK_FILTERED,
50    WARM_CACHE_FILL_FRACTION, WARM_CACHE_PROBE_INTERVAL, WarmBlockCacheStats,
51    disable_auto_compactions, hexastore_readahead_env_bytes, iterator_readahead_bytes,
52    pin_index_env_enabled, scan_async_io_env_enabled, sst_filter_env_enabled,
53    warm_cache_env_enabled,
54};
55
56/// Removed knob: a set value warns once and is ignored (the seek-union
57/// mode was deleted; see [`domain_scan_mode`]).
58pub(crate) const DOMAIN_SEEK_UNION_ENV: &str = "WARATAH_DOMAIN_SEEK_UNION";
59/// Parallel worker count for domain scans. **Enabled by default** at the
60/// storage worker pool's width in slices
61/// ([`worker_pool::default_walk_width`]); `0` / `1` select the legacy walk
62/// (warned), a valid `K` sets the slice count, and values above
63/// [`DOMAIN_WALKS_MAX`] clamp.
64pub(crate) const DOMAIN_WALKS_ENV: &str = "WARATAH_DOMAIN_WALKS";
65/// `WARATAH_DOMAIN_WALKS` minimum (below it the knob is legacy) ...
66pub(crate) const DOMAIN_WALKS_MIN: usize = 2;
67/// ... and maximum (values above clamp to it).
68pub(crate) const DOMAIN_WALKS_MAX: usize = 64;
69
70/// Domain-scan execution mode for the RocksDB backend.
71///
72/// All modes prepare constraints with `build_walk_constraints`
73/// (`prepare_constraints_sorted` + precomputed per-constraint prefix and
74/// resume seek) and emit in **key order** regardless of the order the
75/// caller passed, bounded by the same `limit`/cursor contract. Key-order
76/// emission is what makes the `start_after` resume skip sound: a cursor
77/// inside constraint C proves every constraint sorting before C was fully
78/// emitted on earlier pages, so dropping them cannot lose hits. Both modes
79/// walk with the confined discipline — one bounded iterator per
80/// constraint — which seeks real term prefixes (the shape per-SST prefix
81/// filters can safely accelerate); they differ only in where the loop
82/// runs: legacy on the calling thread over the whole list, parallel over
83/// key-disjoint runs on the storage worker pool.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub(crate) enum DomainScanMode {
86    /// Per-constraint bounded iterators over the key-sorted constraint
87    /// list, on the calling thread (the default).
88    Legacy,
89    /// `K` worker slices, each walking one key-disjoint run of the sorted
90    /// constraints with its own per-constraint bounded iterators; ordered
91    /// concatenation merge.
92    ParallelWalks(usize),
93}
94
95/// Resolved domain-scan mode for this process.
96///
97/// Precedence: `WARATAH_DOMAIN_WALKS ≥ 2` → parallel; else legacy.
98/// Partition / standalone children inherit the variable, so setting it
99/// before `waratah start` switches the whole cluster. A set
100/// `WARATAH_DOMAIN_SEEK_UNION` warns and is ignored: the seek-union mode
101/// (one shared iterator seeking across constraints) was removed after
102/// measurement showed it indistinguishable from legacy at every
103/// constraint scale — the per-constraint cost is the seek itself, which
104/// both disciplines pay once per constraint — and the shared-iterator
105/// successor seeks were the shape per-SST prefix filters cannot
106/// accelerate safely.
107pub(crate) fn domain_scan_mode() -> DomainScanMode {
108    static MODE: OnceLock<DomainScanMode> = OnceLock::new();
109    *MODE.get_or_init(|| {
110        if let Ok(raw) = std::env::var(DOMAIN_SEEK_UNION_ENV) {
111            eprintln!(
112                "waratah-storage: ignoring WARATAH_DOMAIN_SEEK_UNION={raw:?}: the seek-union \
113                 mode was removed; domain scans are legacy or WARATAH_DOMAIN_WALKS=K parallel"
114            );
115        }
116        match std::env::var(DOMAIN_WALKS_ENV).ok() {
117            // Unset: enabled at the storage pool's width in slices
118            // (resolved once here at first use — serving processes install
119            // their pool at startup, before any walk can resolve this). The
120            // dispatch clamp keeps an explicit K within the width, and a
121            // width below 2 falls back to the legacy walk.
122            None => DomainScanMode::ParallelWalks(worker_pool::default_walk_width()),
123            // Explicit value: 0 / 1 / junk = legacy (opt-out — warned so a
124            // typo'd disable is never silent); K >= 2 = that slice count.
125            Some(raw) => domain_walks_from_env(Some(raw.as_str()))
126                .map(DomainScanMode::ParallelWalks)
127                .unwrap_or(DomainScanMode::Legacy),
128        }
129    })
130}
131
132/// Parse an EXPLICIT `WARATAH_DOMAIN_WALKS` value into a worker count.
133///
134/// `0` / `1` / junk warn and return `None` (the legacy opt-out — domain
135/// scans are otherwise enabled by default at the storage pool's width);
136/// values above [`DOMAIN_WALKS_MAX`] clamp to it. The unset case never
137/// reaches here — [`domain_scan_mode`] defaults it to enabled.
138fn domain_walks_from_env(raw: Option<&str>) -> Option<usize> {
139    let raw = raw?;
140    match raw.trim().parse::<usize>() {
141        Ok(workers) if (DOMAIN_WALKS_MIN..=DOMAIN_WALKS_MAX).contains(&workers) => Some(workers),
142        Ok(workers) if workers > DOMAIN_WALKS_MAX => {
143            eprintln!(
144                "waratah-storage: clamping WARATAH_DOMAIN_WALKS={raw} to {DOMAIN_WALKS_MAX} workers"
145            );
146            Some(DOMAIN_WALKS_MAX)
147        }
148        Ok(_) => {
149            eprintln!(
150                "waratah-storage: ignoring WARATAH_DOMAIN_WALKS={raw} (needs >= \
151                 {DOMAIN_WALKS_MIN}); using legacy domain scans"
152            );
153            None
154        }
155        Err(_) => {
156            eprintln!(
157                "waratah-storage: ignoring invalid WARATAH_DOMAIN_WALKS {raw:?} (expected a \
158                 worker count >= {DOMAIN_WALKS_MIN}); using legacy domain scans"
159            );
160            None
161        }
162    }
163}
164
165/// Self-attestation for benchmark discipline: once per process, the first
166/// non-legacy domain-scan call prints the active mode on stderr.
167fn attest_domain_scan_mode(mode: DomainScanMode) {
168    static ATTESTED: OnceLock<()> = OnceLock::new();
169    if mode == DomainScanMode::Legacy {
170        return;
171    }
172    if ATTESTED.set(()).is_ok() {
173        match mode {
174            DomainScanMode::Legacy => unreachable!("checked above"),
175            DomainScanMode::ParallelWalks(workers) => {
176                eprintln!("storage-trace domain scan: parallel K={workers}");
177            }
178        }
179    }
180}
181
182/// Parallel worker count for pattern-count walks (`= <K>`, `K ≥ 2`).
183///
184/// **Enabled by default** at the storage worker pool's width in slices
185/// ([`worker_pool::default_walk_width`]). Explicit values override: `0` /
186/// `1` keep the serial walk (`0` and junk warn so a typo'd disable is never
187/// silent), a valid `K` sets the slice count, and values above
188/// [`COUNT_WALKS_MAX`] clamp. Partition / standalone children inherit the
189/// variable, so setting it before `waratah start` switches the whole
190/// cluster.
191pub(crate) const COUNT_WALKS_ENV: &str = "WARATAH_COUNT_WALKS";
192/// `WARATAH_COUNT_WALKS` minimum (below it counts stay serial) ...
193pub(crate) const COUNT_WALKS_MIN: usize = 2;
194/// ... and maximum (values above clamp to it).
195pub(crate) const COUNT_WALKS_MAX: usize = 64;
196/// Per-slice occupancy log for sliced counts (`= 1`). Prints one line per
197/// sliced count with each slice's row share — the measurement behind the
198/// byte-even skew discussion (hash-uniform regions slice near-evenly; bnode /
199/// literal clusters light up as single-slice hot spots).
200const COUNT_WALKS_DEBUG_ENV: &str = "WARATAH_COUNT_WALKS_DEBUG";
201
202/// Pattern-count execution mode for the RocksDB backend.
203///
204/// Counts have no `limit` budget interaction to preserve (limited counts stay
205/// serial — see [`RocksDbStorage::count_pattern_impl_with_mode`]), so unlike
206/// [`DomainScanMode`] there are exactly two modes.
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub(crate) enum CountWalkMode {
209    /// One iterator, the pre-knob behavior (the default).
210    Serial,
211    /// `K` scoped threads over byte-range slices of the walk; the merge is a
212    /// sum, so no ordering question exists.
213    Parallel(usize),
214}
215
216/// Resolved pattern-count mode for this process.
217///
218/// Precedence and inheritance mirror [`domain_scan_mode`]: a valid
219/// `WARATAH_COUNT_WALKS` value enables parallel counts for the whole cluster.
220pub(crate) fn count_walk_mode() -> CountWalkMode {
221    static MODE: OnceLock<CountWalkMode> = OnceLock::new();
222    *MODE.get_or_init(|| match std::env::var(COUNT_WALKS_ENV).ok() {
223        // Unset: enabled at the storage pool's width in slices (resolved
224        // once here at first use — serving processes install their pool at
225        // startup, before any walk can resolve this). The dispatch clamp
226        // keeps an explicit K within the width, and a width below 2 falls
227        // back to the serial walk.
228        None => CountWalkMode::Parallel(worker_pool::default_walk_width()),
229        // Explicit value: 0 / 1 / junk = serial (opt-out — warned so a
230        // typo'd disable is never silent); K >= 2 = that slice count.
231        Some(raw) => count_walks_from_env(Some(raw.as_str()))
232            .map(CountWalkMode::Parallel)
233            .unwrap_or(CountWalkMode::Serial),
234    })
235}
236
237/// Parse an EXPLICIT `WARATAH_COUNT_WALKS` value into a worker count.
238///
239/// `0` / `1` / junk warn and return `None` (the serial opt-out — the count
240/// walk is otherwise enabled by default at the storage pool's width);
241/// values above [`COUNT_WALKS_MAX`] clamp to it. The unset case never
242/// reaches here — [`count_walk_mode`] defaults it to enabled.
243fn count_walks_from_env(raw: Option<&str>) -> Option<usize> {
244    let raw = raw?;
245    match raw.trim().parse::<usize>() {
246        Ok(workers) if (COUNT_WALKS_MIN..=COUNT_WALKS_MAX).contains(&workers) => Some(workers),
247        Ok(workers) if workers > COUNT_WALKS_MAX => {
248            eprintln!(
249                "waratah-storage: clamping WARATAH_COUNT_WALKS={raw} to {COUNT_WALKS_MAX} workers"
250            );
251            Some(COUNT_WALKS_MAX)
252        }
253        Ok(_) => {
254            eprintln!(
255                "waratah-storage: ignoring WARATAH_COUNT_WALKS={raw} (needs >= \
256                 {COUNT_WALKS_MIN}); using serial pattern counts"
257            );
258            None
259        }
260        Err(_) => {
261            eprintln!(
262                "waratah-storage: ignoring invalid WARATAH_COUNT_WALKS {raw:?} (expected a \
263                 worker count >= {COUNT_WALKS_MIN}); using serial pattern counts"
264            );
265            None
266        }
267    }
268}
269
270/// `true` when `WARATAH_COUNT_WALKS_DEBUG=1` asks for the per-slice
271/// occupancy log.
272fn count_walks_debug_enabled() -> bool {
273    static DEBUG: OnceLock<bool> = OnceLock::new();
274    *DEBUG.get_or_init(|| std::env::var(COUNT_WALKS_DEBUG_ENV).ok().as_deref() == Some("1"))
275}
276
277/// Self-attestation for benchmark discipline: once per process, the first
278/// parallel count prints the active mode on stderr.
279fn attest_count_walk_mode(mode: CountWalkMode) {
280    static ATTESTED: OnceLock<()> = OnceLock::new();
281    if let CountWalkMode::Parallel(workers) = mode
282        && ATTESTED.set(()).is_ok()
283    {
284        eprintln!("storage-trace pattern count: parallel K={workers}");
285    }
286}
287
288/// One byte-range slice of a parallel pattern-count walk: keys `>= start`,
289/// `< end` (`None` = through the end of the scan prefix's range).
290#[derive(Debug, Clone)]
291pub(crate) struct CountSlice {
292    /// Inclusive lower seek target.
293    pub(crate) start: Vec<u8>,
294    /// Exclusive upper bound; `None` runs to the pattern prefix's end (the
295    /// CF end for a full-axis count, whose prefix is empty).
296    pub(crate) end: Option<Vec<u8>>,
297}
298
299/// Slicing plan for one parallel pattern count.
300struct CountWalkPlan {
301    /// Scan prefix of the walk (leading bound slots; empty for a full-axis
302    /// count). The unbounded tail slice's iterator bound is derived from it.
303    prefix: Vec<u8>,
304    /// Key-disjoint ascending slices covering the whole range.
305    slices: Vec<CountSlice>,
306}
307
308/// `true` when the window constrains specific named graphs (allow-list or
309/// block-list — both name graphs). A default-graph-only allow window and an
310/// unconstrained filter are scoping modes, not graph bindings, and stay
311/// eligible for parallel counts.
312fn graph_window_names_terms(filter: &GByteFilter) -> bool {
313    match filter {
314        GByteFilter::Unconstrained | GByteFilter::EmptyWindow => false,
315        GByteFilter::Window { named, extras, .. } => !named.is_empty() || !extras.is_empty(),
316    }
317}
318
319/// Eligibility + slicing plan for a parallel pattern count, or `None` when
320/// the request's shape must stay serial.
321///
322/// Mode table (bound slots = S/P/O term slots; the graph slot is the trailing
323/// slot of every permutation and its binding is carried by `graph_filter`,
324/// not the scan prefix):
325///
326/// - **Full-axis count** (hexastore: no slot bound; TSG: class and subject
327///   unbound): slices cover the whole CF range. Byte-even boundaries; on TSG
328///   a non-empty `class_totals` hint aligns boundaries with class-term starts
329///   instead, balanced by the exact per-class row counts.
330/// - **Prefix-arena count** (hexastore: leading slot bound, no other slot
331///   bound; TSG: class bound, subject unbound): slices cover the bound term's
332///   arena, byte-even.
333/// - **Serial** (no plan): any non-leading slot bound — the walk degenerates
334///   into a residual filter whose byte distribution slicing cannot reason
335///   about — a bound `graph_name` other than the default graph (the default
336///   graph is scoping metadata and counts as unbound) — and any named-graph
337///   window on TSG. `merge_default_graph` also forces serial (checked by the
338///   caller): its graph-variant dedup state is per-walk, so a boundary
339///   between two graph variants of one triple would count the triple twice.
340///
341/// Reachability note for the straddle machinery this plan feeds: a
342/// byte-even boundary splits a version group only when its boundary u64
343/// equals a leading term's first 8 payload bytes (~2⁻⁶⁴ per
344/// group-boundary pair), and TSG class-aligned boundaries never split one;
345/// the straddle handling in `count_walk_slice` stays correct for manual
346/// slices and future generators.
347fn count_walk_plan(
348    workers: usize,
349    permutation: IndexPermutation,
350    pattern: &EncodedTriplePattern,
351    graph_filter: &GByteFilter,
352    class_totals: &[(StrHash, u64)],
353    // Lazy: probed from the range's first key (one seek). Evaluated only
354    // by the byte-even branches, after eligibility — the hint-aligned TSG
355    // branch never needs it.
356    arena_tag: impl Fn() -> u8,
357) -> Option<CountWalkPlan> {
358    // `graph_name` is scoping metadata: `DefaultGraph` expresses the default
359    // graph and never counts as a bound; any other term bound in the graph
360    // slot is a residual constraint.
361    let graph_scoping_only = pattern
362        .graph_name
363        .as_ref()
364        .is_none_or(|term| matches!(term, EncodedTerm::DefaultGraph));
365    if !graph_scoping_only {
366        return None;
367    }
368    let slots = permutation.slot_order();
369    let leading_bound = pattern.bound_slot(slots[0]).is_some();
370    let non_leading_bound = slots[1..]
371        .iter()
372        .filter(|slot| **slot != QuadSlot::Graph)
373        .any(|slot| pattern.bound_slot(*slot).is_some());
374    let prefix = pattern.build_scan_prefix_bytes(permutation);
375    let slices = if permutation == IndexPermutation::Tsg {
376        // TSG's leading slot is the class (the `rdf:type` object). A bound
377        // subject is non-leading; a named-graph window cannot be sliced
378        // meaningfully on TSG either (the G term sits inside the key).
379        if non_leading_bound || graph_window_names_terms(graph_filter) {
380            return None;
381        }
382        if leading_bound {
383            // Prefix arena: byte-even inside the class span.
384            count_slices_even(&prefix, arena_tag(), workers)
385        } else {
386            // Full axis: exact class totals (when the caller supplied them)
387            // cut the walk at class boundaries with balanced row shares.
388            count_slices_tsg_classes(class_totals, workers)
389                .unwrap_or_else(|| count_slices_even(&prefix, arena_tag(), workers))
390        }
391    } else if leading_bound {
392        if non_leading_bound {
393            return None;
394        }
395        // Prefix arena: byte-even inside the bound term's span.
396        count_slices_even(&prefix, arena_tag(), workers)
397    } else if non_leading_bound {
398        return None;
399    } else {
400        // Full-axis hexastore count: the prefix is empty (no slot bound).
401        count_slices_even(&prefix, arena_tag(), workers)
402    };
403    Some(CountWalkPlan { prefix, slices })
404}
405
406/// `workers - 1` ascending synthetic boundaries spreading the dominant
407/// term-type region just above `prefix`: each is
408/// `prefix ‖ arena_tag ‖ be64(step * j)`.
409///
410/// `arena_tag` is the first key's type-tag byte above the prefix (probed by
411/// the caller). Real keys always start their suffix with a type tag byte
412/// (≤ 0x2D — the highest written tag id, `TYPE_BLOB_LITERAL`), so spreading
413/// boundaries over the *raw* byte space would place
414/// every boundary above the whole key population and one slice would carry
415/// everything. After the tag byte, hash-referenced payload bytes are
416/// uniformly distributed, so these boundaries are near-even for the dominant
417/// region; keys of other (higher) type regions fall into the last slice —
418/// the documented skew case (numerical blank-node ids, common inline
419/// literals). The occupancy log (debug knob) exposes the actual
420/// distribution.
421fn even_boundaries(prefix: &[u8], arena_tag: u8, workers: usize) -> Vec<Vec<u8>> {
422    let mut out = Vec::with_capacity(workers.saturating_sub(1));
423    if workers < 2 {
424        return out;
425    }
426    // `step * workers <= u64::MAX`, so no `step * j` overflows.
427    let step = (u64::MAX / workers as u64).max(1);
428    for j in 1..workers as u64 {
429        let mut boundary = prefix.to_vec();
430        boundary.push(arena_tag);
431        boundary.extend_from_slice(&step.saturating_mul(j).to_be_bytes());
432        out.push(boundary);
433    }
434    out
435}
436
437/// `workers` slices from [`even_boundaries`]: `[prefix, b1), [b1, b2), …,
438/// [b_{K-1}, prefix end)`.
439fn count_slices_even(prefix: &[u8], arena_tag: u8, workers: usize) -> Vec<CountSlice> {
440    let boundaries = even_boundaries(prefix, arena_tag, workers);
441    let mut slices = Vec::with_capacity(boundaries.len() + 1);
442    let mut start = prefix.to_vec();
443    for boundary in &boundaries {
444        slices.push(CountSlice {
445            start,
446            end: Some(boundary.clone()),
447        });
448        start = boundary.clone();
449    }
450    slices.push(CountSlice { start, end: None });
451    slices
452}
453
454/// TSG full-axis slices aligned with class-term starts, balanced by the
455/// exact per-class row totals (greedy: close a slice once it has accumulated
456/// at least `total / workers` estimated rows).
457///
458/// Class-aligned boundaries are structurally version-group aligned — every
459/// version of one triple carries its class term prefix — so the straddle
460/// skip never fires on this path. Classes the hint does not know about
461/// (non-named-node classes, post-hint inserts) stay covered: slice 0 opens
462/// at the CF start and the tail runs to the CF end. Returns `None` (fall
463/// back to byte-even) when the hint is too thin to cut with.
464fn count_slices_tsg_classes(
465    class_totals: &[(StrHash, u64)],
466    workers: usize,
467) -> Option<Vec<CountSlice>> {
468    let total: u64 = class_totals.iter().map(|(_, rows)| *rows).sum();
469    if workers < 2 || class_totals.len() < 2 || total == 0 {
470        return None;
471    }
472    // The hint is consumed in ascending `StrHash` order — boundaries must
473    // strictly ascend for the slices to stay disjoint. The partition's
474    // profile map (BTreeMap) guarantees it; this makes the assumption loud
475    // if that container ever changes.
476    debug_assert!(
477        class_totals.windows(2).all(|w| w[0].0 < w[1].0),
478        "class_totals hint must ascend by StrHash"
479    );
480    let class_prefix =
481        |hash: &StrHash| encode_term_bytes(&EncodedTerm::NamedNode { iri_id: *hash });
482    let target = total.div_ceil(workers as u64);
483    let mut slices = Vec::new();
484    // `None` start = CF start: classes missing from the hint that sort before
485    // the first hinted class stay in slice 0.
486    let mut open_start: Option<Vec<u8>> = None;
487    let mut accumulated = 0u64;
488    for index in 0..class_totals.len() - 1 {
489        accumulated = accumulated.saturating_add(class_totals[index].1);
490        if accumulated >= target {
491            let boundary = class_prefix(&class_totals[index + 1].0);
492            slices.push(CountSlice {
493                start: open_start.unwrap_or_default(),
494                end: Some(boundary.clone()),
495            });
496            open_start = Some(boundary);
497            accumulated = 0;
498        }
499    }
500    slices.push(CountSlice {
501        start: open_start.unwrap_or_default(),
502        end: None,
503    });
504    Some(slices)
505}
506
507/// One sorted constraint of a confined / parallel domain walk, with its encoded
508/// prefix bytes and resume seek precomputed.
509///
510/// Cloned into each pool work unit: units own their slice because the
511/// worker pool outlives a single scan call.
512#[derive(Clone)]
513struct WalkConstraint {
514    constraint: EncodedTerm,
515    /// `encode_term_bytes(constraint)` — the membership prefix.
516    c_bytes: Vec<u8>,
517    /// Inclusive seek for this constraint: its prefix, or the exclusive
518    /// resume successor when it equals `start_after_constraint`.
519    seek: Vec<u8>,
520}
521
522/// Shared per-call context for the union / parallel walkers.
523struct DomainWalkCtx<'a> {
524    permutation: IndexPermutation,
525    snapshot: SnapshotId,
526    g_window: GWindowKind,
527    graph_name: Option<&'a EncodedTerm>,
528    graph_filter_terms: &'a [EncodedTerm],
529    graph_filter_allow: bool,
530    iri_only_head: bool,
531}
532
533impl<'a> DomainWalkCtx<'a> {
534    fn new(
535        permutation: IndexPermutation,
536        snapshot: SnapshotId,
537        graph_name: Option<&'a EncodedTerm>,
538        graph_filter_terms: &'a [EncodedTerm],
539        graph_filter_allow: bool,
540        iri_only_head: bool,
541    ) -> Self {
542        Self {
543            permutation,
544            snapshot,
545            g_window: classify_g_window(graph_name, graph_filter_terms, graph_filter_allow),
546            graph_name,
547            graph_filter_terms,
548            graph_filter_allow,
549            iri_only_head,
550        }
551    }
552
553    /// Copy into an owned context: pool work units outlive this call's
554    /// borrows, so each one carries its own copy of the caller's filter
555    /// terms (usually a handful of encodings).
556    fn into_owned(self) -> DomainWalkCtxOwned {
557        DomainWalkCtxOwned {
558            permutation: self.permutation,
559            snapshot: self.snapshot,
560            g_window: self.g_window,
561            graph_name: self.graph_name.cloned(),
562            graph_filter_terms: self.graph_filter_terms.to_vec(),
563            graph_filter_allow: self.graph_filter_allow,
564            iri_only_head: self.iri_only_head,
565        }
566    }
567}
568
569/// Owned twin of [`DomainWalkCtx`], shared by the pool work units of one
570/// parallel domain scan.
571struct DomainWalkCtxOwned {
572    permutation: IndexPermutation,
573    snapshot: SnapshotId,
574    g_window: GWindowKind,
575    graph_name: Option<EncodedTerm>,
576    graph_filter_terms: Vec<EncodedTerm>,
577    graph_filter_allow: bool,
578    iri_only_head: bool,
579}
580
581impl DomainWalkCtxOwned {
582    /// Borrow as the walker's per-call context.
583    fn as_borrowed(&self) -> DomainWalkCtx<'_> {
584        DomainWalkCtx {
585            permutation: self.permutation,
586            snapshot: self.snapshot,
587            g_window: self.g_window,
588            graph_name: self.graph_name.as_ref(),
589            graph_filter_terms: &self.graph_filter_terms,
590            graph_filter_allow: self.graph_filter_allow,
591            iri_only_head: self.iri_only_head,
592        }
593    }
594}
595
596/// Sorted, deduped, resume-filtered walk constraints for union / parallel.
597///
598/// [`prepare_constraints_sorted`] provides key order — the modes' documented
599/// emission order — and [`head_resume_seek`] then drops the constraints the
600/// resume cursor has exhausted (the same skip legacy applies per iteration,
601/// hoisted into prep). Distinct encoded terms are never byte-prefixes of each
602/// other, so the sorted prefixes are disjoint key ranges.
603fn build_walk_constraints(
604    permutation: IndexPermutation,
605    constraints: &[EncodedTerm],
606    start_after_constraint: Option<&EncodedTerm>,
607    start_after_term: Option<&EncodedTerm>,
608) -> Result<Vec<WalkConstraint>, StorageError> {
609    let sorted = prepare_constraints_sorted(permutation, constraints)?;
610    let mut out = Vec::with_capacity(sorted.len());
611    for constraint in sorted {
612        let Some(seek) = head_resume_seek(&constraint, start_after_constraint, start_after_term)
613        else {
614            // Sorts before the resume cursor: exhausted before this call.
615            continue;
616        };
617        let c_bytes = encode_term_bytes(&constraint);
618        out.push(WalkConstraint {
619            constraint,
620            c_bytes,
621            seek,
622        });
623    }
624    Ok(out)
625}
626
627/// One walker's `limit` budget, decremented once per emitted hit.
628///
629/// `None` = unlimited (no atomics on the walk). Callers create one budget
630/// per walker: the union walk owns a single budget, the parallel drivers
631/// build one per slice. A budget caps only its own walker's pushes — a
632/// shared budget would let a later slice starve an earlier one mid-range,
633/// and the caller's resume cursor could never revisit the holes;
634/// per-worker budgets plus the ordered merge + truncate yield exactly the
635/// key-first `limit` hits (see the parallel driver docs).
636fn limit_budget(limit: u64) -> Option<AtomicUsize> {
637    (limit > 0).then(|| AtomicUsize::new(limit_to_usize(limit)))
638}
639
640/// Saturating `u64` → `usize` for limit caps and truncations.
641///
642/// Lossless on 64-bit; on a 32-bit target a `u64` limit beyond `usize::MAX`
643/// saturates — consistent with the budget caps, and a `Vec` cannot hold
644/// more than `usize::MAX` elements regardless.
645fn limit_to_usize(limit: u64) -> usize {
646    usize::try_from(limit).unwrap_or(usize::MAX)
647}
648
649/// Consume one unit of a walker's own limit budget; `false` when exhausted.
650fn take_budget(budget: Option<&AtomicUsize>) -> bool {
651    match budget {
652        None => true,
653        Some(budget) => budget
654            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |left| {
655                left.checked_sub(1)
656            })
657            .is_ok(),
658    }
659}
660
661/// Split `len` items into contiguous balanced slices. Slice boundaries fall
662/// on constraint boundaries; per-constraint weight is unknowable pre-walk, so
663/// skew within a slice is documented (balanced by constraint count only).
664/// Total: empty input yields no slices (the drivers early-return on empty
665/// constraint lists before reaching here, so this is a robustness guard, not
666/// a reachable path). Shared by the domain-scan and registry parallel walks.
667pub(crate) fn split_slices(len: usize, workers: usize) -> Vec<std::ops::Range<usize>> {
668    if len == 0 {
669        return Vec::new();
670    }
671    let count = workers.clamp(1, len);
672    let base = len / count;
673    let rem = len % count;
674    let mut slices = Vec::with_capacity(count);
675    let mut start = 0;
676    for index in 0..count {
677        let size = base + usize::from(index < rem);
678        slices.push(start..start + size);
679        start += size;
680    }
681    slices
682}
683
684/// One parallel domain-scan slice: a storage worker's confined walk (one
685/// bounded iterator per constraint) over an owned, sorted, key-disjoint
686/// run of constraints with its own limit budget.
687///
688/// Units own their inputs because the worker pool outlives individual calls;
689/// the run copy is small against the I/O each slice performs.
690struct DomainHitsUnit {
691    db: Db,
692    cf: ColumnFamily,
693    ctx: Arc<DomainWalkCtxOwned>,
694    slice: Vec<WalkConstraint>,
695    budget: Option<AtomicUsize>,
696}
697
698impl PoolUnit for DomainHitsUnit {
699    type Output = Result<Vec<DomainScanHit>, StorageError>;
700
701    fn execute(self) -> Self::Output {
702        let ctx = self.ctx.as_borrowed();
703        confined_hits_on(&self.db, &self.cf, &ctx, &self.slice, self.budget.as_ref())
704    }
705}
706
707/// Walk one contiguous run of sorted constraints with the confined
708/// discipline — one bounded iterator per constraint (also the whole-list
709/// body of legacy mode). Each iterator's prefix bound confines the walk
710/// to one constraint's key range, so every seek targets a real term
711/// prefix: the shape per-SST prefix filters can safely accelerate.
712fn confined_hits_on(
713    db: &Db,
714    cf: &ColumnFamily,
715    ctx: &DomainWalkCtx<'_>,
716    slice: &[WalkConstraint],
717    budget: Option<&AtomicUsize>,
718) -> Result<Vec<DomainScanHit>, StorageError> {
719    let mut hits = Vec::new();
720    for item in slice {
721        if let Some(budget) = budget
722            && budget.load(Ordering::Relaxed) == 0
723        {
724            break;
725        }
726        let mut iter = db.scan_prefix(cf, &item.c_bytes);
727        if item.seek.as_slice() > item.c_bytes.as_slice() {
728            iter.seek(&item.seek);
729        }
730        let mut state = SnapshotScanState::default();
731        while iter.is_valid() {
732            let Some(key) = iter.key() else { break };
733            if !key.starts_with(&item.c_bytes) {
734                break;
735            }
736            let Some(value) = iter.value() else {
737                return Err(StorageError::Corrupt(
738                    "iterator key without value".to_owned(),
739                ));
740            };
741            let head = match consider_head_key(
742                &mut state,
743                ctx.snapshot,
744                key,
745                value,
746                item.c_bytes.len(),
747                graph_hops_after_head(ctx.permutation, true),
748                ctx.g_window,
749                ctx.graph_name,
750                ctx.graph_filter_terms,
751                ctx.graph_filter_allow,
752                ctx.iri_only_head,
753            )? {
754                HeadVerdict::Candidate { head } => head,
755                HeadVerdict::Skip => {
756                    iter.next();
757                    continue;
758                }
759            };
760            // Skip-scan past the rest of this head term: the encoded bytes
761            // are already in the key — build the seek from them directly
762            // instead of a decode + re-encode round trip. Capacity is the
763            // two byte spans actually copied (constraint prefix + head
764            // region); `head.end` would size it only by coincidence of the
765            // head offset equaling the prefix length.
766            let mut skip = Vec::with_capacity(item.c_bytes.len() + head.len());
767            skip.extend_from_slice(&item.c_bytes);
768            skip.extend_from_slice(&key[head.clone()]);
769            let step = byte_successor(&skip);
770            if !take_budget(budget) {
771                break;
772            }
773            hits.push(DomainScanHit {
774                constraint: item.constraint.clone(),
775                term: head_term_from_region(&key[head.clone()])?,
776            });
777            match step {
778                Some(next) => iter.seek(&next),
779                None => break,
780            }
781            state = SnapshotScanState::default();
782        }
783        iter.status()?;
784    }
785    Ok(hits)
786}
787
788/// One parallel domain-counts-scan slice unit: the confined counts walk
789/// ([`confined_counts_on`]) over an owned, sorted, key-disjoint run of
790/// constraints with its own limit budget, plus the count-mode flags that
791/// shape each run. Units own their inputs because the worker pool outlives
792/// individual calls; the run copy is small against the I/O each slice
793/// performs.
794struct DomainCountsUnit {
795    db: Db,
796    cf: ColumnFamily,
797    ctx: Arc<DomainWalkCtxOwned>,
798    slice: Vec<WalkConstraint>,
799    budget: Option<AtomicUsize>,
800    merge_default_graph: bool,
801    count_mode: DomainCountMode,
802}
803
804impl PoolUnit for DomainCountsUnit {
805    type Output = Result<Vec<DomainScanCountHit>, StorageError>;
806
807    fn execute(self) -> Self::Output {
808        let ctx = self.ctx.as_borrowed();
809        confined_counts_on(
810            &self.db,
811            &self.cf,
812            &ctx,
813            &self.slice,
814            self.budget.as_ref(),
815            self.merge_default_graph,
816            self.count_mode,
817        )
818    }
819}
820
821/// Walk one contiguous run of sorted constraints with the confined
822/// count discipline — one bounded iterator per constraint, run-merge per
823/// head, `merge_default_graph` triple skips (also the whole-list body of
824/// legacy counts mode). Run-merge semantics: the head is the second key
825/// component, so equal head terms are contiguous and a changed head
826/// *region* closes the run — byte identity is term identity for canonical,
827/// self-delimiting encodings. `state` dedupes version chains across the
828/// constraint (keys are visited exactly once in order); merge mode seeks
829/// past extra G of a counted triple and resets it (the open run continues
830/// across the seek — only the MVCC state resets).
831fn confined_counts_on(
832    db: &Db,
833    cf: &ColumnFamily,
834    ctx: &DomainWalkCtx<'_>,
835    slice: &[WalkConstraint],
836    budget: Option<&AtomicUsize>,
837    merge_default_graph: bool,
838    count_mode: DomainCountMode,
839) -> Result<Vec<DomainScanCountHit>, StorageError> {
840    let mut hits = Vec::new();
841    for item in slice {
842        if let Some(budget) = budget
843            && budget.load(Ordering::Relaxed) == 0
844        {
845            break;
846        }
847        let mut iter = db.scan_prefix(cf, &item.c_bytes);
848        if item.seek.as_slice() > item.c_bytes.as_slice() {
849            iter.seek(&item.seek);
850        }
851        let mut state = SnapshotScanState::default();
852        // The run currently being counted: its head term's encoded bytes
853        // (`run_head[..run_len]`) plus the mode counter. Runs never span
854        // constraints, so both are declared per constraint and flushed at
855        // the boundary. Encoded terms are canonical and self-delimiting,
856        // so the boundary test is a region compare, and the emitted term
857        // is decoded from the saved bytes only at flush time.
858        let mut run_head = [0u8; WRITTEN_TERM_MAX_SIZE];
859        let mut run_len = 0usize;
860        let mut current: Option<RunCounter> = None;
861        while iter.is_valid() {
862            let Some(key) = iter.key() else { break };
863            if !key.starts_with(&item.c_bytes) {
864                break;
865            }
866            let Some(value) = iter.value() else {
867                return Err(StorageError::Corrupt(
868                    "iterator key without value".to_owned(),
869                ));
870            };
871            let head = match consider_head_key(
872                &mut state,
873                ctx.snapshot,
874                key,
875                value,
876                item.c_bytes.len(),
877                graph_hops_after_head(ctx.permutation, true),
878                ctx.g_window,
879                ctx.graph_name,
880                ctx.graph_filter_terms,
881                ctx.graph_filter_allow,
882                ctx.iri_only_head,
883            )? {
884                HeadVerdict::Candidate { head } => head,
885                HeadVerdict::Skip => {
886                    iter.next();
887                    continue;
888                }
889            };
890            let opens_new_run = current.is_none() || run_head[..run_len] != key[head.clone()];
891            if opens_new_run {
892                if let Some(run) = current.take() {
893                    // A flushed run takes one budget unit; when the
894                    // budget is dead the closed run is dropped unpushed
895                    // and the caller's resume cursor re-walks it on the
896                    // next page.
897                    if !take_budget(budget) {
898                        break;
899                    }
900                    hits.push(DomainScanCountHit {
901                        constraint: item.constraint.clone(),
902                        term: head_term_from_region(&run_head[..run_len])?,
903                        count: run.total(),
904                    });
905                }
906                run_head[..head.len()].copy_from_slice(&key[head.clone()]);
907                run_len = head.len();
908                current = Some(RunCounter::new(count_mode));
909            }
910            if let Some(run) = &mut current {
911                match count_mode {
912                    DomainCountMode::Rows => run.observe_rows(),
913                    DomainCountMode::DistinctTerms => {
914                        let slot2 = region_after_head(key, head.end)?;
915                        run.observe_distinct_terms(key, &slot2);
916                    }
917                    DomainCountMode::DistinctGraphs => {
918                        let slot2 = region_after_head(key, head.end)?;
919                        let logical_end = key.len() - COMMIT_TS_LEN;
920                        run.observe_distinct_graphs(&key[slot2.end..logical_end]);
921                    }
922                }
923            }
924            if merge_default_graph {
925                // Merge semantics: the counted triple is unique across
926                // graphs, so skip its remaining G-variants and older
927                // versions. Chain `Next()` while the key still shares the
928                // triple's S/P/O prefix — a Next is ~20-50x cheaper than a
929                // Seek on this iterator stack — and pay one Seek only for a
930                // chain longer than MERGE_NEXT_CHAIN_LIMIT.
931                //
932                // `prefix` is copied out because `logical` borrows the
933                // iterator key, which dies on the first `next()`.
934                let mut stop_walk = false;
935                let tp_len = {
936                    let logical = versioned_key_term_prefix(key)?;
937                    triple_prefix_len(logical)?
938                };
939                let mut prefix = [0u8; MERGE_TRIPLE_PREFIX_MAX];
940                prefix[..tp_len].copy_from_slice(&key[..tp_len]);
941                let mut chained = 0usize;
942                loop {
943                    iter.next();
944                    let Some(next_key) = iter.is_valid().then(|| iter.key()).flatten() else {
945                        break; // range exhausted mid-chain; the outer loop sees !is_valid
946                    };
947                    if !next_key.starts_with(&prefix[..tp_len]) {
948                        break; // next triple reached: plain advance, MVCC state untouched
949                    }
950                    chained += 1;
951                    if chained < MERGE_NEXT_CHAIN_LIMIT {
952                        continue;
953                    }
954                    // Bounded fallback: one seek finishes the chain. The
955                    // seek can skip unvisited keys, so it resets the MVCC
956                    // state — but NOT the open run: the next key can share
957                    // the head, so the run continues across the merge
958                    // advance. The Next chain above visits keys in order
959                    // and must not reset either state or run — the next
960                    // considered key has a different S/P/O, so the stale
961                    // handled-logical can never match it.
962                    match byte_successor(&prefix[..tp_len]) {
963                        Some(next) => {
964                            iter.seek(&next);
965                            state = SnapshotScanState::default();
966                        }
967                        None => stop_walk = true,
968                    }
969                    break;
970                }
971                if stop_walk {
972                    break;
973                }
974            } else {
975                iter.next();
976            }
977        }
978        // Flush the trailing run. A failed `take_budget` means the page
979        // filled mid-run: drop it unpushed — the cursor resumes the
980        // client past the last emitted triple and this run is re-walked
981        // (and emitted) on the next page.
982        if let Some(run) = current.take() {
983            if take_budget(budget) {
984                hits.push(DomainScanCountHit {
985                    constraint: item.constraint.clone(),
986                    term: head_term_from_region(&run_head[..run_len])?,
987                    count: run.total(),
988                });
989            } else {
990                break;
991            }
992        }
993        iter.status()?;
994    }
995    Ok(hits)
996}
997
998/// RocksDB-backed hexastore storage for one partition axis.
999pub struct RocksDbStorage {
1000    axis: PartitionAxis,
1001    /// Directory the RocksDB store was opened at. Kept so derived on-disk
1002    /// state (the text plugin's Tantivy directory) lands beside the
1003    /// hexastore instead of in a process-relative location.
1004    path: PathBuf,
1005    db: Db,
1006    cf0: ColumnFamily,
1007    cf1: ColumnFamily,
1008    /// S-axis MVCC named-graph catalog. `None` on P/O.
1009    ///
1010    /// A future G axis may hold a duplicate of this CF for in-partition checks;
1011    /// that replica is not a second source of truth and is not opened here.
1012    cf_catalog: Option<ColumnFamily>,
1013    /// O-axis geometry index (`geo_index`, GeoSPARQL). `None` on S/P. The
1014    /// partition applies compute-derived S2 postings verbatim — this CF never
1015    /// derives cells and never reads blobs.
1016    cf_geo: Option<ColumnFamily>,
1017    cf_temporal: Option<ColumnFamily>,
1018    cf_temporal_meta: Option<ColumnFamily>,
1019    /// O-axis geo-index metadata (`geo_index_meta`, single-key rebuild
1020    /// epoch). `None` on S/P.
1021    cf_geo_meta: Option<ColumnFamily>,
1022    permutations: [IndexPermutation; 2],
1023}
1024
1025impl fmt::Debug for RocksDbStorage {
1026    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1027        f.debug_struct("RocksDbStorage")
1028            .field("axis", &self.axis)
1029            .field("permutations", &self.permutations)
1030            .finish_non_exhaustive()
1031    }
1032}
1033
1034impl RocksDbStorage {
1035    /// Open a RocksDB instance at `path` with axis-local column families.
1036    pub fn open(path: &Path, axis: PartitionAxis) -> Result<Self, StorageError> {
1037        Self::open_with_hooks(path, axis, RocksDbOptionsHooks::default())
1038    }
1039
1040    /// Open with optional DB/CF options hooks (stats collectors, listeners).
1041    pub fn open_with_hooks(
1042        path: &Path,
1043        axis: PartitionAxis,
1044        hooks: RocksDbOptionsHooks<'_>,
1045    ) -> Result<Self, StorageError> {
1046        if let Some(parent) = path.parent() {
1047            std::fs::create_dir_all(parent).map_err(|e| StorageError::Backend(e.to_string()))?;
1048        }
1049        std::fs::create_dir_all(path).map_err(|e| StorageError::Backend(e.to_string()))?;
1050
1051        let permutations = IndexPermutation::for_axis(axis);
1052        let mut column_families: Vec<ColumnFamilyDefinition> = permutations
1053            .into_iter()
1054            .map(|p| ColumnFamilyDefinition {
1055                name: p.cf_name(),
1056                // A fixed 17-byte prefix always ends at a slot-0 term boundary
1057                // when slot 0 is a node: every named-node / blank-node encoding
1058                // is exactly one type byte + 16 payload bytes (see the
1059                // TERM_WIDTH table and its node-width test). TSG qualifies
1060                // because the compute write funnel rejects rdf:type quads
1061                // whose object is a literal (the only variable-width term
1062                // kind that could appear there). OPSG keeps 0: its leading
1063                // object may be any term, including short literals whose
1064                // encodings are narrower than 17 bytes.
1065                min_prefix_size: match p {
1066                    IndexPermutation::Opsg => 0,
1067                    _ => 17,
1068                },
1069                // Per-SST prefix blooms only where the leading term is
1070                // fixed-width AND high-cardinality: SPOG/SOPG (subject —
1071                // node-only by RDF grammar, so the 17-byte prefix is always
1072                // term-aligned) and TSG (class — node-only via the write
1073                // funnel's rdf:type object rule). PSOG/POSG stay unfiltered:
1074                // predicates cluster contiguously and are few, so their
1075                // bloom would nearly always answer "present" — pure
1076                // overhead. OPSG needs a variable-width-aware extractor
1077                // before a filter could be sound (short literal objects).
1078                prefix_filter: matches!(
1079                    p,
1080                    IndexPermutation::Spog | IndexPermutation::Sopg | IndexPermutation::Tsg
1081                ),
1082                permutation: Some(p),
1083            })
1084            .collect();
1085        if axis == PartitionAxis::S {
1086            column_families.push(ColumnFamilyDefinition {
1087                name: NAMED_GRAPHS_CATALOG_CF,
1088                min_prefix_size: CATALOG_MIN_PREFIX_SIZE,
1089                prefix_filter: false,
1090                permutation: None,
1091            });
1092        }
1093        if axis == PartitionAxis::O {
1094            // Range-partitioned by cell id (never term hash) — no prefix
1095            // extractor; candidate scans seek into cell-id intervals.
1096            column_families.push(ColumnFamilyDefinition {
1097                name: GEO_INDEX_CF,
1098                min_prefix_size: 0,
1099                prefix_filter: false,
1100                permutation: None,
1101            });
1102            // Single-key metadata CF (rebuild epoch): never walked, never
1103            // prefix-scanned.
1104            column_families.push(ColumnFamilyDefinition {
1105                name: GEO_INDEX_META_CF,
1106                min_prefix_size: 0,
1107                prefix_filter: false,
1108                permutation: None,
1109            });
1110            // Range-partitioned by node start key (never term hash) — no
1111            // prefix extractor; candidate scans seek into key intervals.
1112            column_families.push(ColumnFamilyDefinition {
1113                name: TEMPORAL_INDEX_CF,
1114                min_prefix_size: 0,
1115                prefix_filter: false,
1116                permutation: None,
1117            });
1118            // Single-key metadata CF (temporal rebuild epoch).
1119            column_families.push(ColumnFamilyDefinition {
1120                name: TEMPORAL_INDEX_META_CF,
1121                min_prefix_size: 0,
1122                prefix_filter: false,
1123                permutation: None,
1124            });
1125        }
1126
1127        // Temporary A/B knob: `TEST_HEXASTORE_READAHEAD_SIZE` overrides the
1128        // hexastore tuning's `0` (engine auto-readahead) with an explicit
1129        // window — engaged from the first IO, fixed-size (no ramp), and the
1130        // two-buffer async prefetch when `WARATAH_SCAN_ASYNC_IO` is on. The
1131        // registry's readahead is resolved separately and is unaffected.
1132        let mut hooks = hooks;
1133        if let Some(bytes) = hexastore_readahead_env_bytes() {
1134            hooks.tuning.iterator_readahead_bytes = bytes;
1135            eprintln!(
1136                "storage-trace hexastore readahead: {} KiB \
1137                 (TEST_HEXASTORE_READAHEAD_SIZE)",
1138                bytes / 1024
1139            );
1140        }
1141
1142        let db = Db::open_read_write_with_hooks(path, column_families, hooks)?;
1143        let cf0 = db.column_family(permutations[0].cf_name())?;
1144        let cf1 = db.column_family(permutations[1].cf_name())?;
1145        let cf_catalog = if axis == PartitionAxis::S {
1146            Some(db.column_family(NAMED_GRAPHS_CATALOG_CF)?)
1147        } else {
1148            None
1149        };
1150        let cf_geo = if axis == PartitionAxis::O {
1151            Some(db.column_family(GEO_INDEX_CF)?)
1152        } else {
1153            None
1154        };
1155        let cf_geo_meta = if axis == PartitionAxis::O {
1156            Some(db.column_family(GEO_INDEX_META_CF)?)
1157        } else {
1158            None
1159        };
1160        let cf_temporal = if axis == PartitionAxis::O {
1161            Some(db.column_family(TEMPORAL_INDEX_CF)?)
1162        } else {
1163            None
1164        };
1165        let cf_temporal_meta = if axis == PartitionAxis::O {
1166            Some(db.column_family(TEMPORAL_INDEX_META_CF)?)
1167        } else {
1168            None
1169        };
1170        Ok(Self {
1171            axis,
1172            path: path.to_path_buf(),
1173            db,
1174            cf0,
1175            cf1,
1176            cf_catalog,
1177            cf_geo,
1178            cf_temporal,
1179            cf_temporal_meta,
1180            cf_geo_meta,
1181            permutations,
1182        })
1183    }
1184
1185    /// Partition axis this store owns.
1186    pub fn axis(&self) -> PartitionAxis {
1187        self.axis
1188    }
1189
1190    /// Directory this store was opened at.
1191    pub fn data_path(&self) -> &Path {
1192        &self.path
1193    }
1194
1195    /// Insert a versioned hexastore record (`Put` or `Delete`).
1196    pub fn insert_quad_version(
1197        &self,
1198        quad: &Quad,
1199        commit_ts: CommitTs,
1200        op: StorageOp,
1201        visibility: VisibilityLabel,
1202    ) -> Result<(), StorageError> {
1203        self.insert_encoded_quad_version(&encode_quad(quad)?, commit_ts, op, visibility)
1204    }
1205
1206    /// Insert an already-encoded quad version (partition-service write path).
1207    pub fn insert_encoded_quad_version(
1208        &self,
1209        encoded: &EncodedQuad,
1210        commit_ts: CommitTs,
1211        op: StorageOp,
1212        visibility: VisibilityLabel,
1213    ) -> Result<(), StorageError> {
1214        let puts = prepare_hexastore_puts(
1215            self.axis,
1216            [HexastoreVersion {
1217                quad: encoded,
1218                commit_ts,
1219                op,
1220                visibility,
1221            }],
1222        );
1223        let catalog = self.catalog_puts_for_encoded(encoded, commit_ts, op)?;
1224        self.apply_prepared_puts_with_catalog(&puts, &catalog)
1225    }
1226
1227    /// Apply pre-encoded index puts as one RocksDB `WriteBatch`.
1228    ///
1229    /// Empty `puts` is a no-op. Caller encodes keys via [`crate::prepare_hexastore_puts`].
1230    /// Does not update the named-graph catalog; use
1231    /// [`Self::apply_prepared_puts_with_catalog`] on the S-axis write path.
1232    pub fn apply_prepared_puts(&self, puts: &[HexastorePut]) -> Result<(), StorageError> {
1233        self.apply_prepared_puts_with_catalog(puts, &[])
1234    }
1235
1236    /// Apply hexastore index puts and catalog puts in the same `WriteBatch`.
1237    ///
1238    /// Empty `puts` and empty `catalog` is a no-op. Catalog puts require the S axis.
1239    pub fn apply_prepared_puts_with_catalog(
1240        &self,
1241        puts: &[HexastorePut],
1242        catalog: &[CatalogPut],
1243    ) -> Result<(), StorageError> {
1244        if puts.is_empty() && catalog.is_empty() {
1245            return Ok(());
1246        }
1247        if !catalog.is_empty() && self.cf_catalog.is_none() {
1248            return Err(StorageError::CatalogNotOnAxis(self.axis));
1249        }
1250        let mut batch = self.db.write_batch();
1251        for put in puts {
1252            let cf = match put.cf_index {
1253                0 => &self.cf0,
1254                1 => &self.cf1,
1255                other => {
1256                    return Err(StorageError::Backend(format!(
1257                        "hexastore put cf_index {other} is not 0 or 1"
1258                    )));
1259                }
1260            };
1261            batch.insert(cf, &put.key, &put.value);
1262        }
1263        if let Some(cf) = &self.cf_catalog {
1264            for put in catalog {
1265                batch.insert(cf, &put.key, &put.value);
1266            }
1267        }
1268        batch.commit()
1269    }
1270
1271    /// Prefix-seek the catalog for each graph and stage `Present` when missing or Dropped.
1272    pub fn catalog_puts_for_insert(
1273        &self,
1274        graphs: &[(EncodedTerm, CommitTs)],
1275    ) -> Result<Vec<CatalogPut>, StorageError> {
1276        if self.axis != PartitionAxis::S {
1277            return Err(StorageError::CatalogNotOnAxis(self.axis));
1278        }
1279        stage_catalog_puts(graphs, |graph| self.catalog_newest_state(graph))
1280    }
1281
1282    /// Insert an empty named graph (or recreate after Dropped) at `commit_ts`.
1283    pub fn add_named_graph(
1284        &self,
1285        graph: &EncodedTerm,
1286        commit_ts: CommitTs,
1287    ) -> Result<(), StorageError> {
1288        require_catalog_graph(graph)?;
1289        let puts = self.catalog_puts_for_insert(&[(graph.clone(), commit_ts)])?;
1290        self.apply_prepared_puts_with_catalog(&[], &puts)
1291    }
1292
1293    /// Named graphs whose newest in-snapshot catalog version is `Present`.
1294    ///
1295    /// Includes empty graphs. Never includes the RDF default graph.
1296    pub fn list_named_graphs(
1297        &self,
1298        snapshot: SnapshotId,
1299    ) -> Result<Vec<EncodedTerm>, StorageError> {
1300        let cf = self.catalog_cf()?;
1301        let mut iter = self.db.scan_prefix(cf, &[]);
1302        let mut entries = Vec::new();
1303        while iter.is_valid() {
1304            let Some(key) = iter.key() else { break };
1305            let Some(value) = iter.value() else {
1306                return Err(StorageError::Corrupt(
1307                    "catalog iterator key without value".to_owned(),
1308                ));
1309            };
1310            entries.push((key.to_vec(), value.to_vec()));
1311            iter.next();
1312        }
1313        iter.status()?;
1314        collect_dedup_visible_catalog_graphs(
1315            entries
1316                .iter()
1317                .map(|(key, value)| (key.as_slice(), value.as_slice())),
1318            snapshot,
1319        )
1320    }
1321
1322    /// Rebuild `named_graphs_catalog` from all SPOG versions (S axis only).
1323    ///
1324    /// For each named graph, records the earliest Put `commit_ts`. Prefix-seeks
1325    /// the catalog and writes `Present` only when the prefix is empty — never
1326    /// clobbers an existing Present or Dropped version.
1327    pub fn rebuild_named_graph_catalog(&self) -> Result<CatalogRebuildStats, StorageError> {
1328        let _ = self.catalog_cf()?;
1329        let mut first_puts = Vec::new();
1330        self.visit_index_versions(IndexPermutation::Spog, |quad, commit_ts, op| {
1331            record_first_put_graph(&mut first_puts, &quad.graph_name, commit_ts, op);
1332            Ok(())
1333        })?;
1334        let mut stats = CatalogRebuildStats::default();
1335        let mut staged = Vec::new();
1336        for (graph, commit_ts) in &first_puts {
1337            if self.catalog_prefix_occupied(graph)? {
1338                stats.graphs_skipped += 1;
1339            } else {
1340                staged.push(CatalogPut::new(
1341                    graph,
1342                    *commit_ts,
1343                    GraphCatalogState::Present,
1344                )?);
1345                stats.graphs_inserted += 1;
1346            }
1347        }
1348        self.apply_prepared_puts_with_catalog(&[], &staged)?;
1349        Ok(stats)
1350    }
1351
1352    /// Walk every versioned key in an axis-local index (no MVCC collapse).
1353    pub fn visit_index_versions(
1354        &self,
1355        permutation: IndexPermutation,
1356        mut visit: impl FnMut(&EncodedQuad, CommitTs, StorageOp) -> Result<(), StorageError>,
1357    ) -> Result<(), StorageError> {
1358        let cf = self.cf_for(permutation)?;
1359        let mut iter = self.db.scan_prefix(cf, &[]);
1360        while iter.is_valid() {
1361            let Some(key) = iter.key() else { break };
1362            let Some(value) = iter.value() else {
1363                return Err(StorageError::Corrupt(
1364                    "iterator key without value".to_owned(),
1365                ));
1366            };
1367            let (quad, commit_ts) = decode_versioned_key(permutation, key)?;
1368            let (op, _visibility) = decode_storage_value(value)?;
1369            visit(&quad, commit_ts, op)?;
1370            iter.next();
1371        }
1372        iter.status()
1373    }
1374
1375    /// Prefix/range scan returning encoded quads visible at `snapshot`.
1376    ///
1377    /// For each logical quad, takes the newest version with `commit_ts <= snapshot`
1378    /// and includes it only if `op == Put`. Visibility is not enforced yet.
1379    pub fn scan_pattern(
1380        &self,
1381        pattern: &EncodedTriplePattern,
1382        snapshot: SnapshotId,
1383    ) -> Result<Vec<EncodedQuad>, StorageError> {
1384        self.scan_pattern_in(pattern.best_permutation(self.axis), pattern, snapshot)
1385    }
1386
1387    /// Scan `pattern` through an explicitly chosen axis-local column family.
1388    ///
1389    /// Returns [`StorageError::PermutationNotOwned`] when `permutation` belongs
1390    /// to another partition axis.
1391    pub fn scan_pattern_in(
1392        &self,
1393        permutation: IndexPermutation,
1394        pattern: &EncodedTriplePattern,
1395        snapshot: SnapshotId,
1396    ) -> Result<Vec<EncodedQuad>, StorageError> {
1397        // Unlimited drain: the page's verdict is ExhaustedScan by
1398        // construction and carries no information for this caller.
1399        self.scan_pattern_page(
1400            permutation,
1401            pattern,
1402            snapshot,
1403            0,
1404            None,
1405            GByteFilter::Unconstrained,
1406            false,
1407            IriOnlyMask::NONE,
1408        )
1409        .map(|page| page.rows)
1410    }
1411
1412    /// Prefix scan with the **full matcher semantics**: residual `graph_filter`
1413    /// membership, `merge_default_graph` whole-triple collapse (rows return with G
1414    /// rewritten to DefaultGraph), the exclusive `start_after` cursor, and
1415    /// `iri_only` segment pushdown all run inside the RowMatcher on raw key
1416    /// bytes. `limit` counts **post-filter** matches (`0` = unlimited) — one
1417    /// continuous walk, no decoded pre-filter chunking.
1418    #[allow(clippy::too_many_arguments)]
1419    pub fn scan_pattern_page(
1420        &self,
1421        permutation: IndexPermutation,
1422        pattern: &EncodedTriplePattern,
1423        snapshot: SnapshotId,
1424        limit: u64,
1425        start_after: Option<&EncodedQuad>,
1426        graph_filter: GByteFilter,
1427        merge_default_graph: bool,
1428        iri_only: IriOnlyMask,
1429    ) -> Result<ScanPage, StorageError> {
1430        self.scan_pattern_page_with_comparisons(
1431            permutation,
1432            pattern,
1433            snapshot,
1434            limit,
1435            start_after,
1436            graph_filter,
1437            merge_default_graph,
1438            iri_only,
1439            &ComparisonMask::default(),
1440        )
1441    }
1442
1443    /// [`Self::scan_pattern_page`] with compiled slot comparisons applied
1444    /// inside the walk, before a row reaches the page.
1445    #[allow(clippy::too_many_arguments)]
1446    pub fn scan_pattern_page_with_comparisons(
1447        &self,
1448        permutation: IndexPermutation,
1449        pattern: &EncodedTriplePattern,
1450        snapshot: SnapshotId,
1451        limit: u64,
1452        start_after: Option<&EncodedQuad>,
1453        graph_filter: GByteFilter,
1454        merge_default_graph: bool,
1455        iri_only: IriOnlyMask,
1456        mask: &ComparisonMask,
1457    ) -> Result<ScanPage, StorageError> {
1458        // The decoded adapter runs the same RowMatcher walk, decodes each
1459        // emitted row, and enforces the post-filter limit; this callback only
1460        // adds the merge-default G rewrite.
1461        let mut out = Vec::new();
1462        let exhausted = self.visit_pattern_quads(
1463            permutation,
1464            pattern,
1465            snapshot,
1466            limit,
1467            start_after,
1468            graph_filter,
1469            merge_default_graph,
1470            iri_only,
1471            mask,
1472            |mut quad| {
1473                if merge_default_graph {
1474                    quad = quad.into_merged_default();
1475                }
1476                out.push(quad);
1477                Ok(true)
1478            },
1479        )?;
1480        Ok(ScanPage {
1481            rows: out,
1482            exhausted: Some(exhausted),
1483        })
1484    }
1485
1486    /// Count matching rows with the **full matcher semantics** — same
1487    /// `graph_filter` / `merge_default_graph` / cursor / `iri_only` contract as
1488    /// [`Self::scan_pattern_page`], counting raw [`KeyRow`]s without
1489    /// decoding any term. `limit` counts post-filter matches (`0` = unlimited).
1490    ///
1491    /// Execution mode resolves once per process from `WARATAH_COUNT_WALKS`
1492    /// (see [`count_walk_mode`]). Eligible shapes slice the walk across
1493    /// scoped threads and sum the per-slice counts — identical results by
1494    /// construction (slices are key-disjoint, and the version-group straddle
1495    /// skip keeps every MVCC group decision with the slice holding the
1496    /// group's newest version). Limited counts (`limit > 0`) and shapes
1497    /// without a usable slice plan stay serial: parallel workers cannot
1498    /// honor a global early-stop budget without coordination, and a limited
1499    /// count is an existence-style check where the serial early exit is
1500    /// already cheap.
1501    #[allow(clippy::too_many_arguments)]
1502    pub fn count_pattern_impl(
1503        &self,
1504        permutation: IndexPermutation,
1505        pattern: &EncodedTriplePattern,
1506        snapshot: SnapshotId,
1507        limit: u64,
1508        graph_filter: GByteFilter,
1509        merge_default_graph: bool,
1510    ) -> Result<u64, StorageError> {
1511        let mode = count_walk_mode();
1512        self.count_pattern_impl_with_mode(
1513            mode,
1514            permutation,
1515            pattern,
1516            snapshot,
1517            limit,
1518            graph_filter,
1519            merge_default_graph,
1520            &[],
1521        )
1522    }
1523
1524    /// [`Self::count_pattern_impl`] with advisory TSG class totals — the
1525    /// partition's local `class_counts` profile map in ascending `StrHash`
1526    /// order. Only the TSG full-axis shape consumes the hint, cutting the
1527    /// walk at class boundaries with balanced row shares; every other shape
1528    /// and every thin/stale hint degrades to byte-even slicing. The hint is
1529    /// advisory in the ARCH.md §10 sense: a wrong estimate picks a wrong
1530    /// slice layout, never a wrong answer. `force_serial` (the partition
1531    /// dispatch gate's on-caller path: a µs-scale count must not pay the
1532    /// worker-pool wake) overrides `WARATAH_COUNT_WALKS` for this call.
1533    #[allow(clippy::too_many_arguments)]
1534    pub fn count_pattern_impl_with_class_totals(
1535        &self,
1536        permutation: IndexPermutation,
1537        pattern: &EncodedTriplePattern,
1538        snapshot: SnapshotId,
1539        limit: u64,
1540        graph_filter: GByteFilter,
1541        merge_default_graph: bool,
1542        class_totals: &[(StrHash, u64)],
1543        force_serial: bool,
1544    ) -> Result<u64, StorageError> {
1545        let mode = if force_serial {
1546            CountWalkMode::Serial
1547        } else {
1548            count_walk_mode()
1549        };
1550        self.count_pattern_impl_with_mode(
1551            mode,
1552            permutation,
1553            pattern,
1554            snapshot,
1555            limit,
1556            graph_filter,
1557            merge_default_graph,
1558            class_totals,
1559        )
1560    }
1561
1562    /// [`Self::count_pattern_impl`] with an explicit mode and hint (tests pin
1563    /// per-mode behavior without process-global env).
1564    #[allow(clippy::too_many_arguments)]
1565    pub(crate) fn count_pattern_impl_with_mode(
1566        &self,
1567        mode: CountWalkMode,
1568        permutation: IndexPermutation,
1569        pattern: &EncodedTriplePattern,
1570        snapshot: SnapshotId,
1571        limit: u64,
1572        graph_filter: GByteFilter,
1573        merge_default_graph: bool,
1574        class_totals: &[(StrHash, u64)],
1575    ) -> Result<u64, StorageError> {
1576        attest_count_walk_mode(mode);
1577        // `merge_default_graph` collapses graph variants of one triple into
1578        // a single row via per-walk dedup state; slices would each hold
1579        // their own state, so a boundary falling between two graph variants
1580        // of the same triple would count it twice. Merge counts are rare —
1581        // keep them serial.
1582        if let CountWalkMode::Parallel(workers) = mode
1583            && limit == 0
1584            && !merge_default_graph
1585        {
1586            let workers = workers.min(worker_pool::effective_width());
1587            // A pool width below 2 cannot slice — and the parallel walk's
1588            // pool wake cannot pay off on it — so fall through to the serial
1589            // walk (this is also how a 1-wide pool handles default-on).
1590            if workers >= 2 {
1591                let cf = self.cf_for(permutation)?;
1592                let prefix = pattern.build_scan_prefix_bytes(permutation);
1593                // Eligibility first: `count_walk_plan` decides the shape gate
1594                // without touching the store. The arena-tag probe (one seek:
1595                // the range's first key's type-tag byte, so boundaries spread
1596                // inside the region real keys occupy — see `even_boundaries`;
1597                // an empty range has no tag and its slices are all empty
1598                // regardless) runs lazily, only when a byte-even branch
1599                // builds boundaries.
1600                if let Some(plan) = count_walk_plan(
1601                    workers,
1602                    permutation,
1603                    pattern,
1604                    &graph_filter,
1605                    class_totals,
1606                    || {
1607                        let probe = self.db.scan_prefix(cf, &prefix);
1608                        let tag = probe.key().and_then(|key| key.get(prefix.len()).copied());
1609                        tag.unwrap_or(0x01)
1610                    },
1611                ) {
1612                    return self.count_pattern_sliced(
1613                        permutation,
1614                        pattern,
1615                        snapshot,
1616                        graph_filter,
1617                        merge_default_graph,
1618                        plan,
1619                    );
1620                }
1621            }
1622        }
1623        let mut count = 0u64;
1624        self.visit_pattern_rows(
1625            permutation,
1626            pattern,
1627            snapshot,
1628            None,
1629            graph_filter,
1630            merge_default_graph,
1631            IriOnlyMask::NONE,
1632            &ComparisonMask::default(),
1633            |_row| {
1634                count += 1;
1635                Ok(limit == 0 || count < limit)
1636            },
1637        )?;
1638        Ok(count)
1639    }
1640
1641    /// Run a planned parallel count: one worker-pool unit per slice, each
1642    /// with its own iterator, [`RowMatcher`], and [`SnapshotScanState`]; the
1643    /// merge is a sum over slice-ordered parts (slices are key-disjoint, so
1644    /// no ordering question exists). Slice count is bounded by
1645    /// [`worker_pool::effective_width`] — extra slices would only queue
1646    /// behind the same fixed workers. A panicking unit is reported by the
1647    /// pool as a backend error; the first storage error wins. Without an
1648    /// installed pool (tests, batch tools) `run_units` falls back to
1649    /// scoped-thread spawning on the calling thread's affinity.
1650    fn count_pattern_sliced(
1651        &self,
1652        permutation: IndexPermutation,
1653        pattern: &EncodedTriplePattern,
1654        snapshot: SnapshotId,
1655        graph_filter: GByteFilter,
1656        merge_default_graph: bool,
1657        plan: CountWalkPlan,
1658    ) -> Result<u64, StorageError> {
1659        let cf = *self.cf_for(permutation)?;
1660        // Units own their inputs (the pool outlives this call, so nothing
1661        // may borrow caller state); the pattern/filter clones are small
1662        // against the I/O each slice walks.
1663        let units: Vec<CountSliceUnit> = plan
1664            .slices
1665            .into_iter()
1666            .enumerate()
1667            .map(|(index, slice)| CountSliceUnit {
1668                db: self.db.clone(),
1669                cf,
1670                permutation,
1671                pattern: pattern.clone(),
1672                snapshot,
1673                graph_filter: graph_filter.clone(),
1674                merge_default_graph,
1675                prefix: plan.prefix.clone(),
1676                slice,
1677                is_first: index == 0,
1678            })
1679            .collect();
1680        let outcomes = worker_pool::run_units(units);
1681        let mut counts = Vec::with_capacity(outcomes.len());
1682        for outcome in outcomes {
1683            match outcome {
1684                UnitOutcome::Ok(part) => counts.push(part?),
1685                UnitOutcome::Panicked(message) => {
1686                    return Err(StorageError::Backend(format!(
1687                        "pattern count worker panicked: {message}"
1688                    )));
1689                }
1690            }
1691        }
1692        if count_walks_debug_enabled() {
1693            let total: u64 = counts.iter().sum();
1694            eprintln!(
1695                "storage-trace pattern count: cf={} slices={} rows={counts:?} total={total}",
1696                permutation.cf_name(),
1697                counts.len(),
1698            );
1699        }
1700        Ok(counts.iter().sum())
1701    }
1702
1703    /// Count matching quads visible at `snapshot` without collecting rows.
1704    ///
1705    /// `limit` of `0` is unlimited; a positive limit stops the iterator once
1706    /// that many matches have been counted.
1707    pub fn count_pattern_best_permutation(
1708        &self,
1709        pattern: &EncodedTriplePattern,
1710        snapshot: SnapshotId,
1711        limit: u64,
1712    ) -> Result<u64, StorageError> {
1713        self.count_pattern_in(
1714            pattern.best_permutation(self.axis),
1715            pattern,
1716            snapshot,
1717            limit,
1718        )
1719    }
1720
1721    /// Count `pattern` through an explicitly chosen axis-local column family.
1722    ///
1723    /// Returns [`StorageError::PermutationNotOwned`] when `permutation` belongs
1724    /// to another partition axis. `limit` of `0` is unlimited.
1725    pub fn count_pattern_in(
1726        &self,
1727        permutation: IndexPermutation,
1728        pattern: &EncodedTriplePattern,
1729        snapshot: SnapshotId,
1730        limit: u64,
1731    ) -> Result<u64, StorageError> {
1732        // Counting never needs terms decoded: walk the raw rows directly.
1733        let mut count = 0u64;
1734        self.visit_pattern_rows(
1735            permutation,
1736            pattern,
1737            snapshot,
1738            None,
1739            GByteFilter::Unconstrained,
1740            false,
1741            IriOnlyMask::NONE,
1742            &ComparisonMask::default(),
1743            |_row| {
1744                count += 1;
1745                Ok(limit == 0 || count < limit)
1746            },
1747        )?;
1748        Ok(count)
1749    }
1750
1751    /// Stream every visible matching row to `emit` in one iterator walk;
1752    /// `emit` returning `false` stops the walk early.
1753    ///
1754    /// Same visibility / cursor contract as [`Self::scan_pattern_page`] with
1755    /// `limit = 0` — the callback decides when to stop. A compiled
1756    /// [`RowMatcher`] applies bound slots, `graph_filter` membership,
1757    /// `merge_default_graph` whole-triple collapse, and the exclusive
1758    /// `start_after` cursor on raw key bytes — no `EncodedTerm` is
1759    /// constructed on the walk.
1760    #[allow(clippy::too_many_arguments)]
1761    pub(crate) fn visit_pattern_rows(
1762        &self,
1763        permutation: IndexPermutation,
1764        pattern: &EncodedTriplePattern,
1765        snapshot: SnapshotId,
1766        start_after: Option<&EncodedQuad>,
1767        graph_filter: GByteFilter,
1768        merge_default_graph: bool,
1769        iri_only: IriOnlyMask,
1770        mask: &ComparisonMask,
1771        mut on_match: impl FnMut(&KeyRow) -> Result<bool, StorageError>,
1772    ) -> Result<ScanExhaustion, StorageError> {
1773        let cf = self.cf_for(permutation)?;
1774        let prefix = pattern.build_scan_prefix_bytes(permutation);
1775
1776        let mut state = SnapshotScanState::default();
1777        let mut matcher = RowMatcher::compile(
1778            pattern,
1779            permutation,
1780            graph_filter,
1781            merge_default_graph,
1782            start_after,
1783            iri_only,
1784        );
1785        // The exclusive-cursor bound is fixed for the whole walk; encode it
1786        // once. Re-encoding per row dominated scan profiles (one key build +
1787        // realloc chain per visited row).
1788        let cursor_key = start_after.map(|quad| encode_index_key(permutation, quad));
1789        let seek = cursor_key
1790            .as_deref()
1791            .filter(|key| *key > prefix.as_slice())
1792            .unwrap_or(prefix.as_slice());
1793        let mut iter = if seek == prefix.as_slice() {
1794            self.db.scan_prefix(cf, &prefix)
1795        } else {
1796            self.db.scan_prefix_from(cf, &prefix, seek)
1797        };
1798        // Walk verdict: the sink stopping the walk (limit reached) is
1799        // `Limited`; every loop exit below left the pattern's key
1800        // range, which is `ExhaustedScan`. A sink error also stops the
1801        // walk and reports `Limited` — the error surfaces from `?`
1802        // and the verdict is discarded, so no caller can act on it.
1803        let mut verdict = ScanExhaustion::ExhaustedScan;
1804        while iter.is_valid() {
1805            let Some(key) = iter.key() else { break };
1806            if !key.starts_with(&prefix) {
1807                break;
1808            }
1809            if let Some(cursor) = cursor_key.as_deref() {
1810                let logical = versioned_key_term_prefix(key)?;
1811                if logical <= cursor {
1812                    iter.next();
1813                    continue;
1814                }
1815            }
1816            let decision = {
1817                let Some(value) = iter.value() else {
1818                    return Err(StorageError::Corrupt(
1819                        "iterator key without value".to_owned(),
1820                    ));
1821                };
1822                matcher.matches_row(key, value, snapshot, &mut state)?
1823            };
1824            if let MatchDecision::Emit {
1825                slot_starts,
1826                commit_ts,
1827            } = decision
1828            {
1829                let row = KeyRow {
1830                    key,
1831                    permutation,
1832                    seg_starts: slot_starts,
1833                    commit_ts,
1834                };
1835                // Slot comparison mask: a proven-false row never reaches
1836                // the page and never counts toward the limit.
1837                if mask.keeps(row.logical(), &row.seg_starts) && !on_match(&row)? {
1838                    verdict = ScanExhaustion::Limited;
1839                    break;
1840                }
1841            }
1842            iter.next();
1843        }
1844        iter.status()?;
1845        Ok(verdict)
1846    }
1847
1848    #[allow(clippy::too_many_arguments)]
1849    pub(crate) fn visit_pattern_quads(
1850        &self,
1851        permutation: IndexPermutation,
1852        pattern: &EncodedTriplePattern,
1853        snapshot: SnapshotId,
1854        limit: u64,
1855        start_after: Option<&EncodedQuad>,
1856        graph_filter: GByteFilter,
1857        merge_default_graph: bool,
1858        iri_only: IriOnlyMask,
1859        mask: &ComparisonMask,
1860        // `true` = keep walking, `false` = the sink is done (guard reached,
1861        // consumer gone). An `Err` aborts with that error.
1862        mut on_match: impl FnMut(EncodedQuad) -> Result<bool, StorageError>,
1863    ) -> Result<ScanExhaustion, StorageError> {
1864        let mut error = None;
1865        let mut matched = 0u64;
1866        // Unary paths decode only rows that already passed the matcher.
1867        // The walk verdict passes through unchanged: the adapter below
1868        // stops the walk only at the limit (`Limited`, the honest
1869        // verdict) or on a decode/sink error (the error surfaces from
1870        // `error` and the verdict is discarded).
1871        let verdict = self.visit_pattern_rows(
1872            permutation,
1873            pattern,
1874            snapshot,
1875            start_after,
1876            graph_filter,
1877            merge_default_graph,
1878            iri_only,
1879            mask,
1880            |row| {
1881                if error.is_some() {
1882                    return Ok(false);
1883                }
1884                match decode_index_key(permutation, row.logical()) {
1885                    Ok(quad) => {
1886                        // EDGE-triggered limit: a row arriving AT the page
1887                        // limit proves more data exists (stop,
1888                        // `Limited`) but is not delivered to the
1889                        // sink; when the data ends exactly at the limit
1890                        // this row never arrives and the walk completes
1891                        // with the terminal verdict.
1892                        if limit > 0 && matched >= limit {
1893                            return Ok(false);
1894                        }
1895                        match on_match(quad) {
1896                            Ok(keep_going) => {
1897                                matched += 1;
1898                                Ok(keep_going)
1899                            }
1900                            Err(e) => {
1901                                error = Some(e);
1902                                Ok(false)
1903                            }
1904                        }
1905                    }
1906                    Err(e) => {
1907                        error = Some(e);
1908                        Ok(false)
1909                    }
1910                }
1911            },
1912        )?;
1913        match error {
1914            Some(e) => Err(e),
1915            None => Ok(verdict),
1916        }
1917    }
1918
1919    /// Allow-list prefix scan with the **full matcher semantics** per tight
1920    /// prefix: residual `graph_filter` membership and `merge_default_graph`
1921    /// collapse (rows return with G rewritten to DefaultGraph) run inside
1922    /// each prefix's RowMatcher. `limit` counts post-filter matches
1923    /// (`0` = unlimited). Returns `None` when `slot` does not extend
1924    /// `permutation`
1925    #[allow(clippy::too_many_arguments)]
1926    pub fn scan_pattern_page_allow_list(
1927        &self,
1928        permutation: IndexPermutation,
1929        pattern: &EncodedTriplePattern,
1930        snapshot: SnapshotId,
1931        limit: u64,
1932        start_after: Option<&EncodedQuad>,
1933        allow_list_slot: QuadSlot,
1934        allow_terms: &[EncodedTerm],
1935        graph_filter: GByteFilter,
1936        merge_default_graph: bool,
1937        iri_only: IriOnlyMask,
1938    ) -> Result<Option<ScanPage>, StorageError> {
1939        self.scan_pattern_page_allow_list_with_comparisons(
1940            permutation,
1941            pattern,
1942            snapshot,
1943            limit,
1944            start_after,
1945            allow_list_slot,
1946            allow_terms,
1947            graph_filter,
1948            merge_default_graph,
1949            iri_only,
1950            &ComparisonMask::default(),
1951        )
1952    }
1953
1954    /// [`Self::scan_pattern_page_allow_list`] with compiled slot comparisons
1955    /// applied inside each tight prefix's walk.
1956    #[allow(clippy::too_many_arguments)]
1957    pub fn scan_pattern_page_allow_list_with_comparisons(
1958        &self,
1959        permutation: IndexPermutation,
1960        pattern: &EncodedTriplePattern,
1961        snapshot: SnapshotId,
1962        limit: u64,
1963        start_after: Option<&EncodedQuad>,
1964        allow_list_slot: QuadSlot,
1965        allow_terms: &[EncodedTerm],
1966        graph_filter: GByteFilter,
1967        merge_default_graph: bool,
1968        iri_only: IriOnlyMask,
1969        mask: &ComparisonMask,
1970    ) -> Result<Option<ScanPage>, StorageError> {
1971        let mut out = Vec::new();
1972        let verdict = self.visit_allow_list_rows(
1973            permutation,
1974            pattern,
1975            snapshot,
1976            start_after,
1977            allow_list_slot,
1978            allow_terms,
1979            graph_filter,
1980            merge_default_graph,
1981            iri_only,
1982            mask,
1983            |row| {
1984                // EDGE-triggered limit: a row arriving AT the page limit
1985                // proves more data exists (stop, `Limited`) but does
1986                // not enter the page; when the data ends exactly at the
1987                // limit this row never arrives and the walk completes with
1988                // the terminal verdict. A LEVEL-triggered check (stop when
1989                // the count reaches the limit) cannot tell those apart.
1990                if limit > 0 && (out.len() as u64) >= limit {
1991                    return Ok(false);
1992                }
1993                let mut quad = decode_index_key(permutation, row.logical())?;
1994                if merge_default_graph {
1995                    quad = quad.into_merged_default();
1996                }
1997                out.push(quad);
1998                Ok(true)
1999            },
2000        )?;
2001        Ok(verdict.map(|exhausted| ScanPage {
2002            rows: out,
2003            exhausted: Some(exhausted),
2004        }))
2005    }
2006
2007    /// Domain scan: distinct slot-1 head terms under each slot-0 constraint
2008    /// on `permutation` (POSG predicates→objects, SPOG subjects→predicates,
2009    /// SOPG subjects→objects, OPSG objects→predicates). Axis-local only.
2010    ///
2011    /// After a visible Put (path 2: whose G is allowed), Seek past the rest of
2012    /// that head term. A Delete only retires that logical quad; keep walking
2013    /// this head. `limit` counts emitted pairs (`0` = unlimited).
2014    /// `iri_only_head` rejects non-NamedNode heads (FILTER(isIRI) pushdown).
2015    ///
2016    /// Execution mode resolves once per process from `WARATAH_DOMAIN_WALKS`
2017    /// (see [`domain_scan_mode`]). Every mode
2018    /// visits constraints in key order (`build_walk_constraints`) and
2019    /// emits in that order regardless of caller order: with `limit > 0` all
2020    /// modes truncate the key-first hits, and `start_after_*` pagination is
2021    /// key-order coherent (constraints sorting before the cursor constraint
2022    /// were fully emitted before it, so the resume skip loses nothing).
2023    #[allow(clippy::too_many_arguments)]
2024    pub fn scan_domain(
2025        &self,
2026        permutation: IndexPermutation,
2027        constraints: &[EncodedTerm],
2028        snapshot: SnapshotId,
2029        limit: u64,
2030        start_after_constraint: Option<&EncodedTerm>,
2031        start_after_term: Option<&EncodedTerm>,
2032        graph_name: Option<&EncodedTerm>,
2033        graph_filter_terms: &[EncodedTerm],
2034        graph_filter_allow: bool,
2035        iri_only_head: bool,
2036    ) -> Result<Vec<DomainScanHit>, StorageError> {
2037        let mode = domain_scan_mode();
2038        attest_domain_scan_mode(mode);
2039        self.scan_domain_with_mode(
2040            mode,
2041            permutation,
2042            constraints,
2043            snapshot,
2044            limit,
2045            start_after_constraint,
2046            start_after_term,
2047            graph_name,
2048            graph_filter_terms,
2049            graph_filter_allow,
2050            iri_only_head,
2051        )
2052    }
2053
2054    /// [`Self::scan_domain`] with an explicit mode (tests pin per-mode
2055    /// behavior without process-global env).
2056    #[allow(clippy::too_many_arguments)]
2057    pub(crate) fn scan_domain_with_mode(
2058        &self,
2059        mode: DomainScanMode,
2060        permutation: IndexPermutation,
2061        constraints: &[EncodedTerm],
2062        snapshot: SnapshotId,
2063        limit: u64,
2064        start_after_constraint: Option<&EncodedTerm>,
2065        start_after_term: Option<&EncodedTerm>,
2066        graph_name: Option<&EncodedTerm>,
2067        graph_filter_terms: &[EncodedTerm],
2068        graph_filter_allow: bool,
2069        iri_only_head: bool,
2070    ) -> Result<Vec<DomainScanHit>, StorageError> {
2071        match mode {
2072            DomainScanMode::Legacy => self.scan_domain_legacy(
2073                permutation,
2074                constraints,
2075                snapshot,
2076                limit,
2077                start_after_constraint,
2078                start_after_term,
2079                graph_name,
2080                graph_filter_terms,
2081                graph_filter_allow,
2082                iri_only_head,
2083            ),
2084            DomainScanMode::ParallelWalks(workers) => self.scan_domain_parallel(
2085                workers,
2086                permutation,
2087                constraints,
2088                snapshot,
2089                limit,
2090                start_after_constraint,
2091                start_after_term,
2092                graph_name,
2093                graph_filter_terms,
2094                graph_filter_allow,
2095                iri_only_head,
2096            ),
2097        }
2098    }
2099
2100    /// Legacy domain scan: the confined walk — one bounded iterator per
2101    /// constraint over the key-sorted constraint list, on the calling
2102    /// thread — emitting in key order (see [`DomainScanMode`]). The loop
2103    /// body is [`confined_hits_on`], shared with the parallel slices.
2104    #[allow(clippy::too_many_arguments)]
2105    fn scan_domain_legacy(
2106        &self,
2107        permutation: IndexPermutation,
2108        constraints: &[EncodedTerm],
2109        snapshot: SnapshotId,
2110        limit: u64,
2111        start_after_constraint: Option<&EncodedTerm>,
2112        start_after_term: Option<&EncodedTerm>,
2113        graph_name: Option<&EncodedTerm>,
2114        graph_filter_terms: &[EncodedTerm],
2115        graph_filter_allow: bool,
2116        iri_only_head: bool,
2117    ) -> Result<Vec<DomainScanHit>, StorageError> {
2118        // Sorted prep is load-bearing, not cosmetic: the per-constraint
2119        // resume skip (`head_resume_seek` drops constraints sorting before
2120        // the cursor constraint) is only sound when the walk visits
2121        // constraints in key order, so a cursor inside constraint C proves
2122        // every constraint sorting before C was fully emitted on earlier
2123        // pages. Caller order cannot express that, so it is normalized
2124        // here regardless of the order the caller passed.
2125        let prepared = build_walk_constraints(
2126            permutation,
2127            constraints,
2128            start_after_constraint,
2129            start_after_term,
2130        )?;
2131        if prepared.is_empty() {
2132            return Ok(Vec::new());
2133        }
2134        let cf = self.cf_for(permutation)?;
2135        let ctx = DomainWalkCtx::new(
2136            permutation,
2137            snapshot,
2138            graph_name,
2139            graph_filter_terms,
2140            graph_filter_allow,
2141            iri_only_head,
2142        );
2143        let budget = limit_budget(limit);
2144        confined_hits_on(&self.db, cf, &ctx, &prepared, budget.as_ref())
2145    }
2146
2147    /// Parallel domain scan: up to `workers` storage worker slices over
2148    /// contiguous key-disjoint runs of the sorted constraints, each
2149    /// constraint walked with its own bounded iterator
2150    /// ([`confined_hits_on`]).
2151    ///
2152    /// The slice count is clamped to the installed worker pool's width
2153    /// (`worker_pool::effective_width`): extra slices would only queue behind
2154    /// the same fixed workers. Units own their runs because the pool outlives
2155    /// this call; the copy is small against the I/O each slice performs.
2156    ///
2157    /// Each worker owns an independent `limit` budget: it walks up to
2158    /// `limit` hits of its slice, so no slice can be left with holes at its
2159    /// truncation point (a shared budget would let a later slice starve an
2160    /// earlier one, and a resume cursor could never revisit the missing
2161    /// keys). Merge is ordered concatenation — slices are key-disjoint
2162    /// ascending and prep deduped — so the merged vector is the unlimited
2163    /// key-order sequence up to over-fetch, and the final truncate yields
2164    /// exactly its key-first `limit` hits. Over-fetch is bounded: each
2165    /// worker buffers at most `limit` hits (K·limit worst case, local only —
2166    /// the wire sees the truncated merge).
2167    #[allow(clippy::too_many_arguments)]
2168    fn scan_domain_parallel(
2169        &self,
2170        workers: usize,
2171        permutation: IndexPermutation,
2172        constraints: &[EncodedTerm],
2173        snapshot: SnapshotId,
2174        limit: u64,
2175        start_after_constraint: Option<&EncodedTerm>,
2176        start_after_term: Option<&EncodedTerm>,
2177        graph_name: Option<&EncodedTerm>,
2178        graph_filter_terms: &[EncodedTerm],
2179        graph_filter_allow: bool,
2180        iri_only_head: bool,
2181    ) -> Result<Vec<DomainScanHit>, StorageError> {
2182        let cf = *self.cf_for(permutation)?;
2183        let prepared = build_walk_constraints(
2184            permutation,
2185            constraints,
2186            start_after_constraint,
2187            start_after_term,
2188        )?;
2189        if prepared.is_empty() {
2190            return Ok(Vec::new());
2191        }
2192        // Owned context shared by the units; the borrowed twin cannot cross
2193        // into a pool worker because the pool outlives this call.
2194        let ctx = Arc::new(
2195            DomainWalkCtx::new(
2196                permutation,
2197                snapshot,
2198                graph_name,
2199                graph_filter_terms,
2200                graph_filter_allow,
2201                iri_only_head,
2202            )
2203            .into_owned(),
2204        );
2205        let workers = workers.min(worker_pool::effective_width());
2206        // A pool width below 2 cannot slice — the pool wake cannot pay off
2207        // on it — so run the legacy walk instead (this is also how a 1-wide
2208        // pool handles default-on).
2209        if workers < 2 {
2210            return self.scan_domain_legacy(
2211                permutation,
2212                constraints,
2213                snapshot,
2214                limit,
2215                start_after_constraint,
2216                start_after_term,
2217                graph_name,
2218                graph_filter_terms,
2219                graph_filter_allow,
2220                iri_only_head,
2221            );
2222        }
2223        let slices = split_slices(prepared.len(), workers);
2224        let units: Vec<DomainHitsUnit> = slices
2225            .iter()
2226            .map(|slice| DomainHitsUnit {
2227                db: self.db.clone(),
2228                cf,
2229                ctx: Arc::clone(&ctx),
2230                // One independent budget per slice: exact key-first
2231                // truncation after the ordered merge (see the fn doc).
2232                slice: prepared[slice.clone()].to_vec(),
2233                budget: limit_budget(limit),
2234            })
2235            .collect();
2236        let outcomes = worker_pool::run_units(units);
2237        let mut hits = Vec::new();
2238        for outcome in outcomes {
2239            // Slice order keeps the merge ordered; a panicking unit surfaces
2240            // as a backend error in that same first-`Err` position.
2241            match outcome {
2242                UnitOutcome::Ok(part) => {
2243                    let mut part = part?;
2244                    hits.append(&mut part);
2245                }
2246                UnitOutcome::Panicked(message) => {
2247                    return Err(StorageError::Backend(format!(
2248                        "domain scan worker panicked: {message}"
2249                    )));
2250                }
2251            }
2252        }
2253        if limit > 0 && hits.len() > limit_to_usize(limit) {
2254            hits.truncate(limit_to_usize(limit));
2255        }
2256        Ok(hits)
2257    }
2258
2259    /// Domain count scan: run lengths of slot-1 head terms under each
2260    /// slot-0 constraint on `permutation`. Axis-local only. Twin of
2261    /// [`Self::scan_domain`] — same visibility semantics (per-logical-quad
2262    /// MVCC collapse, `op == Put`, graph window, `iri_only_head`), but the
2263    /// walk iterates every key of the constraint prefix instead of seeking
2264    /// past runs. What one increment represents is `mode` — see
2265    /// [`DomainCountMode`]. With `merge_default_graph` set the walk seeks
2266    /// past extra G per counted triple, which makes `Rows` coincide with
2267    /// `DistinctTerms`. Runs with zero visible rows are not emitted.
2268    /// `limit` counts emitted triples (`0` = unlimited).
2269    ///
2270    /// Execution mode resolves once per process from `WARATAH_DOMAIN_WALKS`
2271    /// (see [`domain_scan_mode`]) — the same
2272    /// switches and emission-order contract as [`Self::scan_domain`].
2273    #[allow(clippy::too_many_arguments)]
2274    pub fn scan_domain_counts(
2275        &self,
2276        permutation: IndexPermutation,
2277        constraints: &[EncodedTerm],
2278        snapshot: SnapshotId,
2279        limit: u64,
2280        start_after_constraint: Option<&EncodedTerm>,
2281        start_after_term: Option<&EncodedTerm>,
2282        graph_name: Option<&EncodedTerm>,
2283        graph_filter_terms: &[EncodedTerm],
2284        graph_filter_allow: bool,
2285        iri_only_head: bool,
2286        merge_default_graph: bool,
2287        mode: DomainCountMode,
2288    ) -> Result<Vec<DomainScanCountHit>, StorageError> {
2289        let exec = domain_scan_mode();
2290        attest_domain_scan_mode(exec);
2291        self.scan_domain_counts_with_mode(
2292            exec,
2293            permutation,
2294            constraints,
2295            snapshot,
2296            limit,
2297            start_after_constraint,
2298            start_after_term,
2299            graph_name,
2300            graph_filter_terms,
2301            graph_filter_allow,
2302            iri_only_head,
2303            merge_default_graph,
2304            mode,
2305        )
2306    }
2307
2308    /// [`Self::scan_domain_counts`] with an explicit mode (tests).
2309    #[allow(clippy::too_many_arguments)]
2310    pub(crate) fn scan_domain_counts_with_mode(
2311        &self,
2312        mode: DomainScanMode,
2313        permutation: IndexPermutation,
2314        constraints: &[EncodedTerm],
2315        snapshot: SnapshotId,
2316        limit: u64,
2317        start_after_constraint: Option<&EncodedTerm>,
2318        start_after_term: Option<&EncodedTerm>,
2319        graph_name: Option<&EncodedTerm>,
2320        graph_filter_terms: &[EncodedTerm],
2321        graph_filter_allow: bool,
2322        iri_only_head: bool,
2323        merge_default_graph: bool,
2324        count_mode: DomainCountMode,
2325    ) -> Result<Vec<DomainScanCountHit>, StorageError> {
2326        // TSG refusal: the distinct modes' region arithmetic assumes a
2327        // 4-slot layout (distinct term at slot 2, G last with a slot
2328        // before it). TSG's third component IS G — see
2329        // [`StorageError::DistinctCountsNotOnTsg`]. Rows mode has no
2330        // per-slot work and stays servable.
2331        if permutation == IndexPermutation::Tsg && count_mode != DomainCountMode::Rows {
2332            return Err(StorageError::DistinctCountsNotOnTsg);
2333        }
2334        match mode {
2335            DomainScanMode::Legacy => self.scan_domain_counts_legacy(
2336                permutation,
2337                constraints,
2338                snapshot,
2339                limit,
2340                start_after_constraint,
2341                start_after_term,
2342                graph_name,
2343                graph_filter_terms,
2344                graph_filter_allow,
2345                iri_only_head,
2346                merge_default_graph,
2347                count_mode,
2348            ),
2349            DomainScanMode::ParallelWalks(workers) => self.scan_domain_counts_parallel(
2350                workers,
2351                permutation,
2352                constraints,
2353                snapshot,
2354                limit,
2355                start_after_constraint,
2356                start_after_term,
2357                graph_name,
2358                graph_filter_terms,
2359                graph_filter_allow,
2360                iri_only_head,
2361                merge_default_graph,
2362                count_mode,
2363            ),
2364        }
2365    }
2366
2367    /// Legacy domain count scan: the confined count walk — one bounded
2368    /// iterator per constraint over the key-sorted constraint list, on the
2369    /// calling thread. The loop body is [`confined_counts_on`], shared with
2370    /// the parallel slices.
2371    #[allow(clippy::too_many_arguments)]
2372    fn scan_domain_counts_legacy(
2373        &self,
2374        permutation: IndexPermutation,
2375        constraints: &[EncodedTerm],
2376        snapshot: SnapshotId,
2377        limit: u64,
2378        start_after_constraint: Option<&EncodedTerm>,
2379        start_after_term: Option<&EncodedTerm>,
2380        graph_name: Option<&EncodedTerm>,
2381        graph_filter_terms: &[EncodedTerm],
2382        graph_filter_allow: bool,
2383        iri_only_head: bool,
2384        merge_default_graph: bool,
2385        count_mode: DomainCountMode,
2386    ) -> Result<Vec<DomainScanCountHit>, StorageError> {
2387        // Sorted prep is load-bearing, not cosmetic: the per-constraint
2388        // resume skip (`head_resume_seek` drops constraints sorting before
2389        // the cursor constraint) is only sound when the walk visits
2390        // constraints in key order, so a cursor inside constraint C proves
2391        // every constraint sorting before C was fully emitted on earlier
2392        // pages. Caller order cannot express that, so it is normalized
2393        // here regardless of the order the caller passed.
2394        let prepared = build_walk_constraints(
2395            permutation,
2396            constraints,
2397            start_after_constraint,
2398            start_after_term,
2399        )?;
2400        if prepared.is_empty() {
2401            return Ok(Vec::new());
2402        }
2403        let cf = self.cf_for(permutation)?;
2404        let ctx = DomainWalkCtx::new(
2405            permutation,
2406            snapshot,
2407            graph_name,
2408            graph_filter_terms,
2409            graph_filter_allow,
2410            iri_only_head,
2411        );
2412        let budget = limit_budget(limit);
2413        confined_counts_on(
2414            &self.db,
2415            cf,
2416            &ctx,
2417            &prepared,
2418            budget.as_ref(),
2419            merge_default_graph,
2420            count_mode,
2421        )
2422    }
2423
2424    /// Parallel domain count scan: the [`Self::scan_domain_parallel`] driver
2425    /// over the count walk — one independent `limit` budget per worker, so
2426    /// the ordered merge truncated to `limit` is exactly the key-first
2427    /// `limit` triples. A run cut short by a worker's own budget is not
2428    /// flushed; it sits strictly after that worker's `limit`-th hit, so it
2429    /// is dropped by the truncation or lies past the caller's resume cursor
2430    /// and is re-walked (and emitted) on the next page — the legacy `full`
2431    /// semantics.
2432    #[allow(clippy::too_many_arguments)]
2433    fn scan_domain_counts_parallel(
2434        &self,
2435        workers: usize,
2436        permutation: IndexPermutation,
2437        constraints: &[EncodedTerm],
2438        snapshot: SnapshotId,
2439        limit: u64,
2440        start_after_constraint: Option<&EncodedTerm>,
2441        start_after_term: Option<&EncodedTerm>,
2442        graph_name: Option<&EncodedTerm>,
2443        graph_filter_terms: &[EncodedTerm],
2444        graph_filter_allow: bool,
2445        iri_only_head: bool,
2446        merge_default_graph: bool,
2447        count_mode: DomainCountMode,
2448    ) -> Result<Vec<DomainScanCountHit>, StorageError> {
2449        let cf = *self.cf_for(permutation)?;
2450        let prepared = build_walk_constraints(
2451            permutation,
2452            constraints,
2453            start_after_constraint,
2454            start_after_term,
2455        )?;
2456        if prepared.is_empty() {
2457            return Ok(Vec::new());
2458        }
2459        // Owned context shared by the units; see [`Self::scan_domain_parallel`].
2460        let ctx = Arc::new(
2461            DomainWalkCtx::new(
2462                permutation,
2463                snapshot,
2464                graph_name,
2465                graph_filter_terms,
2466                graph_filter_allow,
2467                iri_only_head,
2468            )
2469            .into_owned(),
2470        );
2471        let workers = workers.min(worker_pool::effective_width());
2472        // A pool width below 2 cannot slice — see [`Self::scan_domain_parallel`].
2473        if workers < 2 {
2474            return self.scan_domain_counts_legacy(
2475                permutation,
2476                constraints,
2477                snapshot,
2478                limit,
2479                start_after_constraint,
2480                start_after_term,
2481                graph_name,
2482                graph_filter_terms,
2483                graph_filter_allow,
2484                iri_only_head,
2485                merge_default_graph,
2486                count_mode,
2487            );
2488        }
2489        let slices = split_slices(prepared.len(), workers);
2490        let units: Vec<DomainCountsUnit> = slices
2491            .iter()
2492            .map(|slice| DomainCountsUnit {
2493                db: self.db.clone(),
2494                cf,
2495                ctx: Arc::clone(&ctx),
2496                // One independent budget per slice: exact key-first
2497                // truncation after the ordered merge (see
2498                // [`Self::scan_domain_parallel`]).
2499                slice: prepared[slice.clone()].to_vec(),
2500                budget: limit_budget(limit),
2501                merge_default_graph,
2502                count_mode,
2503            })
2504            .collect();
2505        let outcomes = worker_pool::run_units(units);
2506        let mut hits = Vec::new();
2507        for outcome in outcomes {
2508            match outcome {
2509                UnitOutcome::Ok(part) => {
2510                    let mut part = part?;
2511                    hits.append(&mut part);
2512                }
2513                UnitOutcome::Panicked(message) => {
2514                    return Err(StorageError::Backend(format!(
2515                        "domain count scan worker panicked: {message}"
2516                    )));
2517                }
2518            }
2519        }
2520        if limit > 0 && hits.len() > limit_to_usize(limit) {
2521            hits.truncate(limit_to_usize(limit));
2522        }
2523        Ok(hits)
2524    }
2525
2526    /// Axis head scan: distinct slot-0 head terms of the whole `permutation`
2527    /// CF (SPOG subjects, PSOG predicates, OPSG objects, TSG classes).
2528    /// Axis-local only.
2529    ///
2530    /// Same skip-scan as [`Self::scan_domain`] with an empty constraint
2531    /// prefix. `limit` counts emitted terms (`0` = unlimited);
2532    /// `start_after_term` is an exclusive resume cursor. `iri_only_head`
2533    /// rejects non-NamedNode heads (FILTER(isIRI) pushdown). With non-empty
2534    /// `head_prefixes` the walk is a seek-union over those partial head-term
2535    /// byte ranges (opaque bytes; see
2536    /// [`prepare_head_prefixes`](crate::encode::head_scan::prepare_head_prefixes)
2537    /// for normalization and resume semantics); empty means the unfiltered
2538    /// whole-CF walk.
2539    #[allow(clippy::too_many_arguments)]
2540    pub fn scan_axis_head(
2541        &self,
2542        permutation: IndexPermutation,
2543        snapshot: SnapshotId,
2544        limit: u64,
2545        start_after_term: Option<&EncodedTerm>,
2546        graph_name: Option<&EncodedTerm>,
2547        graph_filter_terms: &[EncodedTerm],
2548        graph_filter_allow: bool,
2549        iri_only_head: bool,
2550        head_prefixes: &[Vec<u8>],
2551    ) -> Result<Vec<EncodedTerm>, StorageError> {
2552        let cf = self.cf_for(permutation)?;
2553        let g_window = classify_g_window(graph_name, graph_filter_terms, graph_filter_allow);
2554        let after_bytes = start_after_term.map(encode_term_bytes);
2555        let prefixes = prepare_head_prefixes(head_prefixes);
2556        let mut terms = Vec::new();
2557        // total_order_seek: the walk skips past heads with
2558        // byte_successor(bare term) — region-crossing seeks that armed
2559        // per-SST prefix filters answer wrongly (see
2560        // Db::scan_prefix_total_order). Unconditional: a no-op with
2561        // filters off, the truncation fix with them on.
2562        let mut iter = self.db.scan_prefix_total_order(cf, &[]);
2563        let mut state = SnapshotScanState::default();
2564        if prefixes.is_empty() {
2565            if let Some(after) = &after_bytes {
2566                let next = match byte_successor(after) {
2567                    Some(next) => next,
2568                    None => return Ok(terms),
2569                };
2570                iter.seek(&next);
2571            }
2572            while iter.is_valid() {
2573                let Some(key) = iter.key() else { break };
2574                let Some(value) = iter.value() else {
2575                    return Err(StorageError::Corrupt(
2576                        "iterator key without value".to_owned(),
2577                    ));
2578                };
2579                let head = match consider_axis_head_key(
2580                    permutation,
2581                    &mut state,
2582                    snapshot,
2583                    key,
2584                    value,
2585                    g_window,
2586                    graph_name,
2587                    graph_filter_terms,
2588                    graph_filter_allow,
2589                    iri_only_head,
2590                )? {
2591                    HeadVerdict::Candidate { head } => head,
2592                    HeadVerdict::Skip => {
2593                        iter.next();
2594                        continue;
2595                    }
2596                };
2597                // Skip-scan past the rest of this head: the encoded bytes
2598                // are the key's own prefix — no decode, no re-encode.
2599                let step = byte_successor(&key[..head.end]);
2600                terms.push(head_term_from_region(&key[head.clone()])?);
2601                if limit > 0 && terms.len() as u64 >= limit {
2602                    break;
2603                }
2604                match step {
2605                    Some(next) => iter.seek(&next),
2606                    None => break,
2607                }
2608                state = SnapshotScanState::default();
2609            }
2610        } else {
2611            // Seek-union: visit only each normalized prefix's key range, in
2612            // byte order. Keys outside a prefix's range are never decoded —
2613            // the `starts_with` gate runs before any term work.
2614            'prefix: for prefix in &prefixes {
2615                let Some(seek) = head_prefix_resume_seek(prefix, after_bytes.as_deref()) else {
2616                    continue;
2617                };
2618                iter.seek(&seek);
2619                state = SnapshotScanState::default();
2620                while iter.is_valid() {
2621                    let Some(key) = iter.key() else { break };
2622                    if !key.starts_with(prefix) {
2623                        break;
2624                    }
2625                    let Some(value) = iter.value() else {
2626                        return Err(StorageError::Corrupt(
2627                            "iterator key without value".to_owned(),
2628                        ));
2629                    };
2630                    let head = match consider_axis_head_key(
2631                        permutation,
2632                        &mut state,
2633                        snapshot,
2634                        key,
2635                        value,
2636                        g_window,
2637                        graph_name,
2638                        graph_filter_terms,
2639                        graph_filter_allow,
2640                        iri_only_head,
2641                    )? {
2642                        HeadVerdict::Candidate { head } => head,
2643                        HeadVerdict::Skip => {
2644                            iter.next();
2645                            continue;
2646                        }
2647                    };
2648                    // Skip-scan past the rest of this head: the encoded
2649                    // bytes are the key's own prefix — no decode, no
2650                    // re-encode.
2651                    let step = byte_successor(&key[..head.end]);
2652                    terms.push(head_term_from_region(&key[head.clone()])?);
2653                    if limit > 0 && terms.len() as u64 >= limit {
2654                        break 'prefix;
2655                    }
2656                    match step {
2657                        Some(next) => iter.seek(&next),
2658                        None => break,
2659                    }
2660                    state = SnapshotScanState::default();
2661                }
2662            }
2663        }
2664        iter.status()?;
2665        Ok(terms)
2666    }
2667
2668    /// Max commit_ts among the versioned keys whose slot-0 head term falls
2669    /// under `head_prefixes` (normalized like [`Self::scan_axis_head`]).
2670    ///
2671    /// Stage 1 of the geo upgrade's two-stage swap: the replacement ts must
2672    /// dominate the newest version of every row it deletes, and the walked
2673    /// data is the only authority for that bound — a freshly opened process's
2674    /// counter is 0 and says nothing about rows written by earlier processes,
2675    /// and the wall clock may have drifted since they landed. Every versioned
2676    /// key carries its commit_ts in the last [`COMMIT_TS_LEN`] bytes, so this
2677    /// is a pure suffix scan: no liveness evaluation, no term decoding. Counting
2678    /// superseded/dead versions too only ever *overestimates* the bound, which
2679    /// is safe — a larger swap ts still sorts ahead of every row it deletes.
2680    /// `0` when no key matches.
2681    pub fn max_commit_ts_under_prefixes(
2682        &self,
2683        permutation: IndexPermutation,
2684        head_prefixes: &[Vec<u8>],
2685    ) -> Result<u64, StorageError> {
2686        let cf = self.cf_for(permutation)?;
2687        let prefixes = prepare_head_prefixes(head_prefixes);
2688        let mut max_ts = 0u64;
2689        // total_order_seek as hardening (see Db::scan_prefix_total_order):
2690        // this walk re-seeks per prefix with real targets, so armed
2691        // pruning is transient and it is correct without the flag — but
2692        // its contract is "must observe every matching key, misses are
2693        // silent" (the geo upgrade's swap bound), it runs once per
2694        // upgrade so the cost is irrelevant, and the flag immunizes it
2695        // against future reshaping into a single-seek or sliced form.
2696        let mut iter = self.db.scan_prefix_total_order(cf, &[]);
2697        if prefixes.is_empty() {
2698            while iter.is_valid() {
2699                let Some(key) = iter.key() else { break };
2700                if key.len() >= crate::encode::COMMIT_TS_LEN {
2701                    let ts = CommitTs::from_descending_be_bytes(
2702                        key[key.len() - crate::encode::COMMIT_TS_LEN..]
2703                            .try_into()
2704                            .expect("slice length checked above"),
2705                    );
2706                    max_ts = max_ts.max(ts.0);
2707                }
2708                iter.next();
2709            }
2710        } else {
2711            for prefix in &prefixes {
2712                iter.seek(prefix);
2713                while iter.is_valid() {
2714                    let Some(key) = iter.key() else { break };
2715                    if !key.starts_with(prefix) {
2716                        break;
2717                    }
2718                    if key.len() >= crate::encode::COMMIT_TS_LEN {
2719                        let ts = CommitTs::from_descending_be_bytes(
2720                            key[key.len() - crate::encode::COMMIT_TS_LEN..]
2721                                .try_into()
2722                                .expect("slice length checked above"),
2723                        );
2724                        max_ts = max_ts.max(ts.0);
2725                    }
2726                    iter.next();
2727                }
2728            }
2729        }
2730        iter.status()?;
2731        Ok(max_ts)
2732    }
2733
2734    /// Axis head count, `TOTAL` mode: the number of distinct slot-0 head
2735    /// terms of the whole CF visible under the graph window. Same skip-walk
2736    /// as [`Self::scan_axis_head`] — each emitted head seeks to its byte
2737    /// successor — but the term is never materialized.
2738    #[allow(clippy::too_many_arguments)]
2739    pub fn count_axis_heads(
2740        &self,
2741        permutation: IndexPermutation,
2742        snapshot: SnapshotId,
2743        graph_name: Option<&EncodedTerm>,
2744        graph_filter_terms: &[EncodedTerm],
2745        graph_filter_allow: bool,
2746        iri_only_head: bool,
2747    ) -> Result<u64, StorageError> {
2748        let cf = self.cf_for(permutation)?;
2749        let g_window = classify_g_window(graph_name, graph_filter_terms, graph_filter_allow);
2750        let mut total = 0u64;
2751        // total_order_seek — see scan_axis_head; the count walk skips past
2752        // heads with byte_successor(bare term) too.
2753        let mut iter = self.db.scan_prefix_total_order(cf, &[]);
2754        let mut state = SnapshotScanState::default();
2755        while iter.is_valid() {
2756            let Some(key) = iter.key() else { break };
2757            let Some(value) = iter.value() else {
2758                return Err(StorageError::Corrupt(
2759                    "iterator key without value".to_owned(),
2760                ));
2761            };
2762            let head = match consider_axis_head_key(
2763                permutation,
2764                &mut state,
2765                snapshot,
2766                key,
2767                value,
2768                g_window,
2769                graph_name,
2770                graph_filter_terms,
2771                graph_filter_allow,
2772                iri_only_head,
2773            )? {
2774                HeadVerdict::Candidate { head } => head,
2775                HeadVerdict::Skip => {
2776                    iter.next();
2777                    continue;
2778                }
2779            };
2780            total += 1;
2781            // Payload-validate the counted head. Every sibling walk decodes
2782            // the head it emits (hits at emission, PER_HEAD and the domain
2783            // counts at run flush), so a corrupt head surfaces as `Corrupt`
2784            // there; without this decode TOTAL would be the one mode that
2785            // silently under-reports instead. The skip-scan touches one key
2786            // per distinct head, so this costs one decode per head, not per
2787            // row — the term is discarded, only the validation matters.
2788            let _ = head_term_from_region(&key[head.clone()])?;
2789            // TOTAL mode needs no term at all — the skip-seek is the key's
2790            // own prefix bytes.
2791            let step = byte_successor(&key[..head.end]);
2792            match step {
2793                Some(next) => iter.seek(&next),
2794                None => break,
2795            }
2796            state = SnapshotScanState::default();
2797        }
2798        iter.status()?;
2799        Ok(total)
2800    }
2801
2802    /// Axis head count, `PER_HEAD` mode: one `(head, count)` hit per slot-0
2803    /// head, `count` being the number of distinct slot-1 terms under it with
2804    /// at least one visible row (TSG: per-class subject counts). Runs the
2805    /// head prefix to EOF instead of skipping it; `limit` counts emitted
2806    /// hits (`0` = unlimited); `start_after_term` is the exclusive resume
2807    /// cursor at head boundaries.
2808    #[allow(clippy::too_many_arguments)]
2809    pub fn scan_axis_head_counts(
2810        &self,
2811        permutation: IndexPermutation,
2812        snapshot: SnapshotId,
2813        limit: u64,
2814        start_after_term: Option<&EncodedTerm>,
2815        graph_name: Option<&EncodedTerm>,
2816        graph_filter_terms: &[EncodedTerm],
2817        graph_filter_allow: bool,
2818        iri_only_head: bool,
2819    ) -> Result<Vec<AxisHeadCountHit>, StorageError> {
2820        let cf = self.cf_for(permutation)?;
2821        let g_window = classify_g_window(graph_name, graph_filter_terms, graph_filter_allow);
2822        let mut hits = Vec::new();
2823        // total_order_seek — see scan_axis_head; the count-heads walk also
2824        // skips past heads with byte_successor(bare term), and its
2825        // start_after resume seek is byte_successor(after) — the same
2826        // region-crossing shape.
2827        let mut iter = self.db.scan_prefix_total_order(cf, &[]);
2828        if let Some(after) = start_after_term {
2829            let next = match byte_successor(&encode_term_bytes(after)) {
2830                Some(next) => next,
2831                None => return Ok(hits),
2832            };
2833            iter.seek(&next);
2834        }
2835        let mut state = SnapshotScanState::default();
2836        // The head run being counted: the head term's encoded bytes
2837        // (`run_head[..run_len]`), the distinct slot-1 count, and the last
2838        // slot-1 region (slot-1 terms are contiguous under their head, so
2839        // boundary counting needs only the previous region — byte identity
2840        // is term identity).
2841        let mut run_head = [0u8; WRITTEN_TERM_MAX_SIZE];
2842        let mut run_len = 0usize;
2843        // Head run accumulator: distinct slot-1 count so far, plus the
2844        // previous row's slot-1 region as `(encoded bytes, used length)` —
2845        // byte identity is term identity.
2846        type Slot1RunAcc = (u64, Option<([u8; WRITTEN_TERM_MAX_SIZE], usize)>);
2847        let mut current: Option<Slot1RunAcc> = None;
2848        let mut full = false;
2849        while iter.is_valid() {
2850            let Some(key) = iter.key() else { break };
2851            let Some(value) = iter.value() else {
2852                return Err(StorageError::Corrupt(
2853                    "iterator key without value".to_owned(),
2854                ));
2855            };
2856            let head = match consider_axis_head_key(
2857                permutation,
2858                &mut state,
2859                snapshot,
2860                key,
2861                value,
2862                g_window,
2863                graph_name,
2864                graph_filter_terms,
2865                graph_filter_allow,
2866                iri_only_head,
2867            )? {
2868                HeadVerdict::Candidate { head } => head,
2869                HeadVerdict::Skip => {
2870                    iter.next();
2871                    continue;
2872                }
2873            };
2874            // Slot 1 starts at the head's end; slot 1 is never G, so the
2875            // term is always present (never the empty default-graph case).
2876            let slot1 = region_after_head(key, head.end)?;
2877            let opens_new_run = current.is_none() || run_head[..run_len] != key[head.clone()];
2878            if opens_new_run {
2879                if let Some((count, _)) = current.take() {
2880                    hits.push(AxisHeadCountHit {
2881                        term: head_term_from_region(&run_head[..run_len])?,
2882                        count,
2883                    });
2884                    if limit > 0 && hits.len() as u64 >= limit {
2885                        full = true;
2886                        break;
2887                    }
2888                }
2889                // `head.len()`, not `head.end`: the buffer is indexed from
2890                // zero, and only the axis walks' hard-coded head offset of
2891                // zero makes the two equal. A future caller with a
2892                // non-zero head offset would corrupt the saved run head
2893                // (or panic on overflow past WRITTEN_TERM_MAX_SIZE).
2894                run_head[..head.len()].copy_from_slice(&key[head.clone()]);
2895                run_len = head.len();
2896                current = Some((0, None));
2897            }
2898            if let Some((count, last)) = &mut current {
2899                let changed = match last.as_ref() {
2900                    Some((prev, prev_len)) => prev[..*prev_len] != key[slot1.clone()],
2901                    None => true,
2902                };
2903                if changed {
2904                    *count += 1;
2905                    let mut saved = [0u8; WRITTEN_TERM_MAX_SIZE];
2906                    saved[..slot1.len()].copy_from_slice(&key[slot1.clone()]);
2907                    *last = Some((saved, slot1.len()));
2908                }
2909            }
2910            iter.next();
2911        }
2912        // Flush the trailing run — unless the page filled mid-run, in which
2913        // case the cursor resumes the client at the last emitted head and
2914        // this run is re-walked (and emitted) on the next page.
2915        if !full && let Some((count, _)) = current {
2916            hits.push(AxisHeadCountHit {
2917                term: head_term_from_region(&run_head[..run_len])?,
2918                count,
2919            });
2920        }
2921        iter.status()?;
2922        Ok(hits)
2923    }
2924
2925    /// Count an allow-list scan with the **full matcher semantics** per tight
2926    /// prefix — residual `graph_filter` membership and `merge_default_graph`
2927    /// collapse inside each prefix's RowMatcher, counting raw [`KeyRow`]s
2928    /// without decoding any term. `limit` counts post-filter matches
2929    /// (`0` = unlimited). Returns `None` when `slot` does not extend
2930    /// `permutation`.
2931    #[allow(clippy::too_many_arguments)]
2932    pub fn count_pattern_allow_list(
2933        &self,
2934        permutation: IndexPermutation,
2935        pattern: &EncodedTriplePattern,
2936        snapshot: SnapshotId,
2937        limit: u64,
2938        allow_list_slot: QuadSlot,
2939        allow_terms: &[EncodedTerm],
2940        graph_filter: GByteFilter,
2941        merge_default_graph: bool,
2942    ) -> Result<Option<u64>, StorageError> {
2943        let mut count = 0u64;
2944        let verdict = self.visit_allow_list_rows(
2945            permutation,
2946            pattern,
2947            snapshot,
2948            None,
2949            allow_list_slot,
2950            allow_terms,
2951            graph_filter,
2952            merge_default_graph,
2953            IriOnlyMask::NONE,
2954            &ComparisonMask::default(),
2955            |_row| {
2956                count += 1;
2957                Ok(limit == 0 || count < limit)
2958            },
2959        )?;
2960        Ok(verdict.map(|_| count))
2961    }
2962
2963    /// One iterator over the shared prefix; `Seek` to each allow-listed tight prefix.
2964    ///
2965    /// Emits raw rows until the prefixes are exhausted or `on_match` returns
2966    /// `false` — callers enforce any `limit` in their callback (it counts
2967    /// post-filter, post-collapse matches). Returns `None` when binding
2968    /// `slot` does not extend `permutation`'s prefix (POSG + unbound O +
2969    /// filter on S, and similar); otherwise `Some(verdict)` — the walk's
2970    /// own [`ScanExhaustion`]: `Limited` when the sink stopped it at
2971    /// the limit, `ExhaustedFilterTerms` when every term's prefix was
2972    /// served.
2973    ///
2974    /// This is like visit_pattern_rows, but for pattern+allow-list scans
2975    /// It handles the start_after cursor, and the resume key.
2976    #[allow(clippy::too_many_arguments)]
2977    pub(crate) fn visit_allow_list_rows(
2978        &self,
2979        permutation: IndexPermutation,
2980        pattern: &EncodedTriplePattern,
2981        snapshot: SnapshotId,
2982        start_after: Option<&EncodedQuad>,
2983        allow_list_slot: QuadSlot,
2984        allow_terms: &[EncodedTerm],
2985        graph_filter: GByteFilter,
2986        merge_default_graph: bool,
2987        iri_only: IriOnlyMask,
2988        mask: &ComparisonMask,
2989        mut on_match: impl FnMut(&KeyRow) -> Result<bool, StorageError>,
2990    ) -> Result<Option<ScanExhaustion>, StorageError> {
2991        let Some(prepared) =
2992            pattern.prepare_tight_allow_list(permutation, allow_list_slot, allow_terms)
2993        else {
2994            // `allow_list_slot` does not extend `permutation`.
2995            // So return `None`, the caller will use a different calling method
2996            return Ok(None);
2997        };
2998        let cf = self.cf_for(permutation)?;
2999        let start_after_prefix_bytes = start_after.map(|after_quad| {
3000            let mut bound = pattern.clone();
3001            bound.bind_slot(
3002                allow_list_slot,
3003                term_in_quad_slot(after_quad, allow_list_slot).clone(),
3004            );
3005            bound.build_scan_prefix_bytes(permutation)
3006        });
3007        let resume_key = start_after.map(|quad| encode_index_key(permutation, quad));
3008
3009        // Walk verdict: `None` above means "no tight allow-list" (the
3010        // caller falls back to per-term walks). `Some(Limited)` is
3011        // the sink stopping at the limit; completing the term loop is
3012        // `Some(ExhaustedFilterTerms)` — the walk never consults key
3013        // ranges outside its terms, so `ExhaustedScan` is not its to
3014        // report. A sink error also stops early; the error surfaces from
3015        // `?` and the verdict is discarded.
3016        let mut verdict = ScanExhaustion::ExhaustedFilterTerms;
3017        let mut iter = self.db.scan_prefix(cf, &prepared.shared_prefix);
3018        for (tight_prefix, term) in &prepared.terms {
3019            if start_after_prefix_bytes
3020                .as_ref()
3021                .is_some_and(|cursor| tight_prefix.as_slice() < cursor.as_slice())
3022            {
3023                continue;
3024            }
3025            let mut bound = pattern.clone();
3026            bound.bind_slot(allow_list_slot, term.clone());
3027            let resuming = start_after_prefix_bytes
3028                .as_ref()
3029                .is_some_and(|cursor| tight_prefix.as_slice() == cursor.as_slice());
3030            let seek: &[u8] = if resuming {
3031                let resume = resume_key.as_ref().expect("resuming implies start_after");
3032                if resume.as_slice() > tight_prefix.as_slice() {
3033                    resume.as_slice()
3034                } else {
3035                    tight_prefix.as_slice()
3036                }
3037            } else {
3038                tight_prefix.as_slice()
3039            };
3040            iter.seek(seek);
3041            let mut state = SnapshotScanState::default();
3042            // One matcher per tight prefix (per seek, never per row): the
3043            // bound filter slot sits after the shared prefix's first gap, so
3044            // the matcher enforces it per row without decoding.
3045            // Dedup never spans prefixes: the allow-listed slot is part of
3046            // the triple, so same-triple rows share one tight prefix and one
3047            // matcher's collapse state.
3048            // `start_after` feeds the resuming prefix's matcher its dedup
3049            // whole-triple cursor (a rewritten-DefaultGraph cursor cannot be
3050            // resumed as one exact key: other-G copies of the same triple
3051            // sort after it and must be skipped too). Non-dedup resumes stay
3052            // exact-key via the `resume_key` compare above.
3053            let mut matcher = RowMatcher::compile(
3054                &bound,
3055                permutation,
3056                graph_filter.clone(),
3057                merge_default_graph,
3058                if resuming { start_after } else { None },
3059                iri_only,
3060            );
3061            while iter.is_valid() {
3062                let Some(key) = iter.key() else { break };
3063                if !key.starts_with(tight_prefix) {
3064                    break;
3065                }
3066                if resuming {
3067                    // `resume_key` (already encoded once above) is fixed for
3068                    // this term's whole range: compare slices, don't rebuild.
3069                    let logical = versioned_key_term_prefix(key)?;
3070                    if logical <= resume_key.as_deref().expect("resuming implies start_after") {
3071                        iter.next();
3072                        continue;
3073                    }
3074                }
3075                let decision = {
3076                    let Some(value) = iter.value() else {
3077                        return Err(StorageError::Corrupt(
3078                            "iterator key without value".to_owned(),
3079                        ));
3080                    };
3081                    matcher.matches_row(key, value, snapshot, &mut state)?
3082                };
3083                if let MatchDecision::Emit {
3084                    slot_starts,
3085                    commit_ts,
3086                } = decision
3087                {
3088                    let row = KeyRow {
3089                        key,
3090                        permutation,
3091                        seg_starts: slot_starts,
3092                        commit_ts,
3093                    };
3094                    // Slot comparison mask: a proven-false row never reaches
3095                    // the page and never counts toward the limit.
3096                    if mask.keeps(row.logical(), &row.seg_starts) && !on_match(&row)? {
3097                        verdict = ScanExhaustion::Limited;
3098                        break;
3099                    }
3100                }
3101                iter.next();
3102            }
3103            if verdict == ScanExhaustion::Limited {
3104                break;
3105            }
3106        }
3107        iter.status()?;
3108        Ok(Some(verdict))
3109    }
3110
3111    /// Apply geometry-index postings as one RocksDB `WriteBatch` (O axis).
3112    ///
3113    /// Apply-and-skip-seek only: keys/values the compute side built are
3114    /// persisted verbatim. Empty `puts` is a no-op.
3115    pub fn apply_geo_puts(&self, puts: &[GeoIndexPut]) -> Result<(), StorageError> {
3116        if puts.is_empty() {
3117            return Ok(());
3118        }
3119        let Some(cf) = &self.cf_geo else {
3120            return Err(StorageError::GeoIndexNotOnAxis(self.axis));
3121        };
3122        let mut batch = self.db.write_batch();
3123        for put in puts {
3124            batch.insert(cf, &put.encode_key(), &put.encode_value());
3125        }
3126        batch.commit()
3127    }
3128
3129    /// Delete every versioned posting of one encoded geo term.
3130    ///
3131    /// Covering cells for one term are not adjacent in cell-major order, so
3132    /// this is a full-CF walk collecting matching keys, then one WriteBatch of
3133    /// Deletes. NOT the rebuild path any more: `waratah geo rebuild-index`
3134    /// wipes the whole CF in one pass (`wipe_geo_index`) — per-term walks
3135    /// made the rebuild quadratic in terms × postings. This stays for the
3136    /// partition RPC surface and single-term surgical use.
3137    pub fn delete_geo_term(&self, term: &[u8]) -> Result<u64, StorageError> {
3138        let Some(cf) = &self.cf_geo else {
3139            return Err(StorageError::GeoIndexNotOnAxis(self.axis));
3140        };
3141        let mut victims: Vec<Vec<u8>> = Vec::new();
3142        let mut iter = self.db.scan_prefix(cf, &[]);
3143        while iter.is_valid() {
3144            if let Some(key) = iter.key() {
3145                let logical_len = key.len().saturating_sub(crate::encode::COMMIT_TS_LEN);
3146                if logical_len > GEO_CELL_ID_LEN && key[GEO_CELL_ID_LEN..logical_len] == *term {
3147                    victims.push(key.to_vec());
3148                }
3149            }
3150            iter.next();
3151        }
3152        iter.status()?;
3153        if victims.is_empty() {
3154            return Ok(0);
3155        }
3156        let mut batch = self.db.write_batch();
3157        for key in &victims {
3158            batch.delete(cf, key);
3159        }
3160        batch.commit()?;
3161        Ok(victims.len() as u64)
3162    }
3163
3164    /// Visit every posting row, decoded, in CF order (read-only; the
3165    /// census/debug surface). Rows stream cell-major with versions of one
3166    /// logical `(cell, term)` key adjacent and newest first — the same
3167    /// order `GeoCandidateState` collapses per logical key. A corrupt row
3168    /// aborts the walk loudly: a diagnostic pass must not silently skip.
3169    pub fn visit_geo_postings(
3170        &self,
3171        on_posting: &mut dyn FnMut(&GeoIndexPut) -> Result<(), StorageError>,
3172    ) -> Result<(), StorageError> {
3173        let Some(cf) = &self.cf_geo else {
3174            return Err(StorageError::GeoIndexNotOnAxis(self.axis));
3175        };
3176        let mut iter = self.db.scan_prefix(cf, &[]);
3177        while iter.is_valid() {
3178            if let (Some(key), Some(value)) = (iter.key(), iter.value()) {
3179                on_posting(&GeoIndexPut::decode(key, value)?)?;
3180            }
3181            iter.next();
3182        }
3183        iter.status()
3184    }
3185
3186    /// Rebuild epoch of the geometry index (O axis) — the TRUST decision.
3187    ///
3188    /// `Ok(None)` on S/P (no CF) and when no epoch was ever stamped: every
3189    /// consumer treats a missing epoch as UNTRUSTED (the flip from the
3190    /// original missing-epoch-trusted default, because geography can be
3191    /// ingested plugin-less, so an empty index is not proof of an empty
3192    /// dataset). `None` also when the liveness marker is absent or disagrees
3193    /// with the epoch: the postings were wiped without the epoch being
3194    /// re-stamped, so the index is empty-but-"trusted" and must read
3195    /// untrusted instead. A malformed value also reads as `None`.
3196    pub fn geo_index_epoch(&self) -> Result<Option<u64>, StorageError> {
3197        let Some(cf) = &self.cf_geo_meta else {
3198            return Ok(None);
3199        };
3200        let epoch = decode_geo_epoch(self.db.get(cf, GEO_INDEX_EPOCH_KEY)?.as_deref());
3201        let liveness = decode_geo_liveness(self.db.get(cf, GEO_INDEX_LIVENESS_KEY)?.as_deref());
3202        Ok(match (epoch, liveness) {
3203            (Some(epoch), Some(live)) if epoch == live => Some(epoch),
3204            _ => None,
3205        })
3206    }
3207
3208    /// Stamp the rebuild epoch of the geometry index (O axis) together with
3209    /// its liveness marker, in ONE write batch.
3210    ///
3211    /// Called by `waratah geo rebuild-index` and by `finish_geo_rebuild`
3212    /// after the postings were rewritten: the epoch is the max `commit_ts`
3213    /// over the geo-contributing version rows the rebuild scanned, and
3214    /// postings stamped at the epoch become visible exactly when the planner
3215    /// starts trusting the index. Both keys land atomically — an epoch without
3216    /// its marker is deliberately unreadable as a trust signal (see
3217    /// [`Self::geo_index_epoch`]).
3218    pub fn set_geo_index_epoch(&self, epoch: u64) -> Result<(), StorageError> {
3219        let Some(cf) = &self.cf_geo_meta else {
3220            return Err(StorageError::GeoIndexNotOnAxis(self.axis));
3221        };
3222        let mut batch = self.db.write_batch();
3223        batch.insert(cf, GEO_INDEX_EPOCH_KEY, &encode_geo_epoch(epoch));
3224        batch.insert(cf, GEO_INDEX_LIVENESS_KEY, &encode_geo_liveness(epoch));
3225        batch.commit()
3226    }
3227
3228    /// Raw stored epoch number, ignoring the liveness marker (`0` when absent
3229    /// or malformed, `0` on S/P).
3230    ///
3231    /// Unlike [`Self::geo_index_epoch`] — which reads `None` unless marker and
3232    /// number agree — this survives a wipe (`wipe_geo_index` drops the marker
3233    /// but keeps the number), so `finish_geo_rebuild` can floor the new epoch
3234    /// at the previously stamped one: a rebuild that writes nothing
3235    /// counter-visible (no orphans; postings only) in a freshly opened process
3236    /// would otherwise stamp 0 over a store whose data sits at higher ts.
3237    pub fn geo_index_epoch_number(&self) -> Result<u64, StorageError> {
3238        let Some(cf) = &self.cf_geo_meta else {
3239            return Ok(0);
3240        };
3241        Ok(decode_geo_epoch(self.db.get(cf, GEO_INDEX_EPOCH_KEY)?.as_deref()).unwrap_or(0))
3242    }
3243
3244    /// Skip-seek candidate scan over merged cell-id intervals (O axis).
3245    ///
3246    /// ONE iterator walk with a seek per interval — never a full CF scan —
3247    /// over the versioned `geo_index` keys, with the caller-owned
3248    /// [`GeoCandidateState`] doing MVCC collapse, the per-stream DISTINCT, and
3249    /// the optional envelope AABB reject. Decoded candidate terms stream to
3250    /// `emit`; returning `false` stops early (limit reached / consumer gone).
3251    /// `limit` of `0` is unlimited. Returns when every interval is drained,
3252    /// `emit` stops, or `limit` distinct candidates were emitted.
3253    pub fn geo_scan_candidates(
3254        &self,
3255        intervals: &[GeoCellInterval],
3256        snapshot: SnapshotId,
3257        query_envelope: Option<&GeoEnvelope>,
3258        limit: u64,
3259        state: &mut GeoCandidateState,
3260        mut emit: impl FnMut(&EncodedTerm) -> Result<bool, StorageError>,
3261    ) -> Result<(), StorageError> {
3262        let Some(cf) = &self.cf_geo else {
3263            return Err(StorageError::GeoIndexNotOnAxis(self.axis));
3264        };
3265        let mut emitted = 0u64;
3266        let mut iter = self.db.scan_prefix(cf, &[]);
3267        for interval in intervals {
3268            let seek_key = interval.min_cell_id.to_be_bytes();
3269            iter.seek(&seek_key);
3270            let max_cell = interval.max_cell_id.to_be_bytes();
3271            while iter.is_valid() {
3272                let Some(key) = iter.key() else { break };
3273                if key.len() < GEO_CELL_ID_LEN || key[..GEO_CELL_ID_LEN] > max_cell[..] {
3274                    break; // past this interval's cell-id range
3275                }
3276                let Some(value) = iter.value() else {
3277                    return Err(StorageError::Corrupt(
3278                        "geo index iterator key without value".to_owned(),
3279                    ));
3280                };
3281                let ts_at = key
3282                    .len()
3283                    .checked_sub(crate::encode::COMMIT_TS_LEN)
3284                    .ok_or_else(|| StorageError::Corrupt("geo index key too short".to_owned()))?;
3285                let commit_ts = CommitTs::from_descending_be_bytes(
3286                    key[ts_at..]
3287                        .try_into()
3288                        .map_err(|_| StorageError::Corrupt("geo commit_ts suffix".to_owned()))?,
3289                );
3290                let header = value
3291                    .get(..crate::encode::STORAGE_VALUE_LEN)
3292                    .ok_or_else(|| StorageError::Corrupt("truncated storage value".to_owned()))?;
3293                let (op, _visibility) = decode_storage_value(header)?;
3294                // Decode the optional envelope only when the query has one
3295                // to compare against (the common point-const path has none).
3296                let stored_envelope = if query_envelope.is_some() && value.len() > 5 {
3297                    Some(GeoEnvelope::decode(&value[5..])?)
3298                } else {
3299                    None
3300                };
3301                let decision = state.consider_posting(
3302                    key,
3303                    commit_ts,
3304                    op,
3305                    snapshot,
3306                    stored_envelope.as_ref(),
3307                    query_envelope,
3308                )?;
3309                if decision == GeoCandidateDecision::Emit {
3310                    let term_len = key.len() - GEO_CELL_ID_LEN - crate::encode::COMMIT_TS_LEN;
3311                    let mut cursor = &key[GEO_CELL_ID_LEN..GEO_CELL_ID_LEN + term_len];
3312                    let term = cursor.read_term()?;
3313                    if !emit(&term)? {
3314                        return Ok(());
3315                    }
3316                    emitted += 1;
3317                    if limit > 0 && emitted >= limit {
3318                        return Ok(());
3319                    }
3320                }
3321                iter.next();
3322            }
3323        }
3324        iter.status()?;
3325        Ok(())
3326    }
3327
3328    /// Apply replace pairs as ONE RocksDB `WriteBatch` on this axis: per
3329    /// pair the old quad's versioned rows are Deleted and the new quad's
3330    /// rows are Put at the shared `commit_ts` — no snapshot sees both rows
3331    /// or neither. Served by every axis partition (each translates the
3332    /// pairs into its own permutations). Empty `pairs` is a no-op.
3333    pub fn apply_replace_pairs(
3334        &self,
3335        pairs: &[ReplacePair],
3336        commit_ts: CommitTs,
3337    ) -> Result<u64, StorageError> {
3338        if pairs.is_empty() {
3339            return Ok(0);
3340        }
3341        let mut versions: Vec<HexastoreVersion<'_>> = Vec::with_capacity(pairs.len() * 2);
3342        let quads: Vec<(crate::encode::EncodedQuad, crate::encode::EncodedQuad)> = pairs
3343            .iter()
3344            .map(|pair| (pair.old_quad(), pair.new_quad()))
3345            .collect();
3346        for (pair, (old, new)) in pairs.iter().zip(&quads) {
3347            let _ = pair;
3348            versions.push(HexastoreVersion {
3349                quad: old,
3350                commit_ts,
3351                op: StorageOp::Delete,
3352                visibility: VisibilityLabel::default(),
3353            });
3354            versions.push(HexastoreVersion {
3355                quad: new,
3356                commit_ts,
3357                op: StorageOp::Put,
3358                visibility: VisibilityLabel::default(),
3359            });
3360        }
3361        let puts = prepare_hexastore_puts(self.axis, versions);
3362        self.apply_prepared_puts(&puts)?;
3363        Ok(pairs.len() as u64)
3364    }
3365
3366    /// Wipe every geo-index posting (O axis; rebuild preamble). The
3367    /// rebuild is an authoritative full replacement: the whole CF is
3368    /// dropped and re-derived from the hexastore under the rebuild lease.
3369    pub fn wipe_geo_index(&self) -> Result<u64, StorageError> {
3370        let Some(cf) = &self.cf_geo else {
3371            return Err(StorageError::GeoIndexNotOnAxis(self.axis));
3372        };
3373        let mut deleted = 0u64;
3374        let mut batch = self.db.write_batch();
3375        let mut iter = self.db.scan_prefix(cf, &[]);
3376        while iter.is_valid() {
3377            if let Some(key) = iter.key() {
3378                batch.delete(cf, key);
3379                deleted += 1;
3380            }
3381            iter.next();
3382        }
3383        iter.status()?;
3384        // Also drop the LIVENESS marker (NOT the epoch) so the trust gate reads
3385        // untrusted for as long as the index is empty — see `geo_index_epoch`.
3386        if let Some(meta) = &self.cf_geo_meta {
3387            batch.delete(meta, GEO_INDEX_LIVENESS_KEY);
3388        }
3389        batch.commit()?;
3390        Ok(deleted)
3391    }
3392
3393    /// Apply temporal-index postings as one RocksDB `WriteBatch` (O axis).
3394    ///
3395    /// Apply-and-skip-seek only: keys/values the compute side built (or the
3396    /// rebuild derived) are persisted verbatim. Empty `puts` is a no-op.
3397    pub fn apply_temporal_puts(&self, puts: &[TemporalIndexPut]) -> Result<(), StorageError> {
3398        if puts.is_empty() {
3399            return Ok(());
3400        }
3401        let Some(cf) = &self.cf_temporal else {
3402            return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
3403        };
3404        let mut batch = self.db.write_batch();
3405        for put in puts {
3406            batch.insert(cf, &put.encode_key(), &put.encode_value());
3407        }
3408        batch.commit()
3409    }
3410
3411    /// Rebuild epoch of the temporal index (O axis) — the TRUST decision.
3412    ///
3413    /// `Ok(None)` on S/P (no CF) and when no epoch was ever stamped. Unlike
3414    /// the geo index, a missing epoch is UNTRUSTED for the temporal rewrite:
3415    /// temporal literals predate the plugin, so the compute auto-rebuild
3416    /// triggers on it at startup and the epoch lands before queries serve.
3417    ///
3418    /// `None` also when the tick-axis ORIGIN version recorded beside the
3419    /// epoch disagrees with [`TEMPORAL_ORIGIN_VERSION`]. The origin moved
3420    /// (B56: calendar families onto the stored `dateTime` origin), which
3421    /// invalidates every posting key and every stored `begin`/`end` pair;
3422    /// an index built under the old origin would otherwise read trusted while
3423    /// its postings sit 306 days from where queries look.
3424    pub fn temporal_index_epoch(&self) -> Result<Option<u64>, StorageError> {
3425        let Some(cf) = &self.cf_temporal_meta else {
3426            return Ok(None);
3427        };
3428        let epoch = decode_temporal_epoch(self.db.get(cf, TEMPORAL_INDEX_EPOCH_KEY)?.as_deref());
3429        let origin = decode_temporal_origin(self.db.get(cf, TEMPORAL_INDEX_ORIGIN_KEY)?.as_deref());
3430        Ok(match (epoch, origin) {
3431            (Some(epoch), Some(version)) if version == TEMPORAL_ORIGIN_VERSION => Some(epoch),
3432            _ => None,
3433        })
3434    }
3435
3436    /// Stamp the rebuild epoch of the temporal index (O axis).
3437    ///
3438    /// Called by the partition-side rebuild after it rewrote the postings:
3439    /// the epoch is the max `commit_ts` over the temporal-contributing
3440    /// version rows the rebuild scanned, and postings stamped at the epoch
3441    /// become visible exactly when the planner starts trusting the index.
3442    ///
3443    /// Also stamps the tick-axis ORIGIN version, in the same batch, so the
3444    /// two cannot diverge: an epoch without a matching origin version is
3445    /// deliberately unreadable as a trust signal (see
3446    /// [`Self::temporal_index_epoch`]).
3447    pub fn set_temporal_index_epoch(&self, epoch: u64) -> Result<(), StorageError> {
3448        let Some(cf) = &self.cf_temporal_meta else {
3449            return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
3450        };
3451        let mut batch = self.db.write_batch();
3452        batch.insert(cf, TEMPORAL_INDEX_EPOCH_KEY, &encode_temporal_epoch(epoch));
3453        batch.insert(
3454            cf,
3455            TEMPORAL_INDEX_ORIGIN_KEY,
3456            &encode_temporal_origin(TEMPORAL_ORIGIN_VERSION),
3457        );
3458        batch.commit()
3459    }
3460
3461    /// Skip-seek candidate scan over merged node-key intervals (O axis).
3462    ///
3463    /// ONE iterator walk with a seek per interval — never a full CF scan —
3464    /// over the versioned `temporal_index` keys, with the caller-owned
3465    /// [`TemporalCandidateState`] doing MVCC collapse, the per-stream
3466    /// DISTINCT, and the exact-interval reject. Decoded candidate terms
3467    /// stream to `emit`; returning `false` stops early (limit reached /
3468    /// consumer gone). `limit` of `0` is unlimited.
3469    pub fn temporal_scan_candidates(
3470        &self,
3471        intervals: &[TemporalCellInterval],
3472        snapshot: SnapshotId,
3473        predicate: &TemporalQueryPredicate,
3474        limit: u64,
3475        state: &mut TemporalCandidateState,
3476        mut emit: impl FnMut(&EncodedTerm) -> Result<bool, StorageError>,
3477    ) -> Result<(), StorageError> {
3478        let Some(cf) = &self.cf_temporal else {
3479            return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
3480        };
3481        let mut emitted = 0u64;
3482        let mut iter = self.db.scan_prefix(cf, &[]);
3483        for interval in intervals {
3484            let seek_key = interval.min_key.to_be_bytes();
3485            iter.seek(&seek_key);
3486            let max_key = interval.max_key.to_be_bytes();
3487            while iter.is_valid() {
3488                let Some(key) = iter.key() else { break };
3489                if key.len() < TEMPORAL_KEY_LEN || key[..TEMPORAL_KEY_LEN] > max_key[..] {
3490                    break; // past this interval's key range
3491                }
3492                let Some(value) = iter.value() else {
3493                    return Err(StorageError::Corrupt(
3494                        "temporal index iterator key without value".to_owned(),
3495                    ));
3496                };
3497                let ts_at = key
3498                    .len()
3499                    .checked_sub(crate::encode::COMMIT_TS_LEN)
3500                    .ok_or_else(|| {
3501                        StorageError::Corrupt("temporal index key too short".to_owned())
3502                    })?;
3503                let commit_ts =
3504                    CommitTs::from_descending_be_bytes(key[ts_at..].try_into().map_err(|_| {
3505                        StorageError::Corrupt("temporal commit_ts suffix".to_owned())
3506                    })?);
3507                let (op, _visibility, begin, end) = decode_temporal_posting_value(value)?;
3508                let decision =
3509                    state.consider_posting(key, commit_ts, op, snapshot, begin, end, predicate)?;
3510                if decision == TemporalCandidateDecision::Emit {
3511                    let term_len = key.len() - TEMPORAL_KEY_LEN - crate::encode::COMMIT_TS_LEN;
3512                    let mut cursor = &key[TEMPORAL_KEY_LEN..TEMPORAL_KEY_LEN + term_len];
3513                    let term = cursor.read_term()?;
3514                    if !emit(&term)? {
3515                        return Ok(());
3516                    }
3517                    emitted += 1;
3518                    if limit > 0 && emitted >= limit {
3519                        return Ok(());
3520                    }
3521                }
3522                iter.next();
3523            }
3524        }
3525        iter.status()?;
3526        Ok(())
3527    }
3528
3529    /// Wipe every temporal-index posting (O axis; rebuild preamble).
3530    ///
3531    /// The rebuild is an authoritative full replacement: the whole CF is
3532    /// dropped and re-derived from the hexastore under the rebuild lock.
3533    pub fn wipe_temporal_index(&self) -> Result<(), StorageError> {
3534        let Some(cf) = &self.cf_temporal else {
3535            return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
3536        };
3537        let mut batch = self.db.write_batch();
3538        let mut iter = self.db.scan_prefix(cf, &[]);
3539        while iter.is_valid() {
3540            if let Some(key) = iter.key() {
3541                batch.delete(cf, key);
3542            }
3543            iter.next();
3544        }
3545        iter.status()?;
3546        // Drop the trust state WITH the postings: the gate checks epoch +
3547        // origin and never a liveness marker, so an epoch that survives its
3548        // index reads TRUSTED over an empty `temporal_index` CF — a rebuild
3549        // failing after the wipe would leave every rewritten temporal
3550        // FILTER silently answering zero rows. Deleting both keys returns
3551        // the index to the never-built, untrusted state; a finished rebuild
3552        // re-stamps them (atomically) and trust resumes. The GEO index's
3553        // liveness marker is not ours to touch here: deleting it used to
3554        // live in this function (copy-pasted from `wipe_geo_index`) and
3555        // collateral-untrusted geo on every temporal rebuild.
3556        if let Some(meta) = &self.cf_temporal_meta {
3557            batch.delete(meta, TEMPORAL_INDEX_EPOCH_KEY);
3558            batch.delete(meta, TEMPORAL_INDEX_ORIGIN_KEY);
3559        }
3560        batch.commit()
3561    }
3562
3563    /// Fold a finished quad run's verdict into its term run's alive flag:
3564    /// a quad whose own-latest version (the op of its FIRST, newest row)
3565    /// is a `Put` keeps the term alive.
3566    fn fold_quad_run(
3567        quad_run: &mut Option<(Vec<u8>, StorageOp)>,
3568        term_run: &mut Option<(Vec<u8>, EncodedTerm, bool)>,
3569    ) {
3570        if let Some((_, quad_op)) = quad_run.take()
3571            && quad_op == StorageOp::Put
3572            && let Some((_, _, alive)) = term_run.as_mut()
3573        {
3574            *alive = true;
3575        }
3576    }
3577
3578    /// Collect the O-axis temporal terms for the rebuild walk.
3579    ///
3580    /// One linear pass over the leading O-permutation CF (object-major key
3581    /// order). Rows for one object term are contiguous, and within that
3582    /// block every distinct quad (the remaining key terms) has its version
3583    /// rows adjacent, NEWEST FIRST (descending commit_ts suffix). A term is
3584    /// collected when ANY quad referencing it has its own-latest version =
3585    /// a visible `Put` (per-quad liveness): the index running AHEAD of the
3586    /// store is harmless (a dead posted term joins nothing), while a live
3587    /// term missing from it would silently drop rows. Deletes are never
3588    /// mirrored to the postings (`waratah_compute/src/fanout.rs` sends none
3589    /// on delete batches), so this walk after the whole-CF wipe is the
3590    /// garbage collector of dead terms. Returns `(terms, epoch)`: the alive
3591    /// native temporal terms in walk order, and the max commit_ts over
3592    /// every row carrying a temporal term (either op) — the epoch source.
3593    pub fn temporal_rebuild_terms(&self) -> Result<(Vec<EncodedTerm>, CommitTs), StorageError> {
3594        if self.axis != PartitionAxis::O {
3595            return Err(StorageError::TemporalIndexNotOnAxis(self.axis));
3596        }
3597        let mut epoch = CommitTs(0);
3598        // Current term run under aggregation: (term bytes, decoded term,
3599        // alive flag = any quad's latest version is a Put).
3600        let mut term_run: Option<(Vec<u8>, EncodedTerm, bool)> = None;
3601        // Current quad run inside the term run: (row key minus the
3602        // commit_ts suffix — identifies the quad, op of its FIRST row,
3603        // which is the quad's latest version in descending-ts order).
3604        let mut quad_run: Option<(Vec<u8>, StorageOp)> = None;
3605        let mut alive_terms: Vec<EncodedTerm> = Vec::new();
3606        let mut iter = self.db.scan_prefix(&self.cf0, &[]);
3607        while iter.is_valid() {
3608            let row = match (iter.key(), iter.value()) {
3609                (Some(key), Some(value)) => (key, value),
3610                _ => {
3611                    iter.next();
3612                    continue;
3613                }
3614            };
3615            let (key, value) = row;
3616            let mut cursor: &[u8] = key;
3617            let term = match cursor.read_term() {
3618                Ok(term) => term,
3619                // Not a decodable leading term (defensive): skip the row.
3620                Err(_) => {
3621                    iter.next();
3622                    continue;
3623                }
3624            };
3625            let term_len = key.len() - cursor.len();
3626            if crate::encode::temporal_term_interval(&term).is_none() {
3627                // Non-temporal terms never carry postings: skip without
3628                // touching the aggregation. A temporal term's rows are
3629                // contiguous, so skipping cannot merge two term runs.
3630                iter.next();
3631                continue;
3632            }
3633            let ts_at = key
3634                .len()
3635                .checked_sub(crate::encode::COMMIT_TS_LEN)
3636                .ok_or_else(|| StorageError::Corrupt("hexastore key too short".to_owned()))?;
3637            let commit_ts = CommitTs::from_descending_be_bytes(
3638                key[ts_at..]
3639                    .try_into()
3640                    .map_err(|_| StorageError::Corrupt("hexastore commit_ts".to_owned()))?,
3641            );
3642            let header = value
3643                .get(..crate::encode::STORAGE_VALUE_LEN)
3644                .ok_or_else(|| StorageError::Corrupt("truncated storage value".to_owned()))?;
3645            let (op, _) = decode_storage_value(header)?;
3646            if commit_ts.0 > epoch.0 {
3647                epoch = commit_ts;
3648            }
3649            let quad_key = &key[..ts_at];
3650            let same_term = term_run
3651                .as_ref()
3652                .is_some_and(|(bytes, _, _)| bytes.as_slice() == &key[..term_len]);
3653            if !same_term {
3654                // Term boundary: the finished term's quad runs have already
3655                // folded into its alive flag; emit the term iff alive.
3656                Self::fold_quad_run(&mut quad_run, &mut term_run);
3657                if let Some((_, term, true)) = term_run.take() {
3658                    alive_terms.push(term);
3659                }
3660                term_run = Some((key[..term_len].to_vec(), term, false));
3661            }
3662            // Quad boundary inside the term (or its first row): the
3663            // finished quad's FIRST row — its latest version — folds into
3664            // the alive flag; older versions of the same quad are ignored.
3665            let same_quad = quad_run
3666                .as_ref()
3667                .is_some_and(|(prefix, _)| prefix.as_slice() == quad_key);
3668            if !same_quad {
3669                Self::fold_quad_run(&mut quad_run, &mut term_run);
3670                quad_run = Some((quad_key.to_vec(), op));
3671            }
3672            iter.next();
3673        }
3674        iter.status()?;
3675        // Tail flush: the last term run.
3676        Self::fold_quad_run(&mut quad_run, &mut term_run);
3677        if let Some((_, term, true)) = term_run.take() {
3678            alive_terms.push(term);
3679        }
3680        Ok((alive_terms, epoch))
3681    }
3682
3683    /// Flush axis-local MemTables to SST files (no-op-equivalent wait on disk).
3684    pub fn flush_memtables(&self) -> Result<(), StorageError> {
3685        let mut cfs: Vec<&ColumnFamily> = vec![&self.cf0, &self.cf1];
3686        if let Some(cf) = &self.cf_catalog {
3687            cfs.push(cf);
3688        }
3689        if let Some(cf) = &self.cf_geo {
3690            cfs.push(cf);
3691        }
3692        if let Some(cf) = &self.cf_geo_meta {
3693            cfs.push(cf);
3694        }
3695        // The temporal CFs were skipped here until audit B40: the postings
3696        // memtable never reached an SST under `--compact`/forced flushes, so
3697        // the table-properties collector's `waratah.stats` histogram blob
3698        // was never produced (and the epoch/meta keys rode the WAL alone).
3699        if let Some(cf) = &self.cf_temporal {
3700            cfs.push(cf);
3701        }
3702        if let Some(cf) = &self.cf_temporal_meta {
3703            cfs.push(cf);
3704        }
3705        self.db.flush_cfs(&cfs)
3706    }
3707
3708    /// Warm this partition's block cache: sequential walks over the
3709    /// axis-local column families, stopping once usage reaches
3710    /// `fill_fraction` of capacity (see [`warm_walk`]).
3711    ///
3712    /// Data CFs (`cf0`/`cf1`) are walked first — they hold the scan blocks
3713    /// queries need — then the smaller index/catalog CFs if capacity remains.
3714    /// A `fill_fraction` of `0` (or below) disables the walk.
3715    pub fn warm_block_cache(
3716        &self,
3717        fill_fraction: f64,
3718    ) -> Result<crate::WarmBlockCacheStats, StorageError> {
3719        let capacity = self.db.block_cache_capacity();
3720        let target = (capacity as f64 * fill_fraction.max(0.0)) as usize;
3721        let usage_before = self.db.block_cache_usage();
3722        let mut cfs: Vec<&ColumnFamily> = vec![&self.cf0, &self.cf1];
3723        if let Some(cf) = &self.cf_catalog {
3724            cfs.push(cf);
3725        }
3726        if let Some(cf) = &self.cf_geo {
3727            cfs.push(cf);
3728        }
3729        if let Some(cf) = &self.cf_geo_meta {
3730            cfs.push(cf);
3731        }
3732        if let Some(cf) = &self.cf_temporal {
3733            cfs.push(cf);
3734        }
3735        if let Some(cf) = &self.cf_temporal_meta {
3736            cfs.push(cf);
3737        }
3738        let entries_touched = if target == 0 {
3739            0
3740        } else {
3741            warm_walk(&self.db, &cfs, target)?
3742        };
3743        Ok(WarmBlockCacheStats {
3744            entries_touched,
3745            usage_before,
3746            usage_after: self.db.block_cache_usage(),
3747            capacity,
3748        })
3749    }
3750
3751    /// Compact both axis-local column families (tests / explicit rewrite).
3752    ///
3753    /// Bottommost compaction is forced, so a trivial move is rewritten and
3754    /// collectors run even when the flushed file had no `waratah.stats`.
3755    pub fn compact_range(&self) {
3756        self.compact_cfs(BottommostLevelCompaction::Force);
3757    }
3758
3759    /// Compact the same column families as [`Self::compact_range`] without
3760    /// rewriting the bottommost level.
3761    ///
3762    /// The L0 merge still runs. A file RocksDB only trivial-moves keeps the
3763    /// `waratah.stats` blob written when it was flushed.
3764    pub fn compact_range_skip_bottommost(&self) {
3765        self.compact_cfs(BottommostLevelCompaction::Skip);
3766    }
3767
3768    fn compact_cfs(&self, bottommost: BottommostLevelCompaction) {
3769        self.db.compact_cf_bottommost(&self.cf0, bottommost);
3770        self.db.compact_cf_bottommost(&self.cf1, bottommost);
3771        if let Some(cf) = &self.cf_catalog {
3772            self.db.compact_cf_bottommost(cf, bottommost);
3773        }
3774        if let Some(cf) = &self.cf_geo {
3775            self.db.compact_cf_bottommost(cf, bottommost);
3776        }
3777        if let Some(cf) = &self.cf_geo_meta {
3778            self.db.compact_cf_bottommost(cf, bottommost);
3779        }
3780        // Same audit-B40 gap as `flush_memtables`: force-compaction must
3781        // also rewrite the temporal index CFs.
3782        if let Some(cf) = &self.cf_temporal {
3783            self.db.compact_cf_bottommost(cf, bottommost);
3784        }
3785        if let Some(cf) = &self.cf_temporal_meta {
3786            self.db.compact_cf_bottommost(cf, bottommost);
3787        }
3788    }
3789
3790    /// Process-wide block cache bytes: `(capacity, charged usage)` — the
3791    /// same counters the warm pass targets. Cheap probe (counter read, no
3792    /// I/O); covers both axis-local CFs and the catalog/index CFs (one
3793    /// shared cache).
3794    pub fn block_cache_bytes(&self) -> Option<(u64, u64)> {
3795        self.db.block_cache_bytes()
3796    }
3797
3798    /// RocksDB LSM size / compaction counters for this partition.
3799    ///
3800    /// Size and key estimates are summed across the axis-local indexes (and the
3801    /// S-axis catalog CF). The empty `default` CF is not included.
3802    pub fn lsm_metrics(&self) -> crate::LsmMetrics {
3803        let mut cfs: Vec<&ColumnFamily> = vec![&self.cf0, &self.cf1];
3804        if let Some(catalog) = &self.cf_catalog {
3805            cfs.push(catalog);
3806        }
3807        if let Some(geo) = &self.cf_geo {
3808            cfs.push(geo);
3809        }
3810        self.db.lsm_metrics_for_cfs(&cfs)
3811    }
3812
3813    /// `rocksdb.num-files-at-level0` summed across the two hexastore CFs.
3814    ///
3815    /// `None` when RocksDB does not report the property. A flush with
3816    /// auto-compaction off leaves files here; a finished full-range compact
3817    /// moves them to a lower level.
3818    pub fn hexastore_level0_files(&self) -> Option<u64> {
3819        let level0 = "rocksdb.num-files-at-level0";
3820        let left = self
3821            .db
3822            .property_value_cf(&self.cf0, level0)
3823            .and_then(|s| s.parse().ok());
3824        let right = self
3825            .db
3826            .property_value_cf(&self.cf1, level0)
3827            .and_then(|s| s.parse().ok());
3828        match (left, right) {
3829            (None, None) => None,
3830            (left, right) => Some(left.unwrap_or(0) + right.unwrap_or(0)),
3831        }
3832    }
3833
3834    /// `user_collected_properties` blobs for `key` on the canonical stats CF,
3835    /// the named-graph catalog CF (S axis), and the plugin-index CFs whose
3836    /// table-properties collectors write under the same key (temporal
3837    /// index; geo index for when its collector lands). Until audit B40 the
3838    /// temporal CF was not read here, so the persisted tick histogram was
3839    /// write-only: serialized into SSTs and never rolled up.
3840    pub fn stats_property_blobs(&self, key: &[u8]) -> Result<Vec<Vec<u8>>, StorageError> {
3841        let mut blobs = self.db.user_property_blobs(&self.cf0, key)?;
3842        if let Some(cf) = &self.cf_catalog {
3843            blobs.extend(self.db.user_property_blobs(cf, key)?);
3844        }
3845        if let Some(cf) = &self.cf_temporal {
3846            blobs.extend(self.db.user_property_blobs(cf, key)?);
3847        }
3848        if let Some(cf) = &self.cf_geo {
3849            blobs.extend(self.db.user_property_blobs(cf, key)?);
3850        }
3851        Ok(blobs)
3852    }
3853
3854    fn cf_for(&self, permutation: IndexPermutation) -> Result<&ColumnFamily, StorageError> {
3855        if permutation == self.permutations[0] {
3856            Ok(&self.cf0)
3857        } else if permutation == self.permutations[1] {
3858            Ok(&self.cf1)
3859        } else {
3860            Err(StorageError::PermutationNotOwned {
3861                index: permutation.cf_name(),
3862                axis: self.axis,
3863            })
3864        }
3865    }
3866
3867    fn catalog_cf(&self) -> Result<&ColumnFamily, StorageError> {
3868        self.cf_catalog
3869            .as_ref()
3870            .ok_or(StorageError::CatalogNotOnAxis(self.axis))
3871    }
3872
3873    fn catalog_puts_for_encoded(
3874        &self,
3875        encoded: &EncodedQuad,
3876        commit_ts: CommitTs,
3877        op: StorageOp,
3878    ) -> Result<Vec<CatalogPut>, StorageError> {
3879        if self.axis != PartitionAxis::S
3880            || op != StorageOp::Put
3881            || !is_catalog_graph(&encoded.graph_name)
3882        {
3883            return Ok(Vec::new());
3884        }
3885        self.catalog_puts_for_insert(&[(encoded.graph_name.clone(), commit_ts)])
3886    }
3887
3888    fn catalog_newest_state(
3889        &self,
3890        graph: &EncodedTerm,
3891    ) -> Result<Option<GraphCatalogState>, StorageError> {
3892        let cf = self.catalog_cf()?;
3893        let prefix = catalog_prefix(graph)?;
3894        let iter = self.db.scan_prefix(cf, &prefix);
3895        if !iter.is_valid() {
3896            iter.status()?;
3897            return Ok(None);
3898        }
3899        let Some(key) = iter.key() else {
3900            iter.status()?;
3901            return Ok(None);
3902        };
3903        if !key.starts_with(&prefix) {
3904            iter.status()?;
3905            return Ok(None);
3906        }
3907        let Some(value) = iter.value() else {
3908            return Err(StorageError::Corrupt(
3909                "catalog iterator key without value".to_owned(),
3910            ));
3911        };
3912        let state = decode_catalog_value(value)?;
3913        iter.status()?;
3914        Ok(Some(state))
3915    }
3916
3917    fn catalog_prefix_occupied(&self, graph: &EncodedTerm) -> Result<bool, StorageError> {
3918        Ok(self.catalog_newest_state(graph)?.is_some())
3919    }
3920}
3921
3922/// Walk one count slice: keys `>= slice.start`, `< slice.end` (or through
3923/// the prefix end when `end` is `None`), full matcher semantics per row.
3924///
3925/// **Version-group ownership across boundaries.** Versions of one logical
3926/// triple are keys sharing a term prefix (descending commit-ts suffix), and
3927/// a group's MVCC decision ([`SnapshotScanState`]) requires walking the
3928/// group newest-first: versions newer than the snapshot are transparent
3929/// (unmarked), so the first version at or under the snapshot decides, and a
3930/// newest `Delete` retires the whole group. The decision therefore belongs
3931/// to the slice holding the group's newest version, wherever the boundary
3932/// falls relative to the *visible* version:
3933///
3934/// - **Straddled at slice start** (non-first slices): one probe — seek the
3935///   first key's term prefix; if the group's newest version sorts before
3936///   the slice start, the group is armed as `skip_logical` and its version
3937///   keys are skipped wherever they appear (an earlier slice owns it).
3938/// - **Straddled at slice end**: seek the crossing key's group newest.
3939///   Inside this slice → this slice owns and processes exactly that logical
3940///   past its end (re-visiting the group's own earlier versions is
3941///   idempotent — [`SnapshotScanState`] collapses by logical). At or past
3942///   the end → the next slice owns; break. One seek per slice.
3943///
3944/// The skip matches **exact** versioned-key length, not just the prefix:
3945/// sibling logicals that extend another's term prefix — named-graph
3946/// variants of a default-graph triple, whose graph term encodes to zero
3947/// bytes — are different groups that sort into the same key region and must
3948/// stay in the walk. Skip mode stays armed for the whole slice because such
3949/// siblings can interleave between the straddled group's version keys.
3950///
3951/// **Reachability.** With the shipped generators the straddle paths are
3952/// defense in depth: byte-even boundaries (`prefix ‖ tag ‖ be64`, 9 bytes
3953/// of suffix) split a version group only when the boundary's u64 equals the
3954/// group's leading term's first 8 payload bytes — a ~2⁻⁶⁴ event per
3955/// group-boundary pair — and TSG class-aligned boundaries cannot split any
3956/// group. The paths stay correct for manual slices and future generators.
3957/// Residual limitation, recorded: in a store mixing default-graph and
3958/// named-graph variants of the same triple, variant keys interleave inside
3959/// a straddled group's key span, and both the probe and the end-crossing
3960/// seek can land on a variant key instead of the group's newest — an
3961/// undercount requires that interleaving *and* a boundary collision
3962/// together; single-graph-kind stores (every realistic corpus) are exact.
3963#[allow(clippy::too_many_arguments)]
3964fn count_walk_slice(
3965    db: &Db,
3966    cf: &ColumnFamily,
3967    permutation: IndexPermutation,
3968    pattern: &EncodedTriplePattern,
3969    snapshot: SnapshotId,
3970    graph_filter: &GByteFilter,
3971    merge_default_graph: bool,
3972    prefix: &[u8],
3973    slice: &CountSlice,
3974    is_first: bool,
3975) -> Result<u64, StorageError> {
3976    let mut matcher = RowMatcher::compile(
3977        pattern,
3978        permutation,
3979        graph_filter.clone(),
3980        merge_default_graph,
3981        None,
3982        IriOnlyMask::NONE,
3983    );
3984    let mut state = SnapshotScanState::default();
3985    // Prefix-bounded iterator positioned at the slice start; the strict
3986    // `key >= end` check below is the slice's exclusive end — a key equal to
3987    // a synthetic boundary itself sorts into the NEXT slice, and the
3988    // iterator's prefix bound alone would still visit it.
3989    // total_order_seek, unconditionally (a measured no-op with filters
3990    // off — no filter blocks are loaded): a count slice is a multi-term
3991    // RANGE iterator. Its seeks (the start probe on non-first slices,
3992    // hint-aligned slice starts) name only the first term visited, and
3993    // that prefix is real and present — but the slice's range continues
3994    // past it, so per-SST prefix pruning would drop every SST lacking the
3995    // probed term and silently undercount (pinned by
3996    // count_walks_stay_exact_with_sst_filters_armed, which fails 6 vs 4
3997    // on this fixture without the flag). No seek-shape fix exists:
3998    // confinement would be the per-term seek-union shape the domain work
3999    // deleted. See scan_prefix_from_total_order.
4000    let mut iter = db.scan_prefix_from_total_order(cf, prefix, &slice.start);
4001    // Term prefix of a logical whose decision belongs to an EARLIER slice
4002    // (a straddler): keys of exactly this logical are skipped wherever they
4003    // appear in this slice. The mode stays armed for the whole slice —
4004    // sibling logicals that merely extend this one (named-graph variants of
4005    // a default-graph triple, whose graph term encodes to zero bytes) can
4006    // interleave between its version keys, so it must not disarm on the
4007    // first differing key.
4008    let mut skip_logical: Option<Vec<u8>> = None;
4009    // Set when this slice owns the decision for the logical that crosses its
4010    // end boundary: keys of exactly that logical are processed past the end,
4011    // and the walk stops at the first different logical (everything after it
4012    // belongs to the next slice).
4013    let mut crossing_logical: Option<Vec<u8>> = None;
4014    if !is_first && iter.is_valid() {
4015        let Some(key) = iter.key() else {
4016            return Err(StorageError::Corrupt(
4017                "valid iterator without key".to_owned(),
4018            ));
4019        };
4020        let first_key = key.to_vec();
4021        let logical = versioned_key_term_prefix(&first_key)?.to_vec();
4022        iter.seek(&logical);
4023        if let Some(newest) = iter.key()
4024            && newest < first_key.as_slice()
4025        {
4026            // Straddler: the group's newest version sorts before this
4027            // slice's start, so an earlier slice owns the decision. Arm the
4028            // skip and resume at the slice start — the seek landed before
4029            // it, in the owning slice's territory.
4030            skip_logical = Some(logical);
4031            iter.seek(&slice.start);
4032        }
4033    }
4034    let mut count = 0u64;
4035    while iter.is_valid() {
4036        let Some(key) = iter.key() else { break };
4037        let key_logical = versioned_key_term_prefix(key)?;
4038        // Straddled group: this slice decided nothing for it; skip its
4039        // version keys (exact logical, exact versioned-key length — a longer
4040        // key extending the logical is a different group and stays in the
4041        // walk).
4042        if let Some(skip) = &skip_logical
4043            && key_logical == skip.as_slice()
4044            && key.len() == skip.len() + COMMIT_TS_LEN
4045        {
4046            iter.next();
4047            continue;
4048        }
4049        if let Some(cross) = &crossing_logical
4050            && key_logical != cross.as_slice()
4051        {
4052            // The owned group is finished; everything from here belongs to
4053            // the next slice.
4054            break;
4055        }
4056        if crossing_logical.is_none()
4057            && let Some(end) = slice.end.as_deref()
4058            && key >= end
4059        {
4060            // The walk reached the slice end inside a group. Who owns the
4061            // decision? Seek the group's newest version: inside this slice →
4062            // this slice owns and processes exactly this logical past its
4063            // end (re-visiting the group's own earlier versions is
4064            // idempotent — [`SnapshotScanState`] collapses by logical); at
4065            // or past the end → the next slice owns (its start is this
4066            // end) — stop here. One seek per slice.
4067            let logical = key_logical.to_vec();
4068            iter.seek(&logical);
4069            let owned = match iter.key() {
4070                Some(newest) => newest >= slice.start.as_slice() && newest < end,
4071                None => false,
4072            };
4073            if owned {
4074                crossing_logical = Some(logical);
4075                continue;
4076            }
4077            break;
4078        }
4079        let Some(value) = iter.value() else {
4080            return Err(StorageError::Corrupt(
4081                "iterator key without value".to_owned(),
4082            ));
4083        };
4084        if matches!(
4085            matcher.matches_row(key, value, snapshot, &mut state)?,
4086            MatchDecision::Emit { .. }
4087        ) {
4088            count += 1;
4089        }
4090        iter.next();
4091    }
4092    iter.status()?;
4093    Ok(count)
4094}
4095
4096/// One worker-pool unit walking one count slice (see
4097/// [`RocksDbStorage::count_pattern_sliced`]). Owns its inputs: the pool
4098/// outlives a single count call, so units cannot borrow caller state.
4099struct CountSliceUnit {
4100    db: Db,
4101    cf: ColumnFamily,
4102    permutation: IndexPermutation,
4103    pattern: EncodedTriplePattern,
4104    snapshot: SnapshotId,
4105    graph_filter: GByteFilter,
4106    merge_default_graph: bool,
4107    prefix: Vec<u8>,
4108    slice: CountSlice,
4109    is_first: bool,
4110}
4111
4112impl PoolUnit for CountSliceUnit {
4113    type Output = Result<u64, StorageError>;
4114
4115    fn execute(self) -> Self::Output {
4116        count_walk_slice(
4117            &self.db,
4118            &self.cf,
4119            self.permutation,
4120            &self.pattern,
4121            self.snapshot,
4122            &self.graph_filter,
4123            self.merge_default_graph,
4124            &self.prefix,
4125            &self.slice,
4126            self.is_first,
4127        )
4128    }
4129}
4130
4131#[cfg(test)]
4132mod tests {
4133    use super::RocksDbStorage;
4134    use crate::encode::{TEMPORAL_INDEX_ORIGIN_KEY, encode_temporal_origin};
4135    use crate::rocksdb_db::DEFAULT_BLOCK_CACHE_BYTES;
4136    use crate::{
4137        BlankNode, CommitTs, DomainCountMode, DomainScanCountHit, EncodedTerm, GraphName,
4138        IndexPermutation, Literal, NamedNode, PartitionAxis, Quad, RocksDbOptionsHooks,
4139        RocksDbTuning, SnapshotId, StorageError, StorageOp, VisibilityLabel,
4140        WARM_CACHE_FILL_FRACTION, WARM_CACHE_PROBE_INTERVAL, encode_quad,
4141    };
4142
4143    fn named_spo(s: &str, o: &str, g: &str) -> Quad {
4144        Quad::new(
4145            NamedNode::new(format!("http://ex/{s}")).unwrap(),
4146            NamedNode::new("http://ex/p").unwrap(),
4147            NamedNode::new(format!("http://ex/{o}")).unwrap(),
4148            GraphName::NamedNode(NamedNode::new(format!("http://ex/{g}")).unwrap()),
4149        )
4150    }
4151
4152    fn count_posg(
4153        store: &RocksDbStorage,
4154        predicate: &EncodedTerm,
4155        allow: &[EncodedTerm],
4156        allow_on: bool,
4157        merge: bool,
4158    ) -> u64 {
4159        store
4160            .scan_domain_counts(
4161                IndexPermutation::Posg,
4162                std::slice::from_ref(predicate),
4163                SnapshotId(9),
4164                0,
4165                None,
4166                None,
4167                None,
4168                allow,
4169                allow_on,
4170                false,
4171                merge,
4172                DomainCountMode::Rows,
4173            )
4174            .unwrap()
4175            .iter()
4176            .map(|hit| hit.count)
4177            .sum()
4178    }
4179
4180    /// Warm pass: data blocks of both permutation CFs land in the cache, the
4181    /// full walk covers every row when the target is far above the data size,
4182    /// and a tiny target stops the walk at the first probe.
4183    #[test]
4184    fn warm_block_cache_fills_and_stops_at_target() {
4185        let mk_dir = |tag: &str| {
4186            std::env::temp_dir().join(format!(
4187                "waratah-warm-{tag}-{}-{}",
4188                std::process::id(),
4189                std::time::SystemTime::now()
4190                    .duration_since(std::time::UNIX_EPOCH)
4191                    .unwrap()
4192                    .as_nanos()
4193            ))
4194        };
4195        let store = RocksDbStorage::open(&mk_dir("full"), PartitionAxis::P).unwrap();
4196        for i in 0..3_000u64 {
4197            store
4198                .insert_quad_version(
4199                    &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
4200                    CommitTs(1),
4201                    StorageOp::Put,
4202                    VisibilityLabel::default(),
4203                )
4204                .unwrap();
4205        }
4206        store.flush_memtables().unwrap();
4207
4208        // Full walk: 3_000 quads × 2 permutation CFs, target (half of the
4209        // 128 MiB default cache) far above the ~0.5 MiB of data.
4210        let stats = store.warm_block_cache(WARM_CACHE_FILL_FRACTION).unwrap();
4211        assert_eq!(stats.entries_touched, 6_000);
4212        assert!(
4213            stats.usage_after > stats.usage_before,
4214            "warm must fill data blocks into the cache"
4215        );
4216        assert_eq!(stats.capacity, DEFAULT_BLOCK_CACHE_BYTES);
4217
4218        // Tiny target: occupancy passes the threshold at the first probe, so
4219        // the walk stops there instead of covering the remaining rows.
4220        let store = RocksDbStorage::open(&mk_dir("tiny"), PartitionAxis::P).unwrap();
4221        for i in 0..3_000u64 {
4222            store
4223                .insert_quad_version(
4224                    &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
4225                    CommitTs(1),
4226                    StorageOp::Put,
4227                    VisibilityLabel::default(),
4228                )
4229                .unwrap();
4230        }
4231        store.flush_memtables().unwrap();
4232        let stats = store.warm_block_cache(1e-5).unwrap();
4233        assert_eq!(stats.entries_touched, WARM_CACHE_PROBE_INTERVAL);
4234    }
4235
4236    /// Scan-async gate: with `scan_async_io` on, the scan iterators and the
4237    /// warm walk run with `ReadOptions::async_io` (io_uring submission where
4238    /// the build supports it; silent sync fallback otherwise) and must
4239    /// return identical results.
4240    #[test]
4241    fn scan_async_io_tuning_scans_and_warms_correctly() {
4242        let dir = std::env::temp_dir().join(format!(
4243            "waratah-scan-async-{}-{}",
4244            std::process::id(),
4245            std::time::SystemTime::now()
4246                .duration_since(std::time::UNIX_EPOCH)
4247                .unwrap()
4248                .as_nanos()
4249        ));
4250        let store = RocksDbStorage::open_with_hooks(
4251            &dir,
4252            PartitionAxis::P,
4253            RocksDbOptionsHooks {
4254                tuning: RocksDbTuning {
4255                    scan_async_io: true,
4256                    ..Default::default()
4257                },
4258                ..Default::default()
4259            },
4260        )
4261        .unwrap();
4262        for i in 0..500u64 {
4263            store
4264                .insert_quad_version(
4265                    &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
4266                    CommitTs(1),
4267                    StorageOp::Put,
4268                    VisibilityLabel::default(),
4269                )
4270                .unwrap();
4271        }
4272        store.flush_memtables().unwrap();
4273
4274        // Scan through the gated iterator path: unchanged results.
4275        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
4276        assert_eq!(count_posg(&store, &p, &[], false, true), 500);
4277
4278        // The warm walk (sequential, where async prefetch engages) still
4279        // fills the cache.
4280        let stats = store.warm_block_cache(WARM_CACHE_FILL_FRACTION).unwrap();
4281        assert!(stats.entries_touched > 0);
4282        assert!(stats.usage_after > stats.usage_before);
4283    }
4284
4285    /// Twin of the memory merge-count cases. RocksDB seek must unique S/P/O
4286    /// without skipping a later Put after a visible Delete.
4287    #[test]
4288    fn domain_counts_merge_uniques_spo_not_heads() {
4289        let dir = std::env::temp_dir().join(format!(
4290            "waratah-merge-counts-{}-{}",
4291            std::process::id(),
4292            std::time::SystemTime::now()
4293                .duration_since(std::time::UNIX_EPOCH)
4294                .unwrap()
4295                .as_nanos()
4296        ));
4297        let store = RocksDbStorage::open(&dir, PartitionAxis::P).unwrap();
4298        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
4299        for (ts, (s, o, g, op)) in (1u64..).zip([
4300            ("s", "o", "g1", StorageOp::Put),
4301            ("s", "o", "g2", StorageOp::Put),
4302            ("s1", "o", "g1", StorageOp::Put),
4303            ("s1", "o", "g2", StorageOp::Put),
4304            ("s2", "o", "g1", StorageOp::Put),
4305            ("s2", "o", "g2", StorageOp::Put),
4306            ("sd", "od", "a", StorageOp::Put),
4307            ("sd", "od", "a", StorageOp::Delete),
4308            ("sd", "od", "b", StorageOp::Put),
4309        ]) {
4310            store
4311                .insert_quad_version(
4312                    &named_spo(s, o, g),
4313                    CommitTs(ts),
4314                    op,
4315                    VisibilityLabel::default(),
4316                )
4317                .unwrap();
4318        }
4319        let g1 = encode_quad(&named_spo("s", "o", "g1")).unwrap().graph_name;
4320        let g2 = encode_quad(&named_spo("s", "o", "g2")).unwrap().graph_name;
4321        let gone = encode_quad(&named_spo("sd", "od", "a")).unwrap().graph_name;
4322
4323        // Same (s,p,o) in two graphs, plus two more subjects on `o`.
4324        // Heads: `o` run is s + s1 + s2 (3 merged, 6 bag) and `od` is 1.
4325        assert_eq!(count_posg(&store, &p, &[], false, true), 4);
4326        assert_eq!(count_posg(&store, &p, &[], false, false), 7);
4327        assert_eq!(count_posg(&store, &p, &[g1, g2], true, true), 3);
4328        assert_eq!(
4329            count_posg(&store, &p, std::slice::from_ref(&gone), true, true),
4330            0
4331        );
4332        drop(store);
4333        let _ = std::fs::remove_dir_all(&dir);
4334    }
4335
4336    /// Twin of the memory paging case. A full page ends on a run boundary;
4337    /// the resume cursor must return the other run once, with its full count.
4338    #[test]
4339    fn domain_counts_cursor_resumes_at_run_boundaries() {
4340        let dir = std::env::temp_dir().join(format!(
4341            "waratah-count-page-{}-{}",
4342            std::process::id(),
4343            std::time::SystemTime::now()
4344                .duration_since(std::time::UNIX_EPOCH)
4345                .unwrap()
4346                .as_nanos()
4347        ));
4348        let store = RocksDbStorage::open(&dir, PartitionAxis::P).unwrap();
4349        let p = NamedNode::new("http://ex/p").unwrap();
4350        let s1 = NamedNode::new("http://ex/s1").unwrap();
4351        let s2 = NamedNode::new("http://ex/s2").unwrap();
4352        let o1 = NamedNode::new("http://ex/o1").unwrap();
4353        let o2 = NamedNode::new("http://ex/o2").unwrap();
4354        for (ts, (subject, object)) in
4355            (1u64..).zip([(s1.clone(), o1.clone()), (s2, o1.clone()), (s1, o2.clone())])
4356        {
4357            store
4358                .insert_quad_version(
4359                    &Quad::new(subject, p.clone(), object, GraphName::DefaultGraph),
4360                    CommitTs(ts),
4361                    StorageOp::Put,
4362                    VisibilityLabel::default(),
4363                )
4364                .unwrap();
4365        }
4366        let predicate = EncodedTerm::from(&p);
4367        let page1 = store
4368            .scan_domain_counts(
4369                IndexPermutation::Posg,
4370                std::slice::from_ref(&predicate),
4371                SnapshotId(9),
4372                1,
4373                None,
4374                None,
4375                None,
4376                &[],
4377                false,
4378                false,
4379                false,
4380                DomainCountMode::Rows,
4381            )
4382            .unwrap();
4383        assert_eq!(page1.len(), 1);
4384        let page2 = store
4385            .scan_domain_counts(
4386                IndexPermutation::Posg,
4387                std::slice::from_ref(&predicate),
4388                SnapshotId(9),
4389                0,
4390                Some(&page1[0].constraint),
4391                Some(&page1[0].term),
4392                None,
4393                &[],
4394                false,
4395                false,
4396                false,
4397                DomainCountMode::Rows,
4398            )
4399            .unwrap();
4400        assert_eq!(page2.len(), 1);
4401        assert_ne!(page1[0].term, page2[0].term);
4402        let o1_term = EncodedTerm::from(&o1);
4403        let (o1_count, o2_count) = if page1[0].term == o1_term {
4404            (page1[0].count, page2[0].count)
4405        } else {
4406            (page2[0].count, page1[0].count)
4407        };
4408        assert_eq!((o1_count, o2_count), (2, 1));
4409        drop(store);
4410        let _ = std::fs::remove_dir_all(&dir);
4411    }
4412
4413    fn open_count_store(tag: &str) -> (std::path::PathBuf, RocksDbStorage) {
4414        let dir = std::env::temp_dir().join(format!(
4415            "waratah-count-modes-{tag}-{}-{}",
4416            std::process::id(),
4417            std::time::SystemTime::now()
4418                .duration_since(std::time::UNIX_EPOCH)
4419                .unwrap()
4420                .as_nanos()
4421        ));
4422        (
4423            dir.clone(),
4424            RocksDbStorage::open(&dir, PartitionAxis::P).unwrap(),
4425        )
4426    }
4427
4428    fn scan_posg_runs(
4429        store: &RocksDbStorage,
4430        predicate: &EncodedTerm,
4431        snapshot: u64,
4432        allow: &[EncodedTerm],
4433        allow_on: bool,
4434        merge: bool,
4435        mode: DomainCountMode,
4436    ) -> Vec<DomainScanCountHit> {
4437        store
4438            .scan_domain_counts(
4439                IndexPermutation::Posg,
4440                std::slice::from_ref(predicate),
4441                SnapshotId(snapshot),
4442                0,
4443                None,
4444                None,
4445                None,
4446                allow,
4447                allow_on,
4448                false,
4449                merge,
4450                mode,
4451            )
4452            .unwrap()
4453    }
4454
4455    fn head_count(hits: &[DomainScanCountHit], head: &EncodedTerm) -> u64 {
4456        hits.iter()
4457            .find(|h| h.term == *head)
4458            .unwrap_or_else(|| panic!("no hit for head {head:?}"))
4459            .count
4460    }
4461
4462    /// TSG axis walks under G windows. TSG keys are `class|subject|G`, so
4463    /// the graph region sits one hop after the head (the subject) — a
4464    /// layout no other test exercised with a window, and the production
4465    /// shape of type-facet queries (bound default graph ⇒ `DefaultOnly`).
4466    /// Every window shape runs through hits, TOTAL, and PER_HEAD on both
4467    /// backends.
4468    #[test]
4469    fn tsg_axis_walks_honor_graph_windows() {
4470        let dir = std::env::temp_dir().join(format!(
4471            "waratah-tsg-windows-{}-{}",
4472            std::process::id(),
4473            std::time::SystemTime::now()
4474                .duration_since(std::time::UNIX_EPOCH)
4475                .unwrap()
4476                .as_nanos()
4477        ));
4478        let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
4479        let memory = Storage::memory(PartitionAxis::O);
4480        let t = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
4481        let type_quad = |s: &str, cls: &str, g: &str| {
4482            let graph = if g == "default" {
4483                GraphName::DefaultGraph
4484            } else {
4485                GraphName::NamedNode(NamedNode::new(format!("http://ex/{g}")).unwrap())
4486            };
4487            Quad::new(
4488                NamedNode::new(format!("http://ex/{s}")).unwrap(),
4489                t.clone(),
4490                NamedNode::new(format!("http://ex/{cls}")).unwrap(),
4491                graph,
4492            )
4493        };
4494        // cls1: s1 in default+g1, s2 in g1+g2. cls2: s3 in default+g1.
4495        let rows = [
4496            ("s1", "cls1", "default"),
4497            ("s1", "cls1", "g1"),
4498            ("s2", "cls1", "g1"),
4499            ("s2", "cls1", "g2"),
4500            ("s3", "cls2", "default"),
4501            ("s3", "cls2", "g1"),
4502        ];
4503        for (ts, (s, cls, g)) in (1u64..).zip(rows) {
4504            let quad = type_quad(s, cls, g);
4505            store
4506                .insert_quad_version(
4507                    &quad,
4508                    CommitTs(ts),
4509                    StorageOp::Put,
4510                    VisibilityLabel::default(),
4511                )
4512                .unwrap();
4513            memory
4514                .insert_quad_version(
4515                    &quad,
4516                    CommitTs(ts),
4517                    StorageOp::Put,
4518                    VisibilityLabel::default(),
4519                )
4520                .unwrap();
4521        }
4522        let g1 = graph_term("g1");
4523        let g2 = graph_term("g2");
4524        let snap = SnapshotId(10);
4525
4526        // (name, graph_name, filter_terms, filter_allow) →
4527        // (TOTAL heads, PER_HEAD [cls1 subjects, cls2 subjects]).
4528        // Ground truth per window from the rows above:
4529        //   bound g1: cls1 {s1,s2} cls2 {s3}; bound default: cls1 {s1} cls2 {s3};
4530        //   allow g1+g2: cls1 {s1,s2} cls2 {s3}; deny g1: cls1 {s1,s2} cls2 {s3}.
4531        let windows: Vec<(&str, Option<EncodedTerm>, Vec<EncodedTerm>, bool)> = vec![
4532            ("bound-g1", Some(g1.clone()), vec![], false),
4533            (
4534                "bound-default",
4535                Some(EncodedTerm::DefaultGraph),
4536                vec![],
4537                false,
4538            ),
4539            ("allow-g1g2", None, vec![g1.clone(), g2.clone()], true),
4540            ("deny-g1", None, vec![g1.clone()], false),
4541        ];
4542        for (name, graph_name, filter, allow) in &windows {
4543            let filter_ref: &[EncodedTerm] = filter;
4544            let hits = store
4545                .scan_axis_head(
4546                    IndexPermutation::Tsg,
4547                    snap,
4548                    0,
4549                    None,
4550                    graph_name.as_ref(),
4551                    filter_ref,
4552                    *allow,
4553                    false,
4554                    &[],
4555                )
4556                .unwrap();
4557            let mem_hits = memory
4558                .scan_axis_head(
4559                    IndexPermutation::Tsg,
4560                    snap,
4561                    0,
4562                    None,
4563                    graph_name.as_ref(),
4564                    filter_ref,
4565                    *allow,
4566                    false,
4567                    &[],
4568                )
4569                .unwrap();
4570            assert_eq!(hits, mem_hits, "hits parity under {name}");
4571            assert_eq!(hits.len(), 2, "both classes visible under {name}: {hits:?}");
4572
4573            let total = store
4574                .count_axis_heads(
4575                    IndexPermutation::Tsg,
4576                    snap,
4577                    graph_name.as_ref(),
4578                    filter_ref,
4579                    *allow,
4580                    false,
4581                )
4582                .unwrap();
4583            let mem_total = memory
4584                .count_axis_heads(
4585                    IndexPermutation::Tsg,
4586                    snap,
4587                    graph_name.as_ref(),
4588                    filter_ref,
4589                    *allow,
4590                    false,
4591                )
4592                .unwrap();
4593            assert_eq!(total, mem_total, "TOTAL parity under {name}");
4594            assert_eq!(total, 2, "TOTAL counts both classes under {name}");
4595
4596            let per_head = store
4597                .scan_axis_head_counts(
4598                    IndexPermutation::Tsg,
4599                    snap,
4600                    0,
4601                    None,
4602                    graph_name.as_ref(),
4603                    filter_ref,
4604                    *allow,
4605                    false,
4606                )
4607                .unwrap();
4608            let mem_per_head = memory
4609                .scan_axis_head_counts(
4610                    IndexPermutation::Tsg,
4611                    snap,
4612                    0,
4613                    None,
4614                    graph_name.as_ref(),
4615                    filter_ref,
4616                    *allow,
4617                    false,
4618                )
4619                .unwrap();
4620            assert_eq!(per_head, mem_per_head, "PER_HEAD parity under {name}");
4621            let mut counts: Vec<u64> = per_head.iter().map(|h| h.count).collect();
4622            counts.sort_unstable();
4623            let expected = match *name {
4624                "bound-default" => vec![1, 1],
4625                _ => vec![1, 2],
4626            };
4627            assert_eq!(
4628                counts, expected,
4629                "PER_HEAD distinct subjects under {name}: {per_head:?}"
4630            );
4631        }
4632
4633        drop(store);
4634        let _ = std::fs::remove_dir_all(&dir);
4635    }
4636
4637    /// TSG + distinct count modes must be refused loudly at both storage
4638    /// entry points: TSG's third component is G, so DistinctTerms would
4639    /// read the graph slot (erroring on default-graph rows, whose G region
4640    /// is empty) and DistinctGraphs would read past it (always empty).
4641    /// Rows mode has no per-slot work and must keep working.
4642    #[test]
4643    fn distinct_count_modes_refuse_tsg() {
4644        let dir = std::env::temp_dir().join(format!(
4645            "waratah-tsg-distinct-refusal-{}-{}",
4646            std::process::id(),
4647            std::time::SystemTime::now()
4648                .duration_since(std::time::UNIX_EPOCH)
4649                .unwrap()
4650                .as_nanos()
4651        ));
4652        let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
4653        let memory = Storage::memory(PartitionAxis::O);
4654        let t = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
4655        let quad = Quad::new(
4656            NamedNode::new("http://ex/s1").unwrap(),
4657            t.clone(),
4658            NamedNode::new("http://ex/cls1").unwrap(),
4659            GraphName::NamedNode(NamedNode::new("http://ex/g1").unwrap()),
4660        );
4661        store
4662            .insert_quad_version(
4663                &quad,
4664                CommitTs(1),
4665                StorageOp::Put,
4666                VisibilityLabel::default(),
4667            )
4668            .unwrap();
4669        memory
4670            .insert_quad_version(
4671                &quad,
4672                CommitTs(1),
4673                StorageOp::Put,
4674                VisibilityLabel::default(),
4675            )
4676            .unwrap();
4677        let cls1 = EncodedTerm::from(&NamedNode::new("http://ex/cls1").unwrap());
4678
4679        for mode in [
4680            DomainCountMode::DistinctTerms,
4681            DomainCountMode::DistinctGraphs,
4682        ] {
4683            let rocks = store.scan_domain_counts(
4684                IndexPermutation::Tsg,
4685                std::slice::from_ref(&cls1),
4686                SnapshotId(10),
4687                0,
4688                None,
4689                None,
4690                None,
4691                &[],
4692                false,
4693                false,
4694                false,
4695                mode,
4696            );
4697            assert!(
4698                matches!(rocks, Err(StorageError::DistinctCountsNotOnTsg)),
4699                "RocksDB must refuse TSG + {mode:?}: {rocks:?}"
4700            );
4701            let mem = memory.scan_domain_counts(
4702                IndexPermutation::Tsg,
4703                std::slice::from_ref(&cls1),
4704                SnapshotId(10),
4705                0,
4706                None,
4707                None,
4708                None,
4709                &[],
4710                false,
4711                false,
4712                false,
4713                mode,
4714            );
4715            assert!(
4716                matches!(mem, Err(StorageError::DistinctCountsNotOnTsg)),
4717                "memory must refuse TSG + {mode:?}: {mem:?}"
4718            );
4719        }
4720
4721        // Rows mode stays servable on TSG: one visible row under cls1.
4722        for hits in [
4723            store.scan_domain_counts(
4724                IndexPermutation::Tsg,
4725                std::slice::from_ref(&cls1),
4726                SnapshotId(10),
4727                0,
4728                None,
4729                None,
4730                None,
4731                &[],
4732                false,
4733                false,
4734                false,
4735                DomainCountMode::Rows,
4736            ),
4737            memory.scan_domain_counts(
4738                IndexPermutation::Tsg,
4739                std::slice::from_ref(&cls1),
4740                SnapshotId(10),
4741                0,
4742                None,
4743                None,
4744                None,
4745                &[],
4746                false,
4747                false,
4748                false,
4749                DomainCountMode::Rows,
4750            ),
4751        ] {
4752            let hits = hits.unwrap();
4753            assert_eq!(hits.len(), 1, "one head (the subject): {hits:?}");
4754            assert_eq!(hits[0].count, 1, "one row: {hits:?}");
4755        }
4756
4757        drop(store);
4758        let _ = std::fs::remove_dir_all(&dir);
4759    }
4760
4761    /// Twin of the memory axis head count test: TOTAL over distinct heads,
4762    /// PER_HEAD over distinct subjects per class, MVCC- and window-aware.
4763    #[test]
4764    fn axis_head_counts_total_and_per_head() {
4765        let dir = std::env::temp_dir().join(format!(
4766            "waratah-count-axis-heads-{}-{}",
4767            std::process::id(),
4768            std::time::SystemTime::now()
4769                .duration_since(std::time::UNIX_EPOCH)
4770                .unwrap()
4771                .as_nanos()
4772        ));
4773        let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
4774        let t = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
4775        let type_quad = |s: &str, cls: &str, g: &str| {
4776            Quad::new(
4777                NamedNode::new(format!("http://ex/{s}")).unwrap(),
4778                t.clone(),
4779                NamedNode::new(format!("http://ex/{cls}")).unwrap(),
4780                GraphName::NamedNode(NamedNode::new(format!("http://ex/{g}")).unwrap()),
4781            )
4782        };
4783        for (ts, (s, cls, g, op)) in (1u64..).zip([
4784            ("s1", "cls1", "g1", StorageOp::Put),
4785            ("s1", "cls1", "g2", StorageOp::Put),
4786            ("s2", "cls1", "g1", StorageOp::Put),
4787            ("s3", "cls2", "g1", StorageOp::Put),
4788            ("s1", "cls1", "g2", StorageOp::Delete),
4789        ]) {
4790            store
4791                .insert_quad_version(
4792                    &type_quad(s, cls, g),
4793                    CommitTs(ts),
4794                    op,
4795                    VisibilityLabel::default(),
4796                )
4797                .unwrap();
4798        }
4799
4800        let total = store
4801            .count_axis_heads(
4802                IndexPermutation::Tsg,
4803                SnapshotId(9),
4804                None,
4805                &[],
4806                false,
4807                false,
4808            )
4809            .unwrap();
4810        assert_eq!(total, 2, "two distinct classes");
4811
4812        let hits = store
4813            .scan_axis_head_counts(
4814                IndexPermutation::Tsg,
4815                SnapshotId(9),
4816                0,
4817                None,
4818                None,
4819                &[],
4820                false,
4821                false,
4822            )
4823            .unwrap();
4824        assert_eq!(hits.len(), 2);
4825        let counts: Vec<u64> = hits.iter().map(|h| h.count).collect();
4826        assert!(
4827            counts.contains(&2),
4828            "cls1 has two distinct subjects: {hits:?}"
4829        );
4830        assert!(counts.contains(&1), "cls2 has one subject: {hits:?}");
4831
4832        let g2 = encode_quad(&type_quad("s1", "cls1", "g2"))
4833            .unwrap()
4834            .graph_name;
4835        let total_g2 = store
4836            .count_axis_heads(
4837                IndexPermutation::Tsg,
4838                SnapshotId(9),
4839                None,
4840                std::slice::from_ref(&g2),
4841                true,
4842                false,
4843            )
4844            .unwrap();
4845        assert_eq!(total_g2, 0, "the g2 copy was deleted");
4846        let at4 = store
4847            .count_axis_heads(
4848                IndexPermutation::Tsg,
4849                SnapshotId(4),
4850                None,
4851                std::slice::from_ref(&g2),
4852                true,
4853                false,
4854            )
4855            .unwrap();
4856        assert_eq!(at4, 1, "one class visible in g2 before the delete");
4857
4858        let page1 = store
4859            .scan_axis_head_counts(
4860                IndexPermutation::Tsg,
4861                SnapshotId(9),
4862                1,
4863                None,
4864                None,
4865                &[],
4866                false,
4867                false,
4868            )
4869            .unwrap();
4870        assert_eq!(page1.len(), 1);
4871        let page2 = store
4872            .scan_axis_head_counts(
4873                IndexPermutation::Tsg,
4874                SnapshotId(9),
4875                0,
4876                Some(&page1[0].term),
4877                None,
4878                &[],
4879                false,
4880                false,
4881            )
4882            .unwrap();
4883        assert_eq!(page2.len(), 1);
4884        assert_ne!(page1[0].term, page2[0].term);
4885        drop(store);
4886        let _ = std::fs::remove_dir_all(&dir);
4887    }
4888
4889    /// Twin of the memory mode matrix. Rows = bag of `(slot-2, G)` rows,
4890    /// DistinctTerms collapses graph multiplicity, DistinctGraphs counts
4891    /// graph terms per head, and MVCC applies per row in every mode.
4892    #[test]
4893    fn domain_counts_modes_select_counting_dimension() {
4894        let (dir, store) = open_count_store("modes");
4895        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
4896        // s1 typed o in g1+g2 (deleted at ts=5), s2 typed o in g1, s3 typed
4897        // o2 in g1.
4898        for (ts, (s, o, g, op)) in (1u64..).zip([
4899            ("s1", "o", "g1", StorageOp::Put),
4900            ("s1", "o", "g2", StorageOp::Put),
4901            ("s2", "o", "g1", StorageOp::Put),
4902            ("s3", "o2", "g1", StorageOp::Put),
4903            ("s1", "o", "g2", StorageOp::Delete),
4904        ]) {
4905            store
4906                .insert_quad_version(
4907                    &named_spo(s, o, g),
4908                    CommitTs(ts),
4909                    op,
4910                    VisibilityLabel::default(),
4911                )
4912                .unwrap();
4913        }
4914
4915        let o_head = encode_quad(&named_spo("s1", "o", "g1")).unwrap().object;
4916        let o2_head = encode_quad(&named_spo("s3", "o2", "g1")).unwrap().object;
4917        let runs = |snapshot: u64, mode: DomainCountMode| {
4918            scan_posg_runs(&store, &p, snapshot, &[], false, false, mode)
4919        };
4920
4921        // Before the delete: o run = (s1,g1) (s1,g2) (s2,g1).
4922        let at4 = runs(4, DomainCountMode::Rows);
4923        assert_eq!(head_count(&at4, &o_head), 3);
4924        assert_eq!(head_count(&at4, &o2_head), 1);
4925        // Distinct slot-2 terms: s1 and s2 under o; graph multiplicity gone.
4926        let terms = runs(4, DomainCountMode::DistinctTerms);
4927        assert_eq!(head_count(&terms, &o_head), 2);
4928        assert_eq!(head_count(&terms, &o2_head), 1);
4929        // Distinct graphs under o: g1 and g2.
4930        let graphs = runs(4, DomainCountMode::DistinctGraphs);
4931        assert_eq!(head_count(&graphs, &o_head), 2);
4932        assert_eq!(head_count(&graphs, &o2_head), 1);
4933
4934        // After the delete the s1/g2 copy is invisible in every mode.
4935        assert_eq!(head_count(&runs(9, DomainCountMode::Rows), &o_head), 2);
4936        assert_eq!(
4937            head_count(&runs(9, DomainCountMode::DistinctTerms), &o_head),
4938            2
4939        );
4940        assert_eq!(
4941            head_count(&runs(9, DomainCountMode::DistinctGraphs), &o_head),
4942            1
4943        );
4944        assert_eq!(
4945            head_count(&runs(9, DomainCountMode::DistinctGraphs), &o2_head),
4946            1
4947        );
4948        drop(store);
4949        let _ = std::fs::remove_dir_all(&dir);
4950    }
4951
4952    /// Twin of the memory graph-window case for the graphs mode.
4953    #[test]
4954    fn domain_counts_distinct_graphs_respects_graph_window() {
4955        let (dir, store) = open_count_store("graph-window");
4956        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
4957        for (ts, g) in (1u64..).zip(["g1", "g2", "g3"]) {
4958            store
4959                .insert_quad_version(
4960                    &named_spo("s", "o", g),
4961                    CommitTs(ts),
4962                    StorageOp::Put,
4963                    VisibilityLabel::default(),
4964                )
4965                .unwrap();
4966        }
4967        let o_head = encode_quad(&named_spo("s", "o", "g1")).unwrap().object;
4968        let g1 = encode_quad(&named_spo("s", "o", "g1")).unwrap().graph_name;
4969        let g3 = encode_quad(&named_spo("s", "o", "g3")).unwrap().graph_name;
4970
4971        let all = scan_posg_runs(
4972            &store,
4973            &p,
4974            9,
4975            &[],
4976            false,
4977            false,
4978            DomainCountMode::DistinctGraphs,
4979        );
4980        assert_eq!(head_count(&all, &o_head), 3);
4981        let allowed = scan_posg_runs(
4982            &store,
4983            &p,
4984            9,
4985            std::slice::from_ref(&g1),
4986            true,
4987            false,
4988            DomainCountMode::DistinctGraphs,
4989        );
4990        assert_eq!(head_count(&allowed, &o_head), 1);
4991        // Block-list excluding g3.
4992        let blocked = scan_posg_runs(
4993            &store,
4994            &p,
4995            9,
4996            std::slice::from_ref(&g3),
4997            false,
4998            false,
4999            DomainCountMode::DistinctGraphs,
5000        );
5001        assert_eq!(head_count(&blocked, &o_head), 2);
5002        drop(store);
5003        let _ = std::fs::remove_dir_all(&dir);
5004    }
5005
5006    /// Twin of the memory merge equivalence: under `merge_default_graph` the
5007    /// walk seeks past extra G per triple, so Rows already counts distinct
5008    /// slot-2 terms.
5009    #[test]
5010    fn domain_counts_merge_makes_rows_equal_distinct_terms() {
5011        let (dir, store) = open_count_store("merge-equiv");
5012        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
5013        for (ts, (s, g)) in (1u64..).zip([("s1", "g1"), ("s1", "g2"), ("s2", "g1")]) {
5014            store
5015                .insert_quad_version(
5016                    &named_spo(s, "o", g),
5017                    CommitTs(ts),
5018                    StorageOp::Put,
5019                    VisibilityLabel::default(),
5020                )
5021                .unwrap();
5022        }
5023        let o_head = encode_quad(&named_spo("s1", "o", "g1")).unwrap().object;
5024        assert_eq!(
5025            head_count(
5026                &scan_posg_runs(&store, &p, 9, &[], false, true, DomainCountMode::Rows),
5027                &o_head
5028            ),
5029            2
5030        );
5031        assert_eq!(
5032            head_count(
5033                &scan_posg_runs(
5034                    &store,
5035                    &p,
5036                    9,
5037                    &[],
5038                    false,
5039                    false,
5040                    DomainCountMode::DistinctTerms
5041                ),
5042                &o_head
5043            ),
5044            2
5045        );
5046        drop(store);
5047        let _ = std::fs::remove_dir_all(&dir);
5048    }
5049
5050    /// The rebuild epoch persists across a reopen, reads `None` before the
5051    /// first stamp, and is rejected on axes without the meta CF.
5052    #[test]
5053    fn geo_index_epoch_persists_across_reopen() {
5054        let dir = std::env::temp_dir().join(format!(
5055            "waratah-geo-epoch-{}-{}",
5056            std::process::id(),
5057            std::time::SystemTime::now()
5058                .duration_since(std::time::UNIX_EPOCH)
5059                .unwrap()
5060                .as_nanos()
5061        ));
5062        let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
5063        assert_eq!(store.geo_index_epoch().unwrap(), None);
5064        store.set_geo_index_epoch(42).unwrap();
5065        assert_eq!(store.geo_index_epoch().unwrap(), Some(42));
5066        drop(store);
5067
5068        // Reopen: the single-key meta CF round-trips the stamped epoch.
5069        let reopened = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
5070        assert_eq!(reopened.geo_index_epoch().unwrap(), Some(42));
5071        drop(reopened);
5072        let _ = std::fs::remove_dir_all(&dir);
5073    }
5074
5075    /// A wiped `geo_index` CF must not read as trusted just because the
5076    /// epoch key survived: the wipe clears the LIVENESS marker, so
5077    /// `geo_index_epoch()` reports `None` (untrusted) until an epoch is
5078    /// stamped again. Without this a trusted-but-empty index answers every
5079    /// `geof:*` rewrite with zero rows.
5080    /// RocksDB twin of the memory origin-version test: an epoch stamped under
5081    /// a DIFFERENT axis origin must read UNTRUSTED, so a store indexed before
5082    /// B56 moved the calendar families 306 days is re-covered by startup's
5083    /// auto-rebuild instead of trusting postings keyed where no query looks.
5084    #[test]
5085    fn temporal_origin_version_gates_the_epoch_trust_decision() {
5086        let dir = std::env::temp_dir().join(format!(
5087            "waratah-temporal-origin-{}-{}",
5088            std::process::id(),
5089            std::time::SystemTime::now()
5090                .duration_since(std::time::UNIX_EPOCH)
5091                .unwrap()
5092                .as_nanos()
5093        ));
5094        let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
5095        assert_eq!(store.temporal_index_epoch().unwrap(), None, "fresh store");
5096
5097        // A stamp under the current origin is trusted.
5098        store.set_temporal_index_epoch(42).unwrap();
5099        assert_eq!(
5100            store.temporal_index_epoch().unwrap(),
5101            Some(42),
5102            "stamped under the current origin"
5103        );
5104
5105        // Simulate a pre-B56 store: same epoch key, stamped under a different
5106        // origin version.
5107        {
5108            let cf = store
5109                .cf_temporal_meta
5110                .as_ref()
5111                .expect("O axis has the meta CF");
5112            let mut batch = store.db.write_batch();
5113            batch.insert(cf, TEMPORAL_INDEX_ORIGIN_KEY, &encode_temporal_origin(0));
5114            batch.commit().unwrap();
5115        }
5116        assert_eq!(
5117            store.temporal_index_epoch().unwrap(),
5118            None,
5119            "an epoch stamped under a different origin must read untrusted"
5120        );
5121
5122        // Re-stamping (what a rebuild's finish does) restores trust.
5123        store.set_temporal_index_epoch(43).unwrap();
5124        assert_eq!(
5125            store.temporal_index_epoch().unwrap(),
5126            Some(43),
5127            "re-stamped"
5128        );
5129
5130        drop(store);
5131        let _ = std::fs::remove_dir_all(&dir);
5132    }
5133
5134    #[test]
5135    fn geo_index_liveness_gates_the_epoch_across_a_wipe() {
5136        let dir = std::env::temp_dir().join(format!(
5137            "waratah-geo-liveness-{}-{}",
5138            std::process::id(),
5139            std::time::SystemTime::now()
5140                .duration_since(std::time::UNIX_EPOCH)
5141                .unwrap()
5142                .as_nanos()
5143        ));
5144        let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
5145        assert_eq!(store.geo_index_epoch().unwrap(), None, "fresh store");
5146
5147        // Stamp: the epoch is readable while the marker agrees with it.
5148        store.set_geo_index_epoch(42).unwrap();
5149        assert_eq!(store.geo_index_epoch().unwrap(), Some(42), "stamped");
5150
5151        // Wipe the postings: the epoch key stays on disk but the marker does
5152        // not, so the TRUST decision flips to untrusted.
5153        store.wipe_geo_index().unwrap();
5154        assert_eq!(
5155            store.geo_index_epoch().unwrap(),
5156            None,
5157            "a wiped index with a surviving epoch must read untrusted"
5158        );
5159
5160        // Re-stamping (what a rebuild's finish does) makes it trusted again.
5161        store.set_geo_index_epoch(43).unwrap();
5162        assert_eq!(store.geo_index_epoch().unwrap(), Some(43), "re-stamped");
5163
5164        drop(store);
5165        let _ = std::fs::remove_dir_all(&dir);
5166    }
5167
5168    #[test]
5169    fn temporal_wipe_untrusts_temporal_and_spares_geo() {
5170        // The copy-paste bug this pins: the temporal wipe used to delete the
5171        // GEO liveness marker (collateral-untrusting geo on every temporal
5172        // rebuild) while leaving the TEMPORAL epoch stamped over the freshly
5173        // emptied index — trusted-empty, so a rebuild failing after the
5174        // wipe answered zero rows from every rewritten temporal FILTER.
5175        let dir = std::env::temp_dir().join(format!(
5176            "waratah-temporal-wipe-{}-{}",
5177            std::process::id(),
5178            std::time::SystemTime::now()
5179                .duration_since(std::time::UNIX_EPOCH)
5180                .unwrap()
5181                .as_nanos()
5182        ));
5183        let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
5184        store.set_geo_index_epoch(7).unwrap();
5185        store.set_temporal_index_epoch(9).unwrap();
5186        assert_eq!(store.temporal_index_epoch().unwrap(), Some(9));
5187        assert_eq!(store.geo_index_epoch().unwrap(), Some(7), "geo trusted");
5188
5189        store.wipe_temporal_index().unwrap();
5190
5191        // Temporal: back to the never-built, untrusted state — a rebuild
5192        // failing here leaves the residual path answering, not zero rows.
5193        assert_eq!(store.temporal_index_epoch().unwrap(), None);
5194        // Geo: untouched — still trusted at its own epoch.
5195        assert_eq!(store.geo_index_epoch().unwrap(), Some(7));
5196
5197        // A finished rebuild re-stamps and trust resumes.
5198        store.set_temporal_index_epoch(10).unwrap();
5199        assert_eq!(store.temporal_index_epoch().unwrap(), Some(10));
5200
5201        drop(store);
5202        let _ = std::fs::remove_dir_all(&dir);
5203    }
5204
5205    #[test]
5206    fn geo_index_epoch_is_rejected_off_the_o_axis() {
5207        let dir = std::env::temp_dir().join(format!(
5208            "waratah-geo-epoch-axis-{}-{}",
5209            std::process::id(),
5210            std::time::SystemTime::now()
5211                .duration_since(std::time::UNIX_EPOCH)
5212                .unwrap()
5213                .as_nanos()
5214        ));
5215        let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
5216        assert_eq!(store.geo_index_epoch().unwrap(), None);
5217        assert!(matches!(
5218            store.set_geo_index_epoch(1),
5219            Err(crate::StorageError::GeoIndexNotOnAxis(_))
5220        ));
5221        drop(store);
5222        let _ = std::fs::remove_dir_all(&dir);
5223    }
5224
5225    fn temporal_event_quad(subject: &str, when: &str) -> Quad {
5226        Quad::new(
5227            NamedNode::new(format!("http://ex/{subject}")).unwrap(),
5228            NamedNode::new("http://ex/observedAt").unwrap(),
5229            crate::Literal::new_typed_literal(
5230                when,
5231                NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#dateTime"),
5232            ),
5233            GraphName::DefaultGraph,
5234        )
5235    }
5236
5237    /// Per-quad liveness (shared-literal delete bug): one temporal literal
5238    /// referenced by two quads stays collectable while ANY referencing
5239    /// quad's own-latest version is a Put; the epoch covers either op.
5240    /// Twin of the memory-backend case, exercised on the real O-permutation
5241    /// key layout (quad version rows contiguous, newest commit_ts first).
5242    #[test]
5243    fn temporal_rebuild_terms_liveness_is_per_quad() {
5244        let dir = std::env::temp_dir().join(format!(
5245            "waratah-temporal-liveness-{}-{}",
5246            std::process::id(),
5247            std::time::SystemTime::now()
5248                .duration_since(std::time::UNIX_EPOCH)
5249                .unwrap()
5250                .as_nanos()
5251        ));
5252        let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
5253        let a = encode_quad(&temporal_event_quad("a", "2020-01-01T00:00:00Z")).unwrap();
5254        let b = encode_quad(&temporal_event_quad("b", "2020-01-01T00:00:00Z")).unwrap();
5255        let term = a.object.clone();
5256
5257        // Both quads live: the term is collected once, epoch = ts 2.
5258        store
5259            .insert_encoded_quad_version(
5260                &a,
5261                CommitTs(1),
5262                StorageOp::Put,
5263                VisibilityLabel::default(),
5264            )
5265            .unwrap();
5266        store
5267            .insert_encoded_quad_version(
5268                &b,
5269                CommitTs(2),
5270                StorageOp::Put,
5271                VisibilityLabel::default(),
5272            )
5273            .unwrap();
5274        let (terms, epoch) = store.temporal_rebuild_terms().unwrap();
5275        assert_eq!(terms, vec![term.clone()]);
5276        assert_eq!(epoch, CommitTs(2));
5277
5278        // Delete ONE quad: the term must survive (the old per-term max-ts
5279        // verdict retracted it — the shared-literal delete bug).
5280        store
5281            .insert_encoded_quad_version(
5282                &b,
5283                CommitTs(3),
5284                StorageOp::Delete,
5285                VisibilityLabel::default(),
5286            )
5287            .unwrap();
5288        let (terms, epoch) = store.temporal_rebuild_terms().unwrap();
5289        assert_eq!(terms, vec![term.clone()]);
5290        assert_eq!(epoch, CommitTs(3));
5291
5292        // Delete the second quad too: now dead.
5293        store
5294            .insert_encoded_quad_version(
5295                &a,
5296                CommitTs(4),
5297                StorageOp::Delete,
5298                VisibilityLabel::default(),
5299            )
5300            .unwrap();
5301        let (terms, epoch) = store.temporal_rebuild_terms().unwrap();
5302        assert!(terms.is_empty());
5303        assert_eq!(epoch, CommitTs(4));
5304
5305        // Reinsert one quad: alive again.
5306        store
5307            .insert_encoded_quad_version(
5308                &b,
5309                CommitTs(5),
5310                StorageOp::Put,
5311                VisibilityLabel::default(),
5312            )
5313            .unwrap();
5314        let (terms, epoch) = store.temporal_rebuild_terms().unwrap();
5315        assert_eq!(terms, vec![term.clone()]);
5316        assert_eq!(epoch, CommitTs(5));
5317        drop(store);
5318        let _ = std::fs::remove_dir_all(&dir);
5319    }
5320    // ---- parallel domain scan mode --------------------------------------
5321    //
5322    // `WARATAH_DOMAIN_WALKS` tests drive `scan_domain_with_mode` /
5323    // `scan_domain_counts_with_mode` directly: the public entry points
5324    // resolve the mode through a process `OnceLock`, which would make
5325    // env-dependent tests order-dependent. The memory backend
5326    // (legacy-only, untouched) is the reference semantics.
5327
5328    use super::{
5329        DomainScanHit, DomainScanMode, domain_walks_from_env, encode_term_bytes, split_slices,
5330    };
5331    use crate::Storage;
5332    use crate::encode::{
5333        COMMIT_TS_LEN, encode_storage_value, encode_versioned_key, prepare_constraints_sorted,
5334    };
5335    use std::path::PathBuf;
5336
5337    const MODES: [DomainScanMode; 4] = [
5338        DomainScanMode::Legacy,
5339        DomainScanMode::ParallelWalks(2),
5340        DomainScanMode::ParallelWalks(3),
5341        DomainScanMode::ParallelWalks(64),
5342    ];
5343
5344    const SNAP: SnapshotId = SnapshotId(1_000);
5345
5346    /// `(s, p, o, g, ts, op)` fixture rows on the P axis. `lit:` objects are
5347    /// literals (exercises `iri_only_head`); `p4` has no rows (empty
5348    /// constraint); `o_dead` is Put then Delete (invisible head); `o3`
5349    /// lives in two graphs (bag count 2, merge count 1).
5350    fn fixture_rows() -> Vec<(
5351        &'static str,
5352        &'static str,
5353        &'static str,
5354        &'static str,
5355        u64,
5356        StorageOp,
5357    )> {
5358        vec![
5359            ("s1", "p1", "o1", "default", 1, StorageOp::Put),
5360            ("s1", "p1", "o2", "default", 2, StorageOp::Put),
5361            ("s2", "p1", "o3", "g1", 3, StorageOp::Put),
5362            ("s2", "p1", "o3", "g2", 4, StorageOp::Put),
5363            ("s3", "p1", "lit:foo", "default", 5, StorageOp::Put),
5364            ("s4", "p1", "o_dead", "default", 6, StorageOp::Put),
5365            ("s4", "p1", "o_dead", "default", 7, StorageOp::Delete),
5366            // Skew: p1 has five heads, p2 and p3 have one each.
5367            ("s5", "p2", "o1", "default", 8, StorageOp::Put),
5368            ("s6", "p3", "o4", "g1", 9, StorageOp::Put),
5369            ("s7", "p3", "o4", "default", 10, StorageOp::Put),
5370        ]
5371    }
5372
5373    fn fixture_quad(s: &str, p: &str, o: &str, g: &str) -> Quad {
5374        let object: crate::Term = if let Some(local) = o.strip_prefix("typed:") {
5375            // BigTypedLiteral on the wire: value and datatype IRIs both
5376            // past the small-string limit hash to 16 bytes each — 33 bytes
5377            // total, the exact WRITTEN_TERM_MAX_SIZE boundary.
5378            crate::Literal::new_typed_literal(
5379                local,
5380                NamedNode::new("http://www.w3.org/2001/XMLSchema#nonNegativeInteger").unwrap(),
5381            )
5382            .into()
5383        } else {
5384            match o.strip_prefix("lit:") {
5385                Some(local) => crate::Literal::from(local).into(),
5386                None => NamedNode::new(format!("http://ex/{o}")).unwrap().into(),
5387            }
5388        };
5389        let graph = if g == "default" {
5390            GraphName::DefaultGraph
5391        } else {
5392            GraphName::NamedNode(NamedNode::new(format!("http://ex/{g}")).unwrap())
5393        };
5394        Quad::new(
5395            NamedNode::new(format!("http://ex/{s}")).unwrap(),
5396            NamedNode::new(format!("http://ex/{p}")).unwrap(),
5397            object,
5398            graph,
5399        )
5400    }
5401
5402    fn constraint(local: &str) -> EncodedTerm {
5403        EncodedTerm::from(&NamedNode::new(format!("http://ex/{local}")).unwrap())
5404    }
5405
5406    fn graph_term(g: &str) -> EncodedTerm {
5407        encode_quad(&fixture_quad("s", "p", "o", g))
5408            .unwrap()
5409            .graph_name
5410    }
5411
5412    fn open_p_store(tag: &str) -> (RocksDbStorage, PathBuf) {
5413        let dir = std::env::temp_dir().join(format!(
5414            "waratah-domain-modes-{tag}-{}-{}",
5415            std::process::id(),
5416            std::time::SystemTime::now()
5417                .duration_since(std::time::UNIX_EPOCH)
5418                .unwrap()
5419                .as_nanos()
5420        ));
5421        let store = RocksDbStorage::open(&dir, PartitionAxis::P).unwrap();
5422        (store, dir)
5423    }
5424
5425    /// Load the fixture into both backends (same insert sequence).
5426    fn load_fixture(rocks: &RocksDbStorage, memory: &Storage) {
5427        for (s, p, o, g, ts, op) in fixture_rows() {
5428            let quad = fixture_quad(s, p, o, g);
5429            rocks
5430                .insert_quad_version(&quad, CommitTs(ts), op, VisibilityLabel::default())
5431                .unwrap();
5432            memory
5433                .insert_quad_version(&quad, CommitTs(ts), op, VisibilityLabel::default())
5434                .unwrap();
5435        }
5436    }
5437
5438    struct DomainArgs<'a> {
5439        graph_name: Option<&'a EncodedTerm>,
5440        filter_terms: &'a [EncodedTerm],
5441        filter_allow: bool,
5442        iri_only: bool,
5443        merge: bool,
5444        /// What one run increment counts (counts walk only). Defaults to the
5445        /// bag-of-rows semantics the corpus was written against.
5446        count_mode: DomainCountMode,
5447    }
5448
5449    impl Default for DomainArgs<'_> {
5450        fn default() -> Self {
5451            Self {
5452                graph_name: None,
5453                filter_terms: &[],
5454                filter_allow: false,
5455                iri_only: false,
5456                merge: false,
5457                count_mode: DomainCountMode::Rows,
5458            }
5459        }
5460    }
5461
5462    #[allow(clippy::too_many_arguments)]
5463    fn scan_hits(
5464        store: &RocksDbStorage,
5465        mode: DomainScanMode,
5466        constraints: &[EncodedTerm],
5467        limit: u64,
5468        after: Option<&(EncodedTerm, EncodedTerm)>,
5469        args: &DomainArgs<'_>,
5470    ) -> Result<Vec<DomainScanHit>, crate::StorageError> {
5471        store.scan_domain_with_mode(
5472            mode,
5473            IndexPermutation::Posg,
5474            constraints,
5475            SNAP,
5476            limit,
5477            after.map(|cursor| &cursor.0),
5478            after.map(|cursor| &cursor.1),
5479            args.graph_name,
5480            args.filter_terms,
5481            args.filter_allow,
5482            args.iri_only,
5483        )
5484    }
5485
5486    fn scan_counts(
5487        store: &RocksDbStorage,
5488        mode: DomainScanMode,
5489        constraints: &[EncodedTerm],
5490        limit: u64,
5491        after: Option<&(EncodedTerm, EncodedTerm)>,
5492        args: &DomainArgs<'_>,
5493    ) -> Result<Vec<DomainScanCountHit>, crate::StorageError> {
5494        store.scan_domain_counts_with_mode(
5495            mode,
5496            IndexPermutation::Posg,
5497            constraints,
5498            SNAP,
5499            limit,
5500            after.map(|cursor| &cursor.0),
5501            after.map(|cursor| &cursor.1),
5502            args.graph_name,
5503            args.filter_terms,
5504            args.filter_allow,
5505            args.iri_only,
5506            args.merge,
5507            args.count_mode,
5508        )
5509    }
5510
5511    /// Memory-backend reference (key emission order, matching every mode).
5512    fn memory_hits(
5513        memory: &Storage,
5514        constraints: &[EncodedTerm],
5515        limit: u64,
5516        after: Option<&(EncodedTerm, EncodedTerm)>,
5517        args: &DomainArgs<'_>,
5518    ) -> Vec<DomainScanHit> {
5519        memory
5520            .scan_domain(
5521                IndexPermutation::Posg,
5522                constraints,
5523                SNAP,
5524                limit,
5525                after.map(|cursor| &cursor.0),
5526                after.map(|cursor| &cursor.1),
5527                args.graph_name,
5528                args.filter_terms,
5529                args.filter_allow,
5530                args.iri_only,
5531            )
5532            .unwrap()
5533    }
5534
5535    fn memory_counts(
5536        memory: &Storage,
5537        constraints: &[EncodedTerm],
5538        limit: u64,
5539        after: Option<&(EncodedTerm, EncodedTerm)>,
5540        args: &DomainArgs<'_>,
5541    ) -> Vec<DomainScanCountHit> {
5542        memory
5543            .scan_domain_counts(
5544                IndexPermutation::Posg,
5545                constraints,
5546                SNAP,
5547                limit,
5548                after.map(|cursor| &cursor.0),
5549                after.map(|cursor| &cursor.1),
5550                args.graph_name,
5551                args.filter_terms,
5552                args.filter_allow,
5553                args.iri_only,
5554                args.merge,
5555                args.count_mode,
5556            )
5557            .unwrap()
5558    }
5559
5560    fn hit_keys(hits: &[DomainScanHit]) -> Vec<(Vec<u8>, Vec<u8>)> {
5561        hits.iter()
5562            .map(|hit| {
5563                (
5564                    encode_term_bytes(&hit.constraint),
5565                    encode_term_bytes(&hit.term),
5566                )
5567            })
5568            .collect()
5569    }
5570
5571    fn count_keys(hits: &[DomainScanCountHit]) -> Vec<(Vec<u8>, Vec<u8>, u64)> {
5572        hits.iter()
5573            .map(|hit| {
5574                (
5575                    encode_term_bytes(&hit.constraint),
5576                    encode_term_bytes(&hit.term),
5577                    hit.count,
5578                )
5579            })
5580            .collect()
5581    }
5582
5583    /// Strictly ascending in encoded key order (the new modes' emission).
5584    fn assert_strictly_key_ordered(hits: &[DomainScanHit]) {
5585        let keys = hit_keys(hits);
5586        assert!(
5587            keys.windows(2).all(|window| window[0] < window[1]),
5588            "expected strict key order, got {keys:?}"
5589        );
5590    }
5591
5592    fn assert_counts_strictly_key_ordered(hits: &[DomainScanCountHit]) {
5593        let mut keys: Vec<(Vec<u8>, Vec<u8>)> = count_keys(hits)
5594            .into_iter()
5595            .map(|(constraint, term, _)| (constraint, term))
5596            .collect();
5597        keys.dedup();
5598        assert!(
5599            keys.windows(2).all(|window| window[0] < window[1]),
5600            "expected strict key order, got {keys:?}"
5601        );
5602    }
5603
5604    #[test]
5605    fn domain_mode_parsers_reject_junk_and_clamp() {
5606        // WALKS: 2..=64 pass, above clamps to 64, below / junk stay legacy.
5607        assert_eq!(domain_walks_from_env(None), None);
5608        assert_eq!(domain_walks_from_env(Some("2")), Some(2));
5609        assert_eq!(domain_walks_from_env(Some("4")), Some(4));
5610        assert_eq!(domain_walks_from_env(Some("64")), Some(64));
5611        assert_eq!(domain_walks_from_env(Some("65")), Some(64));
5612        assert_eq!(domain_walks_from_env(Some("1000")), Some(64));
5613        assert_eq!(domain_walks_from_env(Some("1")), None);
5614        assert_eq!(domain_walks_from_env(Some("0")), None);
5615        assert_eq!(domain_walks_from_env(Some("junk")), None);
5616        assert_eq!(domain_walks_from_env(Some("")), None);
5617        // Mode resolution lives in `domain_scan_mode`'s OnceLock —
5618        // process-global, pinned by the resolver unit tests above, not
5619        // re-testable per process here.
5620    }
5621
5622    #[test]
5623    fn split_slices_balances_and_covers() {
5624        assert!(split_slices(0, 8).is_empty());
5625        assert_eq!(split_slices(5, 2), vec![0..3, 3..5]);
5626        assert_eq!(split_slices(6, 4), vec![0..2, 2..4, 4..5, 5..6]);
5627        assert_eq!(split_slices(1, 8), vec![0..1]);
5628        assert_eq!(split_slices(2, 64), vec![0..1, 1..2]);
5629        assert_eq!(split_slices(4, 4), vec![0..1, 1..2, 2..3, 3..4]);
5630        // Generic partition property: contiguous, covering, non-empty.
5631        for &(len, workers) in &[(7usize, 3usize), (1, 64), (64, 64), (3, 2)] {
5632            let slices = split_slices(len, workers);
5633            assert_eq!(slices.first().unwrap().start, 0);
5634            assert_eq!(slices.last().unwrap().end, len);
5635            for (a, b) in slices.iter().zip(slices.iter().skip(1)) {
5636                assert_eq!(a.end, b.start);
5637            }
5638            assert!(slices.iter().all(|slice| !slice.is_empty()));
5639        }
5640    }
5641
5642    #[test]
5643    fn prepare_constraints_sorted_matches_key_bytes() {
5644        // Encoded order is StrHash order, not lexical — the sorted prep must
5645        // order by key bytes (the union/parallel emission order).
5646        let terms: Vec<EncodedTerm> = ["p1", "p2", "p3", "p4"]
5647            .iter()
5648            .map(|local| constraint(local))
5649            .collect();
5650        let sorted = prepare_constraints_sorted(IndexPermutation::Posg, &terms).unwrap();
5651        let keys: Vec<Vec<u8>> = sorted.iter().map(encode_term_bytes).collect();
5652        let mut want = keys.clone();
5653        want.sort();
5654        assert_eq!(keys, want);
5655    }
5656
5657    /// Equivalence corpus: identical hit sets across legacy / union /
5658    /// parallel and the memory reference, over graph filters, `iri_only`,
5659    /// shuffled caller orders, duplicates, and empty / single inputs.
5660    /// Legacy additionally matches the memory backend *exactly in caller
5661    /// order*; union / parallel emit in strict key order.
5662    #[test]
5663    fn domain_scan_modes_match_memory_reference() {
5664        let (store, dir) = open_p_store("corpus");
5665        let memory = Storage::memory(PartitionAxis::P);
5666        load_fixture(&store, &memory);
5667
5668        let p1 = constraint("p1");
5669        let p2 = constraint("p2");
5670        let p3 = constraint("p3");
5671        let p4 = constraint("p4");
5672        // "Sorted" is key order, computed at runtime (StrHash order).
5673        let mut sorted_all = vec![p1.clone(), p2.clone(), p3.clone(), p4.clone()];
5674        sorted_all.sort_by_key(encode_term_bytes);
5675        let constraint_sets: Vec<Vec<EncodedTerm>> = vec![
5676            sorted_all,
5677            vec![p1.clone()],
5678            vec![],                                               // empty input
5679            vec![p2.clone(), p1.clone(), p2.clone(), p3.clone()], // shuffled + duplicate
5680            vec![p3.clone(), p4.clone(), p1.clone()],
5681            vec![p4.clone()], // constraint with no rows
5682        ];
5683
5684        let g1 = graph_term("g1");
5685        let g2 = graph_term("g2");
5686        let graph_cases: Vec<(&str, Option<EncodedTerm>, Vec<EncodedTerm>, bool)> = vec![
5687            ("unconstrained", None, Vec::new(), false),
5688            ("bound-g1", Some(g1.clone()), Vec::new(), false),
5689            ("allow-g1g2", None, vec![g1.clone(), g2.clone()], true),
5690            ("block-g1", None, vec![g1.clone()], false),
5691        ];
5692
5693        for (case_name, graph_name, filter_terms, filter_allow) in &graph_cases {
5694            for &iri_only in &[false, true] {
5695                let args = DomainArgs {
5696                    graph_name: graph_name.as_ref(),
5697                    filter_terms,
5698                    filter_allow: *filter_allow,
5699                    iri_only,
5700                    merge: false,
5701                    count_mode: DomainCountMode::Rows,
5702                };
5703                for constraints in &constraint_sets {
5704                    let memory_ref = memory_hits(&memory, constraints, 0, None, &args);
5705                    for mode in MODES {
5706                        let got = scan_hits(&store, mode, constraints, 0, None, &args).unwrap();
5707                        // Identical hit multisets across all modes and the
5708                        // memory reference.
5709                        let mut got_keys = hit_keys(&got);
5710                        let mut want_keys = hit_keys(&memory_ref);
5711                        got_keys.sort();
5712                        want_keys.sort();
5713                        assert_eq!(
5714                            got_keys, want_keys,
5715                            "mode {mode:?} case {case_name} iri {iri_only} constraints {constraints:?}"
5716                        );
5717                        if mode == DomainScanMode::Legacy {
5718                            // Legacy matches the memory twin element-for-
5719                            // element (both emit key order).
5720                            assert_eq!(got, memory_ref, "legacy case {case_name}");
5721                        } else {
5722                            assert_strictly_key_ordered(&got);
5723                        }
5724                    }
5725                }
5726            }
5727        }
5728        drop(store);
5729        let _ = std::fs::remove_dir_all(&dir);
5730    }
5731
5732    /// Every mode emits in key order regardless of the caller's constraint
5733    /// order, agreeing element-for-element with the memory reference:
5734    /// key-order visitation is what makes the resume cursor's skip sound
5735    /// (constraints sorting before the cursor were fully emitted before it).
5736    #[test]
5737    fn domain_scan_emission_order_is_key_order() {
5738        let (store, dir) = open_p_store("order");
5739        let memory = Storage::memory(PartitionAxis::P);
5740        load_fixture(&store, &memory);
5741
5742        let first = constraint("p1");
5743        let second = constraint("p2");
5744        let (first, second) = if encode_term_bytes(&first) < encode_term_bytes(&second) {
5745            (first, second)
5746        } else {
5747            (second, first)
5748        };
5749        let shuffled = [second.clone(), first.clone()]; // descending key order
5750
5751        // Key-order expectation: the per-constraint scans concatenated in
5752        // key order.
5753        let first_hits = scan_hits(
5754            &store,
5755            DomainScanMode::Legacy,
5756            std::slice::from_ref(&first),
5757            0,
5758            None,
5759            &Default::default(),
5760        )
5761        .unwrap();
5762        let second_hits = scan_hits(
5763            &store,
5764            DomainScanMode::Legacy,
5765            std::slice::from_ref(&second),
5766            0,
5767            None,
5768            &Default::default(),
5769        )
5770        .unwrap();
5771        let want = [first_hits, second_hits].concat();
5772
5773        for mode in [DomainScanMode::Legacy, DomainScanMode::ParallelWalks(2)] {
5774            let got = scan_hits(&store, mode, &shuffled, 0, None, &Default::default()).unwrap();
5775            assert_strictly_key_ordered(&got);
5776            assert_eq!(got, want, "mode {mode:?} must emit in key order");
5777        }
5778        // The memory reference agrees element-for-element: it key-sorts its
5779        // constraint list too.
5780        assert_eq!(
5781            want,
5782            memory_hits(&memory, &shuffled, 0, None, &Default::default())
5783        );
5784        drop(store);
5785        let _ = std::fs::remove_dir_all(&dir);
5786    }
5787
5788    fn paginate_hits(
5789        store: &RocksDbStorage,
5790        mode: DomainScanMode,
5791        constraints: &[EncodedTerm],
5792        batch: u64,
5793        args: &DomainArgs<'_>,
5794    ) -> Vec<DomainScanHit> {
5795        let mut out = Vec::new();
5796        let mut after: Option<(EncodedTerm, EncodedTerm)> = None;
5797        for _ in 0..10_000 {
5798            let page = scan_hits(store, mode, constraints, batch, after.as_ref(), args).unwrap();
5799            let done = page.len() < batch as usize;
5800            if let Some(last) = page.last() {
5801                after = Some((last.constraint.clone(), last.term.clone()));
5802            }
5803            let empty = page.is_empty();
5804            out.extend(page);
5805            if done || empty {
5806                return out;
5807            }
5808        }
5809        panic!("pagination did not terminate");
5810    }
5811
5812    /// Pagination chains: every mode covers every hit for every input order
5813    /// — all modes visit constraints in key order, so the resume cursor is
5814    /// coherent even when the caller order is shuffled or carries
5815    /// duplicates.
5816    #[test]
5817    fn domain_scan_pagination_chains_cover_all_hits() {
5818        let (store, dir) = open_p_store("pages");
5819        let memory = Storage::memory(PartitionAxis::P);
5820        load_fixture(&store, &memory);
5821
5822        let p1 = constraint("p1");
5823        let p2 = constraint("p2");
5824        let p3 = constraint("p3");
5825        let p4 = constraint("p4");
5826        let mut sorted_all = vec![p1.clone(), p2.clone(), p3.clone(), p4.clone()];
5827        sorted_all.sort_by_key(encode_term_bytes);
5828        let shuffled_dup = vec![p2.clone(), p1.clone(), p2.clone(), p3.clone()];
5829
5830        for &batch in &[1u64, 2, 3, 100] {
5831            for mode in MODES {
5832                for constraints in [&sorted_all, &shuffled_dup] {
5833                    let chain =
5834                        paginate_hits(&store, mode, constraints, batch, &Default::default());
5835                    let full =
5836                        scan_hits(&store, mode, constraints, 0, None, &Default::default()).unwrap();
5837                    assert_eq!(
5838                        chain, full,
5839                        "mode {mode:?} batch {batch} constraints {constraints:?}"
5840                    );
5841                }
5842            }
5843            // Cross-backend: the parallel chain equals the memory reference set.
5844            let chain = paginate_hits(
5845                &store,
5846                DomainScanMode::ParallelWalks(2),
5847                &sorted_all,
5848                batch,
5849                &Default::default(),
5850            );
5851            let reference = memory_hits(&memory, &sorted_all, 0, None, &Default::default());
5852            let mut chain_keys = hit_keys(&chain);
5853            let mut reference_keys = hit_keys(&reference);
5854            chain_keys.sort();
5855            reference_keys.sort();
5856            assert_eq!(chain_keys, reference_keys);
5857        }
5858        drop(store);
5859        let _ = std::fs::remove_dir_all(&dir);
5860    }
5861
5862    /// Legacy pagination with caller order in descending key order and a
5863    /// one-hit batch: the walk visits constraints in key order (sorted
5864    /// prep), so the cursor's skip of key-earlier constraints is sound —
5865    /// the chain covers every hit of both constraints and matches the
5866    /// memory reference element-for-element.
5867    #[test]
5868    fn legacy_shuffled_pagination_chain_covers_every_constraint() {
5869        let (store, dir) = open_p_store("legacy-cursor");
5870        let memory = Storage::memory(PartitionAxis::P);
5871        load_fixture(&store, &memory);
5872
5873        let first = constraint("p1");
5874        let second = constraint("p2");
5875        let (first, second) = if encode_term_bytes(&first) < encode_term_bytes(&second) {
5876            (first, second)
5877        } else {
5878            (second, first)
5879        };
5880        let shuffled = [second.clone(), first.clone()];
5881
5882        let legacy_chain = paginate_hits(
5883            &store,
5884            DomainScanMode::Legacy,
5885            &shuffled,
5886            1,
5887            &Default::default(),
5888        );
5889        let legacy_full = scan_hits(
5890            &store,
5891            DomainScanMode::Legacy,
5892            &shuffled,
5893            0,
5894            None,
5895            &Default::default(),
5896        )
5897        .unwrap();
5898        assert_eq!(
5899            legacy_chain, legacy_full,
5900            "the legacy chain must cover both constraints under a shuffled caller order"
5901        );
5902        assert_eq!(
5903            legacy_chain,
5904            memory_hits(&memory, &shuffled, 0, None, &Default::default()),
5905            "the memory reference must agree on the same shuffled input"
5906        );
5907        drop(store);
5908        let _ = std::fs::remove_dir_all(&dir);
5909    }
5910
5911    /// `limit` truncation: every mode truncates the key-first prefix of its
5912    /// unlimited key-order emission (per-worker budgets make the parallel
5913    /// merge deterministic — exactly the unlimited key-order prefix).
5914    #[test]
5915    fn domain_scan_limit_truncation_follows_mode_order() {
5916        let (store, dir) = open_p_store("limits");
5917        let p1 = constraint("p1");
5918        let p2 = constraint("p2");
5919        let p3 = constraint("p3");
5920        let shuffled = vec![p2, p3, p1]; // caller order ≠ key order (usually)
5921        let memory = Storage::memory(PartitionAxis::P);
5922        load_fixture(&store, &memory);
5923
5924        let legacy_full = scan_hits(
5925            &store,
5926            DomainScanMode::Legacy,
5927            &shuffled,
5928            0,
5929            None,
5930            &Default::default(),
5931        )
5932        .unwrap();
5933        assert!(
5934            legacy_full.len() > 3,
5935            "fixture too small for a truncation test"
5936        );
5937
5938        let limits = [1u64, 2, 3, 5, 7]
5939            .into_iter()
5940            .filter(|limit| *limit <= legacy_full.len() as u64);
5941        for limit in limits {
5942            let legacy = scan_hits(
5943                &store,
5944                DomainScanMode::Legacy,
5945                &shuffled,
5946                limit,
5947                None,
5948                &Default::default(),
5949            )
5950            .unwrap();
5951            assert_eq!(
5952                legacy,
5953                legacy_full[..limit as usize],
5954                "legacy limit {limit}"
5955            );
5956
5957            for workers in [2usize, 3usize, 64] {
5958                let parallel = scan_hits(
5959                    &store,
5960                    DomainScanMode::ParallelWalks(workers),
5961                    &shuffled,
5962                    limit,
5963                    None,
5964                    &Default::default(),
5965                )
5966                .unwrap();
5967                assert_eq!(
5968                    parallel,
5969                    legacy_full[..limit as usize],
5970                    "parallel {workers} limit {limit}"
5971                );
5972            }
5973        }
5974        drop(store);
5975        let _ = std::fs::remove_dir_all(&dir);
5976    }
5977
5978    /// Count twin of the equivalence corpus: identical
5979    /// `(constraint, term, count)` multisets across all modes and the memory
5980    /// reference, in bag and merge modes.
5981    #[test]
5982    fn domain_scan_counts_modes_match_memory_reference() {
5983        let (store, dir) = open_p_store("counts");
5984        let memory = Storage::memory(PartitionAxis::P);
5985        load_fixture(&store, &memory);
5986
5987        let p1 = constraint("p1");
5988        let p2 = constraint("p2");
5989        let p3 = constraint("p3");
5990        let p4 = constraint("p4");
5991        let mut sorted_all = vec![p1.clone(), p2.clone(), p3.clone(), p4.clone()];
5992        sorted_all.sort_by_key(encode_term_bytes);
5993        let constraint_sets: Vec<Vec<EncodedTerm>> = vec![
5994            sorted_all,
5995            vec![p1.clone()],
5996            vec![],
5997            vec![p2.clone(), p1.clone(), p2.clone(), p3.clone()],
5998            vec![p3.clone(), p1.clone()],
5999        ];
6000
6001        let g1 = graph_term("g1");
6002        let g2 = graph_term("g2");
6003        // (merge_default_graph, DomainCountMode) combos. DistinctGraphs
6004        // requires merge unset (merge collapses G by construction).
6005        let count_combos: Vec<(bool, DomainCountMode)> = vec![
6006            (false, DomainCountMode::Rows),
6007            (true, DomainCountMode::Rows),
6008            (false, DomainCountMode::DistinctTerms),
6009            (false, DomainCountMode::DistinctGraphs),
6010        ];
6011        for &(merge, count_mode) in &count_combos {
6012            let graph_cases: Vec<(&str, Option<EncodedTerm>, Vec<EncodedTerm>, bool)> = vec![
6013                ("unconstrained", None, Vec::new(), false),
6014                ("bound-g1", Some(g1.clone()), Vec::new(), false),
6015                // Restricted-mode production shape: the DefaultOnly window.
6016                (
6017                    "bound-default",
6018                    Some(EncodedTerm::DefaultGraph),
6019                    Vec::new(),
6020                    false,
6021                ),
6022                ("allow-g1g2", None, vec![g1.clone(), g2.clone()], true),
6023            ];
6024            for (case_name, graph_name, filter_terms, filter_allow) in &graph_cases {
6025                for constraints in &constraint_sets {
6026                    let args = DomainArgs {
6027                        graph_name: graph_name.as_ref(),
6028                        filter_terms,
6029                        filter_allow: *filter_allow,
6030                        iri_only: false,
6031                        merge,
6032                        count_mode,
6033                    };
6034                    let memory_ref = memory_counts(&memory, constraints, 0, None, &args);
6035                    for mode in MODES {
6036                        let got = scan_counts(&store, mode, constraints, 0, None, &args).unwrap();
6037                        let mut got_keys = count_keys(&got);
6038                        let mut want_keys = count_keys(&memory_ref);
6039                        got_keys.sort();
6040                        want_keys.sort();
6041                        assert_eq!(
6042                            got_keys, want_keys,
6043                            "counts mode {mode:?} merge {merge} count_mode {count_mode:?} case {case_name} constraints {constraints:?}"
6044                        );
6045                        if mode == DomainScanMode::Legacy {
6046                            assert_eq!(got, memory_ref, "counts legacy case {case_name}");
6047                        } else {
6048                            assert_counts_strictly_key_ordered(&got);
6049                        }
6050                    }
6051                }
6052            }
6053        }
6054        drop(store);
6055        let _ = std::fs::remove_dir_all(&dir);
6056    }
6057
6058    /// Count pagination chains: a run cut short by the batch budget is not
6059    /// flushed; the cursor re-walks and emits it on the next page. Union /
6060    /// parallel chains must still cover every run with correct counts.
6061    #[test]
6062    fn domain_scan_counts_pagination_chains_cover_all_runs() {
6063        let (store, dir) = open_p_store("count-pages");
6064        let memory = Storage::memory(PartitionAxis::P);
6065        load_fixture(&store, &memory);
6066
6067        let p1 = constraint("p1");
6068        let p2 = constraint("p2");
6069        let p3 = constraint("p3");
6070        let p4 = constraint("p4");
6071        let mut sorted_all = vec![p1.clone(), p2.clone(), p3.clone(), p4.clone()];
6072        sorted_all.sort_by_key(encode_term_bytes);
6073        let shuffled_dup = vec![p2.clone(), p1.clone(), p2.clone(), p3.clone()];
6074
6075        fn paginate(
6076            store: &RocksDbStorage,
6077            mode: DomainScanMode,
6078            constraints: &[EncodedTerm],
6079            batch: u64,
6080            args: &DomainArgs<'_>,
6081        ) -> Vec<DomainScanCountHit> {
6082            let mut out = Vec::new();
6083            let mut after: Option<(EncodedTerm, EncodedTerm)> = None;
6084            for _ in 0..10_000 {
6085                let page =
6086                    scan_counts(store, mode, constraints, batch, after.as_ref(), args).unwrap();
6087                let done = page.len() < batch as usize;
6088                if let Some(last) = page.last() {
6089                    after = Some((last.constraint.clone(), last.term.clone()));
6090                }
6091                let empty = page.is_empty();
6092                out.extend(page);
6093                if done || empty {
6094                    return out;
6095                }
6096            }
6097            panic!("count pagination did not terminate");
6098        }
6099
6100        // (merge_default_graph, DomainCountMode) combos; DistinctGraphs
6101        // requires merge unset.
6102        let count_combos: Vec<(bool, DomainCountMode)> = vec![
6103            (false, DomainCountMode::Rows),
6104            (true, DomainCountMode::Rows),
6105            (false, DomainCountMode::DistinctTerms),
6106            (false, DomainCountMode::DistinctGraphs),
6107        ];
6108        for &(merge, count_mode) in &count_combos {
6109            let args = DomainArgs {
6110                merge,
6111                count_mode,
6112                ..Default::default()
6113            };
6114            for &batch in &[1u64, 2, 3, 100] {
6115                for mode in MODES {
6116                    for constraints in [&sorted_all, &shuffled_dup] {
6117                        let chain = paginate(&store, mode, constraints, batch, &args);
6118                        let full = scan_counts(&store, mode, constraints, 0, None, &args).unwrap();
6119                        if mode == DomainScanMode::Legacy && *constraints != sorted_all {
6120                            continue; // pre-existing legacy cursor incoherence
6121                        }
6122                        assert_eq!(
6123                            chain, full,
6124                            "counts mode {mode:?} merge {merge} count_mode {count_mode:?} batch {batch}"
6125                        );
6126                    }
6127                }
6128                let chain = paginate(
6129                    &store,
6130                    DomainScanMode::ParallelWalks(2),
6131                    &sorted_all,
6132                    batch,
6133                    &args,
6134                );
6135                let reference = memory_counts(&memory, &sorted_all, 0, None, &args);
6136                let mut chain_keys = count_keys(&chain);
6137                let mut reference_keys = count_keys(&reference);
6138                chain_keys.sort();
6139                reference_keys.sort();
6140                assert_eq!(
6141                    chain_keys, reference_keys,
6142                    "merge {merge} count_mode {count_mode:?} batch {batch}"
6143                );
6144            }
6145        }
6146        drop(store);
6147        let _ = std::fs::remove_dir_all(&dir);
6148    }
6149
6150    /// Count `limit` truncation: same contract as the distinct scan — legacy
6151    /// caller-first, union and parallel key-first (per-worker budgets make
6152    /// the parallel merge deterministic).
6153    #[test]
6154    fn domain_scan_counts_limit_truncation_follows_mode_order() {
6155        let (store, dir) = open_p_store("count-limits");
6156        let p1 = constraint("p1");
6157        let p2 = constraint("p2");
6158        let p3 = constraint("p3");
6159        let shuffled = vec![p2, p3, p1];
6160        let memory = Storage::memory(PartitionAxis::P);
6161        load_fixture(&store, &memory);
6162
6163        let legacy_full = scan_counts(
6164            &store,
6165            DomainScanMode::Legacy,
6166            &shuffled,
6167            0,
6168            None,
6169            &Default::default(),
6170        )
6171        .unwrap();
6172        assert!(
6173            legacy_full.len() > 2,
6174            "fixture too small for a truncation test"
6175        );
6176
6177        let limits = [1u64, 2, 3, 5, 7]
6178            .into_iter()
6179            .filter(|limit| *limit <= legacy_full.len() as u64);
6180        for limit in limits {
6181            let legacy = scan_counts(
6182                &store,
6183                DomainScanMode::Legacy,
6184                &shuffled,
6185                limit,
6186                None,
6187                &Default::default(),
6188            )
6189            .unwrap();
6190            assert_eq!(
6191                legacy,
6192                legacy_full[..limit as usize],
6193                "legacy limit {limit}"
6194            );
6195
6196            for workers in [2usize, 3usize, 64] {
6197                let parallel = scan_counts(
6198                    &store,
6199                    DomainScanMode::ParallelWalks(workers),
6200                    &shuffled,
6201                    limit,
6202                    None,
6203                    &Default::default(),
6204                )
6205                .unwrap();
6206                assert_eq!(
6207                    parallel,
6208                    legacy_full[..limit as usize],
6209                    "parallel {workers} limit {limit}"
6210                );
6211            }
6212        }
6213        drop(store);
6214        let _ = std::fs::remove_dir_all(&dir);
6215    }
6216
6217    /// Parallel-specific edges: K = 1 behaves like legacy; K > len and a
6218    /// single constraint clamp to the constraint count; a single-constraint
6219    /// parallel scan equals the legacy scan.
6220    ///
6221    /// Also installs the process-wide storage worker pool (idempotent), so
6222    /// this test and every later domain-walk test in the binary exercise the
6223    /// pool dispatch path rather than the scoped-thread fallback. First
6224    /// install wins for the whole test binary, so which arm a given test
6225    /// sees depends on scheduling — accepted: assertions hold at any slice
6226    /// count, and the fallback arm is covered directly (bypassing the
6227    /// global install) by `scoped_fallback_runs_units_in_order_without_a_pool`
6228    /// in `worker_pool.rs`.
6229    #[test]
6230    fn domain_scan_parallel_edge_cases_match_legacy() {
6231        crate::worker_pool::init_worker_pool(None, 3);
6232        let (store, dir) = open_p_store("parallel-edges");
6233        let p1 = constraint("p1");
6234        let p2 = constraint("p2");
6235        let mut both = vec![p1.clone(), p2.clone()];
6236        both.sort_by_key(encode_term_bytes);
6237
6238        let legacy = scan_hits(
6239            &store,
6240            DomainScanMode::Legacy,
6241            &both,
6242            0,
6243            None,
6244            &Default::default(),
6245        )
6246        .unwrap();
6247
6248        // K = 1 (below the parser's floor, but the walker must behave).
6249        let one_worker = scan_hits(
6250            &store,
6251            DomainScanMode::ParallelWalks(1),
6252            &both,
6253            0,
6254            None,
6255            &Default::default(),
6256        )
6257        .unwrap();
6258        assert_eq!(one_worker, legacy);
6259
6260        // K > len clamps to one worker per constraint.
6261        let many_workers = scan_hits(
6262            &store,
6263            DomainScanMode::ParallelWalks(64),
6264            &both,
6265            0,
6266            None,
6267            &Default::default(),
6268        )
6269        .unwrap();
6270        assert_eq!(many_workers, legacy);
6271
6272        // Single constraint: every mode agrees with the plain scan.
6273        let single_legacy = scan_hits(
6274            &store,
6275            DomainScanMode::Legacy,
6276            std::slice::from_ref(&p1),
6277            0,
6278            None,
6279            &Default::default(),
6280        )
6281        .unwrap();
6282        let single_parallel = scan_hits(
6283            &store,
6284            DomainScanMode::ParallelWalks(4),
6285            std::slice::from_ref(&p1),
6286            0,
6287            None,
6288            &Default::default(),
6289        )
6290        .unwrap();
6291        assert_eq!(single_parallel, single_legacy);
6292        drop(store);
6293        let _ = std::fs::remove_dir_all(&dir);
6294    }
6295
6296    /// Armed per-SST prefix filters must not truncate the confined domain
6297    /// walks. The safety is structural: on the filter-marked CFs (spog /
6298    /// sopg) the leading term is always a node, every node encoding is
6299    /// exactly 17 bytes (TERM_WIDTH: hash nodes are 1 + 16 payload;
6300    /// SmallBlankNode pads its inline id into a fixed 16-byte payload),
6301    /// and the 17-byte extractor window therefore always lands on the
6302    /// constraint's own prefix for all three seek shapes of the confined
6303    /// walk — the initial `c_bytes` seek, the resume successor of
6304    /// `c_bytes ‖ head`, and the per-head successor of `c_bytes ‖ head`
6305    /// (the incremented byte sits at position >= 17, outside the
6306    /// window). This test pins that arithmetic empirically: an S-axis
6307    /// store (sopg and spog carry filter blocks), filters force-armed,
6308    /// one constraint's rows split across SSTs so every walk consults
6309    /// the per-SST blooms, both modes, hits + counts + limit truncation
6310    /// + a paged-cursor chain — all equal to the memory reference.
6311    ///
6312    /// The axis-head scans do NOT share this safety (their bare-term
6313    /// successors increment inside the window) and are not exercised
6314    /// here; see the yago armed-filter truncation record.
6315    #[test]
6316    fn confined_domain_scans_stay_correct_with_sst_filters_armed() {
6317        crate::worker_pool::init_worker_pool(None, 3);
6318        crate::rocksdb_db::TEST_SST_FILTER_FORCE_ON
6319            .store(true, std::sync::atomic::Ordering::Relaxed);
6320        let dir = std::env::temp_dir().join(format!(
6321            "waratah-domain-filtered-{}-{}",
6322            std::process::id(),
6323            std::time::SystemTime::now()
6324                .duration_since(std::time::UNIX_EPOCH)
6325                .unwrap()
6326                .as_nanos()
6327        ));
6328        let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
6329        let memory = Storage::memory(PartitionAxis::S);
6330
6331        let quad = |subject: crate::NamedOrBlankNode, predicate: &str, object: &str| {
6332            Quad::new(
6333                subject,
6334                NamedNode::new(format!("http://ex/{predicate}")).unwrap(),
6335                NamedNode::new(format!("http://ex/{object}")).unwrap(),
6336                GraphName::DefaultGraph,
6337            )
6338        };
6339        let named = |local: &str| {
6340            crate::NamedOrBlankNode::from(NamedNode::new(format!("http://ex/{local}")).unwrap())
6341        };
6342        let blank = crate::BlankNode::new("b").unwrap();
6343        let mut ts = 1u64;
6344        let mut put = |quad: Quad| {
6345            store
6346                .insert_quad_version(
6347                    &quad,
6348                    CommitTs(ts),
6349                    StorageOp::Put,
6350                    VisibilityLabel::default(),
6351                )
6352                .unwrap();
6353            memory
6354                .insert_quad_version(
6355                    &quad,
6356                    CommitTs(ts),
6357                    StorageOp::Put,
6358                    VisibilityLabel::default(),
6359                )
6360                .unwrap();
6361            ts += 1;
6362        };
6363
6364        // Two flush boundaries: one constraint's rows span SSTs, so the
6365        // bloom is consulted per SST during every walk. The blank-node
6366        // subject exercises the padded 17-byte SmallBlankNode encoding.
6367        put(quad(named("s1"), "p1", "o1"));
6368        put(quad(named("s2"), "p1", "o2"));
6369        store.flush_memtables().unwrap();
6370        put(quad(named("s1"), "p2", "o3"));
6371        put(quad(
6372            crate::NamedOrBlankNode::from(blank.clone()),
6373            "p1",
6374            "o4",
6375        ));
6376        put(quad(named("s2"), "p2", "o1"));
6377        store.flush_memtables().unwrap();
6378
6379        // Deliberately unsorted: every mode normalizes to key order.
6380        let constraints = vec![
6381            EncodedTerm::from(&blank),
6382            constraint("s2"),
6383            constraint("s1"),
6384            constraint("absent"),
6385        ];
6386
6387        // The memory reference emits in its own order; sorting by the
6388        // encoded (constraint, head) bytes reproduces the Rocks key order
6389        // every mode must emit (constraints then heads, both deduped).
6390        let sorted_hits = |mut hits: Vec<DomainScanHit>| {
6391            hits.sort_by_key(|hit| {
6392                (
6393                    encode_term_bytes(&hit.constraint),
6394                    encode_term_bytes(&hit.term),
6395                )
6396            });
6397            hits
6398        };
6399
6400        let reference = sorted_hits(
6401            memory
6402                .scan_domain(
6403                    IndexPermutation::Sopg,
6404                    &constraints,
6405                    SNAP,
6406                    0,
6407                    None,
6408                    None,
6409                    None,
6410                    &[],
6411                    false,
6412                    false,
6413                )
6414                .unwrap(),
6415        );
6416
6417        for mode in MODES {
6418            let full = store
6419                .scan_domain_with_mode(
6420                    mode,
6421                    IndexPermutation::Sopg,
6422                    &constraints,
6423                    SNAP,
6424                    0,
6425                    None,
6426                    None,
6427                    None,
6428                    &[],
6429                    false,
6430                    false,
6431                )
6432                .unwrap();
6433            assert_eq!(full, reference, "sopg full {mode:?}");
6434
6435            for limit in [1u64, 2, 3] {
6436                let limited = store
6437                    .scan_domain_with_mode(
6438                        mode,
6439                        IndexPermutation::Sopg,
6440                        &constraints,
6441                        SNAP,
6442                        limit,
6443                        None,
6444                        None,
6445                        None,
6446                        &[],
6447                        false,
6448                        false,
6449                    )
6450                    .unwrap();
6451                assert_eq!(
6452                    limited,
6453                    reference[..limit as usize],
6454                    "sopg limit {limit} {mode:?}"
6455                );
6456            }
6457
6458            // Paged-cursor chain: each page's last (constraint, head)
6459            // becomes the next page's exclusive resume — the seek shape
6460            // whose successor key is the bloom-sensitive one.
6461            let mut chain = Vec::new();
6462            let mut after: Option<(EncodedTerm, EncodedTerm)> = None;
6463            for _ in 0..100 {
6464                let page = store
6465                    .scan_domain_with_mode(
6466                        mode,
6467                        IndexPermutation::Sopg,
6468                        &constraints,
6469                        SNAP,
6470                        2,
6471                        after.as_ref().map(|c| &c.0),
6472                        after.as_ref().map(|c| &c.1),
6473                        None,
6474                        &[],
6475                        false,
6476                        false,
6477                    )
6478                    .unwrap();
6479                if page.is_empty() {
6480                    break;
6481                }
6482                let done = page.len() < 2;
6483                if let Some(last) = page.last() {
6484                    after = Some((last.constraint.clone(), last.term.clone()));
6485                }
6486                chain.extend(page);
6487                if done {
6488                    break;
6489                }
6490            }
6491            assert_eq!(chain, reference, "sopg paged chain {mode:?}");
6492
6493            // SubjectPreds over spog: same arithmetic, the other filtered
6494            // CF of this axis.
6495            let spog = store
6496                .scan_domain_with_mode(
6497                    mode,
6498                    IndexPermutation::Spog,
6499                    &constraints,
6500                    SNAP,
6501                    0,
6502                    None,
6503                    None,
6504                    None,
6505                    &[],
6506                    false,
6507                    false,
6508                )
6509                .unwrap();
6510            let spog_reference = sorted_hits(
6511                memory
6512                    .scan_domain(
6513                        IndexPermutation::Spog,
6514                        &constraints,
6515                        SNAP,
6516                        0,
6517                        None,
6518                        None,
6519                        None,
6520                        &[],
6521                        false,
6522                        false,
6523                    )
6524                    .unwrap(),
6525            );
6526            assert_eq!(spog, spog_reference, "spog {mode:?}");
6527
6528            // Counts twin over sopg (bag-of-rows mode).
6529            let counts = store
6530                .scan_domain_counts_with_mode(
6531                    mode,
6532                    IndexPermutation::Sopg,
6533                    &constraints,
6534                    SNAP,
6535                    0,
6536                    None,
6537                    None,
6538                    None,
6539                    &[],
6540                    false,
6541                    false,
6542                    false,
6543                    DomainCountMode::Rows,
6544                )
6545                .unwrap();
6546            let mut counts_reference = memory
6547                .scan_domain_counts(
6548                    IndexPermutation::Sopg,
6549                    &constraints,
6550                    SNAP,
6551                    0,
6552                    None,
6553                    None,
6554                    None,
6555                    &[],
6556                    false,
6557                    false,
6558                    false,
6559                    DomainCountMode::Rows,
6560                )
6561                .unwrap();
6562            counts_reference.sort_by_key(|hit| {
6563                (
6564                    encode_term_bytes(&hit.constraint),
6565                    encode_term_bytes(&hit.term),
6566                )
6567            });
6568            assert_eq!(counts, counts_reference, "sopg counts {mode:?}");
6569        }
6570        drop(store);
6571        let _ = std::fs::remove_dir_all(&dir);
6572    }
6573
6574    /// Armed per-SST prefix filters must not truncate the axis-head walks.
6575    ///
6576    /// The yago failure shape: the unconstrained classes head scan over
6577    /// tsg emits a head then seeks `byte_successor(bare term)`, whose
6578    /// 17-byte prefix belongs to no key; a bloom consult answers "absent"
6579    /// and the SST is marked exhausted. The fix is structural — the head
6580    /// walks' single iterator carries `total_order_seek`
6581    /// (`Db::scan_prefix_total_order`), which disarms the consult for
6582    /// that iterator unconditionally. This test pins it empirically: an
6583    /// O-axis store (tsg carries filter blocks), filters force-armed,
6584    /// classes whose rows span SST boundaries (the bloom is consulted
6585    /// per SST on every skip seek), unconstrained scan, limit
6586    /// truncation, and a paged `start_after_term` resume chain — all
6587    /// equal to the memory reference, with the allow-list
6588    /// (`head_prefixes`) mode included.
6589    #[test]
6590    fn axis_head_scans_stay_complete_with_sst_filters_armed() {
6591        crate::rocksdb_db::TEST_SST_FILTER_FORCE_ON
6592            .store(true, std::sync::atomic::Ordering::Relaxed);
6593        let dir = std::env::temp_dir().join(format!(
6594            "waratah-head-filtered-{}-{}",
6595            std::process::id(),
6596            std::time::SystemTime::now()
6597                .duration_since(std::time::UNIX_EPOCH)
6598                .unwrap()
6599                .as_nanos()
6600        ));
6601        let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
6602        let memory = Storage::memory(PartitionAxis::O);
6603
6604        let type_node = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
6605        let quad = |subject: &str, class: &str| {
6606            Quad::new(
6607                NamedNode::new(format!("http://ex/{subject}")).unwrap(),
6608                type_node.clone(),
6609                NamedNode::new(format!("http://ex/{class}")).unwrap(),
6610                GraphName::DefaultGraph,
6611            )
6612        };
6613        let mut ts = 1u64;
6614        let mut put = |quad: Quad| {
6615            store
6616                .insert_quad_version(
6617                    &quad,
6618                    CommitTs(ts),
6619                    StorageOp::Put,
6620                    VisibilityLabel::default(),
6621                )
6622                .unwrap();
6623            memory
6624                .insert_quad_version(
6625                    &quad,
6626                    CommitTs(ts),
6627                    StorageOp::Put,
6628                    VisibilityLabel::default(),
6629                )
6630                .unwrap();
6631            ts += 1;
6632        };
6633        // Flush boundaries split classes across SSTs; C2's rows straddle
6634        // one, so both its SST blooms must be consulted on every skip
6635        // seek past C2 or into it.
6636        put(quad("s1", "C1"));
6637        put(quad("s2", "C1"));
6638        put(quad("s3", "C2"));
6639        store.flush_memtables().unwrap();
6640        put(quad("s4", "C2"));
6641        put(quad("s5", "C3"));
6642        store.flush_memtables().unwrap();
6643        put(quad("s6", "C4"));
6644        store.flush_memtables().unwrap();
6645
6646        let classes = |terms: Vec<EncodedTerm>| -> Vec<String> {
6647            terms
6648                .iter()
6649                .map(|t| match t {
6650                    EncodedTerm::NamedNode { iri_id } => format!("{iri_id:?}"),
6651                    other => panic!("unexpected head term {other:?}"),
6652                })
6653                .collect()
6654        };
6655        let want = memory
6656            .scan_axis_head(
6657                IndexPermutation::Tsg,
6658                SNAP,
6659                0,
6660                None,
6661                None,
6662                &[],
6663                false,
6664                false,
6665                &[],
6666            )
6667            .unwrap();
6668        assert_eq!(want.len(), 4, "fixture must hold four classes");
6669
6670        // Unconstrained walk — the exact truncation shape from yago.
6671        let full = store
6672            .scan_axis_head(
6673                IndexPermutation::Tsg,
6674                SNAP,
6675                0,
6676                None,
6677                None,
6678                &[],
6679                false,
6680                false,
6681                &[],
6682            )
6683            .unwrap();
6684        assert_eq!(
6685            classes(full),
6686            classes(want.clone()),
6687            "armed unconstrained walk"
6688        );
6689
6690        // Paged resume chain: each page's last head feeds the next page's
6691        // exclusive `byte_successor(after)` seek.
6692        let mut chain = Vec::new();
6693        let mut after: Option<EncodedTerm> = None;
6694        for _ in 0..100 {
6695            let page = store
6696                .scan_axis_head(
6697                    IndexPermutation::Tsg,
6698                    SNAP,
6699                    2,
6700                    after.as_ref(),
6701                    None,
6702                    &[],
6703                    false,
6704                    false,
6705                    &[],
6706                )
6707                .unwrap();
6708            if page.is_empty() {
6709                break;
6710            }
6711            let done = page.len() < 2;
6712            after = Some(page.last().unwrap().clone());
6713            chain.extend(page);
6714            if done {
6715                break;
6716            }
6717        }
6718        assert_eq!(classes(chain), classes(want.clone()), "armed resume chain");
6719
6720        // Allow-list mode shares the same iterator (and the same
6721        // bare-term successor per head): one prefix list spanning two
6722        // classes, and a resume cursor inside the first. Prefixes are
6723        // partial *encoded* term bytes (type byte + hash prefix), not
6724        // IRI text — truncate the reference heads to 10 bytes.
6725        let both = vec![
6726            encode_term_bytes(&want[1])[..10].to_vec(),
6727            encode_term_bytes(&want[3])[..10].to_vec(),
6728        ];
6729        let listed = store
6730            .scan_axis_head(
6731                IndexPermutation::Tsg,
6732                SNAP,
6733                0,
6734                None,
6735                None,
6736                &[],
6737                false,
6738                false,
6739                &both,
6740            )
6741            .unwrap();
6742        assert_eq!(classes(listed.clone()).len(), 2, "armed allow-list walk");
6743        let listed_want = memory
6744            .scan_axis_head(
6745                IndexPermutation::Tsg,
6746                SNAP,
6747                0,
6748                None,
6749                None,
6750                &[],
6751                false,
6752                false,
6753                &both,
6754            )
6755            .unwrap();
6756        assert_eq!(
6757            classes(listed),
6758            classes(listed_want),
6759            "armed allow-list reference"
6760        );
6761
6762        // Counts twin: TOTAL over the whole CF.
6763        let total = store
6764            .count_axis_heads(IndexPermutation::Tsg, SNAP, None, &[], false, false)
6765            .unwrap();
6766        let total_want = memory
6767            .count_axis_heads(IndexPermutation::Tsg, SNAP, None, &[], false, false)
6768            .unwrap();
6769        assert_eq!(total, total_want, "armed count_axis_heads");
6770
6771        // Counts per head, paged.
6772        let counts = store
6773            .scan_axis_head_counts(
6774                IndexPermutation::Tsg,
6775                SNAP,
6776                0,
6777                None,
6778                None,
6779                &[],
6780                false,
6781                false,
6782            )
6783            .unwrap();
6784        let counts_want = memory
6785            .scan_axis_head_counts(
6786                IndexPermutation::Tsg,
6787                SNAP,
6788                0,
6789                None,
6790                None,
6791                &[],
6792                false,
6793                false,
6794            )
6795            .unwrap();
6796        assert_eq!(
6797            counts.len(),
6798            counts_want.len(),
6799            "armed scan_axis_head_counts"
6800        );
6801
6802        // max_commit_ts_under_prefixes under armed serving: per-prefix
6803        // re-seeks make its pruning transient, so it is correct without
6804        // the flag — these assertions pin that the hardening flag
6805        // changes nothing. All four class prefixes, so the ground truth
6806        // is deterministic: the last put's ts. Memory twin is the
6807        // reference.
6808        let all_prefixes: Vec<_> = want
6809            .iter()
6810            .map(|t| encode_term_bytes(t)[..10].to_vec())
6811            .collect();
6812        let max_rocks = store
6813            .max_commit_ts_under_prefixes(IndexPermutation::Tsg, &all_prefixes)
6814            .unwrap();
6815        let max_memory = memory
6816            .max_commit_ts_under_prefixes(IndexPermutation::Tsg, &all_prefixes)
6817            .unwrap();
6818        assert_eq!(max_rocks, max_memory, "armed max_commit_ts (prefixes)");
6819        assert_eq!(max_rocks, 6, "fixture ground truth: last put ts");
6820        let max_all = store
6821            .max_commit_ts_under_prefixes(IndexPermutation::Tsg, &[])
6822            .unwrap();
6823        assert_eq!(max_all, 6, "armed max_commit_ts (whole CF)");
6824
6825        drop(store);
6826        drop(memory);
6827        let _ = std::fs::remove_dir_all(&dir);
6828    }
6829
6830    /// Error propagation: a corrupt value row under one constraint fails the
6831    /// scan in every mode (parallel workers surface the first `Err`).
6832    #[test]
6833    fn domain_scan_modes_propagate_corrupt_rows() {
6834        for tag_mode in [
6835            DomainScanMode::Legacy,
6836            DomainScanMode::ParallelWalks(2),
6837            DomainScanMode::ParallelWalks(4),
6838        ] {
6839            let tag = match tag_mode {
6840                DomainScanMode::Legacy => "corrupt-legacy",
6841                DomainScanMode::ParallelWalks(2) => "corrupt-par2",
6842                DomainScanMode::ParallelWalks(_) => "corrupt-par4",
6843            };
6844            let (store, dir) = open_p_store(tag);
6845            // One normal constraint (p2) plus the constraint holding the
6846            // corrupt row (p1).
6847            let s5 = fixture_quad("s5", "p2", "o1", "default");
6848            store
6849                .insert_quad_version(&s5, CommitTs(8), StorageOp::Put, VisibilityLabel::default())
6850                .unwrap();
6851            let victim = fixture_quad("s1", "p1", "o1", "default");
6852            store
6853                .insert_quad_version(
6854                    &victim,
6855                    CommitTs(1),
6856                    StorageOp::Put,
6857                    VisibilityLabel::default(),
6858                )
6859                .unwrap();
6860            // Rewrite that version's row with a 1-byte value (needs 5).
6861            let encoded = encode_quad(&victim).unwrap();
6862            let key = encode_versioned_key(IndexPermutation::Posg, &encoded, CommitTs(1));
6863            let cf = store.cf_for(IndexPermutation::Posg).unwrap();
6864            store.db.insert(cf, &key, &[0x01]).unwrap();
6865
6866            let p1 = constraint("p1");
6867            let p2 = constraint("p2");
6868            let mut constraints = vec![p2.clone(), p1.clone()];
6869            constraints.sort_by_key(encode_term_bytes);
6870            let result = scan_hits(&store, tag_mode, &constraints, 0, None, &Default::default());
6871            assert!(
6872                matches!(&result, Err(crate::StorageError::Corrupt(_))),
6873                "mode {tag_mode:?} must propagate the corrupt row: {result:?}"
6874            );
6875            let counts = scan_counts(&store, tag_mode, &constraints, 0, None, &Default::default());
6876            assert!(
6877                matches!(&counts, Err(crate::StorageError::Corrupt(_))),
6878                "counts mode {tag_mode:?} must propagate the corrupt row: {counts:?}"
6879            );
6880            drop(store);
6881            let _ = std::fs::remove_dir_all(&dir);
6882        }
6883    }
6884
6885    /// Key-corruption propagation: the region-based head walks must report
6886    /// a truncated head — or a following component cut into the commit
6887    /// timestamp — as `Corrupt`, never panic and never fold timestamp
6888    /// bytes into an emitted term or a distinct-count region. The
6889    /// corrupt-VALUE contract is pinned by
6890    /// `domain_scan_modes_propagate_corrupt_rows`; this pins the
6891    /// corrupt-KEY contract that came with replacing per-row full-key
6892    /// decodes with width-table region arithmetic.
6893    #[test]
6894    fn head_walks_report_truncated_head_keys_as_corrupt() {
6895        let (store, dir) = open_p_store("corrupt-key");
6896        // One valid POSG row: key = p1 | o1 | s1 | (default graph) | ts.
6897        // Constraint, head, and slot-1 are 17-byte NamedNodes, so the head
6898        // sits at [c_len, c_len + 17) and slot-1 at [c_len + 17, c_len + 34).
6899        let victim = fixture_quad("s1", "p1", "o1", "default");
6900        store
6901            .insert_quad_version(
6902                &victim,
6903                CommitTs(1),
6904                StorageOp::Put,
6905                VisibilityLabel::default(),
6906            )
6907            .unwrap();
6908        let encoded = encode_quad(&victim).unwrap();
6909        let valid = encode_versioned_key(IndexPermutation::Posg, &encoded, CommitTs(1));
6910        let cf = store.cf_for(IndexPermutation::Posg).unwrap();
6911        let value = encode_storage_value(StorageOp::Put, VisibilityLabel::default());
6912        let c_len = encode_term_bytes(&constraint("p1")).len();
6913        let head_len = 17usize;
6914        let splice = |keep: usize| {
6915            let mut key = Vec::new();
6916            key.extend_from_slice(&valid[..keep]);
6917            key.extend_from_slice(&valid[valid.len() - COMMIT_TS_LEN..]);
6918            key
6919        };
6920
6921        // Shape 1 — head cut so hard that its claimed width runs past the
6922        // whole key: unchecked, `&key[head]` panics inside the walk.
6923        store.db.insert(cf, &splice(c_len + 3), &value).unwrap();
6924        // Shape 2 — head cut by < COMMIT_TS_LEN bytes so the claimed width
6925        // lands inside the timestamp: unchecked, the walk emits a term
6926        // decoded from timestamp bytes.
6927        store
6928            .db
6929            .insert(cf, &splice(c_len + head_len - 4), &value)
6930            .unwrap();
6931        // Shape 3 — head intact, slot-1 cut into the timestamp: unchecked,
6932        // the counts/PER_HEAD region arithmetic folds ts bytes into the
6933        // distinct-term comparison.
6934        store
6935            .db
6936            .insert(cf, &splice(c_len + head_len + 13), &value)
6937            .unwrap();
6938        // Shape 4 — the axis-head term itself (offset 0) truncated: the
6939        // axis walks must fail the same way the domain walks do.
6940        store.db.insert(cf, &splice(3), &value).unwrap();
6941
6942        let p1 = constraint("p1");
6943        let result = scan_hits(
6944            &store,
6945            DomainScanMode::Legacy,
6946            std::slice::from_ref(&p1),
6947            0,
6948            None,
6949            &Default::default(),
6950        );
6951        assert!(
6952            matches!(&result, Err(crate::StorageError::Corrupt(_))),
6953            "domain hits walk must report a truncated head key: {result:?}"
6954        );
6955        for count_mode in [
6956            DomainCountMode::Rows,
6957            DomainCountMode::DistinctTerms,
6958            DomainCountMode::DistinctGraphs,
6959        ] {
6960            let counts = scan_counts(
6961                &store,
6962                DomainScanMode::Legacy,
6963                std::slice::from_ref(&p1),
6964                0,
6965                None,
6966                &DomainArgs {
6967                    count_mode,
6968                    ..Default::default()
6969                },
6970            );
6971            assert!(
6972                matches!(&counts, Err(crate::StorageError::Corrupt(_))),
6973                "counts walk {count_mode:?} must report a truncated head key: {counts:?}"
6974            );
6975        }
6976
6977        // The same CF via the axis entry points. `scan_axis_head` and
6978        // `count_axis_heads` only ever read the offset-0 head term, so
6979        // shape 4 is what they must reject; `scan_axis_head_counts` also
6980        // derives the slot-1 region and is caught by shapes 1–3 as well.
6981        //
6982        // Ordering dependency, deliberately relied on: the axis walks
6983        // consider only the FIRST key under each head prefix and seek
6984        // past the rest, so these assertions require a corrupt key to be
6985        // reached before the walk can emit the valid p1 head and skip
6986        // away. The c-prefixed shapes (1–3, mid-hop) share p1 as their
6987        // axis head, and whether `valid` or a corrupt sibling sorts first
6988        // under p1 depends on fixture hash bytes — so shape 4 (its own
6989        // short prefix, which sorts after every c-prefixed key via the
6990        // timestamp's 0xFF and is reached only after the p1 range is
6991        // skipped) is what makes the axis `Corrupt` assertions
6992        // load-bearing regardless of that hash order. Renaming the
6993        // fixture terms can change which shape fires first, but shape 4
6994        // fires last and unconditionally.
6995        let axis_err = store.scan_axis_head(
6996            IndexPermutation::Posg,
6997            SNAP,
6998            0,
6999            None,
7000            None,
7001            &[],
7002            false,
7003            false,
7004            &[],
7005        );
7006        assert!(
7007            matches!(&axis_err, Err(crate::StorageError::Corrupt(_))),
7008            "axis head scan must report a truncated head key: {axis_err:?}"
7009        );
7010        let axis_total =
7011            store.count_axis_heads(IndexPermutation::Posg, SNAP, None, &[], false, false);
7012        assert!(
7013            matches!(&axis_total, Err(crate::StorageError::Corrupt(_))),
7014            "axis head total must report a truncated head key: {axis_total:?}"
7015        );
7016        let axis_counts = store.scan_axis_head_counts(
7017            IndexPermutation::Posg,
7018            SNAP,
7019            0,
7020            None,
7021            None,
7022            &[],
7023            false,
7024            false,
7025        );
7026        assert!(
7027            matches!(&axis_counts, Err(crate::StorageError::Corrupt(_))),
7028            "axis PER_HEAD counts must report a truncated head key: {axis_counts:?}"
7029        );
7030
7031        // Mid-hop truncation under a constrained window: a key whose head
7032        // is intact but whose slot-2 is cut entirely (the hop from the
7033        // head's end lands on the timestamp's first byte — `0xFF` under
7034        // descending encoding, which the width table holds at UNKNOWN).
7035        // The G-region arithmetic must report `Corrupt` in both the
7036        // DefaultOnly (byte-shape) and General (decode) windows; under an
7037        // unconstrained window this key is a legitimate candidate (no G
7038        // work runs), so the assertion is scoped to the windows.
7039        let mid_hop = splice(c_len + head_len);
7040        store.db.insert(cf, &mid_hop, &value).unwrap();
7041        for (tag, graph_name) in [
7042            ("default-only", Some(EncodedTerm::DefaultGraph)),
7043            ("general", Some(constraint("g1"))),
7044        ] {
7045            let args = DomainArgs {
7046                graph_name: graph_name.as_ref(),
7047                ..Default::default()
7048            };
7049            let hits = scan_hits(
7050                &store,
7051                DomainScanMode::Legacy,
7052                std::slice::from_ref(&p1),
7053                0,
7054                None,
7055                &args,
7056            );
7057            assert!(
7058                matches!(&hits, Err(crate::StorageError::Corrupt(_))),
7059                "hits walk under {tag} window must report the mid-hop key: {hits:?}"
7060            );
7061            let counts = scan_counts(
7062                &store,
7063                DomainScanMode::Legacy,
7064                std::slice::from_ref(&p1),
7065                0,
7066                None,
7067                &args,
7068            );
7069            assert!(
7070                matches!(&counts, Err(crate::StorageError::Corrupt(_))),
7071                "counts walk under {tag} window must report the mid-hop key: {counts:?}"
7072            );
7073        }
7074
7075        drop(store);
7076        let _ = std::fs::remove_dir_all(&dir);
7077    }
7078
7079    /// Payload corruption with VALID extents, isolated from the extent
7080    /// shapes: the axis-head slot (offset 0) carries a small-literal
7081    /// header — type byte 16, width 17, the same extent as the named node
7082    /// it replaces — whose length byte 0x20 exceeds the small-string
7083    /// maximum. Extent checks pass; only a decode rejects it. Every axis
7084    /// walk decodes the head it counts or emits — TOTAL included, whose
7085    /// validation decode exists exactly for this shape — so the corruption
7086    /// surfaces as `Corrupt` in all three, never a silent under-count.
7087    /// The key sorts first in the CF (type byte 16 sorts before any named
7088    /// node), so the walks hit it deterministically; the domain walks
7089    /// would skip it (slot-0 bytes are not the p1 constraint).
7090    #[test]
7091    fn axis_walks_report_payload_corrupt_heads_as_corrupt() {
7092        let (store, dir) = open_p_store("corrupt-payload");
7093        let victim = fixture_quad("s1", "p1", "o1", "default");
7094        store
7095            .insert_quad_version(
7096                &victim,
7097                CommitTs(1),
7098                StorageOp::Put,
7099                VisibilityLabel::default(),
7100            )
7101            .unwrap();
7102        let encoded = encode_quad(&victim).unwrap();
7103        let valid = encode_versioned_key(IndexPermutation::Posg, &encoded, CommitTs(1));
7104        let cf = store.cf_for(IndexPermutation::Posg).unwrap();
7105        let value = encode_storage_value(StorageOp::Put, VisibilityLabel::default());
7106        let c_len = encode_term_bytes(&constraint("p1")).len();
7107        // Small-literal wire form: type byte + 16 content bytes whose LAST
7108        // byte is the UTF-8 length. Declaring length 4 with 0xFF as the
7109        // first content byte is invalid UTF-8 — `SmallString::from_be_bytes`
7110        // rejects it, while the 17-byte extent stays valid.
7111        let mut payload_corrupt = vec![16u8, 0xFF];
7112        payload_corrupt.extend_from_slice(&[0u8; 14]);
7113        payload_corrupt.push(4);
7114        payload_corrupt.extend_from_slice(&valid[c_len..]);
7115        store.db.insert(cf, &payload_corrupt, &value).unwrap();
7116
7117        let hits = store.scan_axis_head(
7118            IndexPermutation::Posg,
7119            SNAP,
7120            0,
7121            None,
7122            None,
7123            &[],
7124            false,
7125            false,
7126            &[],
7127        );
7128        assert!(
7129            matches!(&hits, Err(crate::StorageError::Corrupt(_))),
7130            "hits walk must decode-reject the payload-corrupt head: {hits:?}"
7131        );
7132        let total = store.count_axis_heads(IndexPermutation::Posg, SNAP, None, &[], false, false);
7133        assert!(
7134            matches!(&total, Err(crate::StorageError::Corrupt(_))),
7135            "TOTAL must decode-reject the payload-corrupt head (no silent \
7136             under-count): {total:?}"
7137        );
7138        let per_head = store.scan_axis_head_counts(
7139            IndexPermutation::Posg,
7140            SNAP,
7141            0,
7142            None,
7143            None,
7144            &[],
7145            false,
7146            false,
7147        );
7148        assert!(
7149            matches!(&per_head, Err(crate::StorageError::Corrupt(_))),
7150            "PER_HEAD must decode-reject the payload-corrupt head: {per_head:?}"
7151        );
7152
7153        drop(store);
7154        let _ = std::fs::remove_dir_all(&dir);
7155    }
7156
7157    /// Wide-term and `iri_only` coverage for the counts walks. The shared
7158    /// corpus only ever writes 17-byte terms, so the run-head and
7159    /// last-slot-2 stack buffers (`[u8; WRITTEN_TERM_MAX_SIZE]`, 33 bytes)
7160    /// were never exercised at exact fit — a sizing off-by-one could not
7161    /// fail a test. A `BigTypedLiteral` object is exactly 33 encoded
7162    /// bytes: under POSG it is a wide *head*; under SPOG (the one
7163    /// permutation whose slot 2 is the object) it is a wide *slot 2* for
7164    /// the distinct-term counter. The `iri_only` + bound-graph cells pin
7165    /// the counts walks' marker-byte filter, which the hits matrix covers
7166    /// only indirectly through the shared `consider_head_key`.
7167    #[test]
7168    fn counts_walks_cover_wide_terms_and_iri_only() {
7169        let typed_object = "typed:a typed literal value well over sixteen bytes";
7170        let rows: Vec<(&str, &str, &str, &str, u64, StorageOp)> = vec![
7171            ("s1", "p1", typed_object, "default", 1, StorageOp::Put),
7172            ("s2", "p1", "o1", "default", 2, StorageOp::Put),
7173            ("s2", "p1", typed_object, "g1", 3, StorageOp::Put),
7174            ("s3", "p1", "o2", "default", 4, StorageOp::Put),
7175        ];
7176        // The wide object must really be the 33-byte exact fit — the test
7177        // is vacuous otherwise.
7178        assert_eq!(
7179            encode_term_bytes(
7180                &encode_quad(&fixture_quad("s", "p", typed_object, "default"))
7181                    .unwrap()
7182                    .object
7183            )
7184            .len(),
7185            33
7186        );
7187
7188        let (store, dir) = open_p_store("counts-wide");
7189        let memory = Storage::memory(PartitionAxis::P);
7190        for (s, p, o, g, ts, op) in &rows {
7191            let quad = fixture_quad(s, p, o, g);
7192            store
7193                .insert_quad_version(&quad, CommitTs(*ts), *op, VisibilityLabel::default())
7194                .unwrap();
7195            memory
7196                .insert_quad_version(&quad, CommitTs(*ts), *op, VisibilityLabel::default())
7197                .unwrap();
7198        }
7199
7200        let p1 = constraint("p1");
7201        let g1 = graph_term("g1");
7202        let cases: Vec<(&str, Option<EncodedTerm>, bool)> = vec![
7203            ("unconstrained", None, false),
7204            ("bound-g1", Some(g1.clone()), false),
7205            ("unconstrained+iri", None, true),
7206            ("bound-g1+iri", Some(g1.clone()), true),
7207        ];
7208        for count_mode in [
7209            DomainCountMode::Rows,
7210            DomainCountMode::DistinctTerms,
7211            DomainCountMode::DistinctGraphs,
7212        ] {
7213            for (tag, graph_name, iri_only) in &cases {
7214                let args = DomainArgs {
7215                    graph_name: graph_name.as_ref(),
7216                    iri_only: *iri_only,
7217                    count_mode,
7218                    ..Default::default()
7219                };
7220                let rocks = scan_counts(
7221                    &store,
7222                    DomainScanMode::Legacy,
7223                    std::slice::from_ref(&p1),
7224                    0,
7225                    None,
7226                    &args,
7227                )
7228                .unwrap();
7229                let mem = memory_counts(&memory, std::slice::from_ref(&p1), 0, None, &args);
7230                assert_eq!(rocks, mem, "{count_mode:?} / {tag}: backends must agree");
7231            }
7232        }
7233
7234        // Spot ground truths (Posg: constraint p1, head = object).
7235        let o1 = EncodedTerm::from(&NamedNode::new("http://ex/o1").unwrap());
7236        let o2 = EncodedTerm::from(&NamedNode::new("http://ex/o2").unwrap());
7237        let typed_head = encode_quad(&fixture_quad("s", "p", typed_object, "default"))
7238            .unwrap()
7239            .object;
7240        let rows_args = DomainArgs {
7241            count_mode: DomainCountMode::Rows,
7242            ..Default::default()
7243        };
7244        let hits = scan_counts(
7245            &store,
7246            DomainScanMode::Legacy,
7247            std::slice::from_ref(&p1),
7248            0,
7249            None,
7250            &rows_args,
7251        )
7252        .unwrap();
7253        assert_eq!(head_count(&hits, &typed_head), 2, "wide head in two graphs");
7254        assert_eq!(head_count(&hits, &o1), 1);
7255        assert_eq!(head_count(&hits, &o2), 1);
7256        // `iri_only` drops the literal (typed) head by marker byte, keeps
7257        // the named-node heads.
7258        let iri_args = DomainArgs {
7259            iri_only: true,
7260            count_mode: DomainCountMode::Rows,
7261            ..Default::default()
7262        };
7263        let iri_hits = scan_counts(
7264            &store,
7265            DomainScanMode::Legacy,
7266            std::slice::from_ref(&p1),
7267            0,
7268            None,
7269            &iri_args,
7270        )
7271        .unwrap();
7272        assert_eq!(iri_hits.len(), 2, "named-node heads only: {iri_hits:?}");
7273        assert_eq!(head_count(&iri_hits, &o1) + head_count(&iri_hits, &o2), 2);
7274
7275        drop(store);
7276        let _ = std::fs::remove_dir_all(&dir);
7277
7278        // Wide slot 2: SPOG (S-axis) is the only counts permutation whose
7279        // slot 2 is the object, so the distinct-term counter's last-slot-2
7280        // buffer needs it — distinct objects under (s2, p1) = {o1, typed}.
7281        let dir = std::env::temp_dir().join(format!(
7282            "waratah-counts-wide-spog-{}-{}",
7283            std::process::id(),
7284            std::time::SystemTime::now()
7285                .duration_since(std::time::UNIX_EPOCH)
7286                .unwrap()
7287                .as_nanos()
7288        ));
7289        let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
7290        let memory = Storage::memory(PartitionAxis::S);
7291        for (s, p, o, g, ts, op) in &rows {
7292            let quad = fixture_quad(s, p, o, g);
7293            store
7294                .insert_quad_version(&quad, CommitTs(*ts), *op, VisibilityLabel::default())
7295                .unwrap();
7296            memory
7297                .insert_quad_version(&quad, CommitTs(*ts), *op, VisibilityLabel::default())
7298                .unwrap();
7299        }
7300        let s2 = EncodedTerm::from(&NamedNode::new("http://ex/s2").unwrap());
7301        let p1_head = constraint("p1");
7302        let distinct = store
7303            .scan_domain_counts(
7304                IndexPermutation::Spog,
7305                std::slice::from_ref(&s2),
7306                SnapshotId(100),
7307                0,
7308                None,
7309                None,
7310                None,
7311                &[],
7312                false,
7313                false,
7314                false,
7315                DomainCountMode::DistinctTerms,
7316            )
7317            .unwrap();
7318        let mem_distinct = memory
7319            .scan_domain_counts(
7320                IndexPermutation::Spog,
7321                std::slice::from_ref(&s2),
7322                SnapshotId(100),
7323                0,
7324                None,
7325                None,
7326                None,
7327                &[],
7328                false,
7329                false,
7330                false,
7331                DomainCountMode::DistinctTerms,
7332            )
7333            .unwrap();
7334        assert_eq!(distinct, mem_distinct, "SPOG wide-slot-2 parity");
7335        assert_eq!(distinct.len(), 1, "one head (p1) under s2: {distinct:?}");
7336        assert_eq!(
7337            distinct[0].count, 2,
7338            "distinct objects {{o1, typed}}: {distinct:?}"
7339        );
7340        assert_eq!(distinct[0].term, p1_head);
7341
7342        drop(store);
7343        let _ = std::fs::remove_dir_all(&dir);
7344    }
7345
7346    /// Future versions (`commit_ts > snapshot`) in the head walks.
7347    /// `SnapshotScanState::consider_slice` returns `false` for a future
7348    /// version WITHOUT marking its logical key handled — so the next,
7349    /// older, visible version of the same triple is still considered and
7350    /// counted. The merge Next-chain's no-reset argument leans on exactly
7351    /// that branch (the post-chain key has a different S/P/O from the
7352    /// stale handled-logical), and no other head-walk fixture has an
7353    /// invisible-but-newest version — every existing row is `ts <= 10`
7354    /// under `SNAP = 1000`. Ground truth: a triple whose newest version
7355    /// is future still contributes its visible older version (s1 under
7356    /// o1, s4 under o3); a future-ONLY triple contributes nothing (o2
7357    /// absent).
7358    #[test]
7359    fn counts_walks_see_older_versions_under_future_heads() {
7360        let (store, dir) = open_p_store("future-ts");
7361        let memory = Storage::memory(PartitionAxis::P);
7362        let rows: Vec<(&str, &str, &str, &str, u64, StorageOp)> = vec![
7363            ("s1", "p1", "o1", "default", 2000, StorageOp::Put),
7364            ("s1", "p1", "o1", "default", 5, StorageOp::Put),
7365            ("s2", "p1", "o1", "default", 6, StorageOp::Put),
7366            ("s3", "p1", "o2", "default", 3000, StorageOp::Put),
7367            ("s4", "p1", "o3", "default", 2500, StorageOp::Put),
7368            ("s4", "p1", "o3", "default", 7, StorageOp::Put),
7369            ("s5", "p1", "o3", "default", 8, StorageOp::Put),
7370        ];
7371        for (s, p, o, g, ts, op) in &rows {
7372            let quad = fixture_quad(s, p, o, g);
7373            store
7374                .insert_quad_version(&quad, CommitTs(*ts), *op, VisibilityLabel::default())
7375                .unwrap();
7376            memory
7377                .insert_quad_version(&quad, CommitTs(*ts), *op, VisibilityLabel::default())
7378                .unwrap();
7379        }
7380
7381        let p1 = constraint("p1");
7382        let o1 = encode_quad(&fixture_quad("s", "p", "o1", "default"))
7383            .unwrap()
7384            .object;
7385        let o3 = encode_quad(&fixture_quad("s", "p", "o3", "default"))
7386            .unwrap()
7387            .object;
7388        // (merge, count mode) combos; DistinctGraphs requires merge unset.
7389        let combos: Vec<(bool, DomainCountMode)> = vec![
7390            (true, DomainCountMode::Rows),
7391            (true, DomainCountMode::DistinctTerms),
7392            (false, DomainCountMode::Rows),
7393            (false, DomainCountMode::DistinctTerms),
7394            (false, DomainCountMode::DistinctGraphs),
7395        ];
7396        for (merge, count_mode) in &combos {
7397            let args = DomainArgs {
7398                merge: *merge,
7399                count_mode: *count_mode,
7400                ..Default::default()
7401            };
7402            let rocks = scan_counts(
7403                &store,
7404                DomainScanMode::Legacy,
7405                std::slice::from_ref(&p1),
7406                0,
7407                None,
7408                &args,
7409            )
7410            .unwrap();
7411            let mem = memory_counts(&memory, std::slice::from_ref(&p1), 0, None, &args);
7412            assert_eq!(
7413                rocks, mem,
7414                "backends must agree (merge={merge}, {count_mode:?})"
7415            );
7416
7417            assert_eq!(rocks.len(), 2, "heads o1 and o3 only: {rocks:?}");
7418            // Per-mode ground truth: Rows and DistinctTerms count the two
7419            // subjects under each head (the future-newest triples'
7420            // visible-older versions included); DistinctGraphs counts
7421            // graphs, and every row here is in the default graph.
7422            let expected = match count_mode {
7423                DomainCountMode::DistinctGraphs => 1,
7424                _ => 2,
7425            };
7426            assert_eq!(
7427                head_count(&rocks, &o1),
7428                expected,
7429                "o1 (merge={merge}, {count_mode:?}): {rocks:?}"
7430            );
7431            assert_eq!(
7432                head_count(&rocks, &o3),
7433                expected,
7434                "o3 (merge={merge}, {count_mode:?}): {rocks:?}"
7435            );
7436        }
7437
7438        drop(store);
7439        let _ = std::fs::remove_dir_all(&dir);
7440    }
7441
7442    /// Merge-mode advance under `merge_default_graph`: after counting a
7443    /// triple the walk skips its remaining G-variants and older versions.
7444    /// Short variant chains advance one row at a time; chains longer than
7445    /// [`MERGE_NEXT_CHAIN_LIMIT`] pay one seek. This fixture spans both
7446    /// branches — one triple in 3 graphs (pure row-advance), one in 60
7447    /// graphs (bounded seek) with a neighbour triple sorting directly
7448    /// after the chain (the seek must land on it, not skip it) — and
7449    /// asserts ground truth plus RocksDB/memory parity.
7450    #[test]
7451    fn merge_counts_next_chain_and_bounded_seek_agree() {
7452        let (store, dir) = open_p_store("merge-chain");
7453        let memory = Storage::memory(PartitionAxis::P);
7454        let mut rows: Vec<(String, &str, &str, String)> = Vec::new();
7455        // 60-graph triple: exceeds the chain bound, exercises the seek.
7456        for i in 0..60 {
7457            rows.push(("s1".into(), "p1", "o1", format!("gc{i:02}")));
7458        }
7459        // Neighbour under the same head: sorts directly after s1's chain.
7460        rows.push(("s2".into(), "p1", "o1", "default".into()));
7461        // New head after the chain: the walk must keep counting past the
7462        // seek landing point.
7463        rows.push(("s3".into(), "p1", "o2", "default".into()));
7464        // 3-graph triple: stays inside the chain bound, pure row-advance.
7465        for g in ["ga", "gb", "gc"] {
7466            rows.push(("s4".into(), "p1", "o3", g.into()));
7467        }
7468        for (s, p, o, g) in &rows {
7469            let quad = fixture_quad(s, p, o, g);
7470            store
7471                .insert_quad_version(
7472                    &quad,
7473                    CommitTs(1),
7474                    StorageOp::Put,
7475                    VisibilityLabel::default(),
7476                )
7477                .unwrap();
7478            memory
7479                .insert_quad_version(
7480                    &quad,
7481                    CommitTs(1),
7482                    StorageOp::Put,
7483                    VisibilityLabel::default(),
7484                )
7485                .unwrap();
7486        }
7487
7488        let p1 = constraint("p1");
7489        for count_mode in [DomainCountMode::Rows, DomainCountMode::DistinctTerms] {
7490            let args = DomainArgs {
7491                merge: true,
7492                count_mode,
7493                ..Default::default()
7494            };
7495            let rocks = scan_counts(
7496                &store,
7497                DomainScanMode::Legacy,
7498                std::slice::from_ref(&p1),
7499                0,
7500                None,
7501                &args,
7502            )
7503            .unwrap();
7504            let mem = memory_counts(&memory, std::slice::from_ref(&p1), 0, None, &args);
7505            assert_eq!(rocks, mem, "backends must agree ({count_mode:?})");
7506
7507            // Ground truth per head: o1 = {s1 merged, s2}, o2 = {s3},
7508            // o3 = {s4 merged}.
7509            let mut counts: Vec<u64> = rocks.iter().map(|h| h.count).collect();
7510            counts.sort_unstable();
7511            assert_eq!(
7512                counts,
7513                vec![1, 1, 2],
7514                "merged counts ({count_mode:?}): {rocks:?}"
7515            );
7516            assert_eq!(rocks.len(), 3, "one hit per head (o1, o2, o3): {rocks:?}");
7517        }
7518
7519        drop(store);
7520        let _ = std::fs::remove_dir_all(&dir);
7521    }
7522
7523    // ==== parallel pattern-count walks (`WARATAH_COUNT_WALKS`) ====
7524
7525    use super::{
7526        CountSlice, CountWalkMode, count_walk_plan, count_walk_slice, count_walks_from_env,
7527        even_boundaries,
7528    };
7529    use crate::StrHash;
7530    use crate::encode::{EncodedQuad, EncodedTriplePattern, GByteFilter};
7531
7532    fn count_store_dir(tag: &str) -> std::path::PathBuf {
7533        std::env::temp_dir().join(format!(
7534            "waratah-count-{tag}-{}-{}",
7535            std::process::id(),
7536            std::time::SystemTime::now()
7537                .duration_since(std::time::UNIX_EPOCH)
7538                .unwrap()
7539                .as_nanos()
7540        ))
7541    }
7542
7543    /// Insert-ready default-graph quad with a named-node predicate.
7544    fn default_spo(s: &str, predicate_iri: &str, o: &str) -> Quad {
7545        Quad::new(
7546            NamedNode::new(format!("http://ex/{s}")).unwrap(),
7547            NamedNode::new(predicate_iri).unwrap(),
7548            NamedNode::new(format!("http://ex/{o}")).unwrap(),
7549            GraphName::DefaultGraph,
7550        )
7551    }
7552
7553    /// `rdf:type` flavor of [`default_spo`].
7554    fn rdf_type_spo(s: &str, o: &str) -> Quad {
7555        default_spo(s, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", o)
7556    }
7557
7558    /// Fully unbound pattern (a full-axis count's shape).
7559    fn unbound_pattern() -> EncodedTriplePattern {
7560        EncodedTriplePattern {
7561            subject: None,
7562            predicate: None,
7563            object: None,
7564            graph_name: None,
7565        }
7566    }
7567
7568    #[allow(clippy::too_many_arguments)]
7569    fn count_run(
7570        store: &RocksDbStorage,
7571        mode: CountWalkMode,
7572        permutation: IndexPermutation,
7573        pattern: &EncodedTriplePattern,
7574        snapshot: SnapshotId,
7575        limit: u64,
7576        graph: &GByteFilter,
7577        merge: bool,
7578        class_totals: &[(StrHash, u64)],
7579    ) -> u64 {
7580        store
7581            .count_pattern_impl_with_mode(
7582                mode,
7583                permutation,
7584                pattern,
7585                snapshot,
7586                limit,
7587                graph.clone(),
7588                merge,
7589                class_totals,
7590            )
7591            .unwrap()
7592    }
7593
7594    /// Fixture store mixing term kinds on every axis: IRI subjects/objects,
7595    /// blank-node subjects, plain and typed (9-byte inline integer) literal
7596    /// objects, two named graphs, and one multi-version group (Put 10 /
7597    /// Put 30; snapshot 25 sees exactly the ts=10 version). Returns the
7598    /// store, its temp dir, the full-axis hexastore total at snapshot 25,
7599    /// and the TSG full-axis total — the TSG family holds every rdf:type
7600    /// row, including the literal-class rows the compute funnel would
7601    /// reject but the storage insert path writes (`prepare_hexastore_puts`
7602    /// gates TSG membership on the predicate alone). A store owns only its
7603    /// axis's permutations (TSG with the O axis), so the caller opens one
7604    /// store per axis, and only the O-axis fixture carries the rdf:type
7605    /// quads — inserting them elsewhere would ask for the un-owned TSG.
7606    fn mixed_kind_store(axis: PartitionAxis) -> (RocksDbStorage, std::path::PathBuf, u64, u64) {
7607        let dir = count_store_dir("perm-mixed");
7608        let store = RocksDbStorage::open(&dir, axis).unwrap();
7609        let integer = NamedNode::new("http://www.w3.org/2001/XMLSchema#integer").unwrap();
7610        let mut quads: Vec<Quad> = Vec::new();
7611        for i in 0..6 {
7612            quads.push(Quad::new(
7613                NamedNode::new(format!("http://ex/s{i}")).unwrap(),
7614                NamedNode::new("http://ex/p0").unwrap(),
7615                NamedNode::new(format!("http://ex/o{i}")).unwrap(),
7616                GraphName::DefaultGraph,
7617            ));
7618        }
7619        for i in 0..3 {
7620            quads.push(Quad::new(
7621                BlankNode::new_unchecked(format!("b{i}")),
7622                NamedNode::new("http://ex/p1").unwrap(),
7623                NamedNode::new(format!("http://ex/o{i}")).unwrap(),
7624                GraphName::DefaultGraph,
7625            ));
7626        }
7627        for i in 0..3 {
7628            quads.push(Quad::new(
7629                NamedNode::new(format!("http://ex/s{i}")).unwrap(),
7630                NamedNode::new("http://ex/p1").unwrap(),
7631                Literal::from(format!("lit{i}")),
7632                GraphName::DefaultGraph,
7633            ));
7634        }
7635        for i in 0..3 {
7636            quads.push(Quad::new(
7637                NamedNode::new(format!("http://ex/s{i}")).unwrap(),
7638                NamedNode::new("http://ex/p2").unwrap(),
7639                Literal::new_typed_literal(["7", "42", "-5"][i], integer.clone()),
7640                GraphName::DefaultGraph,
7641            ));
7642        }
7643        // rdf:type quads only in the O-axis fixture: they are the rows the
7644        // un-owned TSG family would receive (gated on the predicate in
7645        // prepare_hexastore_puts), so S/P stores must not see them.
7646        let rdf_type = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
7647        if axis == PartitionAxis::O {
7648            for i in 0..6 {
7649                quads.push(Quad::new(
7650                    NamedNode::new(format!("http://ex/s{i}")).unwrap(),
7651                    rdf_type.clone(),
7652                    NamedNode::new(format!("http://ex/C{}", i % 2)).unwrap(),
7653                    GraphName::DefaultGraph,
7654                ));
7655            }
7656            for (subject, value) in [("t0", "7"), ("t1", "42")] {
7657                quads.push(Quad::new(
7658                    NamedNode::new(format!("http://ex/{subject}")).unwrap(),
7659                    rdf_type.clone(),
7660                    Literal::new_typed_literal(value, integer.clone()),
7661                    GraphName::DefaultGraph,
7662                ));
7663            }
7664        }
7665        quads.push(named_spo("n0", "no0", "g0"));
7666        quads.push(named_spo("n1", "no1", "g0"));
7667        quads.push(named_spo("n2", "no2", "g1"));
7668        // Multi-version group: the newest Put(30) sorts beyond snapshot 25,
7669        // so the visible version is Put(10) — one row, not two.
7670        let mv = Quad::new(
7671            NamedNode::new("http://ex/s9").unwrap(),
7672            NamedNode::new("http://ex/p9").unwrap(),
7673            NamedNode::new("http://ex/o9").unwrap(),
7674            GraphName::DefaultGraph,
7675        );
7676        for ts in [10u64, 30] {
7677            store
7678                .insert_quad_version(
7679                    &mv,
7680                    CommitTs(ts),
7681                    StorageOp::Put,
7682                    VisibilityLabel::default(),
7683                )
7684                .unwrap();
7685        }
7686        for quad in &quads {
7687            store
7688                .insert_quad_version(
7689                    quad,
7690                    CommitTs(1),
7691                    StorageOp::Put,
7692                    VisibilityLabel::default(),
7693                )
7694                .unwrap();
7695        }
7696        store.flush_memtables().unwrap();
7697        let tsg_total = if axis == PartitionAxis::O { 8 } else { 0 };
7698        (store, dir, quads.len() as u64 + 1, tsg_total)
7699    }
7700
7701    /// Equivalence matrix: the parallel walk machinery (slice plan,
7702    /// boundary construction, straddle ownership) branches on
7703    /// per-permutation slot orders, and the suite previously exercised
7704    /// only Spog and Tsg. Every permutation must count identically serial
7705    /// vs parallel on a mixed-kind store, full-axis and prefix-arena
7706    /// alike — including the short (9-byte inline integer) leading terms
7707    /// whose arena boundaries land inside the SST-filter extractor window.
7708    #[test]
7709    fn count_parallel_matches_serial_on_every_permutation() {
7710        let (s_store, s_dir, no_type_total, _) = mixed_kind_store(PartitionAxis::S);
7711        let (p_store, p_dir, _, _) = mixed_kind_store(PartitionAxis::P);
7712        let (o_store, o_dir, full_total, tsg_total) = mixed_kind_store(PartitionAxis::O);
7713        let snapshot = SnapshotId(25);
7714        let store_for = |permutation| match permutation {
7715            IndexPermutation::Spog | IndexPermutation::Sopg => &s_store,
7716            IndexPermutation::Posg | IndexPermutation::Psog => &p_store,
7717            IndexPermutation::Opsg | IndexPermutation::Tsg => &o_store,
7718        };
7719        let permutations = [
7720            IndexPermutation::Spog,
7721            IndexPermutation::Sopg,
7722            IndexPermutation::Posg,
7723            IndexPermutation::Psog,
7724            IndexPermutation::Opsg,
7725            IndexPermutation::Tsg,
7726        ];
7727        for permutation in permutations {
7728            let store = store_for(permutation);
7729            // TSG full-axis keys on the rdf:type predicate (the family only
7730            // holds type rows); hexastore full-axis is fully unbound.
7731            let pattern = if permutation == IndexPermutation::Tsg {
7732                EncodedTriplePattern {
7733                    predicate: Some(crate::RDF_TYPE),
7734                    ..unbound_pattern()
7735                }
7736            } else {
7737                unbound_pattern()
7738            };
7739            let expected = match permutation {
7740                IndexPermutation::Tsg => tsg_total,
7741                IndexPermutation::Opsg => full_total,
7742                _ => no_type_total,
7743            };
7744            let serial = count_run(
7745                store,
7746                CountWalkMode::Serial,
7747                permutation,
7748                &pattern,
7749                snapshot,
7750                0,
7751                &GByteFilter::Unconstrained,
7752                false,
7753                &[],
7754            );
7755            let parallel = count_run(
7756                store,
7757                CountWalkMode::Parallel(4),
7758                permutation,
7759                &pattern,
7760                snapshot,
7761                0,
7762                &GByteFilter::Unconstrained,
7763                false,
7764                &[],
7765            );
7766            assert_eq!(serial, expected, "{permutation:?} full-axis serial total");
7767            assert_eq!(
7768                parallel, serial,
7769                "{permutation:?} full-axis parallel must equal serial"
7770            );
7771        }
7772
7773        // Prefix-arena cases: bind each permutation's leading slot. The
7774        // typed-integer object and class cases carry the short (9-byte)
7775        // leading terms; the absent subject exercises the empty-arena
7776        // boundary machinery.
7777        let integer = NamedNode::new("http://www.w3.org/2001/XMLSchema#integer").unwrap();
7778        let term = |iri: &str| EncodedTerm::from(&NamedNode::new(iri).unwrap());
7779        let arena_cases: Vec<(&str, IndexPermutation, EncodedTriplePattern, bool)> = vec![
7780            (
7781                "IRI subject",
7782                IndexPermutation::Spog,
7783                EncodedTriplePattern {
7784                    subject: Some(term("http://ex/s0")),
7785                    ..unbound_pattern()
7786                },
7787                true,
7788            ),
7789            (
7790                "IRI subject (Sopg)",
7791                IndexPermutation::Sopg,
7792                EncodedTriplePattern {
7793                    subject: Some(term("http://ex/s0")),
7794                    ..unbound_pattern()
7795                },
7796                true,
7797            ),
7798            (
7799                "blank-node subject",
7800                IndexPermutation::Spog,
7801                EncodedTriplePattern {
7802                    subject: Some(EncodedTerm::from(&BlankNode::new_unchecked("b0"))),
7803                    ..unbound_pattern()
7804                },
7805                true,
7806            ),
7807            (
7808                "IRI predicate",
7809                IndexPermutation::Posg,
7810                EncodedTriplePattern {
7811                    predicate: Some(term("http://ex/p0")),
7812                    ..unbound_pattern()
7813                },
7814                true,
7815            ),
7816            (
7817                "IRI predicate (Psog)",
7818                IndexPermutation::Psog,
7819                EncodedTriplePattern {
7820                    predicate: Some(term("http://ex/p0")),
7821                    ..unbound_pattern()
7822                },
7823                true,
7824            ),
7825            (
7826                "IRI object",
7827                IndexPermutation::Opsg,
7828                EncodedTriplePattern {
7829                    object: Some(term("http://ex/o0")),
7830                    ..unbound_pattern()
7831                },
7832                true,
7833            ),
7834            (
7835                "plain literal object",
7836                IndexPermutation::Opsg,
7837                EncodedTriplePattern {
7838                    object: Some(EncodedTerm::from(&Literal::from("lit0"))),
7839                    ..unbound_pattern()
7840                },
7841                true,
7842            ),
7843            (
7844                "typed integer object (9-byte leading term)",
7845                IndexPermutation::Opsg,
7846                EncodedTriplePattern {
7847                    object: Some(EncodedTerm::from(&Literal::new_typed_literal(
7848                        "42",
7849                        integer.clone(),
7850                    ))),
7851                    ..unbound_pattern()
7852                },
7853                true,
7854            ),
7855            (
7856                "IRI class (Tsg arena)",
7857                IndexPermutation::Tsg,
7858                EncodedTriplePattern {
7859                    predicate: Some(crate::RDF_TYPE),
7860                    object: Some(term("http://ex/C0")),
7861                    ..unbound_pattern()
7862                },
7863                true,
7864            ),
7865            (
7866                "typed integer class (9-byte Tsg leading term)",
7867                IndexPermutation::Tsg,
7868                EncodedTriplePattern {
7869                    predicate: Some(crate::RDF_TYPE),
7870                    object: Some(EncodedTerm::from(&Literal::new_typed_literal(
7871                        "7",
7872                        integer.clone(),
7873                    ))),
7874                    ..unbound_pattern()
7875                },
7876                true,
7877            ),
7878            (
7879                "absent subject (empty arena)",
7880                IndexPermutation::Spog,
7881                EncodedTriplePattern {
7882                    subject: Some(term("http://ex/absent")),
7883                    ..unbound_pattern()
7884                },
7885                false,
7886            ),
7887        ];
7888        for (label, permutation, pattern, nonempty) in arena_cases {
7889            let store = store_for(permutation);
7890            let serial = count_run(
7891                store,
7892                CountWalkMode::Serial,
7893                permutation,
7894                &pattern,
7895                snapshot,
7896                0,
7897                &GByteFilter::Unconstrained,
7898                false,
7899                &[],
7900            );
7901            let parallel = count_run(
7902                store,
7903                CountWalkMode::Parallel(4),
7904                permutation,
7905                &pattern,
7906                snapshot,
7907                0,
7908                &GByteFilter::Unconstrained,
7909                false,
7910                &[],
7911            );
7912            assert_eq!(
7913                parallel, serial,
7914                "{label}: {permutation:?} arena parallel must equal serial"
7915            );
7916            assert_eq!(
7917                serial > 0,
7918                nonempty,
7919                "{label}: expected nonempty={nonempty}"
7920            );
7921        }
7922        drop(s_store);
7923        drop(p_store);
7924        drop(o_store);
7925        for dir in [&s_dir, &p_dir, &o_dir] {
7926            let _ = std::fs::remove_dir_all(dir);
7927        }
7928    }
7929
7930    /// Armed-filter pin for the count walks (the arming checklist's
7931    /// pattern-count requirement). With per-SST prefix filters force-armed
7932    /// at open (arming is a property of the OPENING process) and the
7933    /// corpus split across several SSTs by batched flushes, every count
7934    /// shape must stay exact: serial ≡ parallel ≡ the memory reference —
7935    /// full-axis byte-even, TSG hint-aligned, and prefix-arena alike. The
7936    /// corpus carries multi-version groups (a retired group and a
7937    /// not-yet-visible newest version) because single-version corpora
7938    /// never exercise the straddle path.
7939    #[test]
7940    fn count_walks_stay_exact_with_sst_filters_armed() {
7941        crate::rocksdb_db::TEST_SST_FILTER_FORCE_ON
7942            .store(true, std::sync::atomic::Ordering::Relaxed);
7943        let rdf_type = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
7944        let s_dir = count_store_dir("armed-s");
7945        let s_store = RocksDbStorage::open(&s_dir, PartitionAxis::S).unwrap();
7946        let s_memory = Storage::memory(PartitionAxis::S);
7947        let o_dir = count_store_dir("armed-o");
7948        let o_store = RocksDbStorage::open(&o_dir, PartitionAxis::O).unwrap();
7949        let o_memory = Storage::memory(PartitionAxis::O);
7950
7951        let put_both = |store: &RocksDbStorage, memory: &Storage, quad: &Quad, ts: u64| {
7952            store
7953                .insert_quad_version(
7954                    quad,
7955                    CommitTs(ts),
7956                    StorageOp::Put,
7957                    VisibilityLabel::default(),
7958                )
7959                .unwrap();
7960            memory
7961                .insert_quad_version(
7962                    quad,
7963                    CommitTs(ts),
7964                    StorageOp::Put,
7965                    VisibilityLabel::default(),
7966                )
7967                .unwrap();
7968        };
7969
7970        // S-axis corpus: plain and named rows only (rdf:type rows would ask
7971        // for the un-owned TSG family). Three batches, flushed apart, so
7972        // term ranges land in different SSTs.
7973        let mut s_expected = 0u64;
7974        let quad = |s: &str, p: &str, o: &str| {
7975            Quad::new(
7976                NamedNode::new(format!("http://ex/{s}")).unwrap(),
7977                NamedNode::new(format!("http://ex/{p}")).unwrap(),
7978                NamedNode::new(format!("http://ex/{o}")).unwrap(),
7979                GraphName::DefaultGraph,
7980            )
7981        };
7982        for i in 0..2 {
7983            put_both(&s_store, &s_memory, &quad("b1", "p0", &format!("w{i}")), 1);
7984            s_expected += 1;
7985        }
7986        s_store.flush_memtables().unwrap();
7987        s_memory.flush_memtables().unwrap();
7988        for i in 0..2 {
7989            put_both(&s_store, &s_memory, &quad("b2", "p1", &format!("x{i}")), 2);
7990            s_expected += 1;
7991        }
7992        let s_named = Quad::new(
7993            NamedNode::new("http://ex/b3").unwrap(),
7994            NamedNode::new("http://ex/p2").unwrap(),
7995            NamedNode::new("http://ex/n0").unwrap(),
7996            GraphName::NamedNode(NamedNode::new("http://ex/g0").unwrap()),
7997        );
7998        put_both(&s_store, &s_memory, &s_named, 3);
7999        s_expected += 1;
8000        s_store.flush_memtables().unwrap();
8001        s_memory.flush_memtables().unwrap();
8002        // Multi-version groups: m1 retired by its newest Delete; m2's
8003        // newest Put(9) is beyond snapshot 5, so Put(3) is the visible one.
8004        let m1 = quad("b4", "p0", "m1");
8005        put_both(&s_store, &s_memory, &m1, 1);
8006        s_store
8007            .insert_quad_version(
8008                &m1,
8009                CommitTs(2),
8010                StorageOp::Delete,
8011                VisibilityLabel::default(),
8012            )
8013            .unwrap();
8014        s_memory
8015            .insert_quad_version(
8016                &m1,
8017                CommitTs(2),
8018                StorageOp::Delete,
8019                VisibilityLabel::default(),
8020            )
8021            .unwrap();
8022        let m2 = quad("b5", "p0", "m2");
8023        put_both(&s_store, &s_memory, &m2, 3);
8024        s_store
8025            .insert_quad_version(&m2, CommitTs(9), StorageOp::Put, VisibilityLabel::default())
8026            .unwrap();
8027        s_memory
8028            .insert_quad_version(&m2, CommitTs(9), StorageOp::Put, VisibilityLabel::default())
8029            .unwrap();
8030        s_store.flush_memtables().unwrap();
8031        s_memory.flush_memtables().unwrap();
8032        // m1's group is retired (its Put was counted above), m2 contributes
8033        // exactly one visible version.
8034        let s_expected = s_expected + 1;
8035
8036        // O-axis corpus: type rows across three classes (TSG + Opsg), plain
8037        // rows, one named row, and the same multi-version groups.
8038        let mut o_expected = 0u64;
8039        let batch = |store: &RocksDbStorage,
8040                     memory: &Storage,
8041                     quads: Vec<Quad>,
8042                     ts: u64,
8043                     o_expected: &mut u64| {
8044            for quad in &quads {
8045                put_both(store, memory, quad, ts);
8046                *o_expected += 1;
8047            }
8048        };
8049        let c0: Vec<Quad> = (0..4)
8050            .map(|i| {
8051                Quad::new(
8052                    NamedNode::new(format!("http://ex/s{i}")).unwrap(),
8053                    rdf_type.clone(),
8054                    NamedNode::new("http://ex/C0").unwrap(),
8055                    GraphName::DefaultGraph,
8056                )
8057            })
8058            .collect();
8059        batch(&o_store, &o_memory, c0, 1, &mut o_expected);
8060        o_store.flush_memtables().unwrap();
8061        o_memory.flush_memtables().unwrap();
8062        let c1: Vec<Quad> = (4..8)
8063            .map(|i| {
8064                Quad::new(
8065                    NamedNode::new(format!("http://ex/s{i}")).unwrap(),
8066                    rdf_type.clone(),
8067                    NamedNode::new("http://ex/C1").unwrap(),
8068                    GraphName::DefaultGraph,
8069                )
8070            })
8071            .collect();
8072        batch(&o_store, &o_memory, c1, 2, &mut o_expected);
8073        let o_named = Quad::new(
8074            NamedNode::new("http://ex/n0").unwrap(),
8075            NamedNode::new("http://ex/p2").unwrap(),
8076            NamedNode::new("http://ex/n1").unwrap(),
8077            GraphName::NamedNode(NamedNode::new("http://ex/g0").unwrap()),
8078        );
8079        batch(&o_store, &o_memory, vec![o_named], 2, &mut o_expected);
8080        o_store.flush_memtables().unwrap();
8081        o_memory.flush_memtables().unwrap();
8082        let c2: Vec<Quad> = (8..12)
8083            .map(|i| {
8084                Quad::new(
8085                    NamedNode::new(format!("http://ex/s{i}")).unwrap(),
8086                    rdf_type.clone(),
8087                    NamedNode::new("http://ex/C2").unwrap(),
8088                    GraphName::DefaultGraph,
8089                )
8090            })
8091            .collect();
8092        batch(&o_store, &o_memory, c2, 3, &mut o_expected);
8093        batch(
8094            &o_store,
8095            &o_memory,
8096            vec![quad("p1", "q0", "y0")],
8097            3,
8098            &mut o_expected,
8099        );
8100        let om1 = Quad::new(
8101            NamedNode::new("http://ex/p2").unwrap(),
8102            NamedNode::new("http://ex/q1").unwrap(),
8103            NamedNode::new("http://ex/m1").unwrap(),
8104            GraphName::DefaultGraph,
8105        );
8106        batch(&o_store, &o_memory, vec![om1.clone()], 1, &mut o_expected);
8107        o_store
8108            .insert_quad_version(
8109                &om1,
8110                CommitTs(2),
8111                StorageOp::Delete,
8112                VisibilityLabel::default(),
8113            )
8114            .unwrap();
8115        o_memory
8116            .insert_quad_version(
8117                &om1,
8118                CommitTs(2),
8119                StorageOp::Delete,
8120                VisibilityLabel::default(),
8121            )
8122            .unwrap();
8123        let om2 = Quad::new(
8124            NamedNode::new("http://ex/p2").unwrap(),
8125            NamedNode::new("http://ex/q1").unwrap(),
8126            NamedNode::new("http://ex/m2").unwrap(),
8127            GraphName::DefaultGraph,
8128        );
8129        batch(&o_store, &o_memory, vec![om2.clone()], 3, &mut o_expected);
8130        o_store
8131            .insert_quad_version(
8132                &om2,
8133                CommitTs(9),
8134                StorageOp::Put,
8135                VisibilityLabel::default(),
8136            )
8137            .unwrap();
8138        o_memory
8139            .insert_quad_version(
8140                &om2,
8141                CommitTs(9),
8142                StorageOp::Put,
8143                VisibilityLabel::default(),
8144            )
8145            .unwrap();
8146        o_store.flush_memtables().unwrap();
8147        o_memory.flush_memtables().unwrap();
8148        // om1 retired, om2 one visible version: 12 type + 1 plain + 1 named
8149        // + 1 visible om2 = 15 Opsg; TSG holds the 12 type rows only.
8150        let o_expected = o_expected - 1;
8151        let tsg_expected = 12u64;
8152        let snapshot = SnapshotId(5);
8153
8154        // Full-axis, S store (spog is filter-marked; serial, parallel,
8155        // memory reference must all agree).
8156        let s_serial = count_run(
8157            &s_store,
8158            CountWalkMode::Serial,
8159            IndexPermutation::Spog,
8160            &unbound_pattern(),
8161            snapshot,
8162            0,
8163            &GByteFilter::Unconstrained,
8164            false,
8165            &[],
8166        );
8167        let s_parallel = count_run(
8168            &s_store,
8169            CountWalkMode::Parallel(4),
8170            IndexPermutation::Spog,
8171            &unbound_pattern(),
8172            snapshot,
8173            0,
8174            &GByteFilter::Unconstrained,
8175            false,
8176            &[],
8177        );
8178        let s_memory_count = s_memory
8179            .count_pattern_impl(
8180                IndexPermutation::Spog,
8181                &unbound_pattern(),
8182                snapshot,
8183                0,
8184                GByteFilter::Unconstrained,
8185                false,
8186            )
8187            .unwrap();
8188        assert_eq!(s_serial, s_expected, "armed full-axis Spog serial");
8189        assert_eq!(s_parallel, s_serial, "armed full-axis Spog parallel");
8190        assert_eq!(s_memory_count, s_serial, "armed full-axis Spog vs memory");
8191
8192        // Prefix-arena, S store: bound subject.
8193        let s_arena_pattern = EncodedTriplePattern {
8194            subject: Some(EncodedTerm::from(&NamedNode::new("http://ex/b2").unwrap())),
8195            ..unbound_pattern()
8196        };
8197        let s_arena_serial = count_run(
8198            &s_store,
8199            CountWalkMode::Serial,
8200            IndexPermutation::Spog,
8201            &s_arena_pattern,
8202            snapshot,
8203            0,
8204            &GByteFilter::Unconstrained,
8205            false,
8206            &[],
8207        );
8208        let s_arena_parallel = count_run(
8209            &s_store,
8210            CountWalkMode::Parallel(4),
8211            IndexPermutation::Spog,
8212            &s_arena_pattern,
8213            snapshot,
8214            0,
8215            &GByteFilter::Unconstrained,
8216            false,
8217            &[],
8218        );
8219        assert_eq!(s_arena_serial, 2, "armed arena Spog serial");
8220        assert_eq!(
8221            s_arena_parallel, s_arena_serial,
8222            "armed arena Spog parallel"
8223        );
8224
8225        // Full-axis, O store: TSG (filter-marked) and Opsg.
8226        let tsg_pattern = EncodedTriplePattern {
8227            predicate: Some(crate::RDF_TYPE),
8228            ..unbound_pattern()
8229        };
8230        let tsg_serial = count_run(
8231            &o_store,
8232            CountWalkMode::Serial,
8233            IndexPermutation::Tsg,
8234            &tsg_pattern,
8235            snapshot,
8236            0,
8237            &GByteFilter::Unconstrained,
8238            false,
8239            &[],
8240        );
8241        let tsg_parallel = count_run(
8242            &o_store,
8243            CountWalkMode::Parallel(4),
8244            IndexPermutation::Tsg,
8245            &tsg_pattern,
8246            snapshot,
8247            0,
8248            &GByteFilter::Unconstrained,
8249            false,
8250            &[],
8251        );
8252        assert_eq!(tsg_serial, tsg_expected, "armed full-axis TSG serial");
8253        assert_eq!(tsg_parallel, tsg_serial, "armed full-axis TSG parallel");
8254
8255        // TSG hint-aligned shape: exact per-class totals, ascending order.
8256        let mut hint: Vec<(StrHash, u64)> = ["http://ex/C0", "http://ex/C1", "http://ex/C2"]
8257            .iter()
8258            .map(|class| (StrHash::new(class), 4))
8259            .collect();
8260        hint.sort_by_key(|(hash, _)| *hash);
8261        let tsg_hint_parallel = count_run(
8262            &o_store,
8263            CountWalkMode::Parallel(4),
8264            IndexPermutation::Tsg,
8265            &tsg_pattern,
8266            snapshot,
8267            0,
8268            &GByteFilter::Unconstrained,
8269            false,
8270            &hint,
8271        );
8272        assert_eq!(
8273            tsg_hint_parallel, tsg_serial,
8274            "armed hint-aligned TSG parallel"
8275        );
8276
8277        // TSG prefix-arena: bound class.
8278        let tsg_arena_pattern = EncodedTriplePattern {
8279            predicate: Some(crate::RDF_TYPE),
8280            object: Some(EncodedTerm::from(&NamedNode::new("http://ex/C0").unwrap())),
8281            ..unbound_pattern()
8282        };
8283        let tsg_arena_serial = count_run(
8284            &o_store,
8285            CountWalkMode::Serial,
8286            IndexPermutation::Tsg,
8287            &tsg_arena_pattern,
8288            snapshot,
8289            0,
8290            &GByteFilter::Unconstrained,
8291            false,
8292            &[],
8293        );
8294        let tsg_arena_parallel = count_run(
8295            &o_store,
8296            CountWalkMode::Parallel(4),
8297            IndexPermutation::Tsg,
8298            &tsg_arena_pattern,
8299            snapshot,
8300            0,
8301            &GByteFilter::Unconstrained,
8302            false,
8303            &[],
8304        );
8305        assert_eq!(tsg_arena_serial, 4, "armed TSG arena serial");
8306        assert_eq!(
8307            tsg_arena_parallel, tsg_arena_serial,
8308            "armed TSG arena parallel"
8309        );
8310
8311        // Opsg full-axis on the O store agrees with the memory reference.
8312        let opsg_serial = count_run(
8313            &o_store,
8314            CountWalkMode::Serial,
8315            IndexPermutation::Opsg,
8316            &unbound_pattern(),
8317            snapshot,
8318            0,
8319            &GByteFilter::Unconstrained,
8320            false,
8321            &[],
8322        );
8323        let opsg_parallel = count_run(
8324            &o_store,
8325            CountWalkMode::Parallel(4),
8326            IndexPermutation::Opsg,
8327            &unbound_pattern(),
8328            snapshot,
8329            0,
8330            &GByteFilter::Unconstrained,
8331            false,
8332            &[],
8333        );
8334        let o_memory_count = o_memory
8335            .count_pattern_impl(
8336                IndexPermutation::Opsg,
8337                &unbound_pattern(),
8338                snapshot,
8339                0,
8340                GByteFilter::Unconstrained,
8341                false,
8342            )
8343            .unwrap();
8344        assert_eq!(opsg_serial, o_expected, "armed full-axis Opsg serial");
8345        assert_eq!(opsg_parallel, opsg_serial, "armed full-axis Opsg parallel");
8346        assert_eq!(
8347            o_memory_count, opsg_serial,
8348            "armed full-axis Opsg vs memory"
8349        );
8350        drop(s_store);
8351        drop(o_store);
8352        drop(s_memory);
8353        drop(o_memory);
8354        let _ = std::fs::remove_dir_all(&s_dir);
8355        let _ = std::fs::remove_dir_all(&o_dir);
8356    }
8357
8358    #[test]
8359    fn count_walks_env_parse_mirrors_domain_walks() {
8360        assert_eq!(count_walks_from_env(None), None);
8361        assert_eq!(count_walks_from_env(Some("8")), Some(8));
8362        assert_eq!(count_walks_from_env(Some(" 16 ")), Some(16));
8363        assert_eq!(count_walks_from_env(Some("0")), None);
8364        assert_eq!(count_walks_from_env(Some("1")), None);
8365        assert_eq!(count_walks_from_env(Some("junk")), None);
8366        assert_eq!(
8367            count_walks_from_env(Some("1000")),
8368            Some(super::COUNT_WALKS_MAX)
8369        );
8370    }
8371
8372    #[test]
8373    fn even_boundaries_ascending_and_region_scoped() {
8374        let prefix = vec![0x01, 0xAA];
8375        // LUBM-style arena: every leading term is a NamedNode (tag 1), so
8376        // boundaries must live inside the tag-1 region — not above it in the
8377        // raw byte space (the all-in-slice-0 failure mode).
8378        let boundaries = even_boundaries(&prefix, 0x01, 8);
8379        assert_eq!(boundaries.len(), 7);
8380        for boundary in &boundaries {
8381            assert!(boundary.starts_with(&prefix), "boundary shares the prefix");
8382            assert_eq!(
8383                boundary[prefix.len()],
8384                0x01,
8385                "boundary inside the dominant tag region"
8386            );
8387        }
8388        for pair in boundaries.windows(2) {
8389            assert!(pair[0] < pair[1], "boundaries strictly ascend");
8390        }
8391        assert!(even_boundaries(&prefix, 0x01, 1).is_empty());
8392    }
8393
8394    #[test]
8395    fn count_walk_plan_shape_matrix() {
8396        let unbound = EncodedTriplePattern {
8397            subject: None,
8398            predicate: None,
8399            object: None,
8400            graph_name: None,
8401        };
8402        let subject = EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap());
8403        let predicate = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
8404        let class = EncodedTerm::from(&NamedNode::new("http://ex/C").unwrap());
8405        let graph = EncodedTerm::from(&NamedNode::new("http://ex/g").unwrap());
8406
8407        // Full axis: empty prefix, slices cover from the CF start.
8408        let plan = count_walk_plan(
8409            4,
8410            IndexPermutation::Spog,
8411            &unbound,
8412            &GByteFilter::Unconstrained,
8413            &[],
8414            || 0x01,
8415        )
8416        .unwrap();
8417        assert!(plan.prefix.is_empty());
8418        assert_eq!(plan.slices.len(), 4);
8419        assert!(plan.slices[0].start.is_empty());
8420        assert!(plan.slices.last().unwrap().end.is_none());
8421        for pair in plan.slices.windows(2) {
8422            assert_eq!(pair[0].end.as_deref(), Some(pair[1].start.as_slice()));
8423        }
8424
8425        // Prefix arena (leading bound, nothing else): slices inside the
8426        // bound term's encoded span.
8427        let bound_subject = EncodedTriplePattern {
8428            subject: Some(subject.clone()),
8429            predicate: None,
8430            object: None,
8431            graph_name: None,
8432        };
8433        let plan = count_walk_plan(
8434            4,
8435            IndexPermutation::Spog,
8436            &bound_subject,
8437            &GByteFilter::Unconstrained,
8438            &[],
8439            || 0x01,
8440        )
8441        .unwrap();
8442        assert!(!plan.prefix.is_empty());
8443        assert!(
8444            plan.slices
8445                .iter()
8446                .all(|slice| slice.start.starts_with(&plan.prefix))
8447        );
8448
8449        // Non-leading bound on a hexastore axis: serial.
8450        let bound_predicate = EncodedTriplePattern {
8451            subject: None,
8452            predicate: Some(predicate),
8453            object: None,
8454            graph_name: None,
8455        };
8456        assert!(
8457            count_walk_plan(
8458                4,
8459                IndexPermutation::Spog,
8460                &bound_predicate,
8461                &GByteFilter::Unconstrained,
8462                &[],
8463                || 0x01,
8464            )
8465            .is_none()
8466        );
8467
8468        // A named graph bound in the pattern's graph slot: serial (scoping
8469        // `DefaultGraph` stays eligible).
8470        let bound_graph = EncodedTriplePattern {
8471            subject: None,
8472            predicate: None,
8473            object: None,
8474            graph_name: Some(graph),
8475        };
8476        assert!(
8477            count_walk_plan(
8478                4,
8479                IndexPermutation::Spog,
8480                &bound_graph,
8481                &GByteFilter::Unconstrained,
8482                &[],
8483                || 0x01,
8484            )
8485            .is_none()
8486        );
8487        let default_scoped = EncodedTriplePattern {
8488            subject: None,
8489            predicate: None,
8490            object: None,
8491            graph_name: Some(EncodedTerm::DefaultGraph),
8492        };
8493        assert!(
8494            count_walk_plan(
8495                4,
8496                IndexPermutation::Spog,
8497                &default_scoped,
8498                &GByteFilter::Unconstrained,
8499                &[],
8500                || 0x01,
8501            )
8502            .is_some()
8503        );
8504
8505        // TSG arena (class bound, subject unbound): byte-even in the class
8506        // span.
8507        let tsg_arena = EncodedTriplePattern {
8508            subject: None,
8509            predicate: Some(crate::RDF_TYPE),
8510            object: Some(class.clone()),
8511            graph_name: None,
8512        };
8513        let plan = count_walk_plan(
8514            4,
8515            IndexPermutation::Tsg,
8516            &tsg_arena,
8517            &GByteFilter::Unconstrained,
8518            &[],
8519            || 0x01,
8520        )
8521        .unwrap();
8522        assert!(!plan.prefix.is_empty());
8523        assert!(
8524            plan.slices
8525                .iter()
8526                .all(|slice| slice.start.starts_with(&plan.prefix))
8527        );
8528
8529        // TSG with a bound subject: serial.
8530        let tsg_subject = EncodedTriplePattern {
8531            subject: Some(subject),
8532            predicate: Some(crate::RDF_TYPE),
8533            object: Some(class),
8534            graph_name: None,
8535        };
8536        assert!(
8537            count_walk_plan(
8538                4,
8539                IndexPermutation::Tsg,
8540                &tsg_subject,
8541                &GByteFilter::Unconstrained,
8542                &[],
8543                || 0x01,
8544            )
8545            .is_none()
8546        );
8547
8548        // TSG full axis with a usable hint: boundaries land exactly on
8549        // class-term starts. Totals are equal so the greedy cut fires after
8550        // the first class regardless of hash sort order.
8551        let hash_a = StrHash::new("http://ex/A");
8552        let hash_b = StrHash::new("http://ex/B");
8553        let mut hint = vec![(hash_b, 40u64), (hash_a, 40u64)];
8554        hint.sort_by_key(|(hash, _)| *hash);
8555        let plan = count_walk_plan(
8556            2,
8557            IndexPermutation::Tsg,
8558            &unbound,
8559            &GByteFilter::Unconstrained,
8560            &hint,
8561            || 0x01,
8562        )
8563        .unwrap();
8564        let expected =
8565            crate::encode::encode_term_bytes(&EncodedTerm::NamedNode { iri_id: hint[1].0 });
8566        assert_eq!(plan.slices.len(), 2);
8567        assert_eq!(plan.slices[0].end.as_deref(), Some(expected.as_slice()));
8568        assert_eq!(plan.slices[0].start, Vec::<u8>::new());
8569        assert!(plan.slices[1].end.is_none());
8570
8571        // Zeroed hint cannot cut: byte-even fallback.
8572        let stale = vec![(hash_a, 0u64), (hash_b, 0u64)];
8573        let plan = count_walk_plan(
8574            2,
8575            IndexPermutation::Tsg,
8576            &unbound,
8577            &GByteFilter::Unconstrained,
8578            &stale,
8579            || 0x01,
8580        )
8581        .unwrap();
8582        assert!(
8583            plan.slices[0]
8584                .end
8585                .as_ref()
8586                .unwrap()
8587                .starts_with(&plan.prefix)
8588        );
8589    }
8590
8591    #[test]
8592    fn full_axis_count_parallel_matches_serial() {
8593        for permutation in [IndexPermutation::Spog, IndexPermutation::Sopg] {
8594            let dir = count_store_dir("fa");
8595            let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
8596            for i in 0..300u64 {
8597                store
8598                    .insert_quad_version(
8599                        &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
8600                        CommitTs(1),
8601                        StorageOp::Put,
8602                        VisibilityLabel::default(),
8603                    )
8604                    .unwrap();
8605            }
8606            store.flush_memtables().unwrap();
8607            let pattern = unbound_pattern();
8608            let serial = count_run(
8609                &store,
8610                CountWalkMode::Serial,
8611                permutation,
8612                &pattern,
8613                SnapshotId(9),
8614                0,
8615                &GByteFilter::Unconstrained,
8616                false,
8617                &[],
8618            );
8619            assert_eq!(serial, 300);
8620            for workers in [2usize, 3, 7, 64] {
8621                let parallel = count_run(
8622                    &store,
8623                    CountWalkMode::Parallel(workers),
8624                    permutation,
8625                    &pattern,
8626                    SnapshotId(9),
8627                    0,
8628                    &GByteFilter::Unconstrained,
8629                    false,
8630                    &[],
8631                );
8632                assert_eq!(parallel, serial, "permutation {permutation:?} K={workers}");
8633            }
8634            drop(store);
8635            let _ = std::fs::remove_dir_all(&dir);
8636        }
8637    }
8638
8639    #[test]
8640    fn prefix_arena_count_parallel_matches_serial() {
8641        let dir = count_store_dir("arena");
8642        let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
8643        for i in 0..120u64 {
8644            store
8645                .insert_quad_version(
8646                    &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
8647                    CommitTs(1),
8648                    StorageOp::Put,
8649                    VisibilityLabel::default(),
8650                )
8651                .unwrap();
8652        }
8653        store.flush_memtables().unwrap();
8654        let subject = EncodedTerm::from(&NamedNode::new("http://ex/s7").unwrap());
8655        let pattern = EncodedTriplePattern {
8656            subject: Some(subject),
8657            predicate: None,
8658            object: None,
8659            graph_name: None,
8660        };
8661        let serial = count_run(
8662            &store,
8663            CountWalkMode::Serial,
8664            IndexPermutation::Spog,
8665            &pattern,
8666            SnapshotId(9),
8667            0,
8668            &GByteFilter::Unconstrained,
8669            false,
8670            &[],
8671        );
8672        assert_eq!(serial, 1, "one quad for s7 in the Spog CF");
8673        for workers in [2usize, 5, 64] {
8674            let parallel = count_run(
8675                &store,
8676                CountWalkMode::Parallel(workers),
8677                IndexPermutation::Spog,
8678                &pattern,
8679                SnapshotId(9),
8680                0,
8681                &GByteFilter::Unconstrained,
8682                false,
8683                &[],
8684            );
8685            assert_eq!(parallel, serial, "K={workers}");
8686        }
8687        drop(store);
8688        let _ = std::fs::remove_dir_all(&dir);
8689    }
8690
8691    /// The straddle trap in its sharpest form: quad Q has three versions and
8692    /// the newest is a `Delete`, so only the slice holding Q's newest key may
8693    /// retire it. A slice starting at an older version must skip the whole
8694    /// group; a naive in-slice decision would resurrect the group and count
8695    /// it twice against the serial walk.
8696    #[test]
8697    fn version_group_straddle_skip_decides_once() {
8698        let dir = count_store_dir("straddle");
8699        let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
8700        let q = Quad::new(
8701            NamedNode::new("http://ex/q").unwrap(),
8702            NamedNode::new("http://ex/p").unwrap(),
8703            NamedNode::new("http://ex/oq").unwrap(),
8704            GraphName::DefaultGraph,
8705        );
8706        let r = Quad::new(
8707            NamedNode::new("http://ex/r").unwrap(),
8708            NamedNode::new("http://ex/p").unwrap(),
8709            NamedNode::new("http://ex/or").unwrap(),
8710            GraphName::DefaultGraph,
8711        );
8712        let q_enc = EncodedQuad::from(&q);
8713        store
8714            .insert_quad_version(&q, CommitTs(10), StorageOp::Put, VisibilityLabel::default())
8715            .unwrap();
8716        store
8717            .insert_quad_version(&q, CommitTs(20), StorageOp::Put, VisibilityLabel::default())
8718            .unwrap();
8719        store
8720            .insert_quad_version(
8721                &q,
8722                CommitTs(30),
8723                StorageOp::Delete,
8724                VisibilityLabel::default(),
8725            )
8726            .unwrap();
8727        store
8728            .insert_quad_version(&r, CommitTs(5), StorageOp::Put, VisibilityLabel::default())
8729            .unwrap();
8730        store.flush_memtables().unwrap();
8731
8732        let pattern = unbound_pattern();
8733        let serial = count_run(
8734            &store,
8735            CountWalkMode::Serial,
8736            IndexPermutation::Spog,
8737            &pattern,
8738            SnapshotId(100),
8739            0,
8740            &GByteFilter::Unconstrained,
8741            false,
8742            &[],
8743        );
8744        assert_eq!(serial, 1, "Q retired by its newest Delete; only R remains");
8745
8746        // Manual split exactly inside Q's version group: the second slice
8747        // starts at the ts=20 version while the newest (ts=30) sorts before
8748        // it, in slice one.
8749        let mid_group = encode_versioned_key(IndexPermutation::Spog, &q_enc, CommitTs(20));
8750        let cf = store.cf_for(IndexPermutation::Spog).unwrap();
8751        let head = count_walk_slice(
8752            &store.db,
8753            cf,
8754            IndexPermutation::Spog,
8755            &pattern,
8756            SnapshotId(100),
8757            &GByteFilter::Unconstrained,
8758            false,
8759            &[],
8760            &CountSlice {
8761                start: Vec::new(),
8762                end: Some(mid_group.clone()),
8763            },
8764            true,
8765        )
8766        .unwrap();
8767        let tail = count_walk_slice(
8768            &store.db,
8769            cf,
8770            IndexPermutation::Spog,
8771            &pattern,
8772            SnapshotId(100),
8773            &GByteFilter::Unconstrained,
8774            false,
8775            &[],
8776            &CountSlice {
8777                start: mid_group,
8778                end: None,
8779            },
8780            false,
8781        )
8782        .unwrap();
8783        assert_eq!(
8784            head + tail,
8785            serial,
8786            "split inside the group must not double-count"
8787        );
8788        drop(store);
8789        let _ = std::fs::remove_dir_all(&dir);
8790    }
8791
8792    /// The straddle trap the first test cannot reach: the boundary falls
8793    /// strictly BETWEEN the newest version (ts=90) and the visible version
8794    /// (ts=50, snapshot 60). The head slice holds the newest — the decision
8795    /// owner — but the visible version sorts past its end, so the owner must
8796    /// cross its own boundary to finish the group; the tail slice's probe
8797    /// must skip the group without swallowing the decision. Without the
8798    /// crossing rule the parallel total is 0 against a serial 1.
8799    #[test]
8800    fn straddle_between_versions_owner_crosses_its_end() {
8801        let dir = count_store_dir("straddle-cross");
8802        let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
8803        let q = Quad::new(
8804            NamedNode::new("http://ex/qx").unwrap(),
8805            NamedNode::new("http://ex/p").unwrap(),
8806            NamedNode::new("http://ex/ox").unwrap(),
8807            GraphName::DefaultGraph,
8808        );
8809        for ts in [10u64, 50, 90] {
8810            store
8811                .insert_quad_version(&q, CommitTs(ts), StorageOp::Put, VisibilityLabel::default())
8812                .unwrap();
8813        }
8814        store.flush_memtables().unwrap();
8815        let pattern = unbound_pattern();
8816        let serial = count_run(
8817            &store,
8818            CountWalkMode::Serial,
8819            IndexPermutation::Spog,
8820            &pattern,
8821            SnapshotId(60),
8822            0,
8823            &GByteFilter::Unconstrained,
8824            false,
8825            &[],
8826        );
8827        assert_eq!(serial, 1, "snapshot 60 sees exactly the ts=50 version");
8828
8829        // Boundary strictly between the ts=90 and ts=50 keys: the newest
8830        // key with a 0x00 byte appended sorts after the newest and before
8831        // the next version (both share the term prefix; ts=50's descending
8832        // suffix byte exceeds ts=90's at the first difference, and 0x00 is
8833        // below both).
8834        let newest =
8835            encode_versioned_key(IndexPermutation::Spog, &EncodedQuad::from(&q), CommitTs(90));
8836        let boundary = {
8837            let mut b = newest.clone();
8838            b.push(0x00);
8839            b
8840        };
8841        let cf = store.cf_for(IndexPermutation::Spog).unwrap();
8842        let head = count_walk_slice(
8843            &store.db,
8844            cf,
8845            IndexPermutation::Spog,
8846            &pattern,
8847            SnapshotId(60),
8848            &GByteFilter::Unconstrained,
8849            false,
8850            &[],
8851            &CountSlice {
8852                start: Vec::new(),
8853                end: Some(boundary.clone()),
8854            },
8855            true,
8856        )
8857        .unwrap();
8858        let tail = count_walk_slice(
8859            &store.db,
8860            cf,
8861            IndexPermutation::Spog,
8862            &pattern,
8863            SnapshotId(60),
8864            &GByteFilter::Unconstrained,
8865            false,
8866            &[],
8867            &CountSlice {
8868                start: boundary,
8869                end: None,
8870            },
8871            false,
8872        )
8873        .unwrap();
8874        assert_eq!(
8875            head, 1,
8876            "owner crosses its end and emits the visible version"
8877        );
8878        assert_eq!(tail, 0, "the straddled group is skipped, not re-decided");
8879        assert_eq!(head + tail, serial);
8880        drop(store);
8881        let _ = std::fs::remove_dir_all(&dir);
8882    }
8883
8884    /// Sibling logicals that extend another's term prefix — named-graph
8885    /// variants of a default-graph triple, whose graph term encodes to zero
8886    /// bytes — sort before the graph-less group (term tags precede the
8887    /// 0xFF-leading descending-ts bytes) and are different groups. Pin the
8888    /// skip's exact-length semantics: a tail slice opening inside the
8889    /// graph-less group skips only that group's version keys and still
8890    /// counts the named-graph variant.
8891    #[test]
8892    fn straddle_skip_spares_sibling_graph_variants() {
8893        let dir = count_store_dir("straddle-sib");
8894        let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
8895        let dg = Quad::new(
8896            NamedNode::new("http://ex/qs").unwrap(),
8897            NamedNode::new("http://ex/p").unwrap(),
8898            NamedNode::new("http://ex/od").unwrap(),
8899            GraphName::DefaultGraph,
8900        );
8901        let named = Quad::new(
8902            NamedNode::new("http://ex/qs").unwrap(),
8903            NamedNode::new("http://ex/p").unwrap(),
8904            NamedNode::new("http://ex/od").unwrap(),
8905            GraphName::NamedNode(NamedNode::new("http://ex/g").unwrap()),
8906        );
8907        store
8908            .insert_quad_version(
8909                &dg,
8910                CommitTs(10),
8911                StorageOp::Put,
8912                VisibilityLabel::default(),
8913            )
8914            .unwrap();
8915        store
8916            .insert_quad_version(
8917                &dg,
8918                CommitTs(20),
8919                StorageOp::Delete,
8920                VisibilityLabel::default(),
8921            )
8922            .unwrap();
8923        store
8924            .insert_quad_version(
8925                &named,
8926                CommitTs(5),
8927                StorageOp::Put,
8928                VisibilityLabel::default(),
8929            )
8930            .unwrap();
8931        store.flush_memtables().unwrap();
8932        let pattern = unbound_pattern();
8933        let serial = count_run(
8934            &store,
8935            CountWalkMode::Serial,
8936            IndexPermutation::Spog,
8937            &pattern,
8938            SnapshotId(100),
8939            0,
8940            &GByteFilter::Unconstrained,
8941            false,
8942            &[],
8943        );
8944        assert_eq!(
8945            serial, 1,
8946            "default-graph group retired by its newest Delete; named variant counts"
8947        );
8948
8949        // Tail opens at the ts=10 key: inside the default-graph group, whose
8950        // newest (ts=20, the Delete) sorts before the boundary.
8951        let tail_start = encode_versioned_key(
8952            IndexPermutation::Spog,
8953            &EncodedQuad::from(&dg),
8954            CommitTs(10),
8955        );
8956        let cf = store.cf_for(IndexPermutation::Spog).unwrap();
8957        let head = count_walk_slice(
8958            &store.db,
8959            cf,
8960            IndexPermutation::Spog,
8961            &pattern,
8962            SnapshotId(100),
8963            &GByteFilter::Unconstrained,
8964            false,
8965            &[],
8966            &CountSlice {
8967                start: Vec::new(),
8968                end: Some(tail_start.clone()),
8969            },
8970            true,
8971        )
8972        .unwrap();
8973        let tail = count_walk_slice(
8974            &store.db,
8975            cf,
8976            IndexPermutation::Spog,
8977            &pattern,
8978            SnapshotId(100),
8979            &GByteFilter::Unconstrained,
8980            false,
8981            &[],
8982            &CountSlice {
8983                start: tail_start,
8984                end: None,
8985            },
8986            false,
8987        )
8988        .unwrap();
8989        assert_eq!(head + tail, serial, "named variant counted exactly once");
8990        drop(store);
8991        let _ = std::fs::remove_dir_all(&dir);
8992    }
8993
8994    /// `merge_default_graph` keeps parallel counts exact by falling back to
8995    /// the serial walk: its graph-variant dedup state is per-walk, so a
8996    /// boundary between two graph variants of one triple would count the
8997    /// triple twice.
8998    #[test]
8999    fn merge_default_graph_parallel_matches_serial() {
9000        let dir = count_store_dir("merge");
9001        let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
9002        for i in 0..40u64 {
9003            store
9004                .insert_quad_version(
9005                    &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
9006                    CommitTs(1),
9007                    StorageOp::Put,
9008                    VisibilityLabel::default(),
9009                )
9010                .unwrap();
9011        }
9012        store.flush_memtables().unwrap();
9013        let pattern = unbound_pattern();
9014        let serial = count_run(
9015            &store,
9016            CountWalkMode::Serial,
9017            IndexPermutation::Spog,
9018            &pattern,
9019            SnapshotId(9),
9020            0,
9021            &GByteFilter::Unconstrained,
9022            true,
9023            &[],
9024        );
9025        assert_eq!(serial, 40);
9026        let parallel = count_run(
9027            &store,
9028            CountWalkMode::Parallel(4),
9029            IndexPermutation::Spog,
9030            &pattern,
9031            SnapshotId(9),
9032            0,
9033            &GByteFilter::Unconstrained,
9034            true,
9035            &[],
9036        );
9037        assert_eq!(parallel, serial);
9038        drop(store);
9039        let _ = std::fs::remove_dir_all(&dir);
9040    }
9041
9042    /// Snapshot visibility across a split: with versions 10/50/90 `Put` and
9043    /// snapshot 60, the visible version is 50 — the slice holding the newest
9044    /// key (90) walks the group newest-first and counts once; a slice
9045    /// starting at 90 itself must transparently pass the too-new version and
9046    /// still yield the same total as the serial walk.
9047    #[test]
9048    fn snapshot_visibility_identical_across_split() {
9049        let dir = count_store_dir("snapshot");
9050        let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
9051        let q = Quad::new(
9052            NamedNode::new("http://ex/q2").unwrap(),
9053            NamedNode::new("http://ex/p").unwrap(),
9054            NamedNode::new("http://ex/o").unwrap(),
9055            GraphName::DefaultGraph,
9056        );
9057        for ts in [10u64, 50, 90] {
9058            store
9059                .insert_quad_version(&q, CommitTs(ts), StorageOp::Put, VisibilityLabel::default())
9060                .unwrap();
9061        }
9062        store.flush_memtables().unwrap();
9063        let pattern = unbound_pattern();
9064        let serial = count_run(
9065            &store,
9066            CountWalkMode::Serial,
9067            IndexPermutation::Spog,
9068            &pattern,
9069            SnapshotId(60),
9070            0,
9071            &GByteFilter::Unconstrained,
9072            false,
9073            &[],
9074        );
9075        assert_eq!(serial, 1);
9076        let newest =
9077            encode_versioned_key(IndexPermutation::Spog, &EncodedQuad::from(&q), CommitTs(90));
9078        let cf = store.cf_for(IndexPermutation::Spog).unwrap();
9079        let head = count_walk_slice(
9080            &store.db,
9081            cf,
9082            IndexPermutation::Spog,
9083            &pattern,
9084            SnapshotId(60),
9085            &GByteFilter::Unconstrained,
9086            false,
9087            &[],
9088            &CountSlice {
9089                start: Vec::new(),
9090                end: Some(newest.clone()),
9091            },
9092            true,
9093        )
9094        .unwrap();
9095        let tail = count_walk_slice(
9096            &store.db,
9097            cf,
9098            IndexPermutation::Spog,
9099            &pattern,
9100            SnapshotId(60),
9101            &GByteFilter::Unconstrained,
9102            false,
9103            &[],
9104            &CountSlice {
9105                start: newest,
9106                end: None,
9107            },
9108            false,
9109        )
9110        .unwrap();
9111        assert_eq!(
9112            head, 0,
9113            "the boundary sits on the group's newest key, so every group key sorts at or after it and the head slice holds none"
9114        );
9115        assert_eq!(
9116            tail, 1,
9117            "the tail owns the group: the too-new newest is transparent, then the visible version emits"
9118        );
9119        assert_eq!(head + tail, serial);
9120        drop(store);
9121        let _ = std::fs::remove_dir_all(&dir);
9122    }
9123
9124    /// TSG full-axis counts: exact class totals cut at class starts (the
9125    /// shape a `count-all-rdf:type` query takes); thin or stale hints
9126    /// degrade to byte-even; the answer is identical either way.
9127    #[test]
9128    fn tsg_full_axis_hint_slices_match_serial() {
9129        let dir = count_store_dir("tsg-hint");
9130        let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
9131        for i in 0..40u64 {
9132            store
9133                .insert_quad_version(
9134                    &rdf_type_spo(&format!("a{i}"), "A"),
9135                    CommitTs(1),
9136                    StorageOp::Put,
9137                    VisibilityLabel::default(),
9138                )
9139                .unwrap();
9140        }
9141        for i in 0..4u64 {
9142            store
9143                .insert_quad_version(
9144                    &rdf_type_spo(&format!("b{i}"), "B"),
9145                    CommitTs(1),
9146                    StorageOp::Put,
9147                    VisibilityLabel::default(),
9148                )
9149                .unwrap();
9150        }
9151        store.flush_memtables().unwrap();
9152        let pattern = EncodedTriplePattern {
9153            subject: None,
9154            predicate: Some(crate::RDF_TYPE),
9155            object: None,
9156            graph_name: None,
9157        };
9158        let serial = count_run(
9159            &store,
9160            CountWalkMode::Serial,
9161            IndexPermutation::Tsg,
9162            &pattern,
9163            SnapshotId(9),
9164            0,
9165            &GByteFilter::Unconstrained,
9166            false,
9167            &[],
9168        );
9169        assert_eq!(serial, 44);
9170
9171        let hash_a = StrHash::new("http://ex/A");
9172        let hash_b = StrHash::new("http://ex/B");
9173        let mut hint = vec![(hash_a, 40u64), (hash_b, 4u64)];
9174        hint.sort_by_key(|(hash, _)| *hash);
9175        for (label, totals) in [
9176            ("hint", hint.as_slice()),
9177            ("empty", &[][..]),
9178            ("stale-zeros", &[(hash_a, 0), (hash_b, 0)][..]),
9179        ] {
9180            for workers in [2usize, 8, 64] {
9181                let parallel = count_run(
9182                    &store,
9183                    CountWalkMode::Parallel(workers),
9184                    IndexPermutation::Tsg,
9185                    &pattern,
9186                    SnapshotId(9),
9187                    0,
9188                    &GByteFilter::Unconstrained,
9189                    false,
9190                    totals,
9191                );
9192                assert_eq!(parallel, serial, "{label} K={workers}");
9193            }
9194        }
9195        drop(store);
9196        let _ = std::fs::remove_dir_all(&dir);
9197    }
9198
9199    /// TSG prefix arena (the `?i a dwc:Identification` shape): class bound,
9200    /// byte-even slices inside the class span, identical to serial.
9201    #[test]
9202    fn tsg_class_arena_count_parallel_matches_serial() {
9203        let dir = count_store_dir("tsg-arena");
9204        let store = RocksDbStorage::open(&dir, PartitionAxis::O).unwrap();
9205        let class_a = EncodedTerm::from(&NamedNode::new("http://ex/Identification").unwrap());
9206        for i in 0..50u64 {
9207            store
9208                .insert_quad_version(
9209                    &rdf_type_spo(&format!("i{i}"), "Identification"),
9210                    CommitTs(1),
9211                    StorageOp::Put,
9212                    VisibilityLabel::default(),
9213                )
9214                .unwrap();
9215        }
9216        for i in 0..10u64 {
9217            store
9218                .insert_quad_version(
9219                    &rdf_type_spo(&format!("o{i}"), "Occurrence"),
9220                    CommitTs(1),
9221                    StorageOp::Put,
9222                    VisibilityLabel::default(),
9223                )
9224                .unwrap();
9225        }
9226        store.flush_memtables().unwrap();
9227        let pattern = EncodedTriplePattern {
9228            subject: None,
9229            predicate: Some(crate::RDF_TYPE),
9230            object: Some(class_a),
9231            graph_name: None,
9232        };
9233        let serial = count_run(
9234            &store,
9235            CountWalkMode::Serial,
9236            IndexPermutation::Tsg,
9237            &pattern,
9238            SnapshotId(9),
9239            0,
9240            &GByteFilter::Unconstrained,
9241            false,
9242            &[],
9243        );
9244        assert_eq!(serial, 50);
9245        for workers in [2usize, 6, 32] {
9246            let parallel = count_run(
9247                &store,
9248                CountWalkMode::Parallel(workers),
9249                IndexPermutation::Tsg,
9250                &pattern,
9251                SnapshotId(9),
9252                0,
9253                &GByteFilter::Unconstrained,
9254                false,
9255                &[],
9256            );
9257            assert_eq!(parallel, serial, "K={workers}");
9258        }
9259        drop(store);
9260        let _ = std::fs::remove_dir_all(&dir);
9261    }
9262
9263    #[test]
9264    fn count_with_limit_stays_exact() {
9265        let dir = count_store_dir("limit");
9266        let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
9267        for i in 0..50u64 {
9268            store
9269                .insert_quad_version(
9270                    &named_spo(&format!("s{i}"), &format!("o{i}"), "g"),
9271                    CommitTs(1),
9272                    StorageOp::Put,
9273                    VisibilityLabel::default(),
9274                )
9275                .unwrap();
9276        }
9277        store.flush_memtables().unwrap();
9278        let pattern = unbound_pattern();
9279        // Limited counts never slice (a parallel budget cannot honor a
9280        // global early stop), but the answer must be exact either way.
9281        for mode in [CountWalkMode::Serial, CountWalkMode::Parallel(4)] {
9282            let count = count_run(
9283                &store,
9284                mode,
9285                IndexPermutation::Spog,
9286                &pattern,
9287                SnapshotId(9),
9288                5,
9289                &GByteFilter::Unconstrained,
9290                false,
9291                &[],
9292            );
9293            assert_eq!(count, 5, "mode {mode:?}");
9294        }
9295        drop(store);
9296        let _ = std::fs::remove_dir_all(&dir);
9297    }
9298
9299    #[test]
9300    fn empty_store_parallel_count_is_zero() {
9301        let dir = count_store_dir("empty");
9302        let store = RocksDbStorage::open(&dir, PartitionAxis::S).unwrap();
9303        let pattern = unbound_pattern();
9304        for workers in [2usize, 64] {
9305            let count = count_run(
9306                &store,
9307                CountWalkMode::Parallel(workers),
9308                IndexPermutation::Spog,
9309                &pattern,
9310                SnapshotId(9),
9311                0,
9312                &GByteFilter::Unconstrained,
9313                false,
9314                &[],
9315            );
9316            assert_eq!(count, 0, "K={workers}");
9317        }
9318        drop(store);
9319        let _ = std::fs::remove_dir_all(&dir);
9320    }
9321}