Skip to main content

waratah_partition/
lib.rs

1//! Hexastore partition process for one axis of the three-way hexastore.
2//!
3//! This crate serves the `Hexastore` service (`InsertQuads`, `ScanPattern`,
4//! `ScanPatternStream`, `CountPattern`, `DomainScan`, `AxisHeadScan`, `FlushMemtables`, `CompactRange`,
5//! `GetStatsProfile`, `ListNamedGraphs`, `AddNamedGraph`, `Health`, `Describe`). String registration and resolution
6//! belong to the separate `waratah_registry` process. A process opens only the
7//! two column families its axis owns, so a request naming another axis or a
8//! foreign index is rejected with a typed error rather than silently served.
9//! `ListNamedGraphs` / `AddNamedGraph` are S-axis only; `DomainScan` /
10//! `AxisHeadScan` serve only permutations owned by the serving axis; other
11//! requests return `UNIMPLEMENTED`.
12//!
13//! Phase 7 observes every insert into a [`waratah_stats::ShardStats`] write-path
14//! profile. On RocksDB flush/compaction a table-properties collector writes
15//! the same sketches into SST `user_collected_properties`; `GetStatsProfile`
16//! reloads live SST blobs only when that cache is stale. `OnFlushBegin` copies
17//! `open` aside (`flushing`) so stats RPCs during the flush stay complete;
18//! `OnFlushCompleted` marks the SST merge stale and the next reload drops
19//! `flushing`, not post-flush `open` writes.
20//! Phase 8 wraps [`PartitionService::insert_quads`] with Multi-Raft
21//! propose/apply; the RPC surface and the versioned record layout stay as-is.
22
23#![deny(unused_must_use)]
24#![warn(missing_docs)]
25
26mod error;
27
28use std::net::SocketAddr;
29use std::ops::Range;
30use std::path::Path;
31use std::sync::{Arc, Mutex};
32use std::time::{Duration, Instant};
33
34// Test hook: `begin_text_rebuild` fails right after taking the lease (the
35// release-on-error path). `Some(())` arms it for the NEXT begin; the begin
36// that consumes it disarms.
37#[cfg(test)]
38thread_local! {
39    static FAIL_TEXT_OPEN: std::cell::Cell<Option<()>> = const { std::cell::Cell::new(None) };
40}
41
42// Test hook: `begin_geo_rebuild` fails right after taking the lease (the
43// release-on-error path), same shape as `FAIL_TEXT_OPEN`.
44#[cfg(test)]
45thread_local! {
46    static FAIL_GEO_WIPE: std::cell::Cell<Option<()>> = const { std::cell::Cell::new(None) };
47}
48
49// Test hook: `stamp_geo_epoch` rendezvouses on a channel — reports
50// "stamp-begun" on entry, sleeps to hold the stamp open, and reports
51// "stamp-written" after the index stamp is written (still under the lease
52// hold). A test races a peer's `begin` against the stamp and reads the
53// message ORDER off the shared channel — deterministic, no timing. Armed
54// on the finisher thread's own cell (the spawn closure sets it before
55// calling finish).
56#[cfg(test)]
57thread_local! {
58    static BLOCK_GEO_STAMP: std::cell::Cell<Option<std::sync::mpsc::Sender<&'static str>>> =
59        const { std::cell::Cell::new(None) };
60}
61
62use bytes::{Bytes, BytesMut};
63use tokio_stream::wrappers::ReceiverStream;
64use tonic::transport::Server;
65use tonic::transport::server::TcpIncoming;
66use tonic::{Request, Response, Status};
67use waratah_proto::pb;
68use waratah_proto::{
69    GRPC_MAX_MESSAGE_SIZE, Hexastore, HexastoreServer, OMIT_GRAPH, OMIT_OBJECT, OMIT_PREDICATE,
70    OMIT_SUBJECT, PatternSlot, QuadVersion, axis_from_proto, axis_to_proto, blocking_join_error,
71    pattern_from_proto, pattern_slot_from_proto, permutation_from_proto, quad_version_from_proto,
72    scan_exhaustion_to_proto, slot_comparisons_from_proto, slot_mask_from_wire, term_from_bytes,
73};
74use waratah_stats::{
75    STATS_USER_PROPERTY_KEY, ShardStats, SstInvalidationFlags, StatsProfile,
76    attach_catalog_stats_collector, attach_geo_stats_collector, attach_stats_collector,
77    attach_stats_event_listener, attach_temporal_stats_collector, merge_sst_property_blobs,
78    named_node_hash, observe_quad, to_bytes,
79};
80use waratah_storage::{
81    CatalogPut, DomainCountMode, DyadicCovererConfig, EncodedQuad, EncodedTerm,
82    EncodedTriplePattern, GByteFilter, GEO_INDEX_CF, GeoCandidateState, GeoCellInterval,
83    GeoEnvelope, GeoIndexPut, GraphCatalogState, HexastoreVersion, IndexPermutation, IriOnlyMask,
84    KeyRow, LsmMetrics, MAIN_REPOSITORY_ID, NAMED_GRAPHS_CATALOG_CF, PartitionAxis, QuadSlot,
85    RDF_TYPE, RocksDbOptionsHooks, ScanExhaustion, SlotComparison, SnapshotId, Storage,
86    StorageBackendKind, StrHash, TEMPORAL_INDEX_CF, TemporalCandidateState, TemporalCellInterval,
87    TemporalIndexPut, TemporalQueryPredicate, WRITE_BATCH_MAX_QUADS, catalog_graphs_from_versions,
88    decode_catalog_value, decode_index_key, encode_term_bytes, postings_for_term,
89    prepare_hexastore_puts,
90};
91
92pub use error::PartitionError;
93
94/// Process identity echoed by `Describe` (listen address, data dir, node id).
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct NodeIdentity {
97    /// Routing-table id (`s-0`, `p-0`, `o-0` on the MVP).
98    pub node_id: String,
99    /// gRPC listen address as advertised (`host:port`), empty if unknown.
100    pub listen: String,
101    /// RocksDB directory, empty for the memory backend.
102    pub data_dir: String,
103    /// Repository this process opened (`main`).
104    pub repository_id: String,
105}
106
107impl Default for NodeIdentity {
108    fn default() -> Self {
109        Self {
110            node_id: String::new(),
111            listen: String::new(),
112            data_dir: String::new(),
113            repository_id: MAIN_REPOSITORY_ID.to_owned(),
114        }
115    }
116}
117
118/// Quads packed into one `ScanPatternStream` gRPC frame.
119///
120/// **Used by:** `scan_pattern_stream_frames` (and the standalone in-process
121/// mirror) as the frame flush threshold for the streamed drain, and to
122/// pre-size the walk-side framebuffer.
123///
124/// **Changing it affects:** the wire size per frame (~150 B/quad worst case
125/// — keep it far below [`waratah_proto::GRPC_MAX_MESSAGE_SIZE`]) and the
126/// partition-side memory ceiling (two outstanding frames on a channel of
127/// capacity 2). Larger frames amortize per-message overhead but delay the
128/// first bytes reaching the consumer and pin more framebuffer memory; the
129/// Rows per streaming frame of a `ScanPatternStream` response — defined in
130/// `waratah_proto` beside the rest of the wire contract (both the partition
131/// packer and the compute-side drainer read it from there). The scan walk
132/// itself is never gated by this value — only channel backpressure
133/// pauses it.
134pub use waratah_proto::SCAN_STREAM_FRAME_ROWS;
135
136/// Hard upper bound on one row's framebuffer bytes: subject, predicate, and
137/// graph top out at 17 bytes (hash IRI / blank node) and the object at 33
138/// (big hash-referenced literal). SPARQL 1.2 triple slots are not writable
139/// yet — `TYPE_TRIPLE` is reserved and the term width table rejects it — so
140/// `min(frame_rows, limit_remaining) × [`WIRE_ROW_MAX_BYTES`]` pre-sizes a
141/// frame buffer exactly. [`BytesMut::extend_from_slice`] still grows safely
142/// if a wider term type ever lands.
143const WIRE_ROW_MAX_BYTES: usize = 17 + 17 + 33 + 17;
144
145/// RocksDB open knobs for a partition process (stats collector, auto-compaction).
146#[derive(Debug, Clone, Copy)]
147pub struct RocksDbOpenOptions {
148    /// Register the `waratah.stats` table-properties collector on the canonical CF.
149    pub attach_collector: bool,
150    /// Disable background compaction (`rocksdb_options_set_disable_auto_compactions`).
151    pub disable_auto_compactions: bool,
152}
153
154impl Default for RocksDbOpenOptions {
155    fn default() -> Self {
156        Self {
157            attach_collector: true,
158            disable_auto_compactions: false,
159        }
160    }
161}
162
163/// `Hexastore` service over one axis-local storage brick.
164#[derive(Debug, Clone)]
165pub struct PartitionService {
166    axis: PartitionAxis,
167    /// Shared storage brick. Reads take no lock at all: RocksDB is internally
168    /// concurrent and snapshot isolation comes from per-row `commit_ts`
169    /// filtering against the compute-assigned snapshot, so an outstanding scan
170    /// is unaffected by concurrent writes. (The in-memory backend serializes
171    /// internally behind the same `Storage` API.)
172    storage: Arc<Storage>,
173    /// Per-axis write mutex: versioned writes are read-modify-write on the
174    /// S-axis catalog (prefix-seek, then one WriteBatch), so writers serialize
175    /// against each other — but never against readers.
176    write_mutex: Arc<Mutex<()>>,
177    stats: Arc<Mutex<ShardStats>>,
178    sst_flags: Arc<SstInvalidationFlags>,
179    /// Emit per-page scan timings and a per-request summary to stderr
180    /// (`--trace` / [`Self::with_trace`]).
181    trace: bool,
182    identity: NodeIdentity,
183    /// Temporal-index rebuild in progress (shared by clones; the Describe
184    /// flag and the rebuild lock's public face — the winner is decided by an
185    /// atomic compare-exchange on this flag).
186    temporal_rebuild_in_progress: Arc<std::sync::atomic::AtomicBool>,
187    /// Geo rebuild lease: `None` = free, `Some(deadline)` = leased until.
188    /// Unlike the temporal rebuild (partition-owned walk, cannot outlive
189    /// itself), the geo walk is driven by an external compute that can die
190    /// mid-rebuild — so the lease expires and a later begin force-takes
191    /// over a stale lease (a crashed driver can never wedge the index).
192    geo_rebuild_lease: Arc<std::sync::Mutex<Option<std::time::Instant>>>,
193    /// Text index handle. `None` until the first touch: the partition adopts
194    /// the stored sidecar if one exists, and only a rebuild request may
195    /// *create* the directory (it carries the analyzer and seed length).
196    /// `Arc` so the short outer lock only hands out the handle — the Tantivy
197    /// commit inside `add_batch` runs without holding it, and candidate
198    /// scans, Describe, and rebuild bookkeeping never wait behind a commit.
199    text_index: Arc<std::sync::Mutex<Option<std::sync::Arc<waratah_text_index::TextIndex>>>>,
200    /// Text rebuild lease, same shape and rationale as the geo lease: the
201    /// walk is compute-driven and the driver can die mid-rebuild. The token
202    /// proves ownership: only the begin call that took the lease can renew
203    /// or finish it, so a stale driver (expired and taken over, or a
204    /// partition restart) can neither stamp nor release.
205    text_rebuild_lease: Arc<std::sync::Mutex<Option<TextRebuildLease>>>,
206    /// Per-rebuild seed accumulator feeding the seed-population sketch
207    /// (`waratah_stats::TextSeedSketch`). `Some` only while a rebuild lease
208    /// is held — ordinary `PutTextIndex` writes never accumulate. The
209    /// buffers hold DISTINCT-seed posting counts per direction; at finish
210    /// they build (fresh build) or delta-merge (additive build) into the
211    /// persisted sidecar, stamped with the same epoch as the index.
212    text_seed_buffers: Arc<std::sync::Mutex<Option<TextSeedBuffers>>>,
213    /// Source of unique lease tokens (process-local; 0 is never minted).
214    text_lease_counter: std::sync::Arc<std::sync::atomic::AtomicU64>,
215    /// The text config this partition may self-create the index with, when
216    /// the launcher enabled the plugin. `None` (or a non-O axis) means a
217    /// `PutTextIndex` before any build is an error rather than a creation.
218    text_self_create: Option<waratah_text_index::TextIndexOptions>,
219    /// Max commit_ts observed by any write on this partition (the geo
220    /// rebuild epoch source, captured at finish under the lease).
221    max_commit_ts: Arc<std::sync::atomic::AtomicU64>,
222    /// Startup cache-warm lifecycle (`WARATAH_WARM_CACHE`). `Some` when the
223    /// launcher handed a tracker in; the `Health` RPC reports warm readiness
224    /// from it so the launcher can hold `/health` until walks finish.
225    warm: Option<Arc<waratah_storage::WarmState>>,
226}
227
228/// How long a geo rebuild lease is trusted before stale takeover. The
229/// lease holder is a live compute streaming terms and posting back; a
230/// generous budget survives slow blob fetches on big stores.
231pub const GEO_REBUILD_LEASE: std::time::Duration = std::time::Duration::from_secs(3600);
232
233/// Row-estimate ceiling for caller-thread scan execution
234/// (`WARATAH_SCAN_DISPATCH_ROW_THRESHOLD` overrides; `0` disables).
235///
236/// A scan whose stats upper bound
237/// ([`PartitionService::scan_runs_on_caller`]) puts the pattern at or
238/// below this many rows runs directly on the calling thread instead of
239/// being handed to a tokio blocking-pool worker — the unary
240/// `scan_pattern` round trip, the streaming drain (which then returns
241/// its frames as an already-collected stream), `CountPattern` (a
242/// count drains the same prefix a scan does), and the predicate-keyed
243/// domain scans (see [`PartitionService::domain_scan_runs_on_caller`]).
244/// A µs-scale seek executed
245/// synchronously beats paying the pool wake, whose CFS wakeup-granularity
246/// delay was measured as a ~600 µs runnable-but-unscheduled stall of the
247/// scan thread behind the small-query latency bimodality. 1024 rows is
248/// ~200 µs of warm row-matching in the common case — a quarter of the
249/// stall it removes; the estimate bounds returned rows, so delete-heavy
250/// uncompacted prefixes can walk more keys than the estimate admits.
251/// Estimates are advisory for the thread choice only; both branches
252/// return identical rows and frame ordering.
253pub const SCAN_DISPATCH_ROW_THRESHOLD: u64 = 1024;
254
255/// Resolved once per process: a number overrides the const (A/B
256/// batteries), `0` disables the gate (every unary scan dispatches, the
257/// pre-gate behavior), junk warns once and keeps the default.
258pub fn scan_dispatch_row_threshold() -> u64 {
259    static GATE: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
260    *GATE.get_or_init(
261        || match std::env::var("WARATAH_SCAN_DISPATCH_ROW_THRESHOLD") {
262            Ok(raw) => match raw.trim().parse::<u64>() {
263                Ok(value) => value,
264                Err(_) => {
265                    eprintln!(
266                        "waratah-partition: ignoring invalid \
267                         WARATAH_SCAN_DISPATCH_ROW_THRESHOLD={raw:?}: use a row count or 0"
268                    );
269                    SCAN_DISPATCH_ROW_THRESHOLD
270                }
271            },
272            Err(_) => SCAN_DISPATCH_ROW_THRESHOLD,
273        },
274    )
275}
276
277/// How long a text rebuild lease is trusted before stale takeover. Same
278/// rationale as [`GEO_REBUILD_LEASE`]: the walk is compute-driven, and a
279/// driver that dies must not wedge the index permanently.
280pub const TEXT_REBUILD_LEASE: std::time::Duration = std::time::Duration::from_secs(3600);
281
282/// One held text rebuild lease: the expiry and the owner's token. The
283/// lease no longer carries a wipe marker — the wipe fence lives on the
284/// index handle, atomic with the delete (see `TextIndex::add_batch`), so
285/// it fences exactly the delete window instead of the lease's whole life.
286#[derive(Debug, Clone, Copy)]
287struct TextRebuildLease {
288    deadline: std::time::Instant,
289    token: u64,
290    /// Whether THIS lease's begin wiped the index. Finish needs it to
291    /// build the seed sketch fresh (documents were re-derived wholesale)
292    /// or delta-merge into the persisted sketch (an additive build over a
293    /// surviving index).
294    wiped: bool,
295}
296
297/// Per-rebuild sketch accumulator: a collecting [`TextSeedSketch`] (its
298/// CMS levels bounded at `min(TEXT_SEED_SKETCH_DEPTH, seed_chars)`), fed
299/// by `apply_text` while the rebuild lease is held; consumed at finish to
300/// stamp (fresh) or delta-merge (additive) the persisted sketch.
301#[derive(Debug)]
302struct TextSeedBuffers {
303    sketch: waratah_stats::TextSeedSketch,
304}
305
306/// Sidecar path for the persisted seed sketch, inside the text index
307/// directory. ONE constant: the name lives in
308/// [`waratah_text_index::SKETCH_FILE`] (the same file `TextIndex::wipe`
309/// removes), so a rename there cannot strand sidecars here.
310fn text_seed_sketch_path(dir: &Path) -> std::path::PathBuf {
311    dir.join(waratah_text_index::SKETCH_FILE)
312}
313
314/// Read the persisted sketch, `Ok(None)` when absent (never built, wiped,
315/// unreadable, or version-mismatched — a broken sidecar degrades to the
316/// unpriced path, never to a wrong price).
317fn read_text_seed_sketch(dir: &Path) -> Option<waratah_stats::TextSeedSketch> {
318    let bytes = std::fs::read(text_seed_sketch_path(dir)).ok()?;
319    let mut slice = bytes.as_slice();
320    let sketch = waratah_stats::TextSeedSketch::decode_body(&mut slice).ok()?;
321    // Trailing bytes after a complete section mean a structurally alien
322    // write (a future layout shipped under the same version constant) —
323    // treat the file as corrupt: unpriced, never partially trusted.
324    (slice.is_empty()).then_some(sketch)
325}
326
327/// Atomically persist the sketch (temp file + rename + best-effort dir
328/// sync, the durability discipline of the meta sidecar).
329fn write_text_seed_sketch(
330    dir: &Path,
331    sketch: &waratah_stats::TextSeedSketch,
332) -> std::io::Result<()> {
333    let mut bytes = Vec::new();
334    sketch.encode_body(&mut bytes);
335    let path = text_seed_sketch_path(dir);
336    let temp = dir.join(format!("{}.tmp", waratah_text_index::SKETCH_FILE));
337    std::fs::write(&temp, &bytes)?;
338    std::fs::rename(&temp, &path)?;
339    if let Ok(handle) = std::fs::File::open(dir) {
340        let _ = handle.sync_all();
341    }
342    Ok(())
343}
344
345impl TextSeedBuffers {
346    fn new(seed_chars: usize) -> Self {
347        Self {
348            sketch: waratah_stats::TextSeedSketch::collector(seed_chars),
349        }
350    }
351
352    /// Record one document's seeds (posting counts, the geo histogram's
353    /// over-count contract: a wipe walk posts each distinct term once, so
354    /// fresh counts are exact distinct terms; additive rebuilds add
355    /// deltas on top, the same permanent over-count as `total_puts`).
356    fn record(&mut self, lexical: &str) {
357        self.sketch.record(lexical);
358    }
359}
360
361impl PartitionService {
362    /// Wrap an already-open storage brick with an in-memory stats store.
363    pub fn new(storage: Storage) -> Self {
364        Self::new_with_stats(storage, ShardStats::memory())
365    }
366
367    /// Wrap storage with an existing [`ShardStats`] holder.
368    pub fn new_with_stats(storage: Storage, stats: ShardStats) -> Self {
369        let sst_flags = Arc::clone(stats.flags());
370        Self {
371            axis: storage.axis(),
372            storage: Arc::new(storage),
373            write_mutex: Arc::new(Mutex::new(())),
374            stats: Arc::new(Mutex::new(stats)),
375            sst_flags,
376            trace: false,
377            identity: NodeIdentity::default(),
378            temporal_rebuild_in_progress: Arc::new(std::sync::atomic::AtomicBool::new(false)),
379            geo_rebuild_lease: Arc::new(std::sync::Mutex::new(None)),
380            text_index: Arc::new(std::sync::Mutex::new(None)),
381            text_rebuild_lease: Arc::new(std::sync::Mutex::new(None)),
382            text_seed_buffers: Arc::new(std::sync::Mutex::new(None)),
383            text_lease_counter: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
384            text_self_create: None,
385            max_commit_ts: Arc::new(std::sync::atomic::AtomicU64::new(0)),
386            warm: None,
387        }
388    }
389
390    /// In-memory partition for tests and lightweight local runs.
391    pub fn memory(axis: PartitionAxis) -> Self {
392        Self::new(Storage::memory(axis))
393    }
394
395    /// The shared storage brick (in-process clients / tests).
396    pub fn storage(&self) -> &Storage {
397        &self.storage
398    }
399
400    /// Warm this partition's block cache (see
401    /// [`Storage::warm_block_cache`]); a no-op on the memory backend. Called
402    /// from the partition process when `WARATAH_WARM_CACHE` is set.
403    pub fn warm_block_cache(
404        &self,
405        fill_fraction: f64,
406    ) -> Result<waratah_storage::WarmBlockCacheStats, PartitionError> {
407        Ok(self.storage.warm_block_cache(fill_fraction)?)
408    }
409
410    /// The shard stats holder (in-process clients / tests).
411    pub fn stats_handle(&self) -> &std::sync::Mutex<ShardStats> {
412        &self.stats
413    }
414
415    /// Open with an explicit backend (dev mode selects memory for speed).
416    pub fn open_with_backend(
417        kind: StorageBackendKind,
418        path: impl AsRef<Path>,
419        axis: PartitionAxis,
420    ) -> Result<Self, PartitionError> {
421        let path = path.as_ref();
422        match kind {
423            StorageBackendKind::Memory => Ok(Self::new(Storage::memory(axis))),
424            StorageBackendKind::RocksDb => Self::open_rocksdb(
425                path,
426                axis,
427                RocksDbOpenOptions {
428                    attach_collector: true,
429                    disable_auto_compactions: false,
430                },
431            ),
432        }
433    }
434
435    /// Open a RocksDB partition with optional stats collector and auto-compaction.
436    pub fn open_rocksdb(
437        path: impl AsRef<Path>,
438        axis: PartitionAxis,
439        options: RocksDbOpenOptions,
440    ) -> Result<Self, PartitionError> {
441        let flags = Arc::new(SstInvalidationFlags::new());
442        let stats = Arc::new(Mutex::new(ShardStats::rocksdb(Arc::clone(&flags))));
443        let flags_for_listener = Arc::clone(&flags);
444        let stats_for_listener = Arc::clone(&stats);
445        let canonical = IndexPermutation::for_axis(axis)[0];
446        let attach_collector = options.attach_collector;
447        let disable_auto = options.disable_auto_compactions;
448        let configure_db = |opts: *mut std::ffi::c_void| {
449            attach_stats_event_listener(
450                opts,
451                Arc::clone(&flags_for_listener),
452                Arc::clone(&stats_for_listener),
453                canonical,
454                (axis == PartitionAxis::S).then_some(NAMED_GRAPHS_CATALOG_CF),
455                (axis == PartitionAxis::O).then_some(TEMPORAL_INDEX_CF),
456                (axis == PartitionAxis::O).then_some(GEO_INDEX_CF),
457            );
458            if disable_auto {
459                waratah_storage::disable_auto_compactions(opts);
460            }
461        };
462        let configure_cf = |perm, opts| {
463            if attach_collector {
464                attach_stats_collector(perm, opts);
465            }
466        };
467        let configure_catalog_cf = |opts| {
468            if attach_collector {
469                attach_catalog_stats_collector(opts);
470            }
471        };
472        let configure_temporal_cf = |opts| {
473            if attach_collector {
474                attach_temporal_stats_collector(opts);
475            }
476        };
477        let configure_geo_cf = |opts| {
478            if attach_collector {
479                attach_geo_stats_collector(opts);
480            }
481        };
482        let storage = Storage::open_rocksdb_with_hooks(
483            path,
484            axis,
485            RocksDbOptionsHooks {
486                configure_db: Some(&configure_db),
487                configure_cf: Some(&configure_cf),
488                configure_catalog_cf: Some(&configure_catalog_cf),
489                configure_temporal_cf: Some(&configure_temporal_cf),
490                configure_geo_cf: Some(&configure_geo_cf),
491                ..Default::default()
492            },
493        )?;
494        Ok(Self {
495            axis: storage.axis(),
496            storage: Arc::new(storage),
497            write_mutex: Arc::new(Mutex::new(())),
498            stats,
499            sst_flags: flags,
500            trace: false,
501            identity: NodeIdentity::default(),
502            temporal_rebuild_in_progress: Arc::new(std::sync::atomic::AtomicBool::new(false)),
503            geo_rebuild_lease: Arc::new(std::sync::Mutex::new(None)),
504            text_index: Arc::new(std::sync::Mutex::new(None)),
505            text_rebuild_lease: Arc::new(std::sync::Mutex::new(None)),
506            text_seed_buffers: Arc::new(std::sync::Mutex::new(None)),
507            text_lease_counter: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
508            text_self_create: None,
509            max_commit_ts: Arc::new(std::sync::atomic::AtomicU64::new(0)),
510            warm: None,
511        })
512    }
513
514    /// Axis this process owns.
515    pub fn axis(&self) -> PartitionAxis {
516        self.axis
517    }
518
519    /// Enable (`--trace`) stderr timing lines for streamed scans.
520    pub fn with_trace(mut self, enabled: bool) -> Self {
521        self.trace = enabled;
522        self
523    }
524
525    /// Set the identity `Describe` reports (listen address, data dir, node id).
526    pub fn with_identity(mut self, identity: NodeIdentity) -> Self {
527        self.identity = identity;
528        self
529    }
530
531    /// Hand in the startup cache-warm tracker. The `Health` RPC reports
532    /// `warm_ready = false` (plus the pending walk names) until every
533    /// tracked walk completes or outlives the tracker's max wait.
534    pub fn with_warm_state(mut self, warm: Arc<waratah_storage::WarmState>) -> Self {
535        self.warm = Some(warm);
536        self
537    }
538
539    /// Identity `Describe` reports.
540    pub fn identity(&self) -> &NodeIdentity {
541        &self.identity
542    }
543
544    /// Apply versioned records to both axis-local indexes and observe stats.
545    ///
546    /// `asserted_axis` of `None` skips the ownership check (the caller did not
547    /// name an axis); a named axis other than [`Self::axis`] is rejected.
548    ///
549    /// Index keys for a multi-quad chunk are encoded before taking the storage
550    /// write lock. Catalog prefix seeks (S axis) run under that lock, then one
551    /// RocksDB `WriteBatch` commits hexastore puts and catalog puts together.
552    /// Chunks are at most [`WRITE_BATCH_MAX_QUADS`].
553    pub fn apply_versions(
554        &self,
555        asserted_axis: Option<PartitionAxis>,
556        versions: &[QuadVersion],
557    ) -> Result<u64, PartitionError> {
558        self.check_axis(asserted_axis)?;
559        for chunk in versions.chunks(WRITE_BATCH_MAX_QUADS) {
560            self.apply_version_chunk(chunk)?;
561        }
562        Ok(versions.len() as u64)
563    }
564
565    fn apply_version_chunk(&self, chunk: &[QuadVersion]) -> Result<(), PartitionError> {
566        let puts = prepare_hexastore_puts(
567            self.axis,
568            chunk.iter().map(|version| HexastoreVersion {
569                quad: &version.quad,
570                commit_ts: version.commit_ts,
571                op: version.op,
572                visibility: version.visibility,
573            }),
574        );
575        let catalog_graphs = if self.axis == PartitionAxis::S {
576            catalog_graphs_from_versions(chunk.iter().map(|version| HexastoreVersion {
577                quad: &version.quad,
578                commit_ts: version.commit_ts,
579                op: version.op,
580                visibility: version.visibility,
581            }))
582        } else {
583            Vec::new()
584        };
585        // High-water commit_ts: the geo rebuild epoch source (captured at
586        // finish under the lease; equal, never +1).
587        for version in chunk {
588            self.max_commit_ts
589                .fetch_max(version.commit_ts.0, std::sync::atomic::Ordering::Relaxed);
590        }
591        let write_guard = self
592            .write_mutex
593            .lock()
594            .map_err(|_| PartitionError::LockPoisoned)?;
595        let storage = self.storage.as_ref();
596        let catalog = if self.axis == PartitionAxis::S {
597            storage.catalog_puts_for_insert(&catalog_graphs)?
598        } else {
599            Vec::new()
600        };
601        storage.apply_prepared_puts_with_catalog(&puts, &catalog)?;
602        // Do not hold the stats lock across insert: auto-flush OnFlushBegin
603        // needs that lock, and a write stall waiting on flush would deadlock.
604        drop(write_guard);
605        let mut stats = self
606            .stats
607            .lock()
608            .map_err(|_| PartitionError::LockPoisoned)?;
609        for version in chunk {
610            observe_quad(stats.open_profile_mut(), &version.quad, version.op);
611        }
612        observe_catalog_puts(&mut stats, &catalog);
613        Ok(())
614    }
615
616    /// S-axis named-graph catalog at `snapshot` (empty graphs included).
617    pub fn list_named_graphs(
618        &self,
619        snapshot: SnapshotId,
620    ) -> Result<Vec<EncodedTerm>, PartitionError> {
621        if self.axis != PartitionAxis::S {
622            return Err(PartitionError::from(
623                waratah_storage::StorageError::CatalogNotOnAxis(self.axis),
624            ));
625        }
626        let storage = self.storage.as_ref();
627        Ok(storage.list_named_graphs(snapshot)?)
628    }
629
630    /// Insert an empty named graph into the S-axis catalog.
631    pub fn add_named_graph(
632        &self,
633        graph: &EncodedTerm,
634        commit_ts: waratah_storage::CommitTs,
635    ) -> Result<(), PartitionError> {
636        if self.axis != PartitionAxis::S {
637            return Err(PartitionError::from(
638                waratah_storage::StorageError::CatalogNotOnAxis(self.axis),
639            ));
640        }
641        let write_guard = self
642            .write_mutex
643            .lock()
644            .map_err(|_| PartitionError::LockPoisoned)?;
645        let storage = self.storage.as_ref();
646        let puts = storage.catalog_puts_for_insert(&[(graph.clone(), commit_ts)])?;
647        storage.apply_prepared_puts_with_catalog(&[], &puts)?;
648        drop(write_guard);
649        if !puts.is_empty() {
650            let mut stats = self
651                .stats
652                .lock()
653                .map_err(|_| PartitionError::LockPoisoned)?;
654            observe_catalog_puts(&mut stats, &puts);
655        }
656        Ok(())
657    }
658
659    /// Scan a pattern as of `snapshot`, returning encoded columns only.
660    ///
661    /// `permutation` of `None` lets the brick pick its longest-prefix
662    /// axis-local index; `limit` of `0` is unlimited.
663    ///
664    /// When `filter_slot` + `filter_terms` are set (Phase 9b broadcast), each
665    /// filter term is bound into that slot and scanned; results are concatenated.
666    pub fn scan(
667        &self,
668        permutation: Option<IndexPermutation>,
669        pattern: &EncodedTriplePattern,
670        snapshot: SnapshotId,
671        limit: u64,
672    ) -> Result<Vec<EncodedQuad>, PartitionError> {
673        // Convenience wrapper: callers of the plain scan want rows only
674        // (a full drain is terminal by construction).
675        self.scan_filtered(
676            permutation,
677            pattern,
678            snapshot,
679            limit,
680            None,
681            &[],
682            None,
683            &[],
684            false,
685            false,
686            IriOnlyMask::NONE,
687            true,
688        )
689        .map(|(rows, _verdict)| rows)
690    }
691
692    /// Scan with an optional broadcast allow-list on one unbound slot.
693    ///
694    /// `start_after` is exclusive. A single prefix scan resumes after that
695    /// logical quad. With `filter_terms`, results are concatenated in **encoded
696    /// tight-prefix order** (not caller allow-list order): terms whose prefix
697    /// sorts before the cursor's slot value are skipped, the matching term's
698    /// prefix resumes at `start_after`, and later terms start from the beginning
699    /// of their prefix. `limit` counts visible matching Puts after MVCC collapse.
700    /// `filter_terms` order does not matter; the same **set** plus `start_after`
701    /// is enough to resume. One filter term still uses a tight prefix iterator.
702    /// Two or more terms share one iterator and `Seek` to each prefix when the
703    /// filter slot extends the index prefix; otherwise each term is bound and
704    /// scanned separately.
705    /// `graph_filter_terms` is a residual G-slot block-list (`allow = false`,
706    /// the default) or allow-list (`allow = true`). Empty block-list blocks
707    /// nothing (`pattern.graph_name` still applies). Empty allow-list allows
708    /// nothing.
709    ///
710    /// Scan-dispatch gate: may this scan run on the calling thread?
711    ///
712    /// Used by every gated fetch shape — the unary `scan_pattern` round
713    /// trip, the streaming drain (`scan_pattern_stream_frames`),
714    /// `CountPattern` (a count drains the same prefix a scan does), and
715    /// predicate-keyed domain scans
716    /// ([`Self::domain_scan_runs_on_caller`]). True when the
717    /// partition's stats upper bound
718    /// ([`ShardStats::exact_scan_rows`]) puts the pattern at or below
719    /// [`scan_dispatch_row_threshold`] rows AND the permutation-aware
720    /// slice rule is satisfied: the walked key range must be narrowed
721    /// past the leading block — on PSOG/POSG the slot after the
722    /// predicate, on TSG the class, on SPOG/SOPG/OPSG the leading
723    /// subject or object — each bound, or covered by a non-empty
724    /// sub-threshold allow-list on that slot; a request with no
725    /// explicit permutation dispatches. Paged unary requests follow the
726    /// same rule (a `limit > 0` page bound only at the predicate
727    /// dispatches). The rule keeps delete churn in a whole leading block
728    /// (version keys far beyond the net-row estimate) off the calling
729    /// worker. Phase-1 estimate sources
730    /// (exact maps only): a bound named predicate's row count, and — for
731    /// `rdf:type` — the class counts for a bound named class or an object
732    /// broadcast allow-list (summed with early exit at the threshold).
733    /// Patterns without a bound named predicate have no phase-1 basis and
734    /// always dispatch.
735    ///
736    /// Dispatch-on-doubt: the gate returns `false` (dispatch) when the
737    /// sealed SST profile has not been loaded or is invalidated
738    /// (`SstInvalidationFlags::sealed_stale` — an empty sealed layer plus
739    /// a live write would otherwise read as an observed zero), when the
740    /// stats mutex is contended or poisoned (`try_lock` — the write path
741    /// holds that mutex across whole write chunks, and waiting would put
742    /// it back on the latency path this gate exists to shorten), or when
743    /// any allow-list term is not a named node (it could match rows the
744    /// named-class map never counts).
745    ///
746    /// The gate is advisory for the thread choice only: the caller
747    /// executes the same `scan_filtered` either way and the rows are
748    /// identical.
749    pub fn scan_runs_on_caller(
750        &self,
751        permutation: Option<IndexPermutation>,
752        pattern: &EncodedTriplePattern,
753        filter_slot: Option<PatternSlot>,
754        filter_terms: &[EncodedTerm],
755    ) -> bool {
756        let threshold = scan_dispatch_row_threshold();
757        if threshold == 0 {
758            return false;
759        }
760        // Sealed SST profile unknown (fresh open before the first reload,
761        // or invalidated by a flush/compaction since): without it the
762        // estimate can only under-count a pre-imported store.
763        if self.sst_flags.sealed_stale() {
764            return false;
765        }
766        let Some(predicate) = pattern.predicate.as_ref() else {
767            return false;
768        };
769        let Some(pred_hash) = named_node_hash(predicate) else {
770            return false;
771        };
772        // A predicate-slot allow-list REBINDS the predicate per term (the
773        // scan becomes a union over the listed predicates), so the bound
774        // predicate's row count no longer bounds the work — dispatch. No
775        // current caller builds this shape (compute drops the filter when
776        // the predicate is bound); the guard keeps the gate's bound true
777        // for every wire shape.
778        if filter_slot == Some(PatternSlot::Predicate) {
779            return false;
780        }
781        // Permutation-aware slice rule: the walked key range must be
782        // narrowed past the leading block, because delete churn can pile
783        // version keys in a whole leading block far beyond the net-row
784        // estimate (the estimate bounds returned rows, not keys visited).
785        // The bound-predicate check above fills key slot 0 on the
786        // predicate-leading permutations, so the required slot here
787        // extends the prefix past the leading block — the Posg/Psog
788        // arms rely on that earlier rejection; reordering these checks
789        // could qualify an empty-prefix scan.
790        // On predicate-leading indexes (PSOG, POSG) the slot AFTER the
791        // predicate must be bound — subject on PSOG, object on POSG; on
792        // TSG the class must be bound (P is implicit rdf:type and absent
793        // from the key, so the class IS the leading segment); on the
794        // non-predicate-leading indexes (SPOG, SOPG, OPSG) the first slot
795        // itself must be bound. A broadcast allow-list on the required
796        // slot qualifies when it is non-empty and smaller than the
797        // threshold (each term seeks its own tight prefix). A bound
798        // graph_name never qualifies — no index leads with G, so G
799        // filters rows without shrinking the walked prefix. A request
800        // with no explicit permutation dispatches: the partition picks
801        // the index, so the gate cannot know which range would be
802        // walked. Put/delete compaction (planned storage work) collapses
803        // the churn itself. Predicate-keyed domain scans are
804        // structurally exempt — the constraint IS the request (see
805        // [`Self::domain_scan_runs_on_caller`]).
806        let allow_list_qualifies = |slot: PatternSlot| {
807            filter_slot == Some(slot)
808                && !filter_terms.is_empty()
809                && filter_terms.len() < threshold as usize
810        };
811        let sliced = match permutation {
812            None => false,
813            Some(IndexPermutation::Posg | IndexPermutation::Opsg | IndexPermutation::Tsg) => {
814                pattern.object.is_some() || allow_list_qualifies(PatternSlot::Object)
815            }
816            Some(IndexPermutation::Psog | IndexPermutation::Spog | IndexPermutation::Sopg) => {
817                pattern.subject.is_some() || allow_list_qualifies(PatternSlot::Subject)
818            }
819        };
820        if !sliced {
821            return false;
822        }
823        let (class_bound, class_filter) = if predicate != &RDF_TYPE {
824            (None, None)
825        } else {
826            match pattern.object.as_ref() {
827                Some(object) => (named_node_hash(object), None),
828                None => {
829                    // A broadcast allow-list on the object slot narrows a
830                    // type scan per class, so the class counts apply. Any
831                    // term that is not a named node could match rows the
832                    // named-class map never counts — dispatch rather than
833                    // under-estimate.
834                    if filter_slot == Some(PatternSlot::Object) && !filter_terms.is_empty() {
835                        let mut hashes = Vec::with_capacity(filter_terms.len());
836                        for term in filter_terms {
837                            let Some(hash) = named_node_hash(term) else {
838                                return false;
839                            };
840                            hashes.push(hash);
841                        }
842                        (None, Some(hashes))
843                    } else {
844                        (None, None)
845                    }
846                }
847            }
848        };
849        let class_filter = class_filter.as_deref();
850        // try_lock: contended or poisoned stats dispatch immediately —
851        // the write path holds this mutex across whole write chunks.
852        let Ok(stats) = self.stats.try_lock() else {
853            return false;
854        };
855        stats
856            .exact_scan_rows(pred_hash, class_bound, class_filter, threshold)
857            .is_some_and(|rows| rows <= threshold)
858    }
859
860    /// Domain-scan gate: may this domain scan run on the calling thread?
861    ///
862    /// Same dispatch-on-doubt rules as [`Self::scan_runs_on_caller`]
863    /// (threshold disabled, sealed SST profile stale, stats mutex
864    /// contended or poisoned → dispatch), applied to the domain-scan
865    /// request shape: `constraints` are the slot-0 terms of
866    /// `permutation`.
867    ///
868    /// Only predicate-keyed domain scans (`Posg`, the `PredicateDomain`
869    /// rewrite) have an exact estimate basis: the per-predicate row
870    /// counts, summed over the constraint list with early exit strictly
871    /// past the threshold (distinct heads under a constraint walk at
872    /// most that predicate's rows). A constraint that is not a named
873    /// node has no exact-map entry and dispatches. Subject- and
874    /// object-keyed permutations have no per-term exact maps at all —
875    /// no basis, always dispatch. Advisory for the thread choice only;
876    /// both branches return identical hits.
877    pub fn domain_scan_runs_on_caller(
878        &self,
879        permutation: IndexPermutation,
880        constraints: &[EncodedTerm],
881    ) -> bool {
882        let threshold = scan_dispatch_row_threshold();
883        if threshold == 0 {
884            return false;
885        }
886        // Sealed SST profile unknown: without it the estimate can only
887        // under-count a pre-imported store.
888        if self.sst_flags.sealed_stale() {
889            return false;
890        }
891        // Both predicate-leading permutations are domain scans whose
892        // constraint IS the slot-0 predicate term: the exact per-predicate
893        // row count bounds the walk equally on POSG and PSOG. S/O-leading
894        // kinds have no equivalent exact-map basis here and dispatch.
895        if !matches!(permutation, IndexPermutation::Posg | IndexPermutation::Psog) {
896            return false;
897        }
898        // try_lock: contended or poisoned stats dispatch immediately —
899        // the write path holds this mutex across whole write chunks.
900        let Ok(stats) = self.stats.try_lock() else {
901            return false;
902        };
903        let mut sum: u64 = 0;
904        for term in constraints {
905            // A constraint that is not a named node has no exact-map key;
906            // count it as unknowable rather than zero.
907            let Some(hash) = named_node_hash(term) else {
908                return false;
909            };
910            // Absent-vs-empty basis rules are exact_scan_rows's: with a
911            // basis present, an absent predicate is an observed zero.
912            match stats.exact_scan_rows(hash, None, None, threshold) {
913                Some(rows) => {
914                    sum = sum.saturating_add(rows);
915                    // Stop once the verdict can no longer be "runs on the
916                    // caller" (final sum <= threshold).
917                    if sum > threshold {
918                        return false;
919                    }
920                }
921                None => return false,
922            }
923        }
924        true
925    }
926
927    /// `merge_default_graph` is the SPARQL default-graph RDF merge: after graph
928    /// membership, keep the first visible S/P/O, skip later named graphs of
929    /// that triple (G is last in every index), and rewrite result G to
930    /// [`EncodedTerm::DefaultGraph`]. Exclusive `start_after` then means "skip
931    /// this whole triple", not one logical quad. `GRAPH` scans must leave this
932    /// false so graph identity stays on the wire.
933    ///
934    /// This is the decoded reference path: each matched row is decoded from
935    /// its raw key and collected into a `Vec<EncodedQuad>`, with the
936    /// default-graph merge applied after the decode. The RPC page walk is
937    /// [`Self::scan_filtered_packed`]; both share
938    /// [`Self::walk_filtered_rows`]'s branch selection and differ only in the
939    /// per-row sink. Returns the rows plus the walk's own
940    /// [`ScanExhaustion`] verdict.
941    #[allow(clippy::too_many_arguments)]
942    pub fn scan_filtered(
943        &self,
944        permutation: Option<IndexPermutation>,
945        pattern: &EncodedTriplePattern,
946        snapshot: SnapshotId,
947        limit: u64,
948        filter_slot: Option<PatternSlot>,
949        filter_terms: &[EncodedTerm],
950        start_after: Option<&EncodedQuad>,
951        graph_filter_terms: &[EncodedTerm],
952        graph_filter_allow: bool,
953        merge_default_graph: bool,
954        iri_only: IriOnlyMask,
955        verdict_wanted: bool,
956    ) -> Result<(Vec<EncodedQuad>, ScanExhaustion), PartitionError> {
957        let mut rows = Vec::new();
958        let mut emit = |row: &KeyRow<'_>| -> Result<bool, PartitionError> {
959            let mut quad = decode_index_key(row.permutation, row.logical())?;
960            if merge_default_graph {
961                quad = quad.into_merged_default();
962            }
963            rows.push(quad);
964            Ok(true)
965        };
966        let (_rows, verdict) = self.walk_filtered_rows(
967            permutation,
968            pattern,
969            snapshot,
970            limit,
971            filter_slot,
972            filter_terms,
973            start_after,
974            graph_filter_terms,
975            graph_filter_allow,
976            merge_default_graph,
977            iri_only,
978            &[],
979            verdict_wanted,
980            &mut emit,
981        )?;
982        Ok((rows, verdict))
983    }
984
985    /// The unary page walk with the packed sink: matched rows go into a
986    /// [`FramePacker`] with the request's `omitted_slots` mask applied during
987    /// the copy — the same `push_row` the stream drain calls — and the page
988    /// returns ONE frame whose every field is a zero-copy slice of the packed
989    /// buffer. No `EncodedTerm` is ever constructed on this path: the mask
990    /// rides at the byte-copy layer, exactly as on the stream, and the Tsg
991    /// predicate and the default-graph merge are applied by `wire_quad` at
992    /// slice time instead of inside storage.
993    ///
994    /// Paging is the decoded path's, exactly: `limit` counts matched rows
995    /// after MVCC collapse and filtering, `start_after` is exclusive, and the
996    /// branch selection is [`Self::scan_filtered`]'s. One page per response;
997    /// the stream's `SCAN_STREAM_FRAME_ROWS` flush threshold does not apply.
998    #[allow(clippy::too_many_arguments)]
999    pub fn scan_filtered_packed(
1000        &self,
1001        permutation: Option<IndexPermutation>,
1002        pattern: &EncodedTriplePattern,
1003        snapshot: SnapshotId,
1004        limit: u64,
1005        filter_slot: Option<PatternSlot>,
1006        filter_terms: &[EncodedTerm],
1007        start_after: Option<&EncodedQuad>,
1008        graph_filter_terms: &[EncodedTerm],
1009        graph_filter_allow: bool,
1010        merge_default_graph: bool,
1011        iri_only: IriOnlyMask,
1012        comparisons: &[SlotComparison],
1013        omitted: u8,
1014        verdict_wanted: bool,
1015    ) -> Result<pb::ScanPatternResponse, PartitionError> {
1016        let mut packer = FramePacker::with_omitted(omitted);
1017        let mut emitted = 0u64;
1018        let verdict = {
1019            // The limit counter is its own variable, NOT `packer.len()`:
1020            // `take_frame` resets the packer, so any future frame split of
1021            // this page must keep counting rows across frames. The limit
1022            // itself is NOT enforced here — every walk branch wraps this
1023            // sink in `scan_page_graph` / `scan_page_graph_allow_list`,
1024            // whose sinks are the single authority for the page limit and
1025            // its edge- vs level-trigger discipline.
1026            let mut emit = |row: &KeyRow<'_>| -> Result<bool, PartitionError> {
1027                let remaining = limit.saturating_sub(emitted);
1028                packer.push_row(row, merge_default_graph, remaining);
1029                emitted += 1;
1030                Ok(true)
1031            };
1032            let (_rows, verdict) = self.walk_filtered_rows(
1033                permutation,
1034                pattern,
1035                snapshot,
1036                limit,
1037                filter_slot,
1038                filter_terms,
1039                start_after,
1040                graph_filter_terms,
1041                graph_filter_allow,
1042                merge_default_graph,
1043                iri_only,
1044                comparisons,
1045                verdict_wanted,
1046                &mut emit,
1047            )?;
1048            verdict
1049        };
1050        // Tsg rows carry no predicate in the key; `wire_quad` inserts this
1051        // constant encoding at slice time.
1052        let rdf_type_wire = Bytes::from(encode_term_bytes(&RDF_TYPE));
1053        let mut response = packer.take_frame(merge_default_graph, &rdf_type_wire);
1054        // The walk's own verdict — the server-side fact that replaces the
1055        // client's short-page inference at every exact limit boundary —
1056        // present iff the consumer purchased one (`verdict_wanted`).
1057        // Without the purchase nothing is claimed, even when the walk's
1058        // fact was free to know (a short page's completed walk): the
1059        // contract is "a verdict appears iff one was asked for".
1060        response.exhausted = verdict_wanted.then(|| scan_exhaustion_to_proto(verdict) as i32);
1061        Ok(response)
1062    }
1063
1064    /// The unary page walk selection, shared verbatim by
1065    /// [`Self::scan_filtered`] (decoded sink) and [`Self::scan_filtered_packed`]
1066    /// (packed sink): multi-seek over the allow-listed tight prefixes when the
1067    /// filter slot extends the pattern's key prefix and at least two terms are
1068    /// listed, one bound-pattern walk per filter term otherwise, and one plain
1069    /// prefix walk with no filter list. Returns the number of rows the sink
1070    /// accepted plus the walk's own [`ScanExhaustion`] verdict.
1071    /// `verdict_wanted` selects the sink discipline at the page limit (see
1072    /// `ScanPatternRequest.verdict_wanted`): `true` keeps the walk running
1073    /// past a full page so its exit settles an honest terminal verdict,
1074    /// `false` stops at the limit'th row. The streaming
1075    /// drain (`scan_filtered_streaming`) mirrors this selection; the
1076    /// decoded-vs-packed differential test checks the two producers against
1077    /// each other.
1078    #[allow(clippy::too_many_arguments)]
1079    fn walk_filtered_rows(
1080        &self,
1081        permutation: Option<IndexPermutation>,
1082        pattern: &EncodedTriplePattern,
1083        snapshot: SnapshotId,
1084        limit: u64,
1085        filter_slot: Option<PatternSlot>,
1086        filter_terms: &[EncodedTerm],
1087        start_after: Option<&EncodedQuad>,
1088        graph_filter_terms: &[EncodedTerm],
1089        graph_filter_allow: bool,
1090        merge_default_graph: bool,
1091        iri_only: IriOnlyMask,
1092        comparisons: &[SlotComparison],
1093        verdict_wanted: bool,
1094        emit: &mut ScanRowEmit<'_>,
1095    ) -> Result<(u64, ScanExhaustion), PartitionError> {
1096        let graph = GByteFilter::compile(graph_filter_terms, graph_filter_allow);
1097        let storage = self.storage.as_ref();
1098
1099        if let (Some(slot), terms) = (filter_slot, filter_terms)
1100            && !terms.is_empty()
1101        {
1102            if terms.len() >= 2 {
1103                let quad_slot = pattern_slot_to_quad(slot);
1104                let permutation =
1105                    resolve_broadcast_permutation(storage, permutation, pattern, slot, &terms[0]);
1106                if let Some(page) = scan_page_graph_allow_list(
1107                    storage,
1108                    permutation,
1109                    pattern,
1110                    snapshot,
1111                    limit,
1112                    start_after,
1113                    &graph,
1114                    merge_default_graph,
1115                    quad_slot,
1116                    terms,
1117                    iri_only,
1118                    comparisons,
1119                    verdict_wanted,
1120                    &mut *emit,
1121                )? {
1122                    return Ok(page);
1123                }
1124            }
1125            return scan_filter_terms_separately(
1126                storage,
1127                permutation,
1128                pattern,
1129                snapshot,
1130                limit,
1131                start_after,
1132                &graph,
1133                merge_default_graph,
1134                slot,
1135                terms,
1136                iri_only,
1137                comparisons,
1138                verdict_wanted,
1139                &mut *emit,
1140            );
1141        }
1142        scan_page_graph(
1143            storage,
1144            permutation,
1145            pattern,
1146            snapshot,
1147            limit,
1148            start_after,
1149            &graph,
1150            merge_default_graph,
1151            iri_only,
1152            comparisons,
1153            verdict_wanted,
1154            &mut *emit,
1155        )
1156    }
1157
1158    /// Stream every visible matching row to `emit` in ONE continuous index
1159    /// walk — no storage-side paging, no lock held (reads are lock-free; see
1160    /// [`Self::storage`]). `emit` receives a raw [`KeyRow`] (key-buffer
1161    /// slices, no decoded terms) and returns `false` to stop the walk early
1162    /// (limit satisfied / consumer gone); the return value is the walk's
1163    /// [`ScanExhaustion`] verdict — a terminal value
1164    /// (`ExhaustedFilterTerms`/`ExhaustedScan`) when the walk ran to
1165    /// completion, `Limited` when `emit` stopped it.
1166    ///
1167    /// Plain patterns (the eager drain's hot path) walk a single iterator
1168    /// through the storage-side RowMatcher: residual G membership, the
1169    /// exclusive `start_after` whole-triple cursor, and `merge_default_graph`
1170    /// collapse run per row on raw key bytes — semantics match unary paging
1171    /// row for row, and no `EncodedTerm` is ever constructed. Broadcast
1172    /// filter shapes run the same raw row walks (multi-seek over the
1173    /// allow-listed tight prefixes, or one bound-pattern walk per term) —
1174    /// every branch emits raw [`KeyRow`] slices and constructs no terms on
1175    /// any branch.
1176    #[allow(clippy::too_many_arguments)]
1177    pub fn scan_filtered_streaming(
1178        &self,
1179        permutation: Option<IndexPermutation>,
1180        pattern: &EncodedTriplePattern,
1181        snapshot: SnapshotId,
1182        filter_slot: Option<PatternSlot>,
1183        filter_terms: &[EncodedTerm],
1184        start_after: Option<&EncodedQuad>,
1185        graph_filter_terms: &[EncodedTerm],
1186        graph_filter_allow: bool,
1187        merge_default_graph: bool,
1188        iri_only: IriOnlyMask,
1189        comparisons: &[SlotComparison],
1190        mut emit: impl FnMut(&KeyRow) -> bool,
1191    ) -> Result<ScanExhaustion, PartitionError> {
1192        let graph = GByteFilter::compile(graph_filter_terms, graph_filter_allow);
1193        if graph.empty_window() {
1194            // No row can match under this graph window: the scan's whole
1195            // scope is (vacuously) served.
1196            return Ok(ScanExhaustion::ExhaustedScan);
1197        }
1198        let storage = self.storage.as_ref();
1199
1200        if let (Some(slot), terms) = (filter_slot, filter_terms)
1201            && !terms.is_empty()
1202        {
1203            // Broadcast shapes: raw multi-seek over the allow-listed tight
1204            // prefixes when the filter slot extends the pattern's key
1205            // prefix, otherwise one bound-pattern walk per term. Both feed
1206            // the same raw [`KeyRow`] slices as the plain branch — binding
1207            // a filter term cannot differ per term value, so one
1208            // permutation resolution covers every walk.
1209            let page_permutation =
1210                resolve_broadcast_permutation(storage, permutation, pattern, slot, &terms[0]);
1211            let quad_slot = pattern_slot_to_quad(slot);
1212            let mut verdict = ScanExhaustion::ExhaustedFilterTerms;
1213            let mut multi_seek = terms.len() >= 2;
1214            if multi_seek {
1215                // `Some(_)` = the tight allow-list served the walk (verdict
1216                // folded below); `None` = slot does not extend the prefix,
1217                // fall through to the per-term walks.
1218                match storage.visit_allow_list_rows_with_comparisons(
1219                    page_permutation,
1220                    pattern,
1221                    snapshot,
1222                    start_after,
1223                    quad_slot,
1224                    terms,
1225                    graph.clone(),
1226                    merge_default_graph,
1227                    iri_only,
1228                    comparisons,
1229                    |row| {
1230                        if !emit(row) {
1231                            verdict = ScanExhaustion::Limited;
1232                            return Ok(false);
1233                        }
1234                        Ok(true)
1235                    },
1236                )? {
1237                    Some(walk_verdict) => {
1238                        if walk_verdict == ScanExhaustion::Limited {
1239                            verdict = ScanExhaustion::Limited;
1240                        }
1241                    }
1242                    None => multi_seek = false,
1243                }
1244            }
1245            if !multi_seek {
1246                // Non-contiguous slot (or a single term): one bound-pattern
1247                // walk per term, skipping terms that sort before the resume
1248                // cursor's own; the resuming term carries `start_after`.
1249                // Completing the loop serves the whole term list; the
1250                // limit/drop stop is `Limited`.
1251                let cursor_term = start_after.map(|quad| term_in_slot(quad, slot));
1252                let mut dont_skip = start_after.is_none();
1253                for term in terms {
1254                    if verdict == ScanExhaustion::Limited {
1255                        break;
1256                    }
1257                    let term_after = if dont_skip {
1258                        None
1259                    } else if Some(term) == cursor_term {
1260                        dont_skip = true;
1261                        start_after
1262                    } else {
1263                        continue;
1264                    };
1265                    let bound = bind_filter_term(pattern, slot, term);
1266                    storage.visit_pattern_rows_with_comparisons(
1267                        page_permutation,
1268                        &bound,
1269                        snapshot,
1270                        term_after,
1271                        graph.clone(),
1272                        merge_default_graph,
1273                        iri_only,
1274                        comparisons,
1275                        |row| {
1276                            if !emit(row) {
1277                                verdict = ScanExhaustion::Limited;
1278                                return Ok(false);
1279                            }
1280                            Ok(true)
1281                        },
1282                    )?;
1283                }
1284            }
1285            return Ok(verdict);
1286        }
1287
1288        // Plain pattern: one iterator for the whole walk; the storage-side
1289        // matcher applies bound slots, graph membership, the dedup cursor,
1290        // and whole-triple collapse before this callback runs — the row is
1291        // forwarded as raw key slices, nothing decoded per row.
1292        let permutation = permutation.unwrap_or_else(|| pattern.best_permutation(self.axis));
1293        let mut stopped = false;
1294        let verdict = storage.visit_pattern_rows_with_comparisons(
1295            permutation,
1296            pattern,
1297            snapshot,
1298            start_after,
1299            graph,
1300            merge_default_graph,
1301            iri_only,
1302            comparisons,
1303            |row| {
1304                if !emit(row) {
1305                    stopped = true;
1306                    return Ok(false);
1307                }
1308                Ok(true)
1309            },
1310        )?;
1311        Ok(if stopped {
1312            ScanExhaustion::Limited
1313        } else {
1314            verdict
1315        })
1316    }
1317
1318    /// Frame stream for a decoded `ScanPatternStream` request — the transport
1319    /// behind the tonic handler, shared with the in-process clients so both
1320    /// deployments run the identical streaming drain.
1321    ///
1322    /// The walk runs on ONE task for the whole prefix
1323    /// (`scan_filtered_streaming`), packing rows into
1324    /// [`SCAN_STREAM_FRAME_ROWS`] frames; the stream closes on prefix
1325    /// exhaustion (`exhausted`), after the request's `limit` rows
1326    /// (`limit`), or when the consumer drops it (`client-dropped`).
1327    ///
1328    /// **Dispatch:** the exact-stats gate
1329    /// ([`Self::scan_runs_on_caller`], `SCAN_DISPATCH_ROW_THRESHOLD`) picks
1330    /// the thread. A drain estimated at or below the threshold runs the
1331    /// whole walk on the calling worker and returns the frames as an
1332    /// already-collected stream — a µs-scale seek-to-EOF must not pay the
1333    /// blocking-pool wake (its CFS wakeup delay is the measured ~600 µs
1334    /// small-query stall). Larger or unestimable drains get the blocking
1335    /// task plus bounded channel below, unchanged. Frames, ordering, and
1336    /// error items are identical either way.
1337    #[allow(clippy::too_many_arguments)]
1338    pub fn scan_pattern_stream_frames(
1339        &self,
1340        permutation: Option<IndexPermutation>,
1341        pattern: EncodedTriplePattern,
1342        snapshot: SnapshotId,
1343        limit: u64,
1344        filter_slot: Option<PatternSlot>,
1345        filter_terms: Vec<EncodedTerm>,
1346        start_after: Option<EncodedQuad>,
1347        graph_filter_terms: Vec<EncodedTerm>,
1348        graph_filter_allow: bool,
1349        merge_default_graph: bool,
1350        iri_only: IriOnlyMask,
1351        comparisons: Vec<SlotComparison>,
1352        omitted: u8,
1353        verdict_wanted: bool,
1354    ) -> ScanPatternResponseStream {
1355        let mut trace = ScanTrace::new(self.trace);
1356        // Tsg keys omit the predicate; its wire field is this constant.
1357        let rdf_type_wire = Bytes::from(encode_term_bytes(&RDF_TYPE));
1358        // Caller-thread drain: estimate at or below the threshold bounds the
1359        // walk exactly as it bounds the unary gate's caller-thread
1360        // branch, so the
1361        // same dispatch-on-doubt rules apply (missing basis, stale sealed
1362        // profile, lock contention → dispatch). No channel, no pool wake;
1363        // frames collect eagerly and stream out already complete. The
1364        // consumer cannot drop mid-walk — the work is bounded by the
1365        // estimate, and a dropped consumer simply never polls the stream.
1366        if self.scan_runs_on_caller(permutation, &pattern, filter_slot, &filter_terms) {
1367            let mut remaining = limit; // 0 = unlimited
1368            let mut packer = FramePacker::with_omitted(omitted);
1369            let mut frames: Vec<pb::ScanPatternResponse> = Vec::new();
1370            let walk_started = Instant::now();
1371            let walked = self.scan_filtered_streaming(
1372                permutation,
1373                &pattern,
1374                snapshot,
1375                filter_slot,
1376                &filter_terms,
1377                start_after.as_ref(),
1378                &graph_filter_terms,
1379                graph_filter_allow,
1380                merge_default_graph,
1381                iri_only,
1382                &comparisons,
1383                |row| {
1384                    // Page-limit discipline, selected by the consumer's
1385                    // `verdict_wanted` declaration:
1386                    // - EDGE-triggered (wanted): a row arriving with the
1387                    //   request limit already reached proves more data
1388                    //   exists (stop; the stop-flush frame carries LIMITED)
1389                    //   but is not packed; when the data ends exactly at
1390                    //   the limit this row never arrives and the walk
1391                    //   completes — the terminal frame then reports it.
1392                    // - LEVEL-triggered (not wanted): stop AT the
1393                    //   limit'th row — no follow-up request can read a
1394                    //   full stream's terminal frame, so the look-ahead
1395                    //   walk buys nothing.
1396                    // Both stops flush the pending partial frame (the
1397                    // packed rows must not be lost).
1398                    if limit > 0 && remaining == 0 {
1399                        if !packer.is_empty() {
1400                            let frame_rows = packer.len();
1401                            // The EDGE-triggered stop-flush: a row
1402                            // arriving with the page full proved more
1403                            // data exists, and this site is reachable
1404                            // only under a purchased verdict (the LEVEL
1405                            // stop below ends unpurchased walks before a
1406                            // row can arrive with the page full). The
1407                            // contract the proto and TERMS state — the
1408                            // limit-stop flush carries LIMITED.
1409                            let mut stop_flush =
1410                                packer.take_frame(merge_default_graph, &rdf_type_wire);
1411                            if verdict_wanted {
1412                                stop_flush.exhausted =
1413                                    Some(scan_exhaustion_to_proto(ScanExhaustion::Limited) as i32);
1414                            }
1415                            frames.push(stop_flush);
1416                            trace.frame_sent(frame_rows, Duration::ZERO);
1417                        }
1418                        return false;
1419                    }
1420                    packer.push_row(row, merge_default_graph, remaining);
1421                    remaining = remaining.saturating_sub(1);
1422                    if packer.len() >= SCAN_STREAM_FRAME_ROWS {
1423                        let frame_rows = packer.len();
1424                        frames.push(packer.take_frame(merge_default_graph, &rdf_type_wire));
1425                        // Same trace shape as the dispatched branch; a
1426                        // collected frame has no channel send to time.
1427                        trace.frame_sent(frame_rows, Duration::ZERO);
1428                    }
1429                    if limit > 0 && remaining == 0 && !verdict_wanted {
1430                        if !packer.is_empty() {
1431                            let frame_rows = packer.len();
1432                            frames.push(packer.take_frame(merge_default_graph, &rdf_type_wire));
1433                            trace.frame_sent(frame_rows, Duration::ZERO);
1434                        }
1435                        return false;
1436                    }
1437                    true
1438                },
1439            );
1440            trace.walk = Some(walk_started.elapsed());
1441            let mut items: Vec<Result<pb::ScanPatternResponse, Status>> =
1442                frames.into_iter().map(Ok).collect();
1443            match walked {
1444                Ok(verdict) => {
1445                    // Flush the trailing partial frame of a COMPLETED walk
1446                    // under either flag — the packed rows must not be lost,
1447                    // and a limit-stop drain already flushed inside the
1448                    // walk. The flushed frame itself carries no verdict:
1449                    // mid-walk frames never do (the walk being live at a
1450                    // frame boundary says nothing about what follows it).
1451                    if verdict.is_terminal() && !packer.is_empty() {
1452                        let frame_rows = packer.len();
1453                        items.push(Ok(packer.take_frame(merge_default_graph, &rdf_type_wire)));
1454                        trace.frame_sent(frame_rows, Duration::ZERO);
1455                    }
1456                    // Terminal frame: the walk's own verdict, so a client
1457                    // that pulled this far knows the walk ended without a
1458                    // confirm request — but only when the verdict was
1459                    // purchased. Without `verdict_wanted` no frame on this
1460                    // stream carries a verdict at all, and none is sent.
1461                    if verdict_wanted && verdict.is_terminal() {
1462                        items.push(Ok(pb::ScanPatternResponse {
1463                            quads: Vec::new(),
1464                            exhausted: Some(scan_exhaustion_to_proto(verdict) as i32),
1465                        }));
1466                    }
1467                    // The label follows the walk's own verdict, not the
1468                    // row counter: at an exact boundary that COMPLETED
1469                    // (data ended exactly at the limit) the verdict is
1470                    // terminal and "exhausted" is the fact, matching the
1471                    // terminal frame just sent.
1472                    let reason = if verdict.is_terminal() {
1473                        "exhausted"
1474                    } else {
1475                        "limit"
1476                    };
1477                    trace.done(reason);
1478                }
1479                Err(error) => {
1480                    // Frames already collected stay ahead of the error,
1481                    // matching the channel's ordering; the trailing partial
1482                    // frame is dropped, as in the dispatched branch.
1483                    items.push(Err(Status::from(error)));
1484                    trace.done("error");
1485                }
1486            }
1487            return Box::pin(tokio_stream::iter(items));
1488        }
1489        // Two outstanding frames: backpressure without pinning much memory.
1490        let (tx, rx) = tokio::sync::mpsc::channel(2);
1491        let service = self.clone();
1492        tokio::task::spawn_blocking(move || {
1493            let mut remaining = limit; // 0 = unlimited
1494            let mut client_dropped = false;
1495            // Walk-side framebuffer: the callback copies each row's term
1496            // bytes once into the packer (contiguous, one allocation per
1497            // frame, no decode). Wire packing runs as one tight pass per
1498            // frame at the boundary — interleaving it per row measurably
1499            // thrashed the walk (~2x partition CPU).
1500            let mut packer = FramePacker::with_omitted(omitted);
1501            let walk_started = Instant::now();
1502            let walked = service.scan_filtered_streaming(
1503                permutation,
1504                &pattern,
1505                snapshot,
1506                filter_slot,
1507                &filter_terms,
1508                start_after.as_ref(),
1509                &graph_filter_terms,
1510                graph_filter_allow,
1511                merge_default_graph,
1512                iri_only,
1513                &comparisons,
1514                |row| {
1515                    // Page-limit discipline, selected by the consumer's
1516                    // `verdict_wanted` declaration (see the
1517                    // caller-collected branch's note for the full
1518                    // reasoning): EDGE-triggered when wanted — a row
1519                    // arriving with the request limit already reached
1520                    // proves more data exists (stop; no terminal frame)
1521                    // but is not packed, and data ending exactly at the
1522                    // limit lets the walk complete and the terminal frame
1523                    // report it; LEVEL-triggered when not — stop AT the
1524                    // limit'th row. Both stops flush the pending partial
1525                    // frame.
1526                    if limit > 0 && remaining == 0 {
1527                        if !packer.is_empty() {
1528                            let frame_rows = packer.len();
1529                            // The EDGE-triggered stop-flush: a row
1530                            // arriving with the page full proved more
1531                            // data exists, and this site is reachable
1532                            // only under a purchased verdict (the LEVEL
1533                            // stop below ends unpurchased walks before a
1534                            // row can arrive with the page full). The
1535                            // contract the proto and TERMS state — the
1536                            // limit-stop flush carries LIMITED.
1537                            let mut stop_flush =
1538                                packer.take_frame(merge_default_graph, &rdf_type_wire);
1539                            if verdict_wanted {
1540                                stop_flush.exhausted =
1541                                    Some(scan_exhaustion_to_proto(ScanExhaustion::Limited) as i32);
1542                            }
1543                            let send_started = Instant::now();
1544                            let sent = tx.blocking_send(Ok(stop_flush));
1545                            trace.frame_sent(frame_rows, send_started.elapsed());
1546                            if sent.is_err() {
1547                                client_dropped = true;
1548                            }
1549                        }
1550                        return false;
1551                    }
1552                    packer.push_row(row, merge_default_graph, remaining);
1553                    remaining = remaining.saturating_sub(1);
1554                    if packer.len() >= SCAN_STREAM_FRAME_ROWS {
1555                        let frame_rows = packer.len();
1556                        let response = packer.take_frame(merge_default_graph, &rdf_type_wire);
1557                        let send_started = Instant::now();
1558                        let sent = tx.blocking_send(Ok(response));
1559                        trace.frame_sent(frame_rows, send_started.elapsed());
1560                        if sent.is_err() {
1561                            client_dropped = true;
1562                            return false;
1563                        }
1564                    }
1565                    if limit > 0 && remaining == 0 && !verdict_wanted {
1566                        if !packer.is_empty() {
1567                            let frame_rows = packer.len();
1568                            let response = packer.take_frame(merge_default_graph, &rdf_type_wire);
1569                            let send_started = Instant::now();
1570                            let sent = tx.blocking_send(Ok(response));
1571                            trace.frame_sent(frame_rows, send_started.elapsed());
1572                            if sent.is_err() {
1573                                client_dropped = true;
1574                            }
1575                        }
1576                        return false;
1577                    }
1578                    true
1579                },
1580            );
1581            trace.walk = Some(walk_started.elapsed());
1582            match walked {
1583                Ok(verdict) => {
1584                    // Flush the trailing partial frame of a COMPLETED walk
1585                    // under either flag (a limit-stop drain already flushed
1586                    // inside the walk; a dropped stream has nowhere to
1587                    // send). The flushed frame carries no verdict —
1588                    // mid-walk frames never do.
1589                    if verdict.is_terminal() && !packer.is_empty() {
1590                        let frame_rows = packer.len();
1591                        let response = packer.take_frame(merge_default_graph, &rdf_type_wire);
1592                        let send_started = Instant::now();
1593                        let sent = tx.blocking_send(Ok(response));
1594                        trace.frame_sent(frame_rows, send_started.elapsed());
1595                        if sent.is_err() {
1596                            client_dropped = true;
1597                        }
1598                    }
1599                    // Terminal frame: the walk's own verdict (see the
1600                    // caller-collected branch's note), only when the
1601                    // verdict was purchased. A dropped stream has nowhere
1602                    // to send it — the client that dropped never reads a
1603                    // verdict anyway.
1604                    if verdict_wanted && verdict.is_terminal() && !client_dropped {
1605                        let _ = tx.blocking_send(Ok(pb::ScanPatternResponse {
1606                            quads: Vec::new(),
1607                            exhausted: Some(scan_exhaustion_to_proto(verdict) as i32),
1608                        }));
1609                    }
1610                    // Same verdict-driven label as the caller-collected
1611                    // branch: a walk that completed at an exact boundary
1612                    // is "exhausted" (the terminal frame says so), a
1613                    // limit-stop is "limit", and a dropped consumer is
1614                    // reported as the drop it is.
1615                    let reason = if client_dropped {
1616                        "client-dropped"
1617                    } else if verdict.is_terminal() {
1618                        "exhausted"
1619                    } else {
1620                        "limit"
1621                    };
1622                    trace.done(reason);
1623                }
1624                Err(error) => {
1625                    let _ = tx.blocking_send(Err(Status::from(error)));
1626                    trace.done("error");
1627                }
1628            }
1629        });
1630        Box::pin(ReceiverStream::new(rx))
1631    }
1632
1633    /// Axis that owns `permutation`.
1634    fn axis_of_permutation(permutation: IndexPermutation) -> PartitionAxis {
1635        PartitionAxis::from(permutation)
1636    }
1637
1638    fn require_owned_permutation(
1639        &self,
1640        rpc: &'static str,
1641        permutation: IndexPermutation,
1642        supported: &[IndexPermutation],
1643    ) -> Result<(), PartitionError> {
1644        if !supported.contains(&permutation) {
1645            return Err(PartitionError::UnsupportedPermutation { rpc, permutation });
1646        }
1647        let owner = Self::axis_of_permutation(permutation);
1648        if owner != self.axis {
1649            return Err(PartitionError::ScanPermutationNotOwned(rpc, self.axis));
1650        }
1651        Ok(())
1652    }
1653
1654    /// Domain scan: distinct slot-1 head terms under each slot-0 constraint
1655    /// of `permutation`.
1656    #[allow(clippy::too_many_arguments)]
1657    pub fn scan_domain(
1658        &self,
1659        permutation: IndexPermutation,
1660        constraints: &[EncodedTerm],
1661        snapshot: SnapshotId,
1662        limit: u64,
1663        start_after_constraint: Option<&EncodedTerm>,
1664        start_after_term: Option<&EncodedTerm>,
1665        graph_name: Option<&EncodedTerm>,
1666        graph_filter_terms: &[EncodedTerm],
1667        graph_filter_allow: bool,
1668        iri_only_head: bool,
1669    ) -> Result<Vec<waratah_storage::DomainScanHit>, PartitionError> {
1670        self.require_owned_permutation(
1671            "DomainScan",
1672            permutation,
1673            &[
1674                IndexPermutation::Spog,
1675                IndexPermutation::Sopg,
1676                IndexPermutation::Psog,
1677                IndexPermutation::Posg,
1678                IndexPermutation::Opsg,
1679            ],
1680        )?;
1681        if constraints.len() > waratah_stats::PUSHDOWN_TERMS_LIMIT as usize {
1682            return Err(PartitionError::DomainScanTooLarge(constraints.len()));
1683        }
1684        if constraints.is_empty() {
1685            return Ok(Vec::new());
1686        }
1687        let storage = self.storage.as_ref();
1688        Ok(storage.scan_domain(
1689            permutation,
1690            constraints,
1691            snapshot,
1692            limit,
1693            start_after_constraint,
1694            start_after_term,
1695            graph_name,
1696            graph_filter_terms,
1697            graph_filter_allow,
1698            iri_only_head,
1699        )?)
1700    }
1701
1702    /// Domain count scan: run lengths of slot-1 head terms under each
1703    /// slot-0 constraint of `permutation`, per `mode`. DistinctGraphs is
1704    /// incompatible with `merge_default_graph` (merge collapses G) and is
1705    /// rejected as invalid argument.
1706    #[allow(clippy::too_many_arguments)]
1707    pub fn scan_domain_counts(
1708        &self,
1709        permutation: IndexPermutation,
1710        constraints: &[EncodedTerm],
1711        snapshot: SnapshotId,
1712        limit: u64,
1713        start_after_constraint: Option<&EncodedTerm>,
1714        start_after_term: Option<&EncodedTerm>,
1715        graph_name: Option<&EncodedTerm>,
1716        graph_filter_terms: &[EncodedTerm],
1717        graph_filter_allow: bool,
1718        iri_only_head: bool,
1719        merge_default_graph: bool,
1720        mode: DomainCountMode,
1721    ) -> Result<Vec<waratah_storage::DomainScanCountHit>, PartitionError> {
1722        if mode == DomainCountMode::DistinctGraphs && merge_default_graph {
1723            return Err(PartitionError::InvalidCountMode);
1724        }
1725        self.require_owned_permutation(
1726            "DomainScanCounts",
1727            permutation,
1728            &[
1729                IndexPermutation::Spog,
1730                IndexPermutation::Sopg,
1731                IndexPermutation::Psog,
1732                IndexPermutation::Posg,
1733                IndexPermutation::Opsg,
1734            ],
1735        )?;
1736        if constraints.len() > waratah_stats::PUSHDOWN_TERMS_LIMIT as usize {
1737            // Terms role (the constant is shared with driver rows by
1738            // design — see the [`waratah_stats::PUSHDOWN_TERMS_LIMIT`]
1739            // definition): the constraint list is what rides the wire;
1740            // it is a terms limit, and the consumer is the
1741            // chunked/serial delivery built for it.
1742            return Err(PartitionError::DomainScanTooLarge(constraints.len()));
1743        }
1744        if constraints.is_empty() {
1745            return Ok(Vec::new());
1746        }
1747        let storage = self.storage.as_ref();
1748        Ok(storage.scan_domain_counts(
1749            permutation,
1750            constraints,
1751            snapshot,
1752            limit,
1753            start_after_constraint,
1754            start_after_term,
1755            graph_name,
1756            graph_filter_terms,
1757            graph_filter_allow,
1758            iri_only_head,
1759            merge_default_graph,
1760            mode,
1761        )?)
1762    }
1763
1764    /// Axis head scan: distinct slot-0 head terms of the whole `permutation`
1765    /// CF. `head_prefixes` are opaque seek-union byte ranges (empty =
1766    /// unfiltered); the partition never interprets them.
1767    #[allow(clippy::too_many_arguments)]
1768    pub fn scan_axis_head(
1769        &self,
1770        permutation: IndexPermutation,
1771        snapshot: SnapshotId,
1772        limit: u64,
1773        start_after_term: Option<&EncodedTerm>,
1774        graph_name: Option<&EncodedTerm>,
1775        graph_filter_terms: &[EncodedTerm],
1776        graph_filter_allow: bool,
1777        iri_only_head: bool,
1778        head_prefixes: &[Vec<u8>],
1779    ) -> Result<Vec<EncodedTerm>, PartitionError> {
1780        self.require_owned_permutation(
1781            "AxisHeadScan",
1782            permutation,
1783            &[
1784                IndexPermutation::Spog,
1785                IndexPermutation::Psog,
1786                IndexPermutation::Opsg,
1787                IndexPermutation::Tsg,
1788            ],
1789        )?;
1790        let storage = self.storage.as_ref();
1791        Ok(storage.scan_axis_head(
1792            permutation,
1793            snapshot,
1794            limit,
1795            start_after_term,
1796            graph_name,
1797            graph_filter_terms,
1798            graph_filter_allow,
1799            iri_only_head,
1800            head_prefixes,
1801        )?)
1802    }
1803
1804    /// Max commit_ts among the versioned keys whose slot-0 head term falls
1805    /// under `head_prefixes` (geo upgrade stage 1: the swap-timestamp bound,
1806    /// derived from the walked data itself — a freshly opened process's
1807    /// counter is 0 and says nothing about rows written by earlier
1808    /// processes, and the wall clock may have drifted since they landed).
1809    pub fn axis_head_max_commit_ts(
1810        &self,
1811        permutation: IndexPermutation,
1812        head_prefixes: &[Vec<u8>],
1813    ) -> Result<u64, PartitionError> {
1814        self.require_owned_permutation(
1815            "AxisHeadMaxCommitTs",
1816            permutation,
1817            &[
1818                IndexPermutation::Spog,
1819                IndexPermutation::Psog,
1820                IndexPermutation::Opsg,
1821                IndexPermutation::Tsg,
1822            ],
1823        )?;
1824        let storage = self.storage.as_ref();
1825        Ok(storage.max_commit_ts_under_prefixes(permutation, head_prefixes)?)
1826    }
1827
1828    /// Axis head count, `TOTAL` mode: distinct slot-0 head terms of the
1829    /// whole `permutation` CF.
1830    #[allow(clippy::too_many_arguments)]
1831    pub fn count_axis_heads(
1832        &self,
1833        permutation: IndexPermutation,
1834        snapshot: SnapshotId,
1835        graph_name: Option<&EncodedTerm>,
1836        graph_filter_terms: &[EncodedTerm],
1837        graph_filter_allow: bool,
1838        iri_only_head: bool,
1839    ) -> Result<u64, PartitionError> {
1840        self.require_owned_permutation(
1841            "AxisHeadScanCounts",
1842            permutation,
1843            &[
1844                IndexPermutation::Spog,
1845                IndexPermutation::Psog,
1846                IndexPermutation::Opsg,
1847                IndexPermutation::Tsg,
1848            ],
1849        )?;
1850        let storage = self.storage.as_ref();
1851        Ok(storage.count_axis_heads(
1852            permutation,
1853            snapshot,
1854            graph_name,
1855            graph_filter_terms,
1856            graph_filter_allow,
1857            iri_only_head,
1858        )?)
1859    }
1860
1861    /// Axis head count, `PER_HEAD` mode: per-head distinct slot-1 counts.
1862    #[allow(clippy::too_many_arguments)]
1863    pub fn scan_axis_head_counts(
1864        &self,
1865        permutation: IndexPermutation,
1866        snapshot: SnapshotId,
1867        limit: u64,
1868        start_after_term: Option<&EncodedTerm>,
1869        graph_name: Option<&EncodedTerm>,
1870        graph_filter_terms: &[EncodedTerm],
1871        graph_filter_allow: bool,
1872        iri_only_head: bool,
1873    ) -> Result<Vec<waratah_storage::AxisHeadCountHit>, PartitionError> {
1874        self.require_owned_permutation(
1875            "AxisHeadScanCounts",
1876            permutation,
1877            &[
1878                IndexPermutation::Spog,
1879                IndexPermutation::Psog,
1880                IndexPermutation::Opsg,
1881                IndexPermutation::Tsg,
1882            ],
1883        )?;
1884        let storage = self.storage.as_ref();
1885        Ok(storage.scan_axis_head_counts(
1886            permutation,
1887            snapshot,
1888            limit,
1889            start_after_term,
1890            graph_name,
1891            graph_filter_terms,
1892            graph_filter_allow,
1893            iri_only_head,
1894        )?)
1895    }
1896
1897    /// Count matching quads as of `snapshot` without returning rows.
1898    ///
1899    /// Same pattern / permutation / broadcast-filter rules as [`Self::scan_filtered`].
1900    /// `limit` of `0` is unlimited; a positive limit stops once that many matches
1901    /// have been counted.
1902    #[allow(clippy::too_many_arguments)]
1903    pub fn count_filtered(
1904        &self,
1905        permutation: Option<IndexPermutation>,
1906        pattern: &EncodedTriplePattern,
1907        snapshot: SnapshotId,
1908        limit: u64,
1909        filter_slot: Option<PatternSlot>,
1910        filter_terms: &[EncodedTerm],
1911        graph_filter_terms: &[EncodedTerm],
1912        graph_filter_allow: bool,
1913        merge_default_graph: bool,
1914    ) -> Result<u64, PartitionError> {
1915        self.count_filtered_inner(
1916            permutation,
1917            pattern,
1918            snapshot,
1919            limit,
1920            filter_slot,
1921            filter_terms,
1922            graph_filter_terms,
1923            graph_filter_allow,
1924            merge_default_graph,
1925            false,
1926        )
1927    }
1928
1929    /// [`Self::count_filtered`] with the parallel count walk force-disabled:
1930    /// the dispatch gate's on-caller path serves counts its exact stats
1931    /// judge µs-scale, where the worker-pool wake would outweigh the walk.
1932    /// The storage-side `WARATAH_COUNT_WALKS` knob stays authoritative for
1933    /// the dispatched path.
1934    #[allow(clippy::too_many_arguments)]
1935    pub fn count_filtered_on_caller(
1936        &self,
1937        permutation: Option<IndexPermutation>,
1938        pattern: &EncodedTriplePattern,
1939        snapshot: SnapshotId,
1940        limit: u64,
1941        filter_slot: Option<PatternSlot>,
1942        filter_terms: &[EncodedTerm],
1943        graph_filter_terms: &[EncodedTerm],
1944        graph_filter_allow: bool,
1945        merge_default_graph: bool,
1946    ) -> Result<u64, PartitionError> {
1947        self.count_filtered_inner(
1948            permutation,
1949            pattern,
1950            snapshot,
1951            limit,
1952            filter_slot,
1953            filter_terms,
1954            graph_filter_terms,
1955            graph_filter_allow,
1956            merge_default_graph,
1957            true,
1958        )
1959    }
1960
1961    #[allow(clippy::too_many_arguments)]
1962    fn count_filtered_inner(
1963        &self,
1964        permutation: Option<IndexPermutation>,
1965        pattern: &EncodedTriplePattern,
1966        snapshot: SnapshotId,
1967        limit: u64,
1968        filter_slot: Option<PatternSlot>,
1969        filter_terms: &[EncodedTerm],
1970        graph_filter_terms: &[EncodedTerm],
1971        graph_filter_allow: bool,
1972        merge_default_graph: bool,
1973        force_serial: bool,
1974    ) -> Result<u64, PartitionError> {
1975        let graph = GByteFilter::compile(graph_filter_terms, graph_filter_allow);
1976        let storage = self.storage.as_ref();
1977
1978        if let (Some(slot), terms) = (filter_slot, filter_terms)
1979            && !terms.is_empty()
1980        {
1981            if terms.len() >= 2 {
1982                let quad_slot = pattern_slot_to_quad(slot);
1983                let permutation =
1984                    resolve_broadcast_permutation(storage, permutation, pattern, slot, &terms[0]);
1985                if let Some(total) = count_page_graph_allow_list(
1986                    storage,
1987                    permutation,
1988                    pattern,
1989                    snapshot,
1990                    limit,
1991                    &graph,
1992                    merge_default_graph,
1993                    quad_slot,
1994                    terms,
1995                )? {
1996                    return Ok(total);
1997                }
1998            }
1999            return count_filter_terms_separately(
2000                storage,
2001                permutation,
2002                pattern,
2003                snapshot,
2004                limit,
2005                &graph,
2006                merge_default_graph,
2007                slot,
2008                terms,
2009                force_serial,
2010            );
2011        }
2012
2013        count_page_graph(
2014            storage,
2015            permutation,
2016            pattern,
2017            snapshot,
2018            limit,
2019            &graph,
2020            merge_default_graph,
2021            &self.tsg_class_totals_hint(permutation, pattern, storage.axis()),
2022            force_serial,
2023        )
2024    }
2025
2026    /// Flush MemTables to SST files. Stats rotation is handled by the event listener.
2027    /// Apply geometry-index postings (O axis only; apply-only, verbatim).
2028    ///
2029    /// The partition NEVER derives S2 cells here and never reads blobs —
2030    /// postings are exactly what compute sent (cell id, term bytes, MVCC
2031    /// metadata, optional CRS84 envelope).
2032    pub fn apply_geo(&self, puts: &[GeoIndexPut]) -> Result<u64, PartitionError> {
2033        if self.axis != PartitionAxis::O {
2034            return Err(PartitionError::from(
2035                waratah_storage::StorageError::GeoIndexNotOnAxis(self.axis),
2036            ));
2037        }
2038        // Postings are store writes too: raise the counter so a rebuild whose
2039        // cover pass is its only write (no orphans, or all orphans invalid)
2040        // still finishes with a counter that reflects the coverage ts.
2041        for put in puts {
2042            self.max_commit_ts
2043                .fetch_max(put.commit_ts.0, std::sync::atomic::Ordering::Relaxed);
2044        }
2045        let storage = self.storage.as_ref();
2046        storage.apply_geo_puts(puts)?;
2047        let mut stats = self
2048            .stats
2049            .lock()
2050            .map_err(|_| PartitionError::LockPoisoned)?;
2051        for put in puts {
2052            if put.op == waratah_storage::StorageOp::Put {
2053                // The histogram rides its own CF-keyed overlay (like the
2054                // catalog count and the temporal histogram): its SST blob
2055                // is produced by the geo CF, so it rotates on that CF's
2056                // flushes, not the canonical hexastore flush.
2057                stats.observe_geo_posting(put.cell_id);
2058            }
2059        }
2060        Ok(puts.len() as u64)
2061    }
2062
2063    /// Delete every posting of one encoded geo term (O axis; rebuild).
2064    pub fn delete_geo_term(&self, term: &[u8]) -> Result<u64, PartitionError> {
2065        if self.axis != PartitionAxis::O {
2066            return Err(PartitionError::from(
2067                waratah_storage::StorageError::GeoIndexNotOnAxis(self.axis),
2068            ));
2069        }
2070        let storage = self.storage.as_ref();
2071        Ok(storage.delete_geo_term(term)?)
2072    }
2073
2074    /// Apply replace pairs as ONE batch on this axis (the migration
2075    /// primitive; served by every axis).
2076    pub fn apply_replaces(
2077        &self,
2078        pairs: &[waratah_storage::ReplacePair],
2079        commit_ts: waratah_storage::CommitTs,
2080    ) -> Result<u64, PartitionError> {
2081        // A write: serialize under the partition write mutex and bump the
2082        // high-water commit_ts like every other write path.
2083        let _write_guard = self
2084            .write_mutex
2085            .lock()
2086            .map_err(|_| PartitionError::LockPoisoned)?;
2087        self.max_commit_ts
2088            .fetch_max(commit_ts.0, std::sync::atomic::Ordering::Relaxed);
2089        let storage = self.storage.as_ref();
2090        Ok(storage.apply_replace_pairs(pairs, commit_ts)?)
2091    }
2092
2093    /// Begin the geo index rebuild: take the rebuild lease (free, or
2094    /// expired-stale takeover) and wipe the whole `geo_index` CF. `Ok(true)`
2095    /// = this caller holds the lease and owns the walk; `Ok(false)` = a
2096    /// fresh lease is held elsewhere (wait on Describe). O axis only.
2097    pub fn begin_geo_rebuild(&self) -> Result<Option<u64>, PartitionError> {
2098        if self.axis != PartitionAxis::O {
2099            return Err(PartitionError::from(
2100                waratah_storage::StorageError::GeoIndexNotOnAxis(self.axis),
2101            ));
2102        }
2103        let now = std::time::Instant::now();
2104        let taken = {
2105            let mut lease = self
2106                .geo_rebuild_lease
2107                .lock()
2108                .map_err(|_| PartitionError::LockPoisoned)?;
2109            let free = match *lease {
2110                None => true,
2111                Some(deadline) => now >= deadline,
2112            };
2113            if free {
2114                *lease = Some(now + GEO_REBUILD_LEASE);
2115            }
2116            free
2117        };
2118        if !taken {
2119            return Ok(None);
2120        }
2121        // The lease is OURS from here: any failure after this point must
2122        // release it on the way out. A FAILED begin is not a dead driver —
2123        // the caller knows the rebuild did not start — and pinning the lease
2124        // for the rest of its duration would block every other driver's
2125        // begin until the deadline expired (same shape as the text begin).
2126        let outcome = (|| -> Result<(), PartitionError> {
2127            #[cfg(test)]
2128            if FAIL_GEO_WIPE.with(|slot| slot.get()).is_some() {
2129                FAIL_GEO_WIPE.with(|slot| slot.set(None));
2130                return Err(PartitionError::Storage(
2131                    waratah_storage::StorageError::Backend(
2132                        "injected geo index wipe failure".to_owned(),
2133                    ),
2134                ));
2135            }
2136            // Wipe under the taken lease: the rebuild is an authoritative
2137            // full replacement (postings of writes racing the walk survive
2138            // it — the write path flushes postings after hexastore commits).
2139            self.storage.as_ref().wipe_geo_index()?;
2140            // The rebuild REPLACES the advisory sketch: the re-coverage
2141            // re-applies every posting, so counts observed before the wipe
2142            // must not survive.
2143            let mut stats = self
2144                .stats
2145                .lock()
2146                .map_err(|_| PartitionError::LockPoisoned)?;
2147            stats.reset_geo_open();
2148            Ok(())
2149        })();
2150        if let Err(error) = outcome {
2151            // Best-effort release: if the lease mutex itself is poisoned
2152            // the deadline expires on its own, and the original error is
2153            // still the one worth reporting. The lease has no token, but no
2154            // takeover can have happened between the take and this
2155            // synchronous, await-free failure path — the deadline is fresh.
2156            let mut lease = self
2157                .geo_rebuild_lease
2158                .lock()
2159                .map_err(|_| PartitionError::LockPoisoned)?;
2160            *lease = None;
2161            return Err(error);
2162        }
2163        Ok(Some(
2164            self.max_commit_ts
2165                .load(std::sync::atomic::Ordering::Relaxed),
2166        ))
2167    }
2168
2169    /// Refresh the held lease's deadline (the driver calls this per batch;
2170    /// a driver that stalls past the deadline loses the lease to takeover).
2171    pub fn renew_geo_rebuild_lease(&self) -> Result<(), PartitionError> {
2172        let mut lease = self
2173            .geo_rebuild_lease
2174            .lock()
2175            .map_err(|_| PartitionError::LockPoisoned)?;
2176        if let Some(deadline) = lease.as_mut() {
2177            *deadline = std::time::Instant::now() + GEO_REBUILD_LEASE;
2178        }
2179        Ok(())
2180    }
2181
2182    /// Finish the geo index rebuild: stamp `epoch = max(previous epoch
2183    /// number, max commit_ts observed on this partition)` (equal, never +1)
2184    /// and release the lease. The previous-epoch floor keeps a rebuild that
2185    /// wrote nothing counter-visible (no orphans; postings only) in a
2186    /// freshly opened process from regressing the epoch to 0 over data at
2187    /// higher ts. Rejected unless the caller holds a fresh lease.
2188    ///
2189    /// Validate, stamp, and release under ONE hold of the lease mutex.
2190    /// Releasing before the stamp opened a window where a peer's
2191    /// `begin_geo_rebuild` could take the free lease and wipe the index
2192    /// BEFORE our stamp landed — a stamped epoch over a cleared index, and
2193    /// a peer walk re-covering a store while the finish still believed it
2194    /// owned the lease (same shape as the text finish). The release happens
2195    /// on the error paths too — a failed stamp must not pin the lease for
2196    /// the rest of its duration.
2197    pub fn finish_geo_rebuild(&self) -> Result<u64, PartitionError> {
2198        if self.axis != PartitionAxis::O {
2199            return Err(PartitionError::from(
2200                waratah_storage::StorageError::GeoIndexNotOnAxis(self.axis),
2201            ));
2202        }
2203        {
2204            let mut lease = self
2205                .geo_rebuild_lease
2206                .lock()
2207                .map_err(|_| PartitionError::LockPoisoned)?;
2208            let held = matches!(*lease, Some(deadline) if std::time::Instant::now() < deadline);
2209            let outcome = if held {
2210                self.stamp_geo_epoch()
2211            } else {
2212                Err(PartitionError::from(
2213                    waratah_storage::StorageError::Backend(
2214                        "geo rebuild finish without a fresh lease".to_owned(),
2215                    ),
2216                ))
2217            };
2218            // Release LAST — and on every path: the lease has no token, but
2219            // nothing can change hands while this mutex is held, so what we
2220            // verified (or failed to verify) is exactly what we clear.
2221            *lease = None;
2222            outcome
2223        }
2224    }
2225
2226    /// The epoch a stamping finish writes: the process-local commit counter
2227    /// floored at the previously stamped epoch number, and the index stamp.
2228    /// Split from [`Self::finish_geo_rebuild`] so the lease mutex can be
2229    /// held across the whole stamp without borrowing conflicts.
2230    fn stamp_geo_epoch(&self) -> Result<u64, PartitionError> {
2231        #[cfg(test)]
2232        let stamp_report = BLOCK_GEO_STAMP.with(|slot| slot.take());
2233        #[cfg(test)]
2234        if let Some(sender) = &stamp_report {
2235            // Hold the stamp open long enough for the test's peer begin to
2236            // run against it; the message order decides the assertion.
2237            let _ = sender.send("stamp-begun");
2238            std::thread::sleep(Duration::from_millis(100));
2239        }
2240        let counter = self
2241            .max_commit_ts
2242            .load(std::sync::atomic::Ordering::Relaxed);
2243        // Floor at the previously stamped epoch number: a rebuild that writes
2244        // nothing counter-visible (no orphans — postings only) in a freshly
2245        // opened process would otherwise stamp 0 over a store whose data sits
2246        // at higher ts. The raw number survives the wipe (which dropped only
2247        // the liveness marker), so it is readable here under the lease.
2248        let previous = self.storage.as_ref().geo_index_epoch_number()?;
2249        let epoch = counter.max(previous);
2250        self.storage.as_ref().set_geo_index_epoch(epoch)?;
2251        #[cfg(test)]
2252        if let Some(sender) = &stamp_report {
2253            // Reported while still under the lease hold: "stamp-written"
2254            // implies the stamp is durable and the lease not yet released.
2255            let _ = sender.send("stamp-written");
2256        }
2257        Ok(epoch)
2258    }
2259
2260    /// Whether a FRESH geo rebuild lease is held (a stale lease reports
2261    /// false — takeover allowed).
2262    pub fn geo_rebuild_in_progress(&self) -> bool {
2263        match self.geo_rebuild_lease.lock().map(|lease| *lease) {
2264            Ok(Some(deadline)) => std::time::Instant::now() < deadline,
2265            _ => false,
2266        }
2267    }
2268
2269    /// Open the text index if it exists on disk but is not held yet.
2270    ///
2271    /// Only an existing sidecar is adopted: creating a directory requires a
2272    /// [`Self::begin_text_rebuild`] request, which is the only caller that can
2273    /// name the analyzer and the seed length. Returns `Ok(None)` when no index
2274    /// exists yet.
2275    fn ensure_text_open(&self) -> Result<(), PartitionError> {
2276        let mut handle = self
2277            .text_index
2278            .lock()
2279            .map_err(|_| PartitionError::LockPoisoned)?;
2280        if handle.is_some() {
2281            return Ok(());
2282        }
2283        let Some(dir) = self.storage.text_index_dir() else {
2284            return Ok(());
2285        };
2286        let Some(meta) = waratah_text_index::meta::read_meta(&dir)? else {
2287            return Ok(());
2288        };
2289        let options = waratah_text_index::TextIndexOptions::new(
2290            meta.analyzer,
2291            meta.seed_chars,
2292            meta.fingerprint,
2293        );
2294        *handle = Some(std::sync::Arc::new(
2295            waratah_text_index::TextIndex::open_or_create(&dir, &options)?,
2296        ));
2297        Ok(())
2298    }
2299
2300    /// The open text index handle, adopting the sidecar or self-creating
2301    /// when the launcher configured this partition to.
2302    ///
2303    /// Self-create covers the `PutTextIndex` before any build case: with the
2304    /// plugin enabled, a startup build that failed leaves no sidecar, and
2305    /// every string insert would otherwise fail with `NotBuilt` — writes
2306    /// must keep working (invariant A: new rows carry documents), while
2307    /// `text:query` keeps failing until a real walk stamps the epoch
2308    /// (invariant B). The created index has no epoch, exactly that state.
2309    fn text_index_handle(
2310        &self,
2311    ) -> Result<std::sync::Arc<waratah_text_index::TextIndex>, PartitionError> {
2312        self.ensure_text_open()?;
2313        let handle = self
2314            .text_index
2315            .lock()
2316            .map_err(|_| PartitionError::LockPoisoned)?;
2317        if let Some(index) = handle.as_ref() {
2318            return Ok(std::sync::Arc::clone(index));
2319        }
2320        drop(handle);
2321        let Some(options) = self.text_self_create.as_ref() else {
2322            return Err(PartitionError::Text(
2323                waratah_text_index::TextIndexError::NotBuilt,
2324            ));
2325        };
2326        let index = std::sync::Arc::new(match self.storage.text_index_dir() {
2327            Some(dir) => waratah_text_index::TextIndex::open_or_create(&dir, options)?,
2328            None => waratah_text_index::TextIndex::create_in_ram(options)?,
2329        });
2330        let mut handle = self
2331            .text_index
2332            .lock()
2333            .map_err(|_| PartitionError::LockPoisoned)?;
2334        // Another writer may have created it between the drop and this lock;
2335        // either handle answers identically (same sidecar config), keep the
2336        // stored one.
2337        Ok(handle.get_or_insert(std::sync::Arc::clone(&index)).clone())
2338    }
2339
2340    /// The fingerprint the index on this partition was built with, if any.
2341    ///
2342    /// Reads the in-memory handle when open, else the sidecar; `None` means
2343    /// the partition has no text index at all.
2344    pub fn text_index_fingerprint(&self) -> Result<Option<String>, PartitionError> {
2345        if let Ok(handle) = self.text_index.lock()
2346            && let Some(index) = handle.as_ref()
2347        {
2348            return Ok(Some(index.fingerprint().to_owned()));
2349        }
2350        match self.storage.text_index_dir() {
2351            Some(dir) => {
2352                Ok(waratah_text_index::meta::read_meta(&dir)?.map(|meta| meta.fingerprint))
2353            }
2354            None => Ok(None),
2355        }
2356    }
2357
2358    /// Configure the text config a `PutTextIndex` may self-create the index
2359    /// with when no sidecar exists (the launcher passes it for the O axis
2360    /// when the plugin is enabled).
2361    pub fn with_text_self_create(
2362        mut self,
2363        options: Option<waratah_text_index::TextIndexOptions>,
2364    ) -> Self {
2365        self.text_self_create = options;
2366        self
2367    }
2368
2369    /// Apply text-index documents (O axis only, applied verbatim).
2370    ///
2371    /// Called by compute BEFORE the three axis `InsertQuads` calls: a visible
2372    /// row therefore never lacks its document. The Tantivy commit and the
2373    /// reader reload happen here, before the acknowledgement, so a later
2374    /// query on this process cannot miss the document.
2375    ///
2376    /// A fresh WIPE rebuild lease fences puts: the wiping build is about to
2377    /// delete every document, and a put committed in that window would be
2378    /// deleted before its row lands, breaking invariant A (the walk's
2379    /// exclusive cursor would never re-derive the row's document). The
2380    /// rejection maps to a transient status, but the standard retry budget
2381    /// (milliseconds) is far shorter than any wipe — in practice the
2382    /// insert FAILS LOUDLY and the load is rerun (documents are
2383    /// idempotent); C3's document-before-row order holds again once the
2384    /// rebuild finishes. An
2385    /// ADDITIVE (live-repair) lease does not fence: it exists precisely so
2386    /// in-progress writes keep landing documents.
2387    pub fn apply_text(
2388        &self,
2389        docs: &[waratah_storage::TextIndexDoc],
2390    ) -> Result<u64, PartitionError> {
2391        if self.axis != PartitionAxis::O {
2392            return Err(PartitionError::from(
2393                waratah_storage::StorageError::TextIndexNotOnAxis(self.axis),
2394            ));
2395        }
2396        if docs.is_empty() {
2397            return Ok(0);
2398        }
2399        // Fail-closed lexical bound (defense in depth: compute screens the
2400        // same bound before the RPC, but this partition is the authority —
2401        // an older or misbehaving client must not land an unindexable
2402        // document).
2403        if let Some(doc) = docs
2404            .iter()
2405            .find(|doc| doc.lexical.len() > waratah_storage::text_index::MAX_INDEXED_LEXICAL_BYTES)
2406        {
2407            return Err(PartitionError::Storage(
2408                waratah_storage::StorageError::Backend(format!(
2409                    "text index: a string literal's lexical is {} bytes, above the {} KiB \
2410                     indexed-lexical limit",
2411                    doc.lexical.len(),
2412                    waratah_storage::text_index::MAX_INDEXED_LEXICAL_BYTES / 1024
2413                )),
2414            ));
2415        }
2416        // The wipe fence lives on the INDEX (see `TextIndex::add_batch`):
2417        // the fence check and the document commit run under one hold of the
2418        // writer mutex, the same hold the wipe's flag-and-delete runs
2419        // under, so a put either commits before the wipe's delete (a
2420        // pre-wipe put — its rows land before the walk's page and the walk
2421        // re-derives them) or is rejected here atomically. The rejection
2422        // maps to a transient status, but the standard retry budget
2423        // (milliseconds) is far shorter than any wipe — in practice the
2424        // insert FAILS LOUDLY and the load is rerun (documents are
2425        // idempotent; no row lands on the rejected path). The old fence
2426        // checked the rebuild lease BEFORE taking the writer — a
2427        // check-then-act gap — and stayed up for the whole walk, fencing
2428        // the walk's OWN re-derivation frames.
2429        let index = self.text_index_handle()?;
2430        index.add_batch(docs).map_err(|error| match error {
2431            waratah_text_index::TextIndexError::WipeInProgress => {
2432                PartitionError::Storage(waratah_storage::StorageError::Backend(
2433                    "text index rebuild is wiping; the write failed — rerun the load \
2434                     once the rebuild finishes"
2435                        .to_owned(),
2436                ))
2437            }
2438            other => other.into(),
2439        })?;
2440        // Feed the seed accumulator while a rebuild is in progress (the
2441        // buffers are `Some` only between begin and finish). Recording
2442        // AFTER the commit keeps the sketch's coverage identical to the
2443        // index's: a rejected frame counts in neither.
2444        if let Ok(mut buffers) = self.text_seed_buffers.lock()
2445            && let Some(state) = buffers.as_mut()
2446        {
2447            for doc in docs {
2448                state.record(&doc.lexical);
2449            }
2450        }
2451        Ok(docs.len() as u64)
2452    }
2453
2454    /// Drain one text candidate request (O axis only).
2455    ///
2456    /// Returns distinct encoded terms. `NotBuilt` is an error rather than an
2457    /// empty set: returning zero rows from an index that does not exist is the
2458    /// trusted-but-empty state the plugin forbids. Reads never SELF-CREATE:
2459    /// only a put may bring the index into existence (invariant A is about
2460    /// writes), and every candidate scan is plan-gated on a trusted index
2461    /// whose sidecar `ensure_text_open` can adopt.
2462    pub fn text_candidates(
2463        &self,
2464        request: &waratah_text_index::TextSearchRequest,
2465    ) -> Result<Vec<Vec<u8>>, PartitionError> {
2466        if self.axis != PartitionAxis::O {
2467            return Err(PartitionError::from(
2468                waratah_storage::StorageError::TextIndexNotOnAxis(self.axis),
2469            ));
2470        }
2471        self.ensure_text_open()?;
2472        let handle = self
2473            .text_index
2474            .lock()
2475            .map_err(|_| PartitionError::LockPoisoned)?;
2476        let Some(index) = handle.as_ref() else {
2477            return Err(PartitionError::Text(
2478                waratah_text_index::TextIndexError::NotBuilt,
2479            ));
2480        };
2481        Ok(index.search(request)?)
2482    }
2483
2484    /// Begin the text index rebuild: refuse a config that does not match the
2485    /// stored index, then take the lease (free, or expired-stale takeover)
2486    /// and open-or-create the directory. `Ok(Some(token))` = this caller
2487    /// holds the lease and owns the walk; every renew / finish must carry
2488    /// the token, so a driver that lost its lease (expired and taken over,
2489    /// or a partition restart) can neither release nor stamp. `Ok(None)` = a
2490    /// fresh lease is held elsewhere.
2491    ///
2492    /// `wipe` mirrors the caller's situation, not a preference: a startup
2493    /// build wipes because nothing is serving, and a repair build does not
2494    /// because an in-progress write's document may describe a row the walk
2495    /// cannot see yet. A WIPE lease fences `PutTextIndex` until it is
2496    /// released (see [`Self::apply_text`]); an additive lease does not.
2497    pub fn begin_text_rebuild(
2498        &self,
2499        options: &waratah_text_index::TextIndexOptions,
2500        wipe: bool,
2501    ) -> Result<Option<u64>, PartitionError> {
2502        if self.axis != PartitionAxis::O {
2503            return Err(PartitionError::from(
2504                waratah_storage::StorageError::TextIndexNotOnAxis(self.axis),
2505            ));
2506        }
2507        // Config identity is checked before the lease so a mismatch cannot
2508        // leave the caller holding a lease it will never finish.
2509        if let Some(stored) = self.text_index_fingerprint()?
2510            && stored != options.fingerprint
2511        {
2512            let dir = self
2513                .storage
2514                .text_index_dir()
2515                .map(|dir| dir.display().to_string())
2516                .unwrap_or_else(|| "<memory>".to_owned());
2517            return Err(PartitionError::Storage(
2518                waratah_storage::StorageError::Backend(format!(
2519                    "the text index at {dir} was built with {stored}, not {}; changing the \
2520                     analyzer or seed length requires an offline rebuild: stop the cluster and \
2521                     delete that directory",
2522                    options.fingerprint
2523                )),
2524            ));
2525        }
2526        let now = std::time::Instant::now();
2527        let taken = {
2528            let mut lease = self
2529                .text_rebuild_lease
2530                .lock()
2531                .map_err(|_| PartitionError::LockPoisoned)?;
2532            let free = match *lease {
2533                None => true,
2534                Some(state) => now >= state.deadline,
2535            };
2536            if free {
2537                // Token 0 is never minted: it means "no token" on the wire.
2538                let token = self
2539                    .text_lease_counter
2540                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2541                    + 1;
2542                *lease = Some(TextRebuildLease {
2543                    deadline: now + TEXT_REBUILD_LEASE,
2544                    token,
2545                    wiped: wipe,
2546                });
2547                Some(token)
2548            } else {
2549                None
2550            }
2551        };
2552        let Some(token) = taken else {
2553            return Ok(None);
2554        };
2555        // The lease is OURS from here: any failure after this point must
2556        // release it on the way out. A FAILED begin is not a dead driver —
2557        // the caller knows the rebuild did not start — and pinning the
2558        // lease for the rest of its hour would block every other driver's
2559        // begin (bounded wait → refusal) until the deadline expired.
2560        let outcome = self.open_and_wipe_text_index(options, wipe);
2561        if let Err(error) = outcome {
2562            // Token-checked release, same hygiene as finish. If the lease
2563            // mutex itself is poisoned the release is best-effort: the
2564            // original error is still the one worth reporting, and the
2565            // deadline expires on its own.
2566            let mut lease = self
2567                .text_rebuild_lease
2568                .lock()
2569                .map_err(|_| PartitionError::LockPoisoned)?;
2570            if matches!(*lease, Some(state) if state.token == token) {
2571                *lease = None;
2572            }
2573            return Err(error);
2574        }
2575        // A rebuild is the sketch's only writer: start the per-rebuild seed
2576        // accumulator fresh. `apply_text` records into it while it is
2577        // `Some` (ordinary text writes never see it), and finish consumes
2578        // it. A wipe removed the persisted sketch alongside the documents
2579        // (see `open_and_wipe_text_index`), so finish builds from scratch;
2580        // an additive build merges its delta into whatever survived.
2581        {
2582            let mut buffers = self
2583                .text_seed_buffers
2584                .lock()
2585                .map_err(|_| PartitionError::LockPoisoned)?;
2586            *buffers = Some(TextSeedBuffers::new(options.seed_chars));
2587        }
2588        Ok(Some(token))
2589    }
2590
2591    /// Open (or self-create) the text index and run the wipe for a WIPE
2592    /// begin. Split from [`Self::begin_text_rebuild`] so begin can release
2593    /// the lease when any of this fails.
2594    fn open_and_wipe_text_index(
2595        &self,
2596        options: &waratah_text_index::TextIndexOptions,
2597        wipe: bool,
2598    ) -> Result<(), PartitionError> {
2599        #[cfg(test)]
2600        if FAIL_TEXT_OPEN.with(|slot| slot.get()).is_some() {
2601            FAIL_TEXT_OPEN.with(|slot| slot.set(None));
2602            return Err(PartitionError::Storage(
2603                waratah_storage::StorageError::Backend(
2604                    "injected text index open failure".to_owned(),
2605                ),
2606            ));
2607        }
2608        let index = {
2609            let mut handle = self
2610                .text_index
2611                .lock()
2612                .map_err(|_| PartitionError::LockPoisoned)?;
2613            if let Some(index) = handle.as_ref() {
2614                std::sync::Arc::clone(index)
2615            } else {
2616                let index = std::sync::Arc::new(match self.storage.text_index_dir() {
2617                    Some(dir) => waratah_text_index::TextIndex::open_or_create(&dir, options)?,
2618                    None => waratah_text_index::TextIndex::create_in_ram(options)?,
2619                });
2620                *handle = Some(std::sync::Arc::clone(&index));
2621                index
2622            }
2623        };
2624        if wipe {
2625            // The wipe also removes the seed-sketch sidecar (inside
2626            // `TextIndex::wipe`, so every wipe path — startup, lease
2627            // begin, offline CLI — gets the same hygiene).
2628            index.wipe()?;
2629        }
2630        Ok(())
2631    }
2632
2633    /// Refresh the held text rebuild lease's deadline. Rejected unless
2634    /// `token` identifies the current FRESH lease: an expired lease means a
2635    /// takeover is possible, so the stale driver must stop renewing.
2636    pub fn renew_text_rebuild_lease(&self, token: u64) -> Result<(), PartitionError> {
2637        let mut lease = self
2638            .text_rebuild_lease
2639            .lock()
2640            .map_err(|_| PartitionError::LockPoisoned)?;
2641        match lease.as_mut() {
2642            Some(state) if state.token == token && std::time::Instant::now() < state.deadline => {
2643                state.deadline = std::time::Instant::now() + TEXT_REBUILD_LEASE;
2644                Ok(())
2645            }
2646            _ => Err(PartitionError::Storage(
2647                waratah_storage::StorageError::Backend(
2648                    "text rebuild lease renew without the current fresh lease".to_owned(),
2649                ),
2650            )),
2651        }
2652    }
2653
2654    /// Finish the text index rebuild: release the lease, and — when `stamp`
2655    /// — stamp `epoch = max commit_ts observed on this partition` on the
2656    /// index. Rejected unless `token` identifies the current FRESH lease.
2657    /// `stamp = false` releases without stamping: an import that failed, or
2658    /// a walk that skipped unresolved lexicals, must not mark the index
2659    /// built; the index stays untrusted and the next start rebuilds.
2660    pub fn finish_text_rebuild(&self, token: u64, stamp: bool) -> Result<u64, PartitionError> {
2661        if self.axis != PartitionAxis::O {
2662            return Err(PartitionError::from(
2663                waratah_storage::StorageError::TextIndexNotOnAxis(self.axis),
2664            ));
2665        }
2666        // Validate, stamp, sketch, and release under ONE hold of the lease
2667        // mutex. Releasing before the stamp opened a window where a peer's
2668        // `begin_text_rebuild(wipe = true)` could take the free lease,
2669        // clear trust, and delete the documents BEFORE our stamp landed —
2670        // a stamped epoch over an emptied index, the state the wipe
2671        // protocol declares unreachable (a multi-compute startup probing
2672        // Describe in that window would drive exactly that peer). begin's
2673        // wipe and this stamp serialise on the same mutex; the hold is
2674        // bounded by two sidecar fsyncs (the epoch stamp + the sketch
2675        // write). The release happens on the error paths too — a failed
2676        // stamp must not pin the lease for the rest of its hour.
2677        {
2678            let mut lease = self
2679                .text_rebuild_lease
2680                .lock()
2681                .map_err(|_| PartitionError::LockPoisoned)?;
2682            let (valid, wiped) = match &*lease {
2683                Some(state)
2684                    if state.token == token && std::time::Instant::now() < state.deadline =>
2685                {
2686                    (true, state.wiped)
2687                }
2688                _ => (false, false),
2689            };
2690            let outcome = if !valid {
2691                Err(PartitionError::Storage(
2692                    waratah_storage::StorageError::Backend(
2693                        "text rebuild finish without the current fresh lease".to_owned(),
2694                    ),
2695                ))
2696            } else if stamp {
2697                self.stamp_text_epoch().inspect(|&epoch| {
2698                    self.finish_seed_sketch(wiped, epoch);
2699                })
2700            } else {
2701                Ok(0)
2702            };
2703            // Release LAST, and only our own token (hygiene; no takeover
2704            // can happen while this mutex is held).
2705            if matches!(&*lease, Some(state) if state.token == token) {
2706                // A valid non-stamping finish never runs
2707                // `finish_seed_sketch`, so its begin-collected buffers
2708                // would leak for the process lifetime (wasted hashing on
2709                // every later literal write). Clear them while we still
2710                // own the lease — a successor's begin cannot install
2711                // fresh buffers until this mutex releases. An INVALID
2712                // lease keeps its buffers: they may already belong to a
2713                // takeover's begin, and begin resets them anyway.
2714                if !stamp && let Ok(mut buffers) = self.text_seed_buffers.lock() {
2715                    *buffers = None;
2716                }
2717                *lease = None;
2718            }
2719            outcome
2720        }
2721    }
2722
2723    /// Build or delta-merge the seed sketch from the accumulated buffers
2724    /// and persist it at `epoch`. Best-effort by contract: a sketch
2725    /// failure leaves the store on the unpriced path (the planner's
2726    /// stamp), never fails a rebuild that already stamped its epoch. A
2727    /// wiped rebuild builds fresh from the buffers (they cover every
2728    /// re-derived term); an additive rebuild folds its delta into the
2729    /// persisted sketch — with NO surviving sketch (never written,
2730    /// deleted mid-write, undecodable) the fold refuses and this finish
2731    /// writes NOTHING, leaving the store unpriced until the next full
2732    /// rebuild: the delta alone would under-price every pre-existing
2733    /// term under a fresh, trusted epoch. Consumes the buffers
2734    /// unconditionally.
2735    fn finish_seed_sketch(&self, wiped: bool, epoch: u64) {
2736        let taken = self
2737            .text_seed_buffers
2738            .lock()
2739            .map(|mut guard| guard.take())
2740            .unwrap_or_else(|_| {
2741                // Poisoned mutex: leave the buffers for no future rebuild —
2742                // begin resets them anyway.
2743                None
2744            });
2745        let Some(state) = taken else {
2746            return;
2747        };
2748        let index_dir = match self.text_index_handle().ok().as_ref().and_then(|i| i.dir()) {
2749            Some(dir) => dir.to_path_buf(),
2750            None => return, // RAM backend: no sketch persistence (test stores).
2751        };
2752        let persisted = if wiped {
2753            None // a wipe removed the sidecar; build fresh below
2754        } else {
2755            read_text_seed_sketch(&index_dir)
2756        };
2757        let mut sketch = if wiped {
2758            // Fresh build: the wipe walk collected every term — write as-is.
2759            state.sketch
2760        } else {
2761            // Additive build: fold the delta into the surviving base. NO
2762            // base (never written, deleted mid-write, undecodable) folds
2763            // to None and this finish writes NOTHING — the delta alone
2764            // prices only the new documents, and stamping that partial
2765            // population with the fresh epoch would present it as trusted:
2766            // an under-estimate for every pre-existing term that no gate
2767            // can catch. The absent sidecar keeps the store unpriced until
2768            // the next full (wipe) rebuild, the same observable state as
2769            // "never built".
2770            let Some(sketch) = waratah_stats::TextSeedSketch::fold_delta(persisted, state.sketch)
2771            else {
2772                return;
2773            };
2774            sketch
2775        };
2776        sketch.epoch = epoch;
2777        let _ = write_text_seed_sketch(&index_dir, &sketch);
2778    }
2779
2780    /// The epoch a stamping finish writes: the process-local commit counter
2781    /// floored at the previously stamped epoch, and the sidecar write.
2782    /// Split from [`Self::finish_text_rebuild`] so the lease mutex can be
2783    /// held across the whole stamp without borrowing conflicts.
2784    fn stamp_text_epoch(&self) -> Result<u64, PartitionError> {
2785        let counter = self
2786            .max_commit_ts
2787            .load(std::sync::atomic::Ordering::Relaxed);
2788        // Floor at the previously stamped epoch number: the counter is
2789        // process-local (0 on a freshly opened partition), while the store's
2790        // rows sit at the timestamps of every process that ever wrote them.
2791        // Stamping the raw counter would report "covered up to 0" over a
2792        // store whose data sits far higher. The raw number survives a wipe
2793        // (which cleared only the epoch), so it is readable here under the
2794        // lease. (Geo's finish floors the same way.)
2795        let index = self.text_index_handle()?;
2796        let previous = index.meta()?.epoch.unwrap_or(0);
2797        let epoch = counter.max(previous);
2798        index.stamp(epoch)?;
2799        Ok(epoch)
2800    }
2801
2802    /// The persisted seed sketch, `None` when absent (not the O axis, no
2803    /// index, no sidecar, or undecodable). Served wire-trimmed by both the
2804    /// gRPC frame and the standalone in-process client.
2805    pub fn text_seed_sketch_frame(&self) -> Option<waratah_stats::TextSeedSketch> {
2806        let index = self.text_index_handle().ok()?;
2807        let dir = index.dir()?;
2808        read_text_seed_sketch(dir)
2809    }
2810
2811    /// Whether a FRESH text rebuild lease is held.
2812    pub fn text_rebuild_in_progress(&self) -> bool {
2813        match self.text_rebuild_lease.lock().map(|lease| *lease) {
2814            Ok(Some(state)) => std::time::Instant::now() < state.deadline,
2815            _ => false,
2816        }
2817    }
2818
2819    /// Number of indexed documents, `None` when no index exists or it cannot
2820    /// be opened (Describe must not fail because a derived index is broken).
2821    fn text_doc_count(&self) -> Option<u64> {
2822        self.ensure_text_open().ok()?;
2823        let handle = self.text_index.lock().ok()?;
2824        handle.as_ref().map(|index| index.doc_count())
2825    }
2826    /// Apply temporal-index postings (O axis) and observe the Put postings
2827    /// into the shard's temporal histogram (same advisory-stats overlay as
2828    /// the hexastore observers; deletes do not observe — the histogram is
2829    /// Put-only by contract).
2830    pub fn apply_temporal(&self, puts: &[TemporalIndexPut]) -> Result<u64, PartitionError> {
2831        if self.axis != PartitionAxis::O {
2832            return Err(PartitionError::from(
2833                waratah_storage::StorageError::TemporalIndexNotOnAxis(self.axis),
2834            ));
2835        }
2836        let storage = self.storage.as_ref();
2837        storage.apply_temporal_puts(puts)?;
2838        let mut stats = self
2839            .stats
2840            .lock()
2841            .map_err(|_| PartitionError::LockPoisoned)?;
2842        for put in puts {
2843            if put.op == waratah_storage::StorageOp::Put {
2844                // The histogram rides its own CF-keyed overlay (like the
2845                // catalog count): its SST blob is produced by the temporal
2846                // CF, so it must rotate on that CF's flushes, not the
2847                // canonical hexastore flush.
2848                stats.observe_temporal_posting(put.node_key);
2849            }
2850        }
2851        Ok(puts.len() as u64)
2852    }
2853
2854    /// Execute the O-axis temporal index rebuild under the rebuild lock.
2855    ///
2856    /// `Ok(true)` = this call ran the rebuild; `Ok(false)` = another rebuild
2857    /// is in progress (caller polls Describe). The walk: wipe the index CF,
2858    /// collect the per-quad-live temporal terms over the leading O
2859    /// permutation (a term stays when ANY referencing quad's own-latest
2860    /// version is a Put — deletes are never mirrored to postings, so this
2861    /// walk after the wipe is the GC of dead terms), derive postings under
2862    /// the requested coverer config, apply them, stamp
2863    /// `epoch = max commit_ts over temporal-carrying rows` (equal, never +1
2864    /// — the epoch derives from the indexed data), and leave the histogram
2865    /// to the observe replay that already ran through `apply_temporal`.
2866    pub fn rebuild_temporal_index(
2867        &self,
2868        config: DyadicCovererConfig,
2869    ) -> Result<bool, PartitionError> {
2870        use std::sync::atomic::Ordering;
2871        if self.axis != PartitionAxis::O {
2872            return Err(PartitionError::from(
2873                waratah_storage::StorageError::TemporalIndexNotOnAxis(self.axis),
2874            ));
2875        }
2876        // Compare-exchange the in-progress flag: one winner runs, everyone
2877        // else reports already-in-progress.
2878        if self
2879            .temporal_rebuild_in_progress
2880            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
2881            .is_err()
2882        {
2883            return Ok(false);
2884        }
2885        let result = self.rebuild_temporal_index_inner(config);
2886        self.temporal_rebuild_in_progress
2887            .store(false, Ordering::Release);
2888        result
2889    }
2890
2891    fn rebuild_temporal_index_inner(
2892        &self,
2893        config: DyadicCovererConfig,
2894    ) -> Result<bool, PartitionError> {
2895        // Serialize against concurrent writes (the walk reads the hexastore;
2896        // a concurrent write's postings land after the wipe and survive —
2897        // they carry their own commit_ts — so the lock is a consistency
2898        // courtesy for the epoch stamp, not a correctness fence).
2899        let _write_guard = self
2900            .write_mutex
2901            .lock()
2902            .map_err(|_| PartitionError::LockPoisoned)?;
2903        rebuild_temporal_index_storage(&self.storage, &self.stats, config)?;
2904        Ok(true)
2905    }
2906
2907    /// Frame stream for a decoded `TemporalCandidateScan` request — the
2908    /// transport behind the tonic handler, shared with in-process clients.
2909    ///
2910    /// ONE blocking task drains the merged key-interval walk (skip-seek
2911    /// union with a fresh [`TemporalCandidateState`]) and packs distinct
2912    /// candidate terms into [`SCAN_STREAM_FRAME_ROWS`] frames. This RPC is
2913    /// never cursor-paged: a second iterator would start a new seen-set and
2914    /// re-emit terms under several covering nodes.
2915    pub fn temporal_candidate_frames(
2916        &self,
2917        intervals: Vec<TemporalCellInterval>,
2918        snapshot: SnapshotId,
2919        predicate: TemporalQueryPredicate,
2920        limit: u64,
2921    ) -> ReceiverStream<Result<pb::TemporalCandidateScanResponse, Status>> {
2922        let (tx, rx) = tokio::sync::mpsc::channel(2);
2923        let service = self.clone();
2924        tokio::spawn(async move {
2925            let tx_frames = tx.clone();
2926            let result = tokio::task::spawn_blocking(move || {
2927                let storage = service.storage.as_ref();
2928                let mut state = TemporalCandidateState::default();
2929                let mut frame: Vec<Vec<u8>> = Vec::with_capacity(SCAN_STREAM_FRAME_ROWS);
2930                let send =
2931                    |frame: &mut Vec<Vec<u8>>| -> Result<bool, waratah_storage::StorageError> {
2932                        let response = pb::TemporalCandidateScanResponse {
2933                            terms: std::mem::take(frame),
2934                        };
2935                        tx_frames.blocking_send(Ok(response)).map_err(|_| {
2936                            waratah_storage::StorageError::Backend(
2937                                "temporal candidate stream closed".to_owned(),
2938                            )
2939                        })?;
2940                        Ok(true)
2941                    };
2942                let mut emitted = 0u64;
2943                storage.temporal_scan_candidates(
2944                    &intervals,
2945                    snapshot,
2946                    &predicate,
2947                    limit,
2948                    &mut state,
2949                    |term| {
2950                        let bytes = waratah_proto::term_to_bytes(term);
2951                        frame.push(bytes);
2952                        emitted += 1;
2953                        if frame.len() >= SCAN_STREAM_FRAME_ROWS {
2954                            send(&mut frame)?;
2955                        }
2956                        Ok(limit == 0 || emitted < limit)
2957                    },
2958                )?;
2959                if !frame.is_empty() {
2960                    send(&mut frame)?;
2961                }
2962                Ok::<(), PartitionError>(())
2963            })
2964            .await;
2965            match result {
2966                Ok(Ok(())) => {}
2967                Ok(Err(error)) => {
2968                    let _ = tx.send(Err(error.into())).await;
2969                }
2970                Err(join) => {
2971                    let _ = tx.send(Err(blocking_join_error("storage", join))).await;
2972                }
2973            }
2974        });
2975        ReceiverStream::new(rx)
2976    }
2977
2978    /// Frame stream for a decoded `GeoCandidateScan` request — the transport
2979    /// behind the tonic handler, shared with in-process clients.
2980    ///
2981    /// ONE blocking task drains the merged cell-interval walk (skip-seek
2982    /// union with a fresh [`GeoCandidateState`]) and packs distinct candidate
2983    /// terms into [`SCAN_STREAM_FRAME_ROWS`] frames. This RPC is never
2984    /// cursor-paged: a second iterator would start a new seen-set and re-emit
2985    /// geometries under several covering cells.
2986    #[allow(clippy::too_many_arguments)]
2987    pub fn geo_candidate_frames(
2988        &self,
2989        intervals: Vec<GeoCellInterval>,
2990        snapshot: SnapshotId,
2991        query_envelope: Option<GeoEnvelope>,
2992        limit: u64,
2993    ) -> ReceiverStream<Result<pb::GeoCandidateScanResponse, Status>> {
2994        let (tx, rx) = tokio::sync::mpsc::channel(2);
2995        let service = self.clone();
2996        tokio::spawn(async move {
2997            // One clone for the walk-side frame flushes; the original stays
2998            // with the outer task for the error paths.
2999            let tx_frames = tx.clone();
3000            let result = tokio::task::spawn_blocking(move || {
3001                let storage = service.storage.as_ref();
3002                let mut state = GeoCandidateState::default();
3003                let mut frame: Vec<Vec<u8>> = Vec::with_capacity(SCAN_STREAM_FRAME_ROWS);
3004                // Full frames flush inside the walk (blocking_send parks the
3005                // walk on channel backpressure); a dropped consumer stops it.
3006                let send =
3007                    |frame: &mut Vec<Vec<u8>>| -> Result<bool, waratah_storage::StorageError> {
3008                        let response = pb::GeoCandidateScanResponse {
3009                            terms: std::mem::take(frame),
3010                        };
3011                        tx_frames.blocking_send(Ok(response)).map_err(|_| {
3012                            waratah_storage::StorageError::Backend(
3013                                "geo candidate stream closed".to_owned(),
3014                            )
3015                        })?;
3016                        Ok(true)
3017                    };
3018                let result = storage.geo_scan_candidates(
3019                    &intervals,
3020                    snapshot,
3021                    query_envelope.as_ref(),
3022                    limit,
3023                    &mut state,
3024                    |term| {
3025                        frame.push(encode_term_bytes(term));
3026                        if frame.len() >= SCAN_STREAM_FRAME_ROWS {
3027                            return send(&mut frame);
3028                        }
3029                        Ok(true)
3030                    },
3031                );
3032                if result.is_ok() && !frame.is_empty() {
3033                    send(&mut frame)?;
3034                }
3035                result?;
3036                Ok::<_, PartitionError>(())
3037            })
3038            .await;
3039            match result {
3040                Ok(Ok(())) => {}
3041                Ok(Err(error)) => {
3042                    let _ = tx.send(Err(Status::from(error))).await;
3043                }
3044                Err(join) => {
3045                    let _ = tx.send(Err(blocking_join_error("storage", join))).await;
3046                }
3047            }
3048        });
3049        ReceiverStream::new(rx)
3050    }
3051
3052    /// Stream one text candidate drain in frame-sized batches.
3053    ///
3054    /// The drain itself is a single index search (the collector dedups by
3055    /// term), so the frames only bound the message size; unlike the scan RPCs
3056    /// there is no cursor, and a second call recomputes the same set.
3057    pub fn text_candidate_frames(
3058        &self,
3059        request: waratah_text_index::TextSearchRequest,
3060        snapshot: SnapshotId,
3061    ) -> ReceiverStream<Result<pb::TextCandidateScanResponse, Status>> {
3062        let (tx, rx) = tokio::sync::mpsc::channel(2);
3063        let service = self.clone();
3064        tokio::spawn(async move {
3065            // One clone for the walk-side frame flushes; the original stays
3066            // with the outer task for the error paths.
3067            let tx_frames = tx.clone();
3068            let result = tokio::task::spawn_blocking(move || -> Result<(), PartitionError> {
3069                // The index carries no per-document visibility: candidates are
3070                // independent of row visibility and the join with visible rows
3071                // is the visibility filter. The timestamp is accepted for
3072                // diagnostics only.
3073                let _ = snapshot;
3074                let terms = service.text_candidates(&request)?;
3075                for chunk in terms.chunks(SCAN_STREAM_FRAME_ROWS) {
3076                    let response = pb::TextCandidateScanResponse {
3077                        terms: chunk.to_vec(),
3078                    };
3079                    if tx_frames.blocking_send(Ok(response)).is_err() {
3080                        // The consumer went away (query cancelled); abandon the
3081                        // drain rather than buffering frames nobody reads.
3082                        return Ok(());
3083                    }
3084                }
3085                Ok(())
3086            })
3087            .await;
3088            match result {
3089                Ok(Ok(())) => {}
3090                Ok(Err(error)) => {
3091                    let _ = tx.send(Err(Status::from(error))).await;
3092                }
3093                Err(join) => {
3094                    let _ = tx.send(Err(blocking_join_error("storage", join))).await;
3095                }
3096            }
3097        });
3098        ReceiverStream::new(rx)
3099    }
3100
3101    /// Encode one resolved row for the wire.
3102    ///
3103    /// `graph` presence, not length, carries the "column requested" fact: the
3104    /// RDF default graph's encoded term is zero bytes, so `Some(empty)` is a
3105    /// real graph and must not collapse to "not requested".
3106    pub fn text_subject_row_to_proto(
3107        row: &waratah_storage::text_index::TextSubjectRow,
3108    ) -> pb::TextSubjectRow {
3109        pb::TextSubjectRow {
3110            subject: waratah_proto::term_to_bytes(&row.subject),
3111            graph: row.graph.as_ref().map(waratah_proto::term_to_bytes),
3112        }
3113    }
3114
3115    /// Resolve one text subject scan: run one search for the request's whole
3116    /// predicate set (a single OR over the stored predicate), walk OPSG for the
3117    /// matched literals at `snapshot`, and hand DISTINCT (subject, graph) rows
3118    /// to `emit` in pages while the walk runs.
3119    ///
3120    /// STREAMING CONTRACT: pages leave as they are produced, so peak memory is
3121    /// one page plus the dedup set rather than the whole answer. `emit`
3122    /// returning `false` means the consumer is gone: the walk stops at the
3123    /// next page boundary and this returns `Ok(())`. An `Err` ends the stream
3124    /// after some rows may already be delivered — a consumer must treat the
3125    /// error as fatal and discard everything received.
3126    ///
3127    /// The guard counts distinct rows and ERRORS when exceeded, never
3128    /// truncates: a dropped subject is a dropped row for `text:query`'s
3129    /// subject form, which has no residual. It also bounds the dedup set at
3130    /// `limit + 1` entries; with `limit == 0` the set is the answer size
3131    /// (there is no seen-set spill yet). The graph column is present only
3132    /// when the request asks for it; dedup then keys on (subject, graph) so a
3133    /// subject matched in several graphs stays distinct where the query binds
3134    /// the graph variable.
3135    pub fn resolve_text_subjects(
3136        &self,
3137        request: &waratah_storage::text_index::TextSubjectRequest,
3138        snapshot: SnapshotId,
3139        emit: &mut dyn FnMut(
3140            &[waratah_storage::text_index::TextSubjectRow],
3141        ) -> Result<bool, PartitionError>,
3142    ) -> Result<(), PartitionError> {
3143        if self.axis != PartitionAxis::O {
3144            return Err(PartitionError::from(
3145                waratah_storage::StorageError::TextIndexNotOnAxis(self.axis),
3146            ));
3147        }
3148        // The merged default graph rewrites every row's G to the unnamed
3149        // graph, so `subject == graph` can never hold; the pair would
3150        // silently answer zero rows. Reject it at the wire boundary.
3151        if request.subject_equals_graph && request.merge_default_graph {
3152            return Err(PartitionError::SubjectEqualsGraphWithMerge);
3153        }
3154        let index = self.text_index_handle()?;
3155        // One drain for the whole predicate set. The drain scoping (which
3156        // literals come back) and the resolve scoping (whose rows they are)
3157        // are the SAME set: a literal is drained if it sits under any named
3158        // predicate, and its OPSG rows are read under any named predicate.
3159        // A per-predicate loop would drain a shared literal once per predicate
3160        // and walk its rows once per predicate, and a later predicate's search
3161        // error could mask the guard verdict already decided by an earlier one.
3162        let search = waratah_text_index::TextSearchRequest {
3163            mode: request.mode,
3164            query: request.query.clone(),
3165            language: request.language.clone(),
3166            limit: 0,
3167        };
3168        let predicate_bytes: Vec<Vec<u8>> = request
3169            .predicates
3170            .iter()
3171            .map(waratah_storage::encode_term_bytes)
3172            .collect();
3173        let graph_filter =
3174            GByteFilter::compile(&request.graph_filter_terms, request.graph_filter_allow);
3175        let mut page: Vec<waratah_storage::text_index::TextSubjectRow> =
3176            Vec::with_capacity(waratah_proto::SCAN_STREAM_FRAME_ROWS);
3177        let mut seen: std::collections::HashSet<Vec<u8>> = std::collections::HashSet::new();
3178        let mut guard_error: Option<PartitionError> = None;
3179        let mut emit_error: Option<PartitionError> = None;
3180        let mut consumer_gone = false;
3181
3182        let terms = index.search_scoped(&search, &predicate_bytes)?;
3183        if !terms.is_empty() {
3184            let objects = terms
3185                .iter()
3186                .map(|bytes| term_from_bytes(bytes).map_err(PartitionError::from))
3187                .collect::<Result<Vec<EncodedTerm>, _>>()?;
3188            self.storage.visit_object_subjects(
3189                &objects,
3190                &request.predicates,
3191                snapshot,
3192                request.graph_name.as_ref(),
3193                &graph_filter,
3194                request.merge_default_graph,
3195                |subject, graph| {
3196                    // `GRAPH ?s` plus `text:query(?s, …)`: one variable must
3197                    // take one value, so the matched row's subject, its
3198                    // graph, and the graph name are the same term. The graph
3199                    // column is not emitted for this shape; the filter is the
3200                    // whole constraint.
3201                    if request.subject_equals_graph && subject != graph {
3202                        return Ok(true);
3203                    }
3204                    // Encoded terms are self-delimiting, so the concatenation
3205                    // is an injective dedup key for the requested row shape; a
3206                    // length prefix would be redundant (`write_term` carries
3207                    // its own type and length markers).
3208                    let mut key = waratah_storage::encode_term_bytes(subject);
3209                    if request.return_graph {
3210                        key.extend(waratah_storage::encode_term_bytes(graph));
3211                    }
3212                    if !seen.insert(key) {
3213                        return Ok(true);
3214                    }
3215                    if request.limit > 0 && seen.len() as u64 > request.limit {
3216                        guard_error = Some(PartitionError::Text(
3217                            waratah_text_index::TextIndexError::SubjectLimitExceeded {
3218                                limit: request.limit,
3219                            },
3220                        ));
3221                        return Ok(false);
3222                    }
3223                    page.push(waratah_storage::text_index::TextSubjectRow {
3224                        subject: subject.clone(),
3225                        graph: request.return_graph.then(|| graph.clone()),
3226                    });
3227                    if page.len() >= waratah_proto::SCAN_STREAM_FRAME_ROWS {
3228                        let ready = std::mem::take(&mut page);
3229                        // The visit closure's error type is the storage's, so
3230                        // an emit failure is parked and re-raised after the
3231                        // walk unwinds.
3232                        match emit(&ready) {
3233                            Ok(true) => {}
3234                            Ok(false) => {
3235                                consumer_gone = true;
3236                                return Ok(false);
3237                            }
3238                            Err(error) => {
3239                                emit_error = Some(error);
3240                                return Ok(false);
3241                            }
3242                        }
3243                    }
3244                    Ok(true)
3245                },
3246            )?;
3247            if let Some(error) = emit_error.take() {
3248                return Err(error);
3249            }
3250        }
3251        if let Some(error) = guard_error {
3252            return Err(error);
3253        }
3254        if !consumer_gone && !page.is_empty() {
3255            // The last, partial page. A `false` here means the consumer left
3256            // while it was in flight; the walk is over either way.
3257            emit(&page)?;
3258        }
3259        Ok(())
3260    }
3261
3262    /// Stream one subject resolve as framed `(subject, graph)` pages.
3263    ///
3264    /// The resolve sends each 8,192-row page as it is produced: one blocking
3265    /// walk behind a bounded frame channel. The first rows reach the consumer
3266    /// before the walk ends, and a cancelled consumer stops the walk at the
3267    /// next page boundary instead of letting it run to completion.
3268    pub fn text_subject_frames(
3269        &self,
3270        request: waratah_storage::text_index::TextSubjectRequest,
3271        snapshot: SnapshotId,
3272    ) -> ReceiverStream<Result<pb::TextSubjectScanResponse, Status>> {
3273        let (tx, rx) = tokio::sync::mpsc::channel(2);
3274        let tx_errors = tx.clone();
3275        let service = self.clone();
3276        tokio::spawn(async move {
3277            let result = tokio::task::spawn_blocking(move || -> Result<(), PartitionError> {
3278                service.resolve_text_subjects(&request, snapshot, &mut |rows| {
3279                    let frame = pb::TextSubjectScanResponse {
3280                        rows: rows
3281                            .iter()
3282                            .map(PartitionService::text_subject_row_to_proto)
3283                            .collect(),
3284                    };
3285                    // A closed channel means the consumer went away; stop the
3286                    // walk rather than buffering frames nobody reads.
3287                    match tx.blocking_send(Ok(frame)) {
3288                        Ok(()) => Ok(true),
3289                        Err(_) => Ok(false),
3290                    }
3291                })
3292            })
3293            .await;
3294            match result {
3295                Ok(Ok(())) => {}
3296                Ok(Err(error)) => {
3297                    let _ = tx_errors.send(Err(Status::from(error))).await;
3298                }
3299                Err(join) => {
3300                    let _ = tx_errors
3301                        .send(Err(blocking_join_error("storage", join)))
3302                        .await;
3303                }
3304            }
3305        });
3306        ReceiverStream::new(rx)
3307    }
3308
3309    /// Flush this partition's MemTables to SSTables.
3310    pub fn flush_memtables(&self) -> Result<(), PartitionError> {
3311        let storage = self.storage.as_ref();
3312        storage.flush_memtables()?;
3313        Ok(())
3314    }
3315
3316    /// Merged shard-level statistical profile (`sealed` ⊕ `flushing` ⊕ `open`).
3317    ///
3318    /// Reloads live SST `waratah.stats` blobs only when the cache is stale.
3319    /// A flush-absorbed reload drops `flushing`, not `open`.
3320    pub fn shard_profile(&self) -> Result<StatsProfile, PartitionError> {
3321        if self.sst_flags.take_sealed_stale() {
3322            // The flag was consumed above, so every early exit below must
3323            // restore it. "Not stale" asserts the sealed layer reflects the
3324            // live SSTs; a failed reload leaves the OLD sealed layer in
3325            // place, and consumers that trust the flag (the scan-dispatch
3326            // gate consults `SstInvalidationFlags::sealed_stale` before
3327            // believing an estimate) would treat an estimate that misses
3328            // the whole SST contents as complete. Consuming first and
3329            // re-marking on error — rather than peeking and clearing on
3330            // success — also preserves a mark set by a flush completing
3331            // DURING the reload: that mark lands after the take, so it is
3332            // not erased by this path.
3333            let reloaded = (|| -> Result<StatsProfile, PartitionError> {
3334                let blobs = {
3335                    let storage = self.storage.as_ref();
3336                    storage.stats_property_blobs(STATS_USER_PROPERTY_KEY)?
3337                };
3338                let sealed = merge_sst_property_blobs(&blobs)?;
3339                let mut stats = self
3340                    .stats
3341                    .lock()
3342                    .map_err(|_| PartitionError::LockPoisoned)?;
3343                stats.apply_sealed_reload(sealed);
3344                stats.merged().map_err(PartitionError::Stats)
3345            })();
3346            match reloaded {
3347                Ok(profile) => Ok(profile),
3348                Err(error) => {
3349                    self.sst_flags.mark_sealed_stale();
3350                    Err(error)
3351                }
3352            }
3353        } else {
3354            let stats = self
3355                .stats
3356                .lock()
3357                .map_err(|_| PartitionError::LockPoisoned)?;
3358            stats.merged().map_err(PartitionError::Stats)
3359        }
3360    }
3361
3362    /// Compact both axis-local column families (synchronous full-range compact).
3363    pub fn compact_range(&self) -> Result<(), PartitionError> {
3364        let storage = self.storage.as_ref();
3365        storage.compact_range();
3366        Ok(())
3367    }
3368
3369    /// Write-path (`open`) put count, before any SST overlay.
3370    pub fn open_total_puts(&self) -> Result<u64, PartitionError> {
3371        let stats = self
3372            .stats
3373            .lock()
3374            .map_err(|_| PartitionError::LockPoisoned)?;
3375        Ok(stats.open_profile().total_puts)
3376    }
3377
3378    /// Advisory `class_counts` snapshot for TSG full-axis parallel counts.
3379    ///
3380    /// Empty unless the count resolves to the TSG index with both the class
3381    /// (leading slot) and the subject unbound — the only shape the storage
3382    /// layer's slice planner consumes the hint on, cutting the walk at
3383    /// class-term boundaries with balanced row shares. A poisoned stats lock
3384    /// degrades to an empty hint (byte-even slices, same answer); a stale
3385    /// snapshot only reshapes slices, never changes the count (the
3386    /// advisory-only stats rule in ARCH.md §10).
3387    fn tsg_class_totals_hint(
3388        &self,
3389        permutation: Option<IndexPermutation>,
3390        pattern: &EncodedTriplePattern,
3391        axis: PartitionAxis,
3392    ) -> Vec<(StrHash, u64)> {
3393        let resolved = permutation.unwrap_or_else(|| pattern.best_permutation(axis));
3394        if resolved != IndexPermutation::Tsg
3395            || pattern.object.is_some()
3396            || pattern.subject.is_some()
3397        {
3398            return Vec::new();
3399        }
3400        let Ok(stats) = self.stats.lock() else {
3401            return Vec::new();
3402        };
3403        stats
3404            .open_profile()
3405            .class_counts
3406            .iter()
3407            .map(|(hash, rows)| (*hash, *rows))
3408            .collect()
3409    }
3410
3411    /// Listener-observed compaction completions (no mutex).
3412    pub fn compaction_event_count(&self) -> u64 {
3413        self.sst_flags.compaction_event_count()
3414    }
3415
3416    /// Listener-observed flush completions (no mutex).
3417    pub fn flush_event_count(&self) -> u64 {
3418        self.sst_flags.flush_event_count()
3419    }
3420
3421    /// Identity + LSM snapshot for `Describe`.
3422    pub fn describe(&self) -> pb::HexastoreDescribeResponse {
3423        let node_id = if self.identity.node_id.is_empty() {
3424            format!("{}-0", self.axis)
3425        } else {
3426            self.identity.node_id.clone()
3427        };
3428        // `shard_profile` reloads sealed SST blobs when the listener has marked
3429        // them stale, then returns `sealed ⊕ flushing ⊕ open`. A cold open
3430        // leaves `sealed` empty until that reload, so reading `merged()` alone
3431        // would report `named_graph_count = 0` for graphs that only live in the
3432        // catalog SSTs. P/O do not own the catalog.
3433        let named_graph_count = if self.axis == PartitionAxis::S {
3434            self.shard_profile()
3435                .ok()
3436                .map(|profile| profile.named_graph_count)
3437        } else {
3438            None
3439        };
3440        let open_total_puts = self.open_total_puts().unwrap_or(0);
3441        let mut metrics = proto_lsm(self.storage.lsm_metrics());
3442        metrics.open_total_puts = Some(open_total_puts);
3443        metrics.compaction_event_count = Some(self.compaction_event_count());
3444        metrics.named_graph_count = named_graph_count;
3445        let text_meta = self.text_index_meta();
3446        pb::HexastoreDescribeResponse {
3447            axis: axis_to_proto(self.axis).into(),
3448            node_id,
3449            listen: self.identity.listen.clone(),
3450            data_dir: self.identity.data_dir.clone(),
3451            backend: proto_backend(self.storage.backend_kind()).into(),
3452            version: waratah_buildinfo::version_string(),
3453            repository_id: if self.identity.repository_id.is_empty() {
3454                MAIN_REPOSITORY_ID.to_owned()
3455            } else {
3456                self.identity.repository_id.clone()
3457            },
3458            metrics: Some(metrics),
3459            serving: true,
3460            // Rebuild epoch of the geometry index (O only; None elsewhere,
3461            // until the first `waratah geo rebuild-index` stamps it, and
3462            // whenever the liveness marker is missing — i.e. while the index
3463            // is empty, including mid-rebuild, so the gate reads untrusted).
3464            geo_index_epoch: self.storage.geo_index_epoch().ok().flatten(),
3465            // Rebuild epoch of the temporal index (O only). ABSENT means
3466            // UNTRUSTED: the compute auto-rebuild triggers on it at startup.
3467            temporal_index_epoch: self.storage.temporal_index_epoch().ok().flatten(),
3468            temporal_rebuild_in_progress: self
3469                .temporal_rebuild_in_progress
3470                .load(std::sync::atomic::Ordering::Relaxed),
3471            geo_rebuild_in_progress: self.geo_rebuild_in_progress(),
3472            // Text index state (O only). An absent epoch means UNTRUSTED: the
3473            // compute auto-builds at startup and keeps the text rewrites off
3474            // until it lands. The fingerprint lets compute detect an index
3475            // built by other settings without opening it.
3476            text_index_epoch: text_meta.as_ref().and_then(|meta| meta.epoch),
3477            text_index_fingerprint: text_meta.map(|meta| meta.fingerprint).unwrap_or_default(),
3478            text_index_terms: self.text_doc_count().unwrap_or(0),
3479            text_rebuild_in_progress: self.text_rebuild_in_progress(),
3480        }
3481    }
3482
3483    /// The text index metadata, `None` when this partition has no index.
3484    ///
3485    /// Best-effort on purpose: Describe must answer even when a derived index
3486    /// is missing or unreadable, and an unreadable index is reported as
3487    /// absent (untrusted) rather than failing the whole probe.
3488    fn text_index_meta(&self) -> Option<waratah_text_index::TextIndexMeta> {
3489        self.ensure_text_open().ok()?;
3490        let handle = self.text_index.lock().ok()?;
3491        handle.as_ref().and_then(|index| index.meta().ok())
3492    }
3493
3494    fn check_axis(&self, asserted: Option<PartitionAxis>) -> Result<(), PartitionError> {
3495        match asserted {
3496            Some(requested) if requested != self.axis => Err(PartitionError::AxisMismatch {
3497                requested,
3498                owned: self.axis,
3499            }),
3500            _ => Ok(()),
3501        }
3502    }
3503}
3504
3505/// The temporal index rebuild walk over one already-open O store: wipe the
3506/// index CF, collect the per-quad-live temporal terms (a term stays when
3507/// ANY referencing quad's own-latest version is a Put — deletes are never
3508/// mirrored to postings, so the walk after the wipe is the GC of dead
3509/// terms), derive postings under `config`, apply them, replace the
3510/// histogram with an exact cut, and stamp
3511/// `epoch = max commit_ts over temporal-carrying rows` (equal, never +1 —
3512/// the epoch derives from the indexed data). Shared by the partition's
3513/// RPC-executed rebuild, the standalone startup path, and the offline CLI.
3514pub fn rebuild_temporal_index_storage(
3515    storage: &Storage,
3516    stats: &Mutex<ShardStats>,
3517    config: DyadicCovererConfig,
3518) -> Result<u64, PartitionError> {
3519    if storage.axis() != PartitionAxis::O {
3520        return Err(PartitionError::from(
3521            waratah_storage::StorageError::TemporalIndexNotOnAxis(storage.axis()),
3522        ));
3523    }
3524    storage.wipe_temporal_index()?;
3525    let (terms, epoch) = storage.temporal_rebuild_terms()?;
3526    let mut puts: Vec<TemporalIndexPut> = Vec::new();
3527    for term in &terms {
3528        puts.extend(postings_for_term(term, epoch, &config));
3529    }
3530    let posted = puts.len() as u64;
3531    storage.apply_temporal_puts(&puts)?;
3532    // The rebuild REPLACES the advisory sketch with an exact cut.
3533    {
3534        let mut stats = stats.lock().map_err(|_| PartitionError::LockPoisoned)?;
3535        stats.reset_temporal_open();
3536        for put in &puts {
3537            stats.observe_temporal_posting(put.node_key);
3538        }
3539    }
3540    storage.set_temporal_index_epoch(epoch.0)?;
3541    Ok(posted)
3542}
3543
3544fn observe_catalog_puts(stats: &mut ShardStats, puts: &[CatalogPut]) {
3545    for put in puts {
3546        match decode_catalog_value(&put.value) {
3547            Ok(GraphCatalogState::Present) => stats.add_named_graphs(1),
3548            Ok(GraphCatalogState::Dropped) => stats.drop_named_graphs(1),
3549            Err(_) => {}
3550        }
3551    }
3552}
3553
3554/// One packed scan row: the index permutation it was walked in plus the
3555/// wire-order segment ranges (subject, predicate, object, graph) of the
3556/// quad's terms inside the frame buffer. Indices line up with the
3557/// [`QuadSlot`] variants, whose declaration order is the wire field order.
3558/// An omitted slot (the Tsg predicate) or a skipped copy (the merge-default
3559/// graph) keeps an empty `start == end` range.
3560struct FrameRow {
3561    /// Index permutation this row was walked in (broadcast pages may differ
3562    /// from the plain-path resolution).
3563    permutation: IndexPermutation,
3564    /// Wire-order term ranges in [`FramePacker::buf`].
3565    segs: [Range<usize>; 4],
3566}
3567
3568/// Walk-side framebuffer packing the rows of ONE `ScanPatternStream` frame.
3569///
3570/// The emit callback copies each row's term bytes once into `buf` —
3571/// contiguous, one allocation per frame, no decode, and the only copy
3572/// between the iterator buffer and the wire. At the frame boundary the
3573/// buffer freezes into a refcounted `Bytes` and every wire field becomes a
3574/// zero-copy slice of it, so the packed bytes live exactly as long as the
3575/// `pb::EncodedQuad`s pointing into them.
3576struct FramePacker {
3577    /// Concatenated wire-term bytes for every row of the current frame.
3578    buf: BytesMut,
3579    /// Per-row segment ranges, in emit order.
3580    rows: Vec<FrameRow>,
3581    /// Slots left empty in every packed row (see
3582    /// `ScanPatternRequest.omitted_slots`). `OMIT_NONE` packs all four.
3583    omitted: u8,
3584}
3585
3586impl FramePacker {
3587    fn with_omitted(omitted: u8) -> Self {
3588        Self {
3589            buf: BytesMut::new(),
3590            rows: Vec::new(),
3591            omitted,
3592        }
3593    }
3594
3595    /// Rows packed into the current frame so far.
3596    fn len(&self) -> usize {
3597        self.rows.len()
3598    }
3599
3600    /// Whether the current frame holds no rows.
3601    fn is_empty(&self) -> bool {
3602        self.rows.is_empty()
3603    }
3604
3605    /// Copy one emitted row into the framebuffer, recording its wire-order
3606    /// segment ranges. A fresh frame buffer is pre-sized for the rows this
3607    /// frame is expected to hold — the frame cap, or what is left of a
3608    /// bounded request (`remaining`, 0 = unbounded; read before the row
3609    /// decrements it).
3610    fn push_row(&mut self, row: &KeyRow<'_>, merge_default_graph: bool, remaining: u64) {
3611        if self.rows.is_empty() {
3612            let rows = remaining.min(SCAN_STREAM_FRAME_ROWS as u64) as usize;
3613            self.buf.reserve(rows * WIRE_ROW_MAX_BYTES);
3614            self.rows.reserve(rows);
3615        }
3616        let mut segs: [Range<usize>; 4] = [0..0, 0..0, 0..0, 0..0];
3617        for slot in [
3618            QuadSlot::Subject,
3619            QuadSlot::Predicate,
3620            QuadSlot::Object,
3621            QuadSlot::Graph,
3622        ] {
3623            // Merge-default rows rewrite the G field to empty (see
3624            // `wire_quad`): the source-graph bytes are skipped here while
3625            // the dedup cursor keeps comparing them upstream, on the raw
3626            // keys.
3627            if merge_default_graph && slot == QuadSlot::Graph {
3628                continue;
3629            }
3630            // `None` when the permutation omits the slot (the Tsg
3631            // predicate, implicit `rdf:type`); an empty slice is the
3632            // default graph's zero-length encoding.
3633            let Some(segment) = row.slot_bytes(slot) else {
3634                continue;
3635            };
3636            // An omitted slot keeps its empty range, so `wire_quad` hands out
3637            // an empty field and the receiver reassembles it from the request's
3638            // own pattern (see `ScanPatternRequest.omitted_slots`).
3639            let slot_bit = match slot {
3640                QuadSlot::Subject => OMIT_SUBJECT,
3641                QuadSlot::Predicate => OMIT_PREDICATE,
3642                QuadSlot::Object => OMIT_OBJECT,
3643                QuadSlot::Graph => OMIT_GRAPH,
3644            };
3645            if self.omitted & slot_bit != 0 {
3646                continue;
3647            }
3648            // this row start location in the framebuffer
3649            let start = self.buf.len();
3650            self.buf.extend_from_slice(segment);
3651            segs[slot as usize] = start..self.buf.len();
3652        }
3653        self.rows.push(FrameRow {
3654            permutation: row.permutation,
3655            segs,
3656        });
3657    }
3658
3659    /// Freeze the framebuffer and build the wire frame. Every field is a
3660    /// refcounted slice of the frozen buffer, so nothing copies and the
3661    /// packed bytes stay alive exactly as long as the returned quads.
3662    fn take_frame(
3663        &mut self,
3664        merge_default_graph: bool,
3665        rdf_type_wire: &Bytes,
3666    ) -> pb::ScanPatternResponse {
3667        let frame = std::mem::take(&mut self.buf).freeze();
3668        let rows = std::mem::take(&mut self.rows);
3669        pb::ScanPatternResponse {
3670            quads: rows
3671                .iter()
3672                .map(|row| {
3673                    wire_quad(
3674                        &frame,
3675                        row,
3676                        merge_default_graph,
3677                        rdf_type_wire,
3678                        self.omitted,
3679                    )
3680                })
3681                .collect(),
3682            // Mid-walk frames carry NO verdict: the walk being live at a
3683            // frame boundary says nothing about what follows the frame.
3684            // The two stamps that carry one — the stream drain's
3685            // limit-stop flush (LIMITED) and its terminal frame, plus the
3686            // unary page handler's response — are applied by the callers
3687            // that know the walk's verdict, and only when purchased.
3688            exhausted: None,
3689        }
3690    }
3691}
3692
3693/// Build the wire quad for a packed row at the frame boundary.
3694///
3695/// Every field is a zero-copy `Bytes::slice` of the frozen framebuffer.
3696/// Merge-default rows rewrite the G field to empty
3697/// (`EncodedQuad::into_merged_default` semantics — the key itself is
3698/// untouched, so the dedup cursor keeps comparing source-graph bytes). Tsg
3699/// rows carry the constant `rdf:type` wire encoding as the predicate.
3700fn wire_quad(
3701    frame: &Bytes,
3702    row: &FrameRow,
3703    merge_default_graph: bool,
3704    rdf_type_wire: &Bytes,
3705    omitted: u8,
3706) -> pb::EncodedQuad {
3707    // Every other omitted slot already holds an empty range from `push_row`;
3708    // the Tsg predicate is the one slot that is synthesised rather than copied,
3709    // so it needs the mask to stay empty.
3710    let predicate = if omitted & OMIT_PREDICATE != 0 {
3711        Bytes::new()
3712    } else if row.permutation == IndexPermutation::Tsg {
3713        rdf_type_wire.clone()
3714    } else {
3715        frame.slice(row.segs[1].clone())
3716    };
3717    pb::EncodedQuad {
3718        subject: frame.slice(row.segs[0].clone()),
3719        predicate,
3720        object: frame.slice(row.segs[2].clone()),
3721        graph_name: if merge_default_graph {
3722            Bytes::new()
3723        } else {
3724            frame.slice(row.segs[3].clone())
3725        },
3726    }
3727}
3728
3729struct PatternRequest {
3730    permutation: Option<IndexPermutation>,
3731    pattern: EncodedTriplePattern,
3732    snapshot: SnapshotId,
3733    limit: u64,
3734    filter_slot: Option<PatternSlot>,
3735    filter_terms: Vec<EncodedTerm>,
3736    start_after: Option<EncodedQuad>,
3737    graph_filter_terms: Vec<EncodedTerm>,
3738    graph_filter_allow: bool,
3739    merge_default_graph: bool,
3740    iri_only: IriOnlyMask,
3741    /// Slot comparisons evaluated inside the walk (ANDed).
3742    comparisons: Vec<SlotComparison>,
3743    /// Response slots to leave empty (see `ScanPatternRequest.omitted_slots`).
3744    omitted: u8,
3745    /// Whether the consumer will issue another request after a FULL page
3746    /// (see `ScanPatternRequest.verdict_wanted`): `true` keeps the walk
3747    /// running past a full page so its own exit reports an honest terminal
3748    /// verdict at exact limit boundaries; `false` stops at the limit'th row.
3749    verdict_wanted: bool,
3750}
3751
3752fn term_in_slot(quad: &EncodedQuad, slot: PatternSlot) -> &EncodedTerm {
3753    match slot {
3754        PatternSlot::Subject => &quad.subject,
3755        PatternSlot::Predicate => &quad.predicate,
3756        PatternSlot::Object => &quad.object,
3757    }
3758}
3759
3760fn pattern_slot_to_quad(slot: PatternSlot) -> QuadSlot {
3761    match slot {
3762        PatternSlot::Subject => QuadSlot::Subject,
3763        PatternSlot::Predicate => QuadSlot::Predicate,
3764        PatternSlot::Object => QuadSlot::Object,
3765    }
3766}
3767
3768fn bind_filter_term(
3769    pattern: &EncodedTriplePattern,
3770    slot: PatternSlot,
3771    term: &EncodedTerm,
3772) -> EncodedTriplePattern {
3773    let mut bound = pattern.clone();
3774    match slot {
3775        PatternSlot::Subject => bound.subject = Some(term.clone()),
3776        PatternSlot::Predicate => bound.predicate = Some(term.clone()),
3777        PatternSlot::Object => bound.object = Some(term.clone()),
3778    }
3779    bound
3780}
3781
3782fn resolve_broadcast_permutation(
3783    storage: &Storage,
3784    permutation: Option<IndexPermutation>,
3785    pattern: &EncodedTriplePattern,
3786    slot: PatternSlot,
3787    first_term: &EncodedTerm,
3788) -> IndexPermutation {
3789    match permutation {
3790        Some(permutation) => permutation,
3791        None => bind_filter_term(pattern, slot, first_term).best_permutation(storage.axis()),
3792    }
3793}
3794
3795/// One iterator per allow-listed term (N=1, or filter slot is not a prefix extension).
3796#[allow(clippy::too_many_arguments)]
3797/// Per-row consumer of the unary page walk, shared by the decoded reference
3798/// path (`scan_filtered`) and the packed RPC path (`scan_filtered_packed`).
3799/// `Ok(false)` stops the walk early (page limit reached). Storage's walk
3800/// callbacks return `StorageError`, so the page helpers wrap this sink and
3801/// surface a sink error after the walk unwinds.
3802type ScanRowEmit<'a> = dyn FnMut(&KeyRow<'_>) -> Result<bool, PartitionError> + 'a;
3803
3804#[allow(clippy::too_many_arguments)]
3805fn scan_filter_terms_separately(
3806    storage: &Storage,
3807    permutation: Option<IndexPermutation>,
3808    pattern: &EncodedTriplePattern,
3809    snapshot: SnapshotId,
3810    limit: u64,
3811    start_after: Option<&EncodedQuad>,
3812    graph: &GByteFilter,
3813    merge_default_graph: bool,
3814    slot: PatternSlot,
3815    terms: &[EncodedTerm],
3816    iri_only: IriOnlyMask,
3817    comparisons: &[SlotComparison],
3818    verdict_wanted: bool,
3819    emit: &mut ScanRowEmit<'_>,
3820) -> Result<(u64, ScanExhaustion), PartitionError> {
3821    let cursor_term = start_after.map(|quad| term_in_slot(quad, slot));
3822    // `false` until we reach the allow-list value that owns `start_after`.
3823    let mut dont_skip = start_after.is_none();
3824    let mut emitted = 0u64;
3825    // Verdict: completing the term loop serves the whole list
3826    // (`ExhaustedFilterTerms`). A limit-stop inside ANY term's walk —
3827    // including the last, where no further loop-iteration limit check
3828    // runs — must propagate the per-term walk's `Limited` instead: a
3829    // terminal claim while the sink refused rows would be a false
3830    // "nothing more exists" and cost the consumer a wrong early stop.
3831    let mut verdict = ScanExhaustion::ExhaustedFilterTerms;
3832    for term in terms {
3833        if limit > 0 && emitted >= limit {
3834            verdict = ScanExhaustion::Limited;
3835            break;
3836        }
3837        let page_after = if !dont_skip {
3838            if Some(term) != cursor_term {
3839                continue;
3840            }
3841            dont_skip = true;
3842            start_after
3843        } else {
3844            None
3845        };
3846        let remaining = if limit == 0 { 0 } else { limit - emitted };
3847        let bound = bind_filter_term(pattern, slot, term);
3848        let (term_rows, term_verdict) = scan_page_graph(
3849            storage,
3850            permutation,
3851            &bound,
3852            snapshot,
3853            remaining,
3854            page_after,
3855            graph,
3856            merge_default_graph,
3857            iri_only,
3858            comparisons,
3859            verdict_wanted,
3860            emit,
3861        )?;
3862        emitted += term_rows;
3863        // Fold the per-term verdict: `Limited` means this term's walk
3864        // stopped at the remaining-limit (the cut landed inside the
3865        // term's prefix), so the outer verdict is `Limited` and no later
3866        // term can emit (the page is full — `emitted == limit`). Also
3867        // ends the loop early on a dropped consumer, skipping the
3868        // remaining terms' seeks with no observable change (the response
3869        // is discarded on a drop). A terminal per-term verdict (the
3870        // term's prefix fully served) folds nothing: later terms may
3871        // still match.
3872        if term_verdict == ScanExhaustion::Limited {
3873            verdict = ScanExhaustion::Limited;
3874            break;
3875        }
3876    }
3877    Ok((emitted, verdict))
3878}
3879
3880#[allow(clippy::too_many_arguments)]
3881fn count_filter_terms_separately(
3882    storage: &Storage,
3883    permutation: Option<IndexPermutation>,
3884    pattern: &EncodedTriplePattern,
3885    snapshot: SnapshotId,
3886    limit: u64,
3887    graph: &GByteFilter,
3888    merge_default_graph: bool,
3889    slot: PatternSlot,
3890    terms: &[EncodedTerm],
3891    force_serial: bool,
3892) -> Result<u64, PartitionError> {
3893    let mut total = 0u64;
3894    for term in terms {
3895        if limit > 0 && total >= limit {
3896            break;
3897        }
3898        let remaining = if limit == 0 { 0 } else { limit - total };
3899        let bound = bind_filter_term(pattern, slot, term);
3900        // Per-term bound patterns are prefix-arena shapes (class bound on
3901        // TSG when the filter slot is the class) — the TSG full-axis hint
3902        // never applies here.
3903        total += count_page_graph(
3904            storage,
3905            permutation,
3906            &bound,
3907            snapshot,
3908            remaining,
3909            graph,
3910            merge_default_graph,
3911            &[],
3912            force_serial,
3913        )?;
3914    }
3915    Ok(total)
3916}
3917
3918/// Per-tight-prefix page over the allow-listed terms, feeding `emit` raw
3919/// [`KeyRow`]s. `Ok(None)` means the filter slot does not extend the pattern's
3920/// key prefix (no tight allow-list) and the caller must fall through to the
3921/// per-term walks. `Ok(Some((rows, verdict)))` carries the walk's own
3922/// [`ScanExhaustion`].
3923#[allow(clippy::too_many_arguments)]
3924fn scan_page_graph_allow_list(
3925    storage: &Storage,
3926    permutation: IndexPermutation,
3927    pattern: &EncodedTriplePattern,
3928    snapshot: SnapshotId,
3929    limit: u64,
3930    start_after: Option<&EncodedQuad>,
3931    graph: &GByteFilter,
3932    merge_default_graph: bool,
3933    slot: QuadSlot,
3934    terms: &[EncodedTerm],
3935    iri_only: IriOnlyMask,
3936    comparisons: &[SlotComparison],
3937    verdict_wanted: bool,
3938    emit: &mut ScanRowEmit<'_>,
3939) -> Result<Option<(u64, ScanExhaustion)>, PartitionError> {
3940    if pattern
3941        .prepare_tight_allow_list(permutation, slot, terms)
3942        .is_none()
3943    {
3944        return Ok(None);
3945    }
3946    if graph.empty_window() {
3947        // No row can match under this graph window: the scan's whole
3948        // scope is (vacuously) served.
3949        return Ok(Some((0, ScanExhaustion::ExhaustedScan)));
3950    }
3951    // Full matcher semantics per tight prefix: the RowMatcher applies the
3952    // graph window, dedup collapse, and the dedup whole-triple cursor on
3953    // raw key bytes. `limit` counts post-filter matches.
3954    let mut emitted = 0u64;
3955    let mut error = None;
3956    let verdict = storage
3957        .visit_allow_list_rows_with_comparisons(
3958            permutation,
3959            pattern,
3960            snapshot,
3961            start_after,
3962            slot,
3963            terms,
3964            graph.clone(),
3965            merge_default_graph,
3966            iri_only,
3967            comparisons,
3968            |row| {
3969                if error.is_some() {
3970                    return Ok(false);
3971                }
3972                // Page-limit discipline, selected by the consumer's
3973                // `verdict_wanted` declaration:
3974                // - EDGE-triggered (`verdict_wanted`): a row arriving AT
3975                //   the page limit proves more data exists (stop,
3976                //   `Limited`) but is not emitted; when the data ends
3977                //   exactly at the limit this row never arrives and the
3978                //   walk completes with the terminal verdict — the fact
3979                //   the wire verdict carries. Costs the walk iterations
3980                //   between the limit'th row and the next emitting row.
3981                // - LEVEL-triggered (not wanted): stop AT the limit'th
3982                //   row. A consumer whose demand equals its whole
3983                //   remaining interest (an ASK / one-shot slice) never
3984                //   reads a full page's verdict, so those iterations buy
3985                //   nothing; the walk's verdict stays `Limited` and the
3986                //   packed response leaves the field unset — a short
3987                //   page's completed walk IS a genuine terminal fact, but
3988                //   the contract is "a verdict appears iff one was asked
3989                //   for".
3990                if limit > 0 && emitted >= limit {
3991                    return Ok(false);
3992                }
3993                match emit(row) {
3994                    Ok(true) => {
3995                        emitted += 1;
3996                        Ok(verdict_wanted || limit == 0 || emitted < limit)
3997                    }
3998                    Ok(false) => Ok(false),
3999                    Err(e) => {
4000                        error = Some(e);
4001                        Ok(false)
4002                    }
4003                }
4004            },
4005        )
4006        .map_err(PartitionError::from)?;
4007    match error {
4008        Some(e) => Err(e),
4009        // `verdict == None` never carries a sink error past this point:
4010        // the caller falls through to the per-term walks.
4011        None => Ok(verdict.map(|exhausted| (emitted, exhausted))),
4012    }
4013}
4014
4015#[allow(clippy::too_many_arguments)]
4016fn count_page_graph_allow_list(
4017    storage: &Storage,
4018    permutation: IndexPermutation,
4019    pattern: &EncodedTriplePattern,
4020    snapshot: SnapshotId,
4021    limit: u64,
4022    graph: &GByteFilter,
4023    merge_default_graph: bool,
4024    slot: QuadSlot,
4025    terms: &[EncodedTerm],
4026) -> Result<Option<u64>, PartitionError> {
4027    if pattern
4028        .prepare_tight_allow_list(permutation, slot, terms)
4029        .is_none()
4030    {
4031        return Ok(None);
4032    }
4033    if graph.empty_window() {
4034        return Ok(Some(0));
4035    }
4036    // Full matcher semantics per tight prefix, counting raw rows — no row
4037    // materialization. Semantics match [`scan_page_graph_allow_list`].
4038    Ok(storage.count_pattern_allow_list(
4039        permutation,
4040        pattern,
4041        snapshot,
4042        limit,
4043        slot,
4044        terms,
4045        graph.clone(),
4046        merge_default_graph,
4047    )?)
4048}
4049
4050/// Apply residual G membership and optional SPARQL default-graph triple merge
4051/// before honouring `limit`.
4052///
4053/// The RowMatcher applies residual G membership, `merge_default_graph`
4054/// whole-triple collapse (rows return with G rewritten to DefaultGraph),
4055/// the dedup whole-triple `start_after` cursor (a rewritten DefaultGraph
4056/// cursor is compared as a triple prefix on raw bytes, not as a full key),
4057/// and `iri_only` pushdown — all on raw key bytes in ONE continuous walk.
4058/// `limit` counts post-filter matches. Each accepted row is handed to `emit`
4059/// as a raw [`KeyRow`]; the sink decides whether to decode it (reference
4060/// path) or pack its bytes (RPC path). Returns the number of rows the sink
4061/// accepted plus the walk's own [`ScanExhaustion`] verdict.
4062#[allow(clippy::too_many_arguments)]
4063fn scan_page_graph(
4064    storage: &Storage,
4065    permutation: Option<IndexPermutation>,
4066    pattern: &EncodedTriplePattern,
4067    snapshot: SnapshotId,
4068    limit: u64,
4069    start_after: Option<&EncodedQuad>,
4070    graph: &GByteFilter,
4071    merge_default_graph: bool,
4072    iri_only: IriOnlyMask,
4073    comparisons: &[SlotComparison],
4074    verdict_wanted: bool,
4075    emit: &mut ScanRowEmit<'_>,
4076) -> Result<(u64, ScanExhaustion), PartitionError> {
4077    if graph.empty_window() {
4078        // No row can match under this graph window: the scan's whole
4079        // scope is (vacuously) served.
4080        return Ok((0, ScanExhaustion::ExhaustedScan));
4081    }
4082    let permutation = match permutation {
4083        Some(permutation) => permutation,
4084        None => pattern.best_permutation(storage.axis()),
4085    };
4086    let mut emitted = 0u64;
4087    let mut error = None;
4088    // A sink error stops the walk and surfaces after it unwinds — the same
4089    // pattern the storage-side decoded page adapters use for decode errors.
4090    let verdict = storage
4091        .visit_pattern_rows_with_comparisons(
4092            permutation,
4093            pattern,
4094            snapshot,
4095            start_after,
4096            graph.clone(),
4097            merge_default_graph,
4098            iri_only,
4099            comparisons,
4100            |row| {
4101                if error.is_some() {
4102                    return Ok(false);
4103                }
4104                // Page-limit discipline, selected by the consumer's
4105                // `verdict_wanted` declaration (see
4106                // `scan_page_graph_allow_list`'s sink for the full note):
4107                // EDGE-triggered when wanted — a row arriving AT the page
4108                // limit proves more data exists (stop, `Limited`)
4109                // but is not emitted, and data ending exactly at the
4110                // limit lets the walk complete with the terminal verdict;
4111                // LEVEL-triggered when not — stop AT the limit'th row.
4112                if limit > 0 && emitted >= limit {
4113                    return Ok(false);
4114                }
4115                match emit(row) {
4116                    Ok(true) => {
4117                        emitted += 1;
4118                        Ok(verdict_wanted || limit == 0 || emitted < limit)
4119                    }
4120                    Ok(false) => Ok(false),
4121                    Err(e) => {
4122                        error = Some(e);
4123                        Ok(false)
4124                    }
4125                }
4126            },
4127        )
4128        .map_err(PartitionError::from)?;
4129    match error {
4130        Some(e) => Err(e),
4131        None => Ok((emitted, verdict)),
4132    }
4133}
4134
4135#[allow(clippy::too_many_arguments)]
4136fn count_page_graph(
4137    storage: &Storage,
4138    permutation: Option<IndexPermutation>,
4139    pattern: &EncodedTriplePattern,
4140    snapshot: SnapshotId,
4141    limit: u64,
4142    graph: &GByteFilter,
4143    merge_default_graph: bool,
4144    class_totals: &[(StrHash, u64)],
4145    force_serial: bool,
4146) -> Result<u64, PartitionError> {
4147    if graph.empty_window() {
4148        return Ok(0);
4149    }
4150    let permutation = match permutation {
4151        Some(permutation) => permutation,
4152        None => pattern.best_permutation(storage.axis()),
4153    };
4154    // Same matcher semantics as [`scan_page_graph`], counting raw [`KeyRow`]s
4155    // inside the walk — no row materialization, no term decoding. `limit`
4156    // counts post-filter matches. `class_totals` rides along as the TSG
4157    // full-axis slice hint (advisory; ignored by every other shape).
4158    Ok(storage.count_pattern_impl_with_class_totals(
4159        permutation,
4160        pattern,
4161        snapshot,
4162        limit,
4163        graph.clone(),
4164        merge_default_graph,
4165        class_totals,
4166        force_serial,
4167    )?)
4168}
4169
4170fn decode_pattern_request(
4171    request: pb::ScanPatternRequest,
4172) -> Result<PatternRequest, PartitionError> {
4173    let permutation = permutation_from_proto(request.permutation());
4174    let pattern = request
4175        .pattern
4176        .as_ref()
4177        .map(pattern_from_proto)
4178        .transpose()
4179        .map_err(PartitionError::from)?
4180        .unwrap_or_default();
4181    let filter_slot = pattern_slot_from_proto(request.filter_slot());
4182    let filter_terms = request
4183        .filter_terms
4184        .iter()
4185        .map(|bytes| term_from_bytes(bytes).map_err(PartitionError::from))
4186        .collect::<Result<Vec<_>, _>>()?;
4187    let start_after = request
4188        .start_after
4189        .as_ref()
4190        .map(waratah_proto::quad_from_proto)
4191        .transpose()
4192        .map_err(PartitionError::from)?;
4193    let graph_filter_terms = request
4194        .graph_filter_terms
4195        .iter()
4196        .map(|bytes| term_from_bytes(bytes).map_err(PartitionError::from))
4197        .collect::<Result<Vec<_>, _>>()?;
4198    let comparisons =
4199        slot_comparisons_from_proto(&request.comparisons).map_err(PartitionError::from)?;
4200    Ok(PatternRequest {
4201        permutation,
4202        pattern,
4203        snapshot: SnapshotId(request.snapshot_id),
4204        limit: request.limit,
4205        filter_slot,
4206        filter_terms,
4207        start_after,
4208        graph_filter_terms,
4209        graph_filter_allow: request.graph_filter_allow,
4210        merge_default_graph: request.merge_default_graph,
4211        iri_only: IriOnlyMask {
4212            subject: request.iri_only_subject,
4213            object: request.iri_only_object,
4214        },
4215        comparisons,
4216        omitted: slot_mask_from_wire(request.omitted_slots).map_err(PartitionError::from)?,
4217        verdict_wanted: request.verdict_wanted,
4218    })
4219}
4220
4221/// A frame send is "blocked" (compute / network could not drain it) past this.
4222const SEND_BLOCKED_THRESHOLD: Duration = Duration::from_millis(1);
4223
4224/// Response stream of `ScanPatternStream`: boxed because the frame source
4225/// is either a blocking-pool producer channel (dispatched drains) or an
4226/// eagerly collected frame list (caller-thread drains — see
4227/// [`PartitionService::scan_pattern_stream_frames`]).
4228type ScanPatternResponseStream = std::pin::Pin<
4229    Box<dyn tokio_stream::Stream<Item = Result<pb::ScanPatternResponse, Status>> + Send>,
4230>;
4231
4232/// Stderr timing trace for one streamed `ScanPatternStream` RPC (`--trace`).
4233///
4234/// Answers, from the partition's side, whether a streamed scan was
4235/// storage-bound or consumer-bound: the whole-prefix walk latency is the
4236/// disk/CPU signal (one continuous iterator — see
4237/// [`PartitionService::scan_filtered_streaming`]), while a channel send
4238/// blocking past [`SEND_BLOCKED_THRESHOLD`] means compute or the network was
4239/// the bottleneck for that frame. Under the compute side's pipelined
4240/// `GROUP BY` drain, walks should overlap result folding — walks piling up
4241/// behind blocked sends is the healthy overlap signature.
4242#[derive(Debug)]
4243struct ScanTrace {
4244    enabled: bool,
4245    started: Instant,
4246    frames: u64,
4247    rows: u64,
4248    walk: Option<Duration>,
4249    send_total: Duration,
4250    send_max: Duration,
4251    sends_blocked: u64,
4252}
4253
4254impl ScanTrace {
4255    fn new(enabled: bool) -> Self {
4256        Self {
4257            enabled,
4258            started: Instant::now(),
4259            frames: 0,
4260            rows: 0,
4261            walk: None,
4262            send_total: Duration::ZERO,
4263            send_max: Duration::ZERO,
4264            sends_blocked: 0,
4265        }
4266    }
4267
4268    /// Record one frame handed to the channel; logs when enabled and when a
4269    /// send blocked past [`SEND_BLOCKED_THRESHOLD`].
4270    fn frame_sent(&mut self, rows: usize, waited: Duration) {
4271        self.frames += 1;
4272        self.rows += rows as u64;
4273        self.send_total += waited;
4274        self.send_max = self.send_max.max(waited);
4275        if waited > SEND_BLOCKED_THRESHOLD {
4276            self.sends_blocked += 1;
4277        }
4278        if self.enabled {
4279            eprintln!(
4280                "partition-trace frame {} rows={} total_rows={} send={:.1}ms",
4281                self.frames,
4282                rows,
4283                self.rows,
4284                waited.as_secs_f64() * 1e3,
4285            );
4286        }
4287        if self.enabled && waited > SEND_BLOCKED_THRESHOLD {
4288            eprintln!(
4289                "partition-trace send blocked waited={:.1}ms",
4290                waited.as_secs_f64() * 1e3,
4291            );
4292        }
4293    }
4294
4295    /// Emit the per-request summary line when enabled.
4296    fn done(&mut self, reason: &str) {
4297        if !self.enabled {
4298            return;
4299        }
4300        let walk = self.walk.unwrap_or_default();
4301        eprintln!(
4302            "partition-trace scan done reason={reason} frames={} rows={} \
4303             wall={:.3}s walk={:.3}s send_total={:.1}ms send_max={:.1}ms sends_blocked={}",
4304            self.frames,
4305            self.rows,
4306            self.started.elapsed().as_secs_f64(),
4307            walk.as_secs_f64(),
4308            self.send_total.as_secs_f64() * 1e3,
4309            self.send_max.as_secs_f64() * 1e3,
4310            self.sends_blocked,
4311        );
4312    }
4313}
4314
4315#[tonic::async_trait]
4316impl Hexastore for PartitionService {
4317    type ScanPatternStreamStream = ScanPatternResponseStream;
4318    type GeoCandidateScanStream = ReceiverStream<Result<pb::GeoCandidateScanResponse, Status>>;
4319    type TemporalCandidateScanStream =
4320        ReceiverStream<Result<pb::TemporalCandidateScanResponse, Status>>;
4321    type TextCandidateScanStream = ReceiverStream<Result<pb::TextCandidateScanResponse, Status>>;
4322    type TextSubjectScanStream = ReceiverStream<Result<pb::TextSubjectScanResponse, Status>>;
4323
4324    async fn insert_quads(
4325        &self,
4326        request: Request<pb::InsertQuadsRequest>,
4327    ) -> Result<Response<pb::InsertQuadsResponse>, Status> {
4328        let request = request.into_inner();
4329        let axis = axis_from_proto(request.axis());
4330        let versions = request
4331            .quads
4332            .iter()
4333            .map(quad_version_from_proto)
4334            .collect::<Result<Vec<_>, _>>()
4335            .map_err(PartitionError::from)?;
4336        let service = self.clone();
4337        let inserted = tokio::task::spawn_blocking(move || service.apply_versions(axis, &versions))
4338            .await
4339            .map_err(|join| blocking_join_error("storage", join))??;
4340        Ok(Response::new(pb::InsertQuadsResponse { inserted }))
4341    }
4342
4343    async fn replace_quads(
4344        &self,
4345        request: Request<pb::ReplaceQuadsRequest>,
4346    ) -> Result<Response<pb::ReplaceQuadsResponse>, Status> {
4347        let request = request.into_inner();
4348        let pairs = request
4349            .pairs
4350            .iter()
4351            .map(waratah_proto::replace_pair_from_proto)
4352            .collect::<Result<Vec<_>, _>>()
4353            .map_err(PartitionError::from)?;
4354        let commit_ts = waratah_storage::CommitTs(request.commit_ts);
4355        let service = self.clone();
4356        let replaced =
4357            tokio::task::spawn_blocking(move || service.apply_replaces(&pairs, commit_ts))
4358                .await
4359                .map_err(|join| blocking_join_error("storage", join))??;
4360        Ok(Response::new(pb::ReplaceQuadsResponse { replaced }))
4361    }
4362
4363    async fn scan_pattern(
4364        &self,
4365        request: Request<pb::ScanPatternRequest>,
4366    ) -> Result<Response<pb::ScanPatternResponse>, Status> {
4367        let recv_at = std::time::SystemTime::now()
4368            .duration_since(std::time::UNIX_EPOCH)
4369            .map(|d| d.as_millis())
4370            .unwrap_or(0);
4371        let request = decode_pattern_request(request.into_inner())?;
4372        let service = self.clone();
4373        let trace = self.trace;
4374        let started = Instant::now();
4375        // Exact-stats gate (SCAN_DISPATCH_ROW_THRESHOLD): at or below the
4376        // threshold's row estimate the walk runs directly on this worker —
4377        // the blocking-pool wake is pure latency for a µs-scale seek, and
4378        // its CFS wakeup delay is the measured ~600 µs small-query stall.
4379        let rows = if service.scan_runs_on_caller(
4380            request.permutation,
4381            &request.pattern,
4382            request.filter_slot,
4383            &request.filter_terms,
4384        ) {
4385            let walk_started = Instant::now();
4386            let response = service.scan_filtered_packed(
4387                request.permutation,
4388                &request.pattern,
4389                request.snapshot,
4390                request.limit,
4391                request.filter_slot,
4392                &request.filter_terms,
4393                request.start_after.as_ref(),
4394                &request.graph_filter_terms,
4395                request.graph_filter_allow,
4396                request.merge_default_graph,
4397                request.iri_only,
4398                &request.comparisons,
4399                request.omitted,
4400                request.verdict_wanted,
4401            )?;
4402            if trace {
4403                // Same walk line as the dispatched branch: unary and
4404                // streamed drains stay comparable in profiles.
4405                eprintln!(
4406                    "partition-trace unary walk rows={} wall={:.3}s",
4407                    response.quads.len(),
4408                    walk_started.elapsed().as_secs_f64()
4409                );
4410            }
4411            response
4412        } else {
4413            tokio::task::spawn_blocking(move || {
4414                let walk_started = Instant::now();
4415                let response = service.scan_filtered_packed(
4416                    request.permutation,
4417                    &request.pattern,
4418                    request.snapshot,
4419                    request.limit,
4420                    request.filter_slot,
4421                    &request.filter_terms,
4422                    request.start_after.as_ref(),
4423                    &request.graph_filter_terms,
4424                    request.graph_filter_allow,
4425                    request.merge_default_graph,
4426                    request.iri_only,
4427                    &request.comparisons,
4428                    request.omitted,
4429                    request.verdict_wanted,
4430                )?;
4431                if trace {
4432                    // Mirrors the streaming drain's walk line so unary and
4433                    // streamed drains are comparable in profiles.
4434                    eprintln!(
4435                        "partition-trace unary walk rows={} wall={:.3}s",
4436                        response.quads.len(),
4437                        walk_started.elapsed().as_secs_f64()
4438                    );
4439                }
4440                Ok::<_, PartitionError>(response)
4441            })
4442            .await
4443            .map_err(|join| blocking_join_error("storage", join))??
4444        };
4445        if trace {
4446            // recv_at/resp_at are absolute epoch ms so a `--debug` run's
4447            // client-side `scan-rpc[...] sent_at=` lines correlate directly:
4448            // arrival delay ⇒ send-side, resp_at→client gap ⇒ response path.
4449            let resp_at = std::time::SystemTime::now()
4450                .duration_since(std::time::UNIX_EPOCH)
4451                .map(|d| d.as_millis())
4452                .unwrap_or(0);
4453            eprintln!(
4454                "partition-trace unary scan done rows={} wall={:.3}s recv_at={} resp_at={}",
4455                rows.quads.len(),
4456                started.elapsed().as_secs_f64(),
4457                recv_at,
4458                resp_at
4459            );
4460        }
4461        Ok(Response::new(rows))
4462    }
4463
4464    /// Storage-driven drain of a prefix as continuous frames.
4465    ///
4466    /// Unlike [`Self::scan_pattern`] (compute-driven: one request carries the
4467    /// exact page it needs), the partition here streams every matching row as
4468    /// it is walked — ONE iterator for the whole prefix, no storage-side page
4469    /// boundaries, no locks held — until the prefix is exhausted, the
4470    /// request's `limit` rows have been emitted, or the consumer drops the
4471    /// stream. Residual G membership, `merge_default_graph` whole-triple cursors,
4472    /// and MVCC snapshot visibility match unary paging exactly (same row
4473    /// pipeline, per row). See [`Self::scan_pattern_stream_frames`].
4474    async fn scan_pattern_stream(
4475        &self,
4476        request: Request<pb::ScanPatternRequest>,
4477    ) -> Result<Response<Self::ScanPatternStreamStream>, Status> {
4478        let request = decode_pattern_request(request.into_inner())?;
4479        let stream = self.scan_pattern_stream_frames(
4480            request.permutation,
4481            request.pattern,
4482            request.snapshot,
4483            request.limit,
4484            request.filter_slot,
4485            request.filter_terms,
4486            request.start_after,
4487            request.graph_filter_terms,
4488            request.graph_filter_allow,
4489            request.merge_default_graph,
4490            request.iri_only,
4491            request.comparisons,
4492            request.omitted,
4493            request.verdict_wanted,
4494        );
4495        Ok(Response::new(stream))
4496    }
4497
4498    async fn count_pattern(
4499        &self,
4500        request: Request<pb::ScanPatternRequest>,
4501    ) -> Result<Response<pb::CountPatternResponse>, Status> {
4502        let request = decode_pattern_request(request.into_inner())?;
4503        if request.iri_only != IriOnlyMask::NONE {
4504            // The count helpers walk raw prefixes without per-slot term
4505            // checks, so an IRI-only pushdown would be silently ignored and
4506            // the count would disagree with the same mask on a scan.
4507            return Err(Status::invalid_argument(
4508                "iri_only flags are not supported on CountPattern",
4509            ));
4510        }
4511        if request.omitted != 0 {
4512            // A count returns no quads, so a mask could only be ignored; a
4513            // silently ignored mask would disagree with the same scan's rows
4514            // if the mask ever grew a meaning for the walk itself.
4515            return Err(Status::invalid_argument(
4516                "omitted_slots is not supported on CountPattern",
4517            ));
4518        }
4519        if request.start_after.is_some() {
4520            // A count is a single scalar with no resume cursor; a silently
4521            // ignored cursor would disagree with the same scan's rows.
4522            return Err(Status::invalid_argument(
4523                "start_after is not supported on CountPattern (counts are not resumable)",
4524            ));
4525        }
4526        if !request.comparisons.is_empty() {
4527            // The count walks count raw rows and never decode a slot term, so
4528            // a slot comparison has no home here. Reject it rather than
4529            // silently disagree with the same scan's rows.
4530            return Err(Status::invalid_argument(
4531                "slot comparisons are not supported on CountPattern",
4532            ));
4533        }
4534        let service = self.clone();
4535        let trace = self.trace;
4536        let started = Instant::now();
4537        // Exact-stats gate (SCAN_DISPATCH_ROW_THRESHOLD): an estimable
4538        // count at or below the threshold runs directly on this worker.
4539        // The count walks the same prefix a scan drains, so for a
4540        // µs-scale count the pool wake is pure latency — the same CFS
4541        // wakeup stall the scan gate removes (see scan_runs_on_caller).
4542        let count = if service.scan_runs_on_caller(
4543            request.permutation,
4544            &request.pattern,
4545            request.filter_slot,
4546            &request.filter_terms,
4547        ) {
4548            // The gate judged this count µs-scale, so the walk stays on the
4549            // caller AND serial: the parallel walk's worker-pool wake would
4550            // outweigh it. The gate's judgment composes over the
4551            // storage-side count-walk knobs.
4552            service.count_filtered_on_caller(
4553                request.permutation,
4554                &request.pattern,
4555                request.snapshot,
4556                request.limit,
4557                request.filter_slot,
4558                &request.filter_terms,
4559                &request.graph_filter_terms,
4560                request.graph_filter_allow,
4561                request.merge_default_graph,
4562            )?
4563        } else {
4564            tokio::task::spawn_blocking(move || {
4565                service.count_filtered(
4566                    request.permutation,
4567                    &request.pattern,
4568                    request.snapshot,
4569                    request.limit,
4570                    request.filter_slot,
4571                    &request.filter_terms,
4572                    &request.graph_filter_terms,
4573                    request.graph_filter_allow,
4574                    request.merge_default_graph,
4575                )
4576            })
4577            .await
4578            .map_err(|join| blocking_join_error("storage", join))??
4579        };
4580        if trace {
4581            eprintln!(
4582                "partition-trace count done count={} wall={:.3}s",
4583                count,
4584                started.elapsed().as_secs_f64()
4585            );
4586        }
4587        Ok(Response::new(pb::CountPatternResponse { count }))
4588    }
4589
4590    async fn domain_scan(
4591        &self,
4592        request: Request<pb::DomainScanRequest>,
4593    ) -> Result<Response<pb::DomainScanResponse>, Status> {
4594        let request = request.into_inner();
4595        let permutation = permutation_from_proto(request.permutation())
4596            .ok_or(PartitionError::PermutationRequired("DomainScan"))?;
4597        let constraints = request
4598            .constraints
4599            .iter()
4600            .map(|bytes| term_from_bytes(bytes).map_err(PartitionError::from))
4601            .collect::<Result<Vec<_>, _>>()?;
4602        let graph_name = match request.graph_name {
4603            Some(bytes) if !bytes.is_empty() => {
4604                Some(term_from_bytes(&bytes).map_err(PartitionError::from)?)
4605            }
4606            Some(_) => Some(EncodedTerm::DefaultGraph),
4607            None => None,
4608        };
4609        let graph_filter_terms = request
4610            .graph_filter_terms
4611            .iter()
4612            .map(|bytes| term_from_bytes(bytes).map_err(PartitionError::from))
4613            .collect::<Result<Vec<_>, _>>()?;
4614        let start_after_constraint = if request.start_after_constraint.is_empty() {
4615            None
4616        } else {
4617            Some(term_from_bytes(&request.start_after_constraint).map_err(PartitionError::from)?)
4618        };
4619        let start_after_term = if request.start_after_term.is_empty() {
4620            None
4621        } else {
4622            Some(term_from_bytes(&request.start_after_term).map_err(PartitionError::from)?)
4623        };
4624        let snapshot = SnapshotId(request.snapshot_id);
4625        let limit = request.limit;
4626        let graph_allow = request.graph_filter_allow;
4627        let iri_only_head = request.iri_only_head;
4628        let service = self.clone();
4629        // Exact-stats gate (SCAN_DISPATCH_ROW_THRESHOLD): a predicate-keyed
4630        // domain scan whose constraint sum is at or below the threshold runs
4631        // directly on this worker — the same pool-wake latency the scan and
4632        // count gates remove (see domain_scan_runs_on_caller).
4633        let hits = if service.domain_scan_runs_on_caller(permutation, &constraints) {
4634            service.scan_domain(
4635                permutation,
4636                &constraints,
4637                snapshot,
4638                limit,
4639                start_after_constraint.as_ref(),
4640                start_after_term.as_ref(),
4641                graph_name.as_ref(),
4642                &graph_filter_terms,
4643                graph_allow,
4644                iri_only_head,
4645            )?
4646        } else {
4647            tokio::task::spawn_blocking(move || {
4648                service.scan_domain(
4649                    permutation,
4650                    &constraints,
4651                    snapshot,
4652                    limit,
4653                    start_after_constraint.as_ref(),
4654                    start_after_term.as_ref(),
4655                    graph_name.as_ref(),
4656                    &graph_filter_terms,
4657                    graph_allow,
4658                    iri_only_head,
4659                )
4660            })
4661            .await
4662            .map_err(|join| blocking_join_error("storage", join))??
4663        };
4664        Ok(Response::new(pb::DomainScanResponse {
4665            hits: hits
4666                .iter()
4667                .map(|hit| pb::DomainScanHit {
4668                    constraint: waratah_proto::term_to_bytes(&hit.constraint),
4669                    term: waratah_proto::term_to_bytes(&hit.term),
4670                })
4671                .collect(),
4672        }))
4673    }
4674
4675    async fn domain_scan_counts(
4676        &self,
4677        request: Request<pb::DomainScanCountRequest>,
4678    ) -> Result<Response<pb::DomainScanCountResponse>, Status> {
4679        let request = request.into_inner();
4680        let mode = waratah_proto::count_mode_from_proto(request.count_mode());
4681        let permutation = permutation_from_proto(request.permutation())
4682            .ok_or(PartitionError::PermutationRequired("DomainScanCounts"))?;
4683        let constraints = request
4684            .constraints
4685            .iter()
4686            .map(|bytes| term_from_bytes(bytes).map_err(PartitionError::from))
4687            .collect::<Result<Vec<_>, _>>()?;
4688        let graph_name = match request.graph_name {
4689            Some(bytes) if !bytes.is_empty() => {
4690                Some(term_from_bytes(&bytes).map_err(PartitionError::from)?)
4691            }
4692            Some(_) => Some(EncodedTerm::DefaultGraph),
4693            None => None,
4694        };
4695        let graph_filter_terms = request
4696            .graph_filter_terms
4697            .iter()
4698            .map(|bytes| term_from_bytes(bytes).map_err(PartitionError::from))
4699            .collect::<Result<Vec<_>, _>>()?;
4700        let start_after_constraint = if request.start_after_constraint.is_empty() {
4701            None
4702        } else {
4703            Some(term_from_bytes(&request.start_after_constraint).map_err(PartitionError::from)?)
4704        };
4705        let start_after_term = if request.start_after_term.is_empty() {
4706            None
4707        } else {
4708            Some(term_from_bytes(&request.start_after_term).map_err(PartitionError::from)?)
4709        };
4710        let snapshot = SnapshotId(request.snapshot_id);
4711        let limit = request.limit;
4712        let graph_allow = request.graph_filter_allow;
4713        let iri_only_head = request.iri_only_head;
4714        let merge_default_graph = request.merge_default_graph;
4715        let service = self.clone();
4716        // Exact-stats gate (SCAN_DISPATCH_ROW_THRESHOLD): same as the
4717        // domain-scan gate — the count variant walks the same prefixes
4718        // (see domain_scan_runs_on_caller).
4719        let hits = if service.domain_scan_runs_on_caller(permutation, &constraints) {
4720            service.scan_domain_counts(
4721                permutation,
4722                &constraints,
4723                snapshot,
4724                limit,
4725                start_after_constraint.as_ref(),
4726                start_after_term.as_ref(),
4727                graph_name.as_ref(),
4728                &graph_filter_terms,
4729                graph_allow,
4730                iri_only_head,
4731                merge_default_graph,
4732                mode,
4733            )?
4734        } else {
4735            tokio::task::spawn_blocking(move || {
4736                service.scan_domain_counts(
4737                    permutation,
4738                    &constraints,
4739                    snapshot,
4740                    limit,
4741                    start_after_constraint.as_ref(),
4742                    start_after_term.as_ref(),
4743                    graph_name.as_ref(),
4744                    &graph_filter_terms,
4745                    graph_allow,
4746                    iri_only_head,
4747                    merge_default_graph,
4748                    mode,
4749                )
4750            })
4751            .await
4752            .map_err(|join| blocking_join_error("storage", join))??
4753        };
4754        Ok(Response::new(pb::DomainScanCountResponse {
4755            hits: hits
4756                .iter()
4757                .map(|hit| pb::DomainScanCountHit {
4758                    constraint: waratah_proto::term_to_bytes(&hit.constraint),
4759                    term: waratah_proto::term_to_bytes(&hit.term),
4760                    count: hit.count,
4761                })
4762                .collect(),
4763        }))
4764    }
4765
4766    async fn axis_head_scan(
4767        &self,
4768        request: Request<pb::AxisHeadScanRequest>,
4769    ) -> Result<Response<pb::AxisHeadScanResponse>, Status> {
4770        let request = request.into_inner();
4771        let permutation = permutation_from_proto(request.permutation())
4772            .ok_or(PartitionError::PermutationRequired("AxisHeadScan"))?;
4773        let graph_name = match request.graph_name {
4774            Some(bytes) if !bytes.is_empty() => {
4775                Some(term_from_bytes(&bytes).map_err(PartitionError::from)?)
4776            }
4777            Some(_) => Some(EncodedTerm::DefaultGraph),
4778            None => None,
4779        };
4780        let graph_filter_terms = request
4781            .graph_filter_terms
4782            .iter()
4783            .map(|bytes| term_from_bytes(bytes).map_err(PartitionError::from))
4784            .collect::<Result<Vec<_>, _>>()?;
4785        let start_after_term = if request.start_after_term.is_empty() {
4786            None
4787        } else {
4788            Some(term_from_bytes(&request.start_after_term).map_err(PartitionError::from)?)
4789        };
4790        let snapshot = SnapshotId(request.snapshot_id);
4791        let limit = request.limit;
4792        let graph_allow = request.graph_filter_allow;
4793        let iri_only_head = request.iri_only_head;
4794        let head_prefixes = request.head_prefixes;
4795        let service = self.clone();
4796        let terms = tokio::task::spawn_blocking(move || {
4797            service.scan_axis_head(
4798                permutation,
4799                snapshot,
4800                limit,
4801                start_after_term.as_ref(),
4802                graph_name.as_ref(),
4803                &graph_filter_terms,
4804                graph_allow,
4805                iri_only_head,
4806                &head_prefixes,
4807            )
4808        })
4809        .await
4810        .map_err(|join| blocking_join_error("storage", join))??;
4811        Ok(Response::new(pb::AxisHeadScanResponse {
4812            terms: terms.iter().map(waratah_proto::term_to_bytes).collect(),
4813        }))
4814    }
4815
4816    async fn axis_head_max_commit_ts(
4817        &self,
4818        request: Request<pb::AxisHeadMaxCommitTsRequest>,
4819    ) -> Result<Response<pb::AxisHeadMaxCommitTsResponse>, Status> {
4820        let request = request.into_inner();
4821        let permutation = permutation_from_proto(request.permutation())
4822            .ok_or(PartitionError::PermutationRequired("AxisHeadMaxCommitTs"))?;
4823        let head_prefixes = request.head_prefixes;
4824        let service = self.clone();
4825        let max_commit_ts = tokio::task::spawn_blocking(move || {
4826            service.axis_head_max_commit_ts(permutation, &head_prefixes)
4827        })
4828        .await
4829        .map_err(|join| blocking_join_error("storage", join))??;
4830        Ok(Response::new(pb::AxisHeadMaxCommitTsResponse {
4831            max_commit_ts,
4832        }))
4833    }
4834
4835    async fn axis_head_scan_counts(
4836        &self,
4837        request: Request<pb::AxisHeadScanCountsRequest>,
4838    ) -> Result<Response<pb::AxisHeadScanCountsResponse>, Status> {
4839        let request = request.into_inner();
4840        let mode = request.mode();
4841        let permutation = permutation_from_proto(request.permutation())
4842            .ok_or(PartitionError::PermutationRequired("AxisHeadScanCounts"))?;
4843        let graph_name = match request.graph_name {
4844            Some(bytes) if !bytes.is_empty() => {
4845                Some(term_from_bytes(&bytes).map_err(PartitionError::from)?)
4846            }
4847            Some(_) => Some(EncodedTerm::DefaultGraph),
4848            None => None,
4849        };
4850        let graph_filter_terms = request
4851            .graph_filter_terms
4852            .iter()
4853            .map(|bytes| term_from_bytes(bytes).map_err(PartitionError::from))
4854            .collect::<Result<Vec<_>, _>>()?;
4855        let start_after_term = if request.start_after_term.is_empty() {
4856            None
4857        } else {
4858            Some(term_from_bytes(&request.start_after_term).map_err(PartitionError::from)?)
4859        };
4860        let snapshot = SnapshotId(request.snapshot_id);
4861        let limit = request.limit;
4862        let graph_allow = request.graph_filter_allow;
4863        let iri_only_head = request.iri_only_head;
4864        let service = self.clone();
4865        let owned = [
4866            IndexPermutation::Spog,
4867            IndexPermutation::Psog,
4868            IndexPermutation::Opsg,
4869            IndexPermutation::Tsg,
4870        ];
4871        // Validate the permutation before the blocking task so the error
4872        // surfaces as the mapped gRPC status.
4873        service.require_owned_permutation("AxisHeadScanCounts", permutation, &owned)?;
4874        match mode {
4875            pb::AxisHeadCountMode::Total => {
4876                let total = tokio::task::spawn_blocking(move || {
4877                    service.count_axis_heads(
4878                        permutation,
4879                        snapshot,
4880                        graph_name.as_ref(),
4881                        &graph_filter_terms,
4882                        graph_allow,
4883                        iri_only_head,
4884                    )
4885                })
4886                .await
4887                .map_err(|join| blocking_join_error("storage", join))??;
4888                Ok(Response::new(pb::AxisHeadScanCountsResponse {
4889                    total,
4890                    hits: Vec::new(),
4891                }))
4892            }
4893            pb::AxisHeadCountMode::PerHead => {
4894                let hits = tokio::task::spawn_blocking(move || {
4895                    service.scan_axis_head_counts(
4896                        permutation,
4897                        snapshot,
4898                        limit,
4899                        start_after_term.as_ref(),
4900                        graph_name.as_ref(),
4901                        &graph_filter_terms,
4902                        graph_allow,
4903                        iri_only_head,
4904                    )
4905                })
4906                .await
4907                .map_err(|join| blocking_join_error("storage", join))??;
4908                Ok(Response::new(pb::AxisHeadScanCountsResponse {
4909                    total: 0,
4910                    hits: hits
4911                        .iter()
4912                        .map(|hit| pb::AxisHeadCountHit {
4913                            term: waratah_proto::term_to_bytes(&hit.term),
4914                            count: hit.count,
4915                        })
4916                        .collect(),
4917                }))
4918            }
4919        }
4920    }
4921
4922    async fn put_geo_index(
4923        &self,
4924        request: Request<pb::PutGeoIndexRequest>,
4925    ) -> Result<Response<pb::PutGeoIndexResponse>, Status> {
4926        let request = request.into_inner();
4927        let puts = request
4928            .puts
4929            .iter()
4930            .map(|put| {
4931                Ok(GeoIndexPut {
4932                    cell_id: put.s2_cell_id,
4933                    term: put.term.clone(),
4934                    commit_ts: waratah_storage::CommitTs(put.commit_ts),
4935                    op: waratah_proto::op_from_proto(
4936                        pb::StorageOp::try_from(put.op).unwrap_or(pb::StorageOp::Unspecified),
4937                    )
4938                    .map_err(PartitionError::from)?,
4939                    visibility: waratah_storage::VisibilityLabel(put.visibility),
4940                    envelope: match &put.crs84_envelope {
4941                        Some(bytes) if bytes.len() == 16 => {
4942                            Some(GeoEnvelope::decode(bytes).map_err(PartitionError::from)?)
4943                        }
4944                        // Only the exact 16-byte payload counts as an envelope
4945                        // (proto3 bytes cannot distinguish absent from empty).
4946                        _ => None,
4947                    },
4948                })
4949            })
4950            .collect::<Result<Vec<_>, PartitionError>>()?;
4951        let service = self.clone();
4952        let applied = tokio::task::spawn_blocking(move || service.apply_geo(&puts))
4953            .await
4954            .map_err(|join| blocking_join_error("storage", join))??;
4955        Ok(Response::new(pb::PutGeoIndexResponse { applied }))
4956    }
4957
4958    async fn delete_geo_term(
4959        &self,
4960        request: Request<pb::DeleteGeoTermRequest>,
4961    ) -> Result<Response<pb::DeleteGeoTermResponse>, Status> {
4962        let term = request.into_inner().term;
4963        let service = self.clone();
4964        let deleted = tokio::task::spawn_blocking(move || service.delete_geo_term(&term))
4965            .await
4966            .map_err(|join| blocking_join_error("storage", join))??;
4967        Ok(Response::new(pb::DeleteGeoTermResponse { deleted }))
4968    }
4969
4970    async fn geo_candidate_scan(
4971        &self,
4972        request: Request<pb::GeoCandidateScanRequest>,
4973    ) -> Result<Response<Self::GeoCandidateScanStream>, Status> {
4974        let request = request.into_inner();
4975        let intervals = request
4976            .intervals
4977            .iter()
4978            .map(|interval| GeoCellInterval {
4979                min_cell_id: interval.min_cell_id,
4980                max_cell_id: interval.max_cell_id,
4981            })
4982            .collect::<Vec<_>>();
4983        let query_envelope = request
4984            .query_envelope
4985            .as_ref()
4986            .filter(|bytes| bytes.len() == 16)
4987            .map(|bytes| GeoEnvelope::decode(bytes))
4988            .transpose()
4989            .map_err(PartitionError::from)?;
4990        let snapshot = SnapshotId(request.snapshot_id);
4991        let stream = self.geo_candidate_frames(intervals, snapshot, query_envelope, request.limit);
4992        Ok(Response::new(stream))
4993    }
4994
4995    async fn put_temporal_index(
4996        &self,
4997        request: Request<pb::PutTemporalIndexRequest>,
4998    ) -> Result<Response<pb::PutTemporalIndexResponse>, Status> {
4999        let request = request.into_inner();
5000        let puts = request
5001            .puts
5002            .iter()
5003            .map(|put| {
5004                if put.node_key.len() != 16 {
5005                    return Err(PartitionError::from(
5006                        waratah_storage::StorageError::Corrupt(format!(
5007                            "temporal node key must be 16 bytes, got {}",
5008                            put.node_key.len()
5009                        )),
5010                    ));
5011                }
5012                if put.begin.len() != 16 || put.end.len() != 16 {
5013                    return Err(PartitionError::from(
5014                        waratah_storage::StorageError::Corrupt(
5015                            "temporal exact pair must be 16 + 16 bytes".to_owned(),
5016                        ),
5017                    ));
5018                }
5019                Ok(TemporalIndexPut {
5020                    node_key: u128::from_be_bytes(put.node_key.as_slice().try_into().unwrap()),
5021                    term: put.term.clone(),
5022                    commit_ts: waratah_storage::CommitTs(put.commit_ts),
5023                    op: waratah_proto::op_from_proto(
5024                        pb::StorageOp::try_from(put.op).unwrap_or(pb::StorageOp::Unspecified),
5025                    )
5026                    .map_err(PartitionError::from)?,
5027                    visibility: waratah_storage::VisibilityLabel(put.visibility),
5028                    begin: i128::from_be_bytes(put.begin.as_slice().try_into().unwrap()),
5029                    end: i128::from_be_bytes(put.end.as_slice().try_into().unwrap()),
5030                })
5031            })
5032            .collect::<Result<Vec<_>, PartitionError>>()?;
5033        let service = self.clone();
5034        let applied = tokio::task::spawn_blocking(move || service.apply_temporal(&puts))
5035            .await
5036            .map_err(|join| blocking_join_error("storage", join))??;
5037        Ok(Response::new(pb::PutTemporalIndexResponse { applied }))
5038    }
5039
5040    async fn temporal_candidate_scan(
5041        &self,
5042        request: Request<pb::TemporalCandidateScanRequest>,
5043    ) -> Result<Response<Self::TemporalCandidateScanStream>, Status> {
5044        let request = request.into_inner();
5045        let intervals = request
5046            .intervals
5047            .iter()
5048            .map(|bytes| TemporalCellInterval::decode(bytes))
5049            .collect::<Result<Vec<_>, _>>()
5050            .map_err(PartitionError::from)?;
5051        let predicate =
5052            TemporalQueryPredicate::decode(&request.predicate).map_err(PartitionError::from)?;
5053        let snapshot = SnapshotId(request.snapshot_id);
5054        let stream = self.temporal_candidate_frames(intervals, snapshot, predicate, request.limit);
5055        Ok(Response::new(stream))
5056    }
5057
5058    async fn rebuild_temporal_index(
5059        &self,
5060        request: Request<pb::RebuildTemporalIndexRequest>,
5061    ) -> Result<Response<pb::RebuildTemporalIndexResponse>, Status> {
5062        let request = request.into_inner();
5063        let config = DyadicCovererConfig {
5064            min_level: request.min_level.min(127) as u8,
5065            max_level: request.max_level.min(128) as u8,
5066            max_nodes: request.max_nodes.max(1) as usize,
5067        };
5068        let service = self.clone();
5069        let started = tokio::task::spawn_blocking(move || service.rebuild_temporal_index(config))
5070            .await
5071            .map_err(|join| blocking_join_error("storage", join))??;
5072        Ok(Response::new(pb::RebuildTemporalIndexResponse {
5073            started,
5074            already_in_progress: !started,
5075        }))
5076    }
5077
5078    async fn rebuild_geo_index(
5079        &self,
5080        _request: Request<pb::RebuildGeoIndexRequest>,
5081    ) -> Result<Response<pb::RebuildGeoIndexResponse>, Status> {
5082        let service = self.clone();
5083        let upgrade_ts = tokio::task::spawn_blocking(move || service.begin_geo_rebuild())
5084            .await
5085            .map_err(|join| blocking_join_error("storage", join))??;
5086        let started = upgrade_ts.is_some();
5087        Ok(Response::new(pb::RebuildGeoIndexResponse {
5088            started,
5089            already_in_progress: !started,
5090            upgrade_ts: upgrade_ts.unwrap_or(0),
5091        }))
5092    }
5093
5094    async fn renew_geo_rebuild_lease(
5095        &self,
5096        _request: Request<pb::RenewGeoRebuildLeaseRequest>,
5097    ) -> Result<Response<pb::RenewGeoRebuildLeaseResponse>, Status> {
5098        let service = self.clone();
5099        tokio::task::spawn_blocking(move || service.renew_geo_rebuild_lease())
5100            .await
5101            .map_err(|join| blocking_join_error("storage", join))??;
5102        Ok(Response::new(pb::RenewGeoRebuildLeaseResponse {}))
5103    }
5104
5105    async fn finish_geo_index_rebuild(
5106        &self,
5107        _request: Request<pb::FinishGeoIndexRebuildRequest>,
5108    ) -> Result<Response<pb::FinishGeoIndexRebuildResponse>, Status> {
5109        let service = self.clone();
5110        let epoch = tokio::task::spawn_blocking(move || service.finish_geo_rebuild())
5111            .await
5112            .map_err(|join| blocking_join_error("storage", join))??;
5113        Ok(Response::new(pb::FinishGeoIndexRebuildResponse { epoch }))
5114    }
5115
5116    async fn put_text_index(
5117        &self,
5118        request: Request<pb::PutTextIndexRequest>,
5119    ) -> Result<Response<pb::PutTextIndexResponse>, Status> {
5120        let request = request.into_inner();
5121        let docs = request
5122            .docs
5123            .iter()
5124            .map(waratah_proto::text_index_doc_from_proto)
5125            .collect::<Vec<_>>();
5126        let service = self.clone();
5127        let applied = tokio::task::spawn_blocking(move || service.apply_text(&docs))
5128            .await
5129            .map_err(|join| blocking_join_error("storage", join))??;
5130        Ok(Response::new(pb::PutTextIndexResponse { applied }))
5131    }
5132
5133    async fn text_candidate_scan(
5134        &self,
5135        request: Request<pb::TextCandidateScanRequest>,
5136    ) -> Result<Response<Self::TextCandidateScanStream>, Status> {
5137        let request = request.into_inner();
5138        let mode = match pb::TextCandidateMode::try_from(request.mode) {
5139            Ok(pb::TextCandidateMode::Fts) => waratah_text_index::TextCandidateMode::Fts,
5140            Ok(pb::TextCandidateMode::Prefix) => waratah_text_index::TextCandidateMode::Prefix,
5141            Ok(pb::TextCandidateMode::Suffix) => waratah_text_index::TextCandidateMode::Suffix,
5142            _ => {
5143                return Err(Status::invalid_argument(
5144                    "TextCandidateScan requires an explicit mode",
5145                ));
5146            }
5147        };
5148        let search = waratah_text_index::TextSearchRequest {
5149            mode,
5150            query: request.query,
5151            language: request.language,
5152            limit: request.limit,
5153        };
5154        let snapshot = SnapshotId(request.snapshot_id);
5155        let stream = self.text_candidate_frames(search, snapshot);
5156        Ok(Response::new(stream))
5157    }
5158
5159    async fn text_subject_scan(
5160        &self,
5161        request: Request<pb::TextSubjectScanRequest>,
5162    ) -> Result<Response<Self::TextSubjectScanStream>, Status> {
5163        let request = request.into_inner();
5164        let mode = match pb::TextCandidateMode::try_from(request.mode) {
5165            Ok(pb::TextCandidateMode::Fts) => waratah_text_index::TextCandidateMode::Fts,
5166            Ok(pb::TextCandidateMode::Prefix) => waratah_text_index::TextCandidateMode::Prefix,
5167            Ok(pb::TextCandidateMode::Suffix) => waratah_text_index::TextCandidateMode::Suffix,
5168            _ => {
5169                return Err(Status::invalid_argument(
5170                    "TextSubjectScan requires an explicit mode",
5171                ));
5172            }
5173        };
5174        let predicates = request
5175            .predicates
5176            .iter()
5177            .map(|bytes| term_from_bytes(bytes).map_err(PartitionError::from))
5178            .collect::<Result<Vec<EncodedTerm>, _>>()?;
5179        let graph_filter_terms = request
5180            .graph_filter_terms
5181            .iter()
5182            .map(|bytes| term_from_bytes(bytes).map_err(PartitionError::from))
5183            .collect::<Result<Vec<EncodedTerm>, _>>()?;
5184        let graph_name = request
5185            .graph_name
5186            .as_deref()
5187            .map(term_from_bytes)
5188            .transpose()
5189            .map_err(PartitionError::from)?;
5190        let subject_request = waratah_storage::text_index::TextSubjectRequest {
5191            mode,
5192            query: request.query,
5193            language: request.language,
5194            limit: request.limit,
5195            predicates,
5196            graph_name,
5197            graph_filter_terms,
5198            graph_filter_allow: request.graph_filter_allow,
5199            merge_default_graph: request.merge_default_graph,
5200            return_graph: request.return_graph,
5201            subject_equals_graph: request.subject_equals_graph,
5202        };
5203        let snapshot = SnapshotId(request.snapshot_id);
5204        let stream = self.text_subject_frames(subject_request, snapshot);
5205        Ok(Response::new(stream))
5206    }
5207
5208    async fn rebuild_text_index(
5209        &self,
5210        request: Request<pb::RebuildTextIndexRequest>,
5211    ) -> Result<Response<pb::RebuildTextIndexResponse>, Status> {
5212        let request = request.into_inner();
5213        let options = waratah_text_index::TextIndexOptions::new(
5214            request.analyzer,
5215            request.seed_chars as usize,
5216            request.fingerprint,
5217        );
5218        let wipe = request.wipe;
5219        let service = self.clone();
5220        let token = tokio::task::spawn_blocking(move || service.begin_text_rebuild(&options, wipe))
5221            .await
5222            .map_err(|join| blocking_join_error("storage", join))??;
5223        Ok(Response::new(pb::RebuildTextIndexResponse {
5224            started: token.is_some(),
5225            already_in_progress: token.is_none(),
5226            lease_token: token.unwrap_or(0),
5227        }))
5228    }
5229
5230    async fn renew_text_rebuild_lease(
5231        &self,
5232        request: Request<pb::RenewTextRebuildLeaseRequest>,
5233    ) -> Result<Response<pb::RenewTextRebuildLeaseResponse>, Status> {
5234        let token = request.into_inner().lease_token;
5235        let service = self.clone();
5236        tokio::task::spawn_blocking(move || service.renew_text_rebuild_lease(token))
5237            .await
5238            .map_err(|join| blocking_join_error("storage", join))??;
5239        Ok(Response::new(pb::RenewTextRebuildLeaseResponse {}))
5240    }
5241
5242    async fn finish_text_index_rebuild(
5243        &self,
5244        request: Request<pb::FinishTextIndexRebuildRequest>,
5245    ) -> Result<Response<pb::FinishTextIndexRebuildResponse>, Status> {
5246        let request = request.into_inner();
5247        let (token, stamp) = (request.lease_token, request.stamp);
5248        let service = self.clone();
5249        let epoch = tokio::task::spawn_blocking(move || service.finish_text_rebuild(token, stamp))
5250            .await
5251            .map_err(|join| blocking_join_error("storage", join))??;
5252        Ok(Response::new(pb::FinishTextIndexRebuildResponse { epoch }))
5253    }
5254
5255    async fn flush_memtables(
5256        &self,
5257        _request: Request<pb::FlushMemtablesRequest>,
5258    ) -> Result<Response<pb::FlushMemtablesResponse>, Status> {
5259        let service = self.clone();
5260        tokio::task::spawn_blocking(move || PartitionService::flush_memtables(&service))
5261            .await
5262            .map_err(|join| blocking_join_error("storage", join))??;
5263        Ok(Response::new(pb::FlushMemtablesResponse {}))
5264    }
5265
5266    async fn compact_range(
5267        &self,
5268        _request: Request<pb::CompactRangeRequest>,
5269    ) -> Result<Response<pb::CompactRangeResponse>, Status> {
5270        let service = self.clone();
5271        tokio::task::spawn_blocking(move || PartitionService::compact_range(&service))
5272            .await
5273            .map_err(|join| blocking_join_error("storage", join))??;
5274        Ok(Response::new(pb::CompactRangeResponse {}))
5275    }
5276
5277    async fn get_stats_profile(
5278        &self,
5279        _request: Request<pb::GetStatsProfileRequest>,
5280    ) -> Result<Response<pb::GetStatsProfileResponse>, Status> {
5281        let service = self.clone();
5282        let profile = tokio::task::spawn_blocking(move || service.shard_profile())
5283            .await
5284            .map_err(|join| blocking_join_error("storage", join))??;
5285        // Transport boundary only: the CORE trim empties geo/temporal (they
5286        // travel in their own frames — `get_geo_histogram` /
5287        // `get_temporal_histogram`) and ranks the per-predicate HLL pairs
5288        // until the serialized blob fits the wire budget. The in-memory
5289        // shard profile and every SST blob stay full-fidelity for merging.
5290        Ok(Response::new(pb::GetStatsProfileResponse {
5291            profile: to_bytes(&profile.capped_for_wire()),
5292        }))
5293    }
5294
5295    async fn get_geo_histogram(
5296        &self,
5297        request: Request<pb::GetGeoHistogramRequest>,
5298    ) -> Result<Response<pb::GetGeoHistogramResponse>, Status> {
5299        let section = request.into_inner().section();
5300        let service = self.clone();
5301        let profile = tokio::task::spawn_blocking(move || service.shard_profile())
5302            .await
5303            .map_err(|join| blocking_join_error("storage", join))??;
5304        // ONE canonical trim (`capped_geo_histogram_for_wire`), then slice
5305        // the requested frame out of it: a frame is a subset-populated
5306        // section (the unrequested maps EMPTY) — a valid merge input on its
5307        // own. Each refresh recomputes `shard_profile`; refreshes are rare
5308        // (startup / post-ingest), so the extra merged() walks are fine.
5309        let trimmed = profile.capped_geo_histogram_for_wire();
5310        let frame = match section {
5311            pb::GeoHistogramSection::Unspecified => {
5312                // Zero is the proto3 default, so an omitted (or unknown)
5313                // `section` lands here — reject rather than silently serve
5314                // the fine frame.
5315                return Err(Status::invalid_argument(
5316                    "section must be FINE or COARSE; UNSPECIFIED names no frame",
5317                ));
5318            }
5319            pb::GeoHistogramSection::Fine => waratah_stats::GeoCellHistogram {
5320                coarse: std::collections::BTreeMap::new(),
5321                ..trimmed
5322            },
5323            pb::GeoHistogramSection::Coarse => waratah_stats::GeoCellHistogram {
5324                fine: std::collections::BTreeMap::new(),
5325                remainder: std::collections::BTreeMap::new(),
5326                ..trimmed
5327            },
5328        };
5329        let mut histogram = Vec::new();
5330        frame.encode_body(&mut histogram);
5331        Ok(Response::new(pb::GetGeoHistogramResponse { histogram }))
5332    }
5333
5334    async fn get_temporal_histogram(
5335        &self,
5336        _request: Request<pb::GetTemporalHistogramRequest>,
5337    ) -> Result<Response<pb::GetTemporalHistogramResponse>, Status> {
5338        let service = self.clone();
5339        let profile = tokio::task::spawn_blocking(move || service.shard_profile())
5340            .await
5341            .map_err(|join| blocking_join_error("storage", join))??;
5342        // Bounded by construction (dyadic level range); no trim machinery —
5343        // an over-budget frame would be a bug, not a trimming decision.
5344        let mut histogram = Vec::new();
5345        profile.temporal_histogram.encode_body(&mut histogram);
5346        Ok(Response::new(pb::GetTemporalHistogramResponse {
5347            histogram,
5348        }))
5349    }
5350
5351    async fn get_text_seed_sketch(
5352        &self,
5353        _request: Request<pb::GetTextSeedSketchRequest>,
5354    ) -> Result<Response<pb::GetTextSeedSketchResponse>, Status> {
5355        // The sketch is COLLECTED on the O partition only, but the RPC must
5356        // answer from EVERY axis: `refresh_stats` fetches one frame per axis
5357        // of `PartitionAxis::ALL`, and an error here aborts the whole
5358        // refresh — startup (`waratah start`) and every post-ingest refresh
5359        // with it. Non-O axes have no text index, so
5360        // `text_seed_sketch_frame()` yields None and this serves EMPTY
5361        // bytes — the same valid-frame convention as the geo/temporal
5362        // frames. Compute decodes only non-empty frames, so an absent
5363        // sketch stays the merge identity, and the rollup's O-first
5364        // preference (`rollup_cluster`) picks the collected sketch.
5365        let service = self.clone();
5366        // Blocking sidecar read (may be a cold page), then the canonical
5367        // wire trim — the partition trims at serve, exactly like the geo
5368        // histogram's frame (`capped_geo_histogram_for_wire`).
5369        let sketch = tokio::task::spawn_blocking(move || service.text_seed_sketch_frame())
5370            .await
5371            .map_err(|join| blocking_join_error("storage", join))?;
5372        let mut sketch_bytes = Vec::new();
5373        if let Some(sketch) = sketch {
5374            sketch.encode_body(&mut sketch_bytes);
5375        }
5376        Ok(Response::new(pb::GetTextSeedSketchResponse {
5377            sketch: sketch_bytes,
5378        }))
5379    }
5380
5381    async fn list_named_graphs(
5382        &self,
5383        request: Request<pb::ListNamedGraphsRequest>,
5384    ) -> Result<Response<pb::ListNamedGraphsResponse>, Status> {
5385        let snapshot = SnapshotId(request.into_inner().snapshot_id);
5386        let service = self.clone();
5387        let graphs = tokio::task::spawn_blocking(move || service.list_named_graphs(snapshot))
5388            .await
5389            .map_err(|join| blocking_join_error("storage", join))??;
5390        Ok(Response::new(pb::ListNamedGraphsResponse {
5391            graph_names: graphs.iter().map(waratah_proto::term_to_bytes).collect(),
5392        }))
5393    }
5394
5395    async fn add_named_graph(
5396        &self,
5397        request: Request<pb::AddNamedGraphRequest>,
5398    ) -> Result<Response<pb::AddNamedGraphResponse>, Status> {
5399        let request = request.into_inner();
5400        let graph = term_from_bytes(&request.graph_name).map_err(PartitionError::from)?;
5401        let commit_ts = waratah_storage::CommitTs(request.commit_ts);
5402        let service = self.clone();
5403        tokio::task::spawn_blocking(move || service.add_named_graph(&graph, commit_ts))
5404            .await
5405            .map_err(|join| blocking_join_error("storage", join))??;
5406        Ok(Response::new(pb::AddNamedGraphResponse {}))
5407    }
5408
5409    async fn health(
5410        &self,
5411        _request: Request<pb::HealthRequest>,
5412    ) -> Result<Response<pb::HealthResponse>, Status> {
5413        let (warm_ready, warm_pending) = match &self.warm {
5414            Some(warm) => {
5415                // Past the max wait a stuck walk warns (stderr, once) and
5416                // stops gating readiness — serving cold beats serving never.
5417                let stuck = warm.stuck_warning().is_some();
5418                (warm.is_done() || stuck, warm.pending())
5419            }
5420            None => (true, Vec::new()),
5421        };
5422        let (cache_capacity_bytes, cache_usage_bytes) =
5423            self.storage.block_cache_bytes().unwrap_or((0, 0));
5424        Ok(Response::new(pb::HealthResponse {
5425            serving: true,
5426            detail: String::new(),
5427            warm_ready,
5428            warm_pending,
5429            cache_capacity_bytes,
5430            cache_usage_bytes,
5431        }))
5432    }
5433
5434    async fn describe(
5435        &self,
5436        _request: Request<pb::HexastoreDescribeRequest>,
5437    ) -> Result<Response<pb::HexastoreDescribeResponse>, Status> {
5438        let service = self.clone();
5439        let response = tokio::task::spawn_blocking(move || service.describe())
5440            .await
5441            .map_err(|join| blocking_join_error("storage", join))?;
5442        Ok(Response::new(response))
5443    }
5444}
5445
5446fn proto_backend(kind: StorageBackendKind) -> pb::StorageBackend {
5447    match kind {
5448        StorageBackendKind::Memory => pb::StorageBackend::Memory,
5449        StorageBackendKind::RocksDb => pb::StorageBackend::Rocksdb,
5450    }
5451}
5452
5453fn proto_lsm(metrics: Option<LsmMetrics>) -> pb::LsmMetrics {
5454    match metrics {
5455        None => pb::LsmMetrics::default(),
5456        Some(m) => pb::LsmMetrics {
5457            estimate_live_data_bytes: m.estimate_live_data_bytes,
5458            estimate_num_keys: m.estimate_num_keys,
5459            total_sst_bytes: m.total_sst_bytes,
5460            memtable_bytes: m.memtable_bytes,
5461            num_running_compactions: m.num_running_compactions,
5462            num_running_flushes: m.num_running_flushes,
5463            open_total_puts: None,
5464            compaction_event_count: None,
5465            named_graph_count: None,
5466            block_cache_capacity_bytes: m.block_cache_capacity_bytes,
5467            block_cache_usage_bytes: m.block_cache_usage_bytes,
5468        },
5469    }
5470}
5471
5472/// Bind a listener for the partition process.
5473///
5474/// Pass port `0` to let the OS choose; the returned address carries the
5475/// resolved port so tests and `waratah_bin` can publish it in a routing table.
5476pub fn bind(addr: SocketAddr) -> Result<(TcpIncoming, SocketAddr), PartitionError> {
5477    // NODELAY on accepted connections: `Server::builder().tcp_nodelay(..)`
5478    // is IGNORED when serving via `serve_with_incoming` (this crate), so the
5479    // flag must ride on the incoming. Without it a large response written
5480    // after the headers sits in the Nagle buffer for the client's ~40ms
5481    // delayed-ACK window.
5482    let incoming = TcpIncoming::bind(addr)?.with_nodelay(Some(true));
5483    let local = incoming.local_addr()?;
5484    Ok((incoming, local))
5485}
5486
5487/// Serve the `Hexastore` service on `incoming` until the future is dropped.
5488pub async fn serve(service: PartitionService, incoming: TcpIncoming) -> Result<(), PartitionError> {
5489    Server::builder()
5490        // NOTE: `.tcp_nodelay(true)` here is ignored for `serve_with_incoming`
5491        // — the operative flag is on the `TcpIncoming` (see [`bind`]).
5492        .add_service(
5493            HexastoreServer::new(service)
5494                .max_decoding_message_size(GRPC_MAX_MESSAGE_SIZE)
5495                .max_encoding_message_size(GRPC_MAX_MESSAGE_SIZE),
5496        )
5497        .serve_with_incoming(incoming)
5498        .await?;
5499    Ok(())
5500}
5501
5502#[cfg(test)]
5503mod tests {
5504    use super::*;
5505    use waratah_proto::{OMIT_NONE, quad_from_proto_omitting};
5506    use waratah_storage::{CommitTs, GraphName, StorageError, StrHash, encode_index_key};
5507
5508    #[test]
5509    fn scan_dispatch_gate_uses_exact_stats() {
5510        // Boundary assertions assume the default threshold; an env override
5511        // (0 disables, or a custom count) changes every gate decision, so
5512        // skip rather than misreport under an override.
5513        if scan_dispatch_row_threshold() != SCAN_DISPATCH_ROW_THRESHOLD {
5514            return;
5515        }
5516        let nn = |iri: &str| EncodedTerm::from(&waratah_storage::NamedNode::new(iri).unwrap());
5517        let pattern_for =
5518            |pred: Option<EncodedTerm>, obj: Option<EncodedTerm>| EncodedTriplePattern {
5519                subject: None,
5520                predicate: pred,
5521                object: obj,
5522                graph_name: None,
5523            };
5524        let service = PartitionService::new(Storage::memory(PartitionAxis::P));
5525
5526        // Empty store: no statistical basis — the gate never opens.
5527        let small = pattern_for(Some(nn("http://ex/small")), Some(nn("http://ex/any")));
5528        assert!(!service.scan_runs_on_caller(Some(IndexPermutation::Posg), &small, None, &[]));
5529
5530        // Observed predicates: at/below the threshold runs on the caller,
5531        // above dispatches. 1024 is the default (env override is
5532        // process-global, so the boundary is asserted via the const).
5533        {
5534            let mut stats = service.stats.lock().unwrap();
5535            let open = stats.open_profile_mut();
5536            open.total_puts = 3;
5537            open.predicate_counts
5538                .insert(StrHash::new("http://ex/small"), 5);
5539            open.predicate_counts.insert(
5540                StrHash::new("http://ex/big"),
5541                SCAN_DISPATCH_ROW_THRESHOLD + 1,
5542            );
5543        }
5544        assert!(service.scan_runs_on_caller(Some(IndexPermutation::Posg), &small, None, &[]));
5545        let big = pattern_for(Some(nn("http://ex/big")), Some(nn("http://ex/any")));
5546        assert!(!service.scan_runs_on_caller(Some(IndexPermutation::Posg), &big, None, &[]));
5547
5548        // Permutation-aware slice rule: a predicate-only pattern walks the
5549        // whole leading predicate block, where delete churn can pile
5550        // version keys beyond the net-row estimate — dispatch even when
5551        // the predicate's count is far below the threshold. The slot
5552        // AFTER the leading segment must be bound (object on POSG,
5553        // subject on PSOG), or covered by a non-empty sub-threshold
5554        // allow-list on that slot.
5555        let pred_only = pattern_for(Some(nn("http://ex/small")), None);
5556        assert!(!service.scan_runs_on_caller(Some(IndexPermutation::Posg), &pred_only, None, &[]));
5557        // A bound SUBJECT narrows PSOG's second segment but not POSG's
5558        // (S is third in the POSG key — the walk still covers every
5559        // object of the predicate).
5560        let with_subject = EncodedTriplePattern {
5561            subject: Some(nn("http://ex/s")),
5562            ..pred_only.clone()
5563        };
5564        assert!(service.scan_runs_on_caller(
5565            Some(IndexPermutation::Psog),
5566            &with_subject,
5567            None,
5568            &[]
5569        ));
5570        assert!(!service.scan_runs_on_caller(
5571            Some(IndexPermutation::Posg),
5572            &with_subject,
5573            None,
5574            &[]
5575        ));
5576        // A Subject-slot allow-list qualifies on PSOG (each term seeks
5577        // its own tight prefix) but not on POSG.
5578        assert!(service.scan_runs_on_caller(
5579            Some(IndexPermutation::Psog),
5580            &pred_only,
5581            Some(PatternSlot::Subject),
5582            &[nn("http://ex/s")],
5583        ));
5584        assert!(!service.scan_runs_on_caller(
5585            Some(IndexPermutation::Posg),
5586            &pred_only,
5587            Some(PatternSlot::Subject),
5588            &[nn("http://ex/s")],
5589        ));
5590        // A bound graph_name never qualifies: no index leads with G, so
5591        // it filters rows without shrinking the walked prefix.
5592        let with_graph = EncodedTriplePattern {
5593            graph_name: Some(nn("http://ex/g")),
5594            ..pred_only.clone()
5595        };
5596        assert!(!service.scan_runs_on_caller(Some(IndexPermutation::Posg), &with_graph, None, &[]));
5597        // No explicit permutation: the partition picks the index, so the
5598        // gate cannot know the walked range — dispatch.
5599        assert!(!service.scan_runs_on_caller(None, &small, None, &[]));
5600
5601        // rdf:type + bound class (TSG: the class is the leading segment,
5602        // P is implicit and absent from the key): exact class counts
5603        // decide, including the observed-zero for an absent class in a
5604        // non-empty map. An open type scan (no bound class) walks the
5605        // whole type index and dispatches.
5606        {
5607            let mut stats = service.stats.lock().unwrap();
5608            let open = stats.open_profile_mut();
5609            open.class_counts
5610                .insert(StrHash::new("http://ex/Person"), 7);
5611        }
5612        let type_person = pattern_for(Some(RDF_TYPE.clone()), Some(nn("http://ex/Person")));
5613        assert!(service.scan_runs_on_caller(Some(IndexPermutation::Tsg), &type_person, None, &[]));
5614        let type_ghost = pattern_for(Some(RDF_TYPE.clone()), Some(nn("http://ex/Ghost")));
5615        assert!(service.scan_runs_on_caller(Some(IndexPermutation::Tsg), &type_ghost, None, &[]));
5616        let type_open = pattern_for(Some(RDF_TYPE.clone()), None);
5617        assert!(!service.scan_runs_on_caller(Some(IndexPermutation::Tsg), &type_open, None, &[]));
5618
5619        // Unbound predicate: no phase-1 basis — always dispatch.
5620        let unbound = pattern_for(None, None);
5621        assert!(!service.scan_runs_on_caller(Some(IndexPermutation::Posg), &unbound, None, &[]));
5622    }
5623
5624    #[tokio::test]
5625    async fn scan_stream_frames_caller_thread_matches_dispatched_rows() {
5626        use tokio_stream::StreamExt as _;
5627        // The caller-thread branch is chosen by the default threshold; an env
5628        // override changes gate decisions, so skip under one.
5629        if scan_dispatch_row_threshold() != SCAN_DISPATCH_ROW_THRESHOLD {
5630            return;
5631        }
5632        let service = PartitionService::memory(PartitionAxis::P);
5633        let nn = |iri: &str| waratah_storage::NamedNode::new(iri).unwrap();
5634        let mut versions = Vec::new();
5635        let mut push = |subject: &str, predicate: &str, object: &str| {
5636            let quad = waratah_storage::Quad::new(
5637                nn(subject),
5638                nn(predicate),
5639                nn(object),
5640                waratah_storage::GraphName::DefaultGraph,
5641            );
5642            versions.push(QuadVersion {
5643                quad: waratah_storage::encode_quad(&quad).unwrap(),
5644                commit_ts: waratah_storage::CommitTs(1),
5645                op: waratah_storage::StorageOp::Put,
5646                visibility: waratah_storage::VisibilityLabel::default(),
5647            });
5648        };
5649        for i in 1..=3 {
5650            push(
5651                &format!("http://ex/s{i}"),
5652                "http://ex/p",
5653                &format!("http://ex/o{i}"),
5654            );
5655        }
5656        for i in 1..=2 {
5657            push(
5658                &format!("http://ex/t{i}"),
5659                "http://ex/q",
5660                &format!("http://ex/u{i}"),
5661            );
5662        }
5663        service
5664            .apply_versions(Some(PartitionAxis::P), &versions)
5665            .unwrap();
5666
5667        let drain = |pattern: EncodedTriplePattern,
5668                     filter_slot: Option<PatternSlot>,
5669                     filter_terms: Vec<EncodedTerm>,
5670                     limit: u64| {
5671            let service = service.clone();
5672            async move {
5673                let stream = service.scan_pattern_stream_frames(
5674                    Some(IndexPermutation::Posg),
5675                    pattern,
5676                    SnapshotId::latest(),
5677                    limit,
5678                    filter_slot,
5679                    filter_terms,
5680                    None,
5681                    vec![],
5682                    false,
5683                    false,
5684                    IriOnlyMask::NONE,
5685                    vec![],
5686                    waratah_proto::OMIT_NONE,
5687                    true,
5688                );
5689                let mut rows = Vec::new();
5690                for frame in stream.collect::<Vec<_>>().await {
5691                    for quad in frame.unwrap().quads {
5692                        rows.push(waratah_proto::quad_from_proto(&quad).unwrap());
5693                    }
5694                }
5695                rows
5696            }
5697        };
5698
5699        // Bound predicate with 3 observed rows (≤ threshold) plus the
5700        // slice rule satisfied by an Object allow-list (non-empty, under
5701        // the threshold): the gate opens, the whole drain runs on the
5702        // calling worker, and the collected frames must carry exactly
5703        // the walk's rows.
5704        let pattern_p = EncodedTriplePattern {
5705            subject: None,
5706            predicate: Some(EncodedTerm::from(&nn("http://ex/p"))),
5707            object: None,
5708            graph_name: None,
5709        };
5710        let list = vec![
5711            EncodedTerm::from(&nn("http://ex/o1")),
5712            EncodedTerm::from(&nn("http://ex/o2")),
5713        ];
5714        // The caller-thread branch must actually be the one exercised.
5715        assert!(service.scan_runs_on_caller(
5716            Some(IndexPermutation::Posg),
5717            &pattern_p,
5718            Some(PatternSlot::Object),
5719            &list,
5720        ));
5721        let rows = drain(
5722            pattern_p.clone(),
5723            Some(PatternSlot::Object),
5724            list.clone(),
5725            0,
5726        )
5727        .await;
5728        let (direct, _) = service
5729            .scan_filtered(
5730                Some(IndexPermutation::Posg),
5731                &pattern_p,
5732                SnapshotId::latest(),
5733                0,
5734                Some(PatternSlot::Object),
5735                &list,
5736                None,
5737                &[],
5738                false,
5739                false,
5740                IriOnlyMask::NONE,
5741                true,
5742            )
5743            .unwrap();
5744        assert_eq!(rows.len(), 2);
5745        assert_eq!(rows, direct, "caller-thread drain rows must equal the walk");
5746
5747        // limit on the caller-thread branch bounds the drain.
5748        assert_eq!(
5749            drain(
5750                pattern_p.clone(),
5751                Some(PatternSlot::Object),
5752                list.clone(),
5753                2
5754            )
5755            .await
5756            .len(),
5757            2
5758        );
5759
5760        // Unbound predicate: no phase-1 estimate basis, so the gate
5761        // dispatches — the blocking-pool branch must return the same rows
5762        // as the direct walk. Same permutation on both sides (row order
5763        // is index-defined: POSG is object-major, PSOG subject-major).
5764        let pattern_any = EncodedTriplePattern::default();
5765        let rows_any = drain(pattern_any.clone(), None, Vec::new(), 0).await;
5766        let (direct_any, _) = service
5767            .scan_filtered(
5768                Some(IndexPermutation::Posg),
5769                &pattern_any,
5770                SnapshotId::latest(),
5771                0,
5772                None,
5773                &[],
5774                None,
5775                &[],
5776                false,
5777                false,
5778                IriOnlyMask::NONE,
5779                true,
5780            )
5781            .unwrap();
5782        assert_eq!(rows_any.len(), 5);
5783        assert_eq!(
5784            rows_any, direct_any,
5785            "dispatched drain rows must equal the walk"
5786        );
5787    }
5788
5789    #[tokio::test]
5790    async fn count_pattern_caller_thread_matches_dispatched_count() {
5791        // Boundary assertions assume the default threshold; an env override
5792        // (0 disables, or a custom count) changes every gate decision, so
5793        // skip rather than misreport under an override.
5794        if scan_dispatch_row_threshold() != SCAN_DISPATCH_ROW_THRESHOLD {
5795            return;
5796        }
5797        let service = PartitionService::memory(PartitionAxis::P);
5798        let nn = |iri: &str| waratah_storage::NamedNode::new(iri).unwrap();
5799        let mut versions = Vec::new();
5800        let mut push = |subject: &str, predicate: &str, object: &str| {
5801            let quad = waratah_storage::Quad::new(
5802                nn(subject),
5803                nn(predicate),
5804                nn(object),
5805                waratah_storage::GraphName::DefaultGraph,
5806            );
5807            versions.push(QuadVersion {
5808                quad: waratah_storage::encode_quad(&quad).unwrap(),
5809                commit_ts: waratah_storage::CommitTs(1),
5810                op: waratah_storage::StorageOp::Put,
5811                visibility: waratah_storage::VisibilityLabel::default(),
5812            });
5813        };
5814        for i in 1..=3 {
5815            push(
5816                &format!("http://ex/s{i}"),
5817                "http://ex/p",
5818                &format!("http://ex/o{i}"),
5819            );
5820        }
5821        push("http://ex/t1", "http://ex/q", "http://ex/u1");
5822        service
5823            .apply_versions(Some(PartitionAxis::P), &versions)
5824            .unwrap();
5825
5826        let pattern_p = EncodedTriplePattern {
5827            subject: None,
5828            predicate: Some(EncodedTerm::from(&nn("http://ex/p"))),
5829            object: None,
5830            graph_name: None,
5831        };
5832        // The gated branch must actually be the one exercised: assert the
5833        // gate opens for this pattern (POSG with a bound object satisfies
5834        // the slice rule) so the handler comparison below
5835        // cannot silently degrade to dispatched-vs-dispatched. A
5836        // predicate-only count violates the slice rule and dispatches.
5837        let pattern_o = EncodedTriplePattern {
5838            object: Some(EncodedTerm::from(&nn("http://ex/o1"))),
5839            ..pattern_p.clone()
5840        };
5841        assert!(service.scan_runs_on_caller(Some(IndexPermutation::Posg), &pattern_o, None, &[]));
5842        assert!(!service.scan_runs_on_caller(Some(IndexPermutation::Posg), &pattern_p, None, &[]));
5843        let response = service
5844            .count_pattern(Request::new(waratah_proto::scan_request_filtered(
5845                &pattern_o,
5846                SnapshotId::latest(),
5847                0,
5848                Some(IndexPermutation::Posg),
5849                None,
5850                &[],
5851            )))
5852            .await
5853            .unwrap()
5854            .into_inner();
5855        assert_eq!(response.count, 1);
5856        assert_eq!(
5857            service
5858                .count_filtered(
5859                    Some(IndexPermutation::Posg),
5860                    &pattern_o,
5861                    SnapshotId::latest(),
5862                    0,
5863                    None,
5864                    &[],
5865                    &[],
5866                    false,
5867                    false,
5868                )
5869                .unwrap(),
5870            1
5871        );
5872
5873        // Unbound predicate: no estimate basis, so the handler takes the
5874        // dispatched branch — same count either way.
5875        let pattern_any = EncodedTriplePattern::default();
5876        assert!(!service.scan_runs_on_caller(
5877            Some(IndexPermutation::Posg),
5878            &pattern_any,
5879            None,
5880            &[]
5881        ));
5882        let response = service
5883            .count_pattern(Request::new(waratah_proto::scan_request(
5884                &pattern_any,
5885                SnapshotId::latest(),
5886                0,
5887                None,
5888            )))
5889            .await
5890            .unwrap()
5891            .into_inner();
5892        assert_eq!(response.count, 4);
5893    }
5894
5895    #[test]
5896    fn domain_scan_gate_predicate_keyed_only() {
5897        // Gate decisions assume the default threshold; an env override
5898        // changes every decision, so skip under one.
5899        if scan_dispatch_row_threshold() != SCAN_DISPATCH_ROW_THRESHOLD {
5900            return;
5901        }
5902        let nn = |iri: &str| EncodedTerm::from(&waratah_storage::NamedNode::new(iri).unwrap());
5903        let service = PartitionService::new(Storage::memory(PartitionAxis::P));
5904
5905        // Empty store: no statistical basis — the gate never opens.
5906        let small = [nn("http://ex/p")];
5907        assert!(!service.domain_scan_runs_on_caller(IndexPermutation::Posg, &small));
5908
5909        // Real puts with two predicates: basis present, summed counts
5910        // decide. A "big" predicate is seeded directly above the
5911        // threshold.
5912        let mut versions = Vec::new();
5913        for i in 1..=3 {
5914            let quad = waratah_storage::Quad::new(
5915                waratah_storage::NamedNode::new(format!("http://ex/s{i}")).unwrap(),
5916                waratah_storage::NamedNode::new("http://ex/p").unwrap(),
5917                waratah_storage::NamedNode::new(format!("http://ex/o{i}")).unwrap(),
5918                waratah_storage::GraphName::DefaultGraph,
5919            );
5920            versions.push(QuadVersion {
5921                quad: waratah_storage::encode_quad(&quad).unwrap(),
5922                commit_ts: waratah_storage::CommitTs(1),
5923                op: waratah_storage::StorageOp::Put,
5924                visibility: waratah_storage::VisibilityLabel::default(),
5925            });
5926        }
5927        service
5928            .apply_versions(Some(PartitionAxis::P), &versions)
5929            .unwrap();
5930        {
5931            let mut stats = service.stats.lock().unwrap();
5932            stats.open_profile_mut().predicate_counts.insert(
5933                waratah_storage::StrHash::new("http://ex/big"),
5934                SCAN_DISPATCH_ROW_THRESHOLD + 1,
5935            );
5936        }
5937
5938        // Posg (PredicateDomain) and Psog (PredicateSubjects) share the
5939        // slot-0 predicate estimate: both walks are bounded by the same
5940        // exact per-predicate row count.
5941        for permutation in [IndexPermutation::Posg, IndexPermutation::Psog] {
5942            assert!(service.domain_scan_runs_on_caller(permutation, &small));
5943            let big = [nn("http://ex/big")];
5944            assert!(!service.domain_scan_runs_on_caller(permutation, &big));
5945            // A non-named constraint has no exact-map key — dispatch.
5946            let literal = [EncodedTerm::from(&waratah_storage::Literal::from("lit"))];
5947            assert!(!service.domain_scan_runs_on_caller(permutation, &literal));
5948        }
5949        // Subject-, object- and type-keyed permutations have no per-term
5950        // maps (and no domain-scan kind maps to TSG).
5951        for permutation in [
5952            IndexPermutation::Spog,
5953            IndexPermutation::Sopg,
5954            IndexPermutation::Opsg,
5955            IndexPermutation::Tsg,
5956        ] {
5957            assert!(!service.domain_scan_runs_on_caller(permutation, &small));
5958        }
5959    }
5960
5961    #[tokio::test]
5962    async fn scan_pattern_applies_slot_comparisons_before_the_page() {
5963        let service = PartitionService::memory(PartitionAxis::P);
5964        let predicate = waratah_storage::NamedNode::new("http://ex/year").unwrap();
5965        let mut versions = Vec::new();
5966        for (index, year) in [1966i64, 1967, 1971, 1972].into_iter().enumerate() {
5967            let quad = waratah_storage::Quad::new(
5968                waratah_storage::NamedNode::new(format!("http://ex/s{index}")).unwrap(),
5969                predicate.clone(),
5970                waratah_storage::Literal::from(year),
5971                waratah_storage::GraphName::DefaultGraph,
5972            );
5973            versions.push(QuadVersion {
5974                quad: waratah_storage::encode_quad(&quad).unwrap(),
5975                commit_ts: waratah_storage::CommitTs(1),
5976                op: waratah_storage::StorageOp::Put,
5977                visibility: waratah_storage::VisibilityLabel::default(),
5978            });
5979        }
5980        service
5981            .apply_versions(Some(PartitionAxis::P), &versions)
5982            .unwrap();
5983
5984        let pattern = EncodedTriplePattern {
5985            subject: None,
5986            predicate: Some(EncodedTerm::from(&predicate)),
5987            object: None,
5988            graph_name: Some(EncodedTerm::DefaultGraph),
5989        };
5990        let comparisons = [SlotComparison {
5991            slot: QuadSlot::Object,
5992            op: waratah_storage::CompareOp::Ge,
5993            term: EncodedTerm::from(&waratah_storage::Literal::from(1967i64)),
5994        }];
5995        let request = waratah_proto::with_comparisons(
5996            waratah_proto::scan_request(
5997                &pattern,
5998                SnapshotId::latest(),
5999                0,
6000                Some(IndexPermutation::Posg),
6001            ),
6002            &comparisons,
6003        )
6004        .unwrap();
6005        let response = service
6006            .scan_pattern(Request::new(request))
6007            .await
6008            .unwrap()
6009            .into_inner();
6010        assert_eq!(response.quads.len(), 3, "1967..=1972");
6011        let expected = [1967i64, 1971, 1972]
6012            .map(|year| EncodedTerm::from(&waratah_storage::Literal::from(year)));
6013        for quad in &response.quads {
6014            let object = waratah_proto::term_from_bytes(&quad.object).unwrap();
6015            assert!(expected.contains(&object), "unexpected object {object:?}");
6016        }
6017
6018        // The streamed drain applies the same mask; the two transports must
6019        // agree row for row.
6020        use tokio_stream::StreamExt;
6021        let request = waratah_proto::with_comparisons(
6022            waratah_proto::scan_request(
6023                &pattern,
6024                SnapshotId::latest(),
6025                0,
6026                Some(IndexPermutation::Posg),
6027            ),
6028            &comparisons,
6029        )
6030        .unwrap();
6031        let stream = service
6032            .scan_pattern_stream(Request::new(request))
6033            .await
6034            .unwrap()
6035            .into_inner();
6036        let mut streamed = 0usize;
6037        for frame in stream.collect::<Vec<_>>().await {
6038            streamed += frame.unwrap().quads.len();
6039        }
6040        assert_eq!(streamed, 3, "the streamed drain applies the same mask");
6041
6042        // A half-filled comparison (empty term) is rejected as
6043        // INVALID_ARGUMENT, not silently read as "object = default graph".
6044        let mut malformed = waratah_proto::scan_request(
6045            &pattern,
6046            SnapshotId::latest(),
6047            0,
6048            Some(IndexPermutation::Posg),
6049        );
6050        malformed.comparisons = vec![pb::SlotComparison {
6051            slot: pb::PatternSlot::Object as i32,
6052            op: pb::CompareOp::Eq as i32,
6053            term: Vec::new(),
6054        }];
6055        let error = service
6056            .scan_pattern(Request::new(malformed))
6057            .await
6058            .expect_err("an empty comparison term must be rejected");
6059        assert_eq!(error.code(), tonic::Code::InvalidArgument);
6060
6061        // CountPattern rejects the field rather than silently disagreeing
6062        // with the same scan's rows.
6063        let mut count_request = waratah_proto::scan_request(
6064            &pattern,
6065            SnapshotId::latest(),
6066            0,
6067            Some(IndexPermutation::Posg),
6068        );
6069        count_request.comparisons = waratah_proto::slot_comparisons_to_proto(&comparisons).unwrap();
6070        let error = service
6071            .count_pattern(Request::new(count_request))
6072            .await
6073            .expect_err("CountPattern must reject slot comparisons");
6074        assert_eq!(error.code(), tonic::Code::InvalidArgument);
6075
6076        // Every row filtered by the mask is a terminal walk, not a full page
6077        // waiting for another request.
6078        let none = [SlotComparison {
6079            slot: QuadSlot::Object,
6080            op: waratah_storage::CompareOp::Gt,
6081            term: EncodedTerm::from(&waratah_storage::Literal::from(9_999i64)),
6082        }];
6083        let request = waratah_proto::with_verdict_wanted(
6084            waratah_proto::with_comparisons(
6085                waratah_proto::scan_request(
6086                    &pattern,
6087                    SnapshotId::latest(),
6088                    0,
6089                    Some(IndexPermutation::Posg),
6090                ),
6091                &none,
6092            )
6093            .unwrap(),
6094            true,
6095        );
6096        let response = service
6097            .scan_pattern(Request::new(request))
6098            .await
6099            .unwrap()
6100            .into_inner();
6101        assert!(response.quads.is_empty());
6102        assert_eq!(
6103            response.exhausted,
6104            Some(waratah_proto::scan_exhaustion_to_proto(ScanExhaustion::ExhaustedScan) as i32)
6105        );
6106    }
6107
6108    #[tokio::test]
6109    async fn domain_scan_caller_thread_matches_dispatched_hits() {
6110        // Same skip rule as the gate tests: an env override changes which
6111        // branch runs.
6112        if scan_dispatch_row_threshold() != SCAN_DISPATCH_ROW_THRESHOLD {
6113            return;
6114        }
6115        let nn = |iri: &str| EncodedTerm::from(&waratah_storage::NamedNode::new(iri).unwrap());
6116        let service = PartitionService::memory(PartitionAxis::P);
6117        let mut versions = Vec::new();
6118        for i in 1..=3 {
6119            let quad = waratah_storage::Quad::new(
6120                waratah_storage::NamedNode::new(format!("http://ex/s{i}")).unwrap(),
6121                waratah_storage::NamedNode::new("http://ex/p").unwrap(),
6122                waratah_storage::NamedNode::new(format!("http://ex/o{i}")).unwrap(),
6123                waratah_storage::GraphName::DefaultGraph,
6124            );
6125            versions.push(QuadVersion {
6126                quad: waratah_storage::encode_quad(&quad).unwrap(),
6127                commit_ts: waratah_storage::CommitTs(1),
6128                op: waratah_storage::StorageOp::Put,
6129                visibility: waratah_storage::VisibilityLabel::default(),
6130            });
6131        }
6132        service
6133            .apply_versions(Some(PartitionAxis::P), &versions)
6134            .unwrap();
6135
6136        let constraints = [nn("http://ex/p")];
6137        // Both predicate-leading kinds may run inline; each must return
6138        // exactly what the blocking walk would.
6139        for permutation in [IndexPermutation::Posg, IndexPermutation::Psog] {
6140            assert!(service.domain_scan_runs_on_caller(permutation, &constraints));
6141
6142            let request = pb::DomainScanRequest {
6143                constraints: constraints
6144                    .iter()
6145                    .map(waratah_proto::term_to_bytes)
6146                    .collect(),
6147                permutation: waratah_proto::permutation_to_proto(permutation) as i32,
6148                snapshot_id: SnapshotId::latest().0,
6149                limit: 0,
6150                ..pb::DomainScanRequest::default()
6151            };
6152            let response = service
6153                .domain_scan(Request::new(request))
6154                .await
6155                .unwrap()
6156                .into_inner();
6157            let got: Vec<(Vec<u8>, Vec<u8>)> = response
6158                .hits
6159                .iter()
6160                .map(|hit| (hit.constraint.clone(), hit.term.clone()))
6161                .collect();
6162            let direct = service
6163                .scan_domain(
6164                    permutation,
6165                    &constraints,
6166                    SnapshotId::latest(),
6167                    0,
6168                    None,
6169                    None,
6170                    None,
6171                    &[],
6172                    false,
6173                    false,
6174                )
6175                .unwrap();
6176            let want: Vec<(Vec<u8>, Vec<u8>)> = direct
6177                .iter()
6178                .map(|hit| {
6179                    (
6180                        waratah_proto::term_to_bytes(&hit.constraint),
6181                        waratah_proto::term_to_bytes(&hit.term),
6182                    )
6183                })
6184                .collect();
6185            assert_eq!(got.len(), 3);
6186            assert_eq!(got, want, "caller-thread domain hits must equal the walk");
6187        }
6188    }
6189
6190    #[tokio::test]
6191    async fn text_seed_sketch_serves_an_empty_frame_from_every_axis() {
6192        // Regression guard for the refresh-startup seam: `refresh_stats`
6193        // fetches one sketch frame per axis of `PartitionAxis::ALL`, so a
6194        // non-O axis answering UNIMPLEMENTED aborts the whole refresh —
6195        // `waratah start` (startup refresh) and every post-ingest refresh
6196        // with it. The RPC must answer everywhere; only O can carry a
6197        // collected sidecar, and a memory-backed store has none, so every
6198        // axis serves empty bytes here (compute decodes only non-empty
6199        // frames — an absent sketch stays the merge identity).
6200        for axis in [PartitionAxis::O, PartitionAxis::P, PartitionAxis::S] {
6201            let service = PartitionService::memory(axis);
6202            let response = service
6203                .get_text_seed_sketch(Request::new(pb::GetTextSeedSketchRequest::default()))
6204                .await
6205                .expect("every axis must answer the sketch RPC, never UNIMPLEMENTED")
6206                .into_inner();
6207            assert!(
6208                response.sketch.is_empty(),
6209                "no persisted sketch on {axis:?}: expected empty bytes"
6210            );
6211        }
6212    }
6213
6214    #[tokio::test]
6215    async fn health_reports_warm_readiness() {
6216        let warm = waratah_storage::WarmState::new(["axis-p"]);
6217        let service = PartitionService::memory(PartitionAxis::P).with_warm_state(warm.clone());
6218
6219        // Walk tracked but unfinished: serving, but not warm-ready. Memory
6220        // backend reports no block cache (zeros).
6221        let response = service
6222            .health(Request::new(pb::HealthRequest::default()))
6223            .await
6224            .unwrap()
6225            .into_inner();
6226        assert!(response.serving);
6227        assert!(!response.warm_ready);
6228        assert_eq!(response.warm_pending, vec!["axis-p".to_owned()]);
6229        assert_eq!(response.cache_capacity_bytes, 0);
6230        assert_eq!(response.cache_usage_bytes, 0);
6231
6232        // Walk completes: warm-ready, pending drained.
6233        warm.complete("axis-p");
6234        let response = service
6235            .health(Request::new(pb::HealthRequest::default()))
6236            .await
6237            .unwrap()
6238            .into_inner();
6239        assert!(response.warm_ready);
6240        assert!(response.warm_pending.is_empty());
6241    }
6242
6243    #[test]
6244    fn warm_block_cache_is_a_noop_on_memory() {
6245        let service = PartitionService::memory(PartitionAxis::S);
6246        let stats = service.warm_block_cache(0.5).unwrap();
6247        assert!(stats.is_noop());
6248    }
6249
6250    #[test]
6251    fn axis_mismatch_is_typed_error() {
6252        let service = PartitionService::memory(PartitionAxis::S);
6253        let error = service
6254            .apply_versions(Some(PartitionAxis::O), &[])
6255            .unwrap_err();
6256        assert!(matches!(
6257            error,
6258            PartitionError::AxisMismatch {
6259                requested: PartitionAxis::O,
6260                owned: PartitionAxis::S
6261            }
6262        ));
6263        assert_eq!(Status::from(error).code(), tonic::Code::FailedPrecondition);
6264    }
6265
6266    #[test]
6267    fn describe_omits_named_graph_count_on_p_and_o() {
6268        for axis in [PartitionAxis::P, PartitionAxis::O] {
6269            let metrics = PartitionService::memory(axis)
6270                .describe()
6271                .metrics
6272                .expect("memory still reports process counters");
6273            assert!(
6274                metrics.named_graph_count.is_none(),
6275                "axis {axis} should omit named_graph_count"
6276            );
6277        }
6278        let s = PartitionService::memory(PartitionAxis::S)
6279            .describe()
6280            .metrics
6281            .unwrap();
6282        assert_eq!(s.named_graph_count, Some(0));
6283    }
6284
6285    #[test]
6286    fn unspecified_axis_skips_the_ownership_check() {
6287        let service = PartitionService::memory(PartitionAxis::P);
6288        assert_eq!(service.apply_versions(None, &[]).unwrap(), 0);
6289        assert_eq!(
6290            service.apply_versions(Some(PartitionAxis::P), &[]).unwrap(),
6291            0
6292        );
6293    }
6294
6295    #[test]
6296    fn s_axis_process_rejects_o_axis_index() {
6297        let service = PartitionService::memory(PartitionAxis::S);
6298        let error = service
6299            .scan(
6300                Some(IndexPermutation::Tsg),
6301                &EncodedTriplePattern::default(),
6302                SnapshotId::default(),
6303                0,
6304            )
6305            .unwrap_err();
6306        assert!(matches!(
6307            error,
6308            PartitionError::Storage(StorageError::PermutationNotOwned {
6309                index: "tsg",
6310                axis: PartitionAxis::S
6311            })
6312        ));
6313        assert_eq!(Status::from(error).code(), tonic::Code::FailedPrecondition);
6314
6315        // Both axis-local indexes are served.
6316        for permutation in IndexPermutation::for_axis(PartitionAxis::S) {
6317            assert!(
6318                service
6319                    .scan(
6320                        Some(permutation),
6321                        &EncodedTriplePattern::default(),
6322                        SnapshotId::default(),
6323                        0,
6324                    )
6325                    .unwrap()
6326                    .is_empty()
6327            );
6328        }
6329    }
6330
6331    #[test]
6332    fn memory_flush_memtables_succeeds() {
6333        let service = PartitionService::memory(PartitionAxis::P);
6334        service.flush_memtables().unwrap();
6335    }
6336
6337    /// Pack one quad through a [`FramePacker`] and return its wire fields.
6338    fn packed_wire_quad(
6339        quad: &EncodedQuad,
6340        permutation: IndexPermutation,
6341        merge_default_graph: bool,
6342    ) -> pb::EncodedQuad {
6343        let mut key = encode_index_key(permutation, quad);
6344        key.extend_from_slice(&CommitTs(7).to_descending_be_bytes());
6345        let row = KeyRow::from_versioned_key(&key, permutation).unwrap();
6346        let mut packer = FramePacker::with_omitted(waratah_proto::OMIT_NONE);
6347        packer.push_row(&row, merge_default_graph, 0);
6348        let rdf_type_wire = Bytes::from(encode_term_bytes(&RDF_TYPE));
6349        packer
6350            .take_frame(merge_default_graph, &rdf_type_wire)
6351            .quads
6352            .remove(0)
6353    }
6354
6355    /// An omitted slot leaves the frame field empty, and reassembly from the
6356    /// request's own pattern restores the exact row — the wire contract the
6357    /// compute side depends on.
6358    #[test]
6359    fn frame_packer_omits_masked_slots_and_reassembles() {
6360        let s = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/s").unwrap());
6361        let p = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/p").unwrap());
6362        let o = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/o").unwrap());
6363        let quad = EncodedQuad::new(s.clone(), p.clone(), o.clone(), EncodedTerm::DefaultGraph);
6364        let mut key = encode_index_key(IndexPermutation::Spog, &quad);
6365        key.extend_from_slice(&CommitTs(7).to_descending_be_bytes());
6366        let row = KeyRow::from_versioned_key(&key, IndexPermutation::Spog).unwrap();
6367        let omitted = waratah_proto::OMIT_SUBJECT | waratah_proto::OMIT_PREDICATE;
6368        let mut packer = FramePacker::with_omitted(omitted);
6369        packer.push_row(&row, false, 0);
6370        let rdf_type_wire = Bytes::from(encode_term_bytes(&RDF_TYPE));
6371        let wire = packer.take_frame(false, &rdf_type_wire).quads.remove(0);
6372        assert!(wire.subject.is_empty(), "omitted subject carries no bytes");
6373        assert!(
6374            wire.predicate.is_empty(),
6375            "omitted predicate carries no bytes"
6376        );
6377        assert!(!wire.object.is_empty(), "an unmasked slot keeps its bytes");
6378        let pattern = EncodedTriplePattern {
6379            subject: Some(s),
6380            predicate: Some(p),
6381            object: None,
6382            graph_name: None,
6383        };
6384        let decoded = waratah_proto::quad_from_proto_omitting(&wire, &pattern, omitted).unwrap();
6385        assert_eq!(decoded.subject, quad.subject);
6386        assert_eq!(decoded.predicate, quad.predicate);
6387        assert_eq!(decoded.object, quad.object);
6388        assert_eq!(decoded.graph_name, quad.graph_name);
6389    }
6390
6391    #[test]
6392    fn frame_packer_slices_match_term_encodings() {
6393        let s = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/s").unwrap());
6394        let p = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/p").unwrap());
6395        // A 33-byte object (typed literal) beside 17-byte S/P/G terms.
6396        let o = EncodedTerm::from(&waratah_storage::Literal::new_typed_literal(
6397            "12345",
6398            waratah_storage::NamedNode::new("http://www.w3.org/2001/XMLSchema#integer").unwrap(),
6399        ));
6400        let g = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/g").unwrap());
6401        let quad = EncodedQuad::new(s.clone(), p.clone(), o.clone(), g.clone());
6402
6403        let wire = packed_wire_quad(&quad, IndexPermutation::Spog, false);
6404        assert_eq!(wire.subject.as_ref(), encode_term_bytes(&s).as_slice());
6405        assert_eq!(wire.predicate.as_ref(), encode_term_bytes(&p).as_slice());
6406        assert_eq!(wire.object.as_ref(), encode_term_bytes(&o).as_slice());
6407        assert_eq!(wire.graph_name.as_ref(), encode_term_bytes(&g).as_slice());
6408
6409        // Merge-default rewrite: the G field collapses to empty while S/P/O
6410        // keep their bytes.
6411        let wire = packed_wire_quad(&quad, IndexPermutation::Spog, true);
6412        assert!(wire.graph_name.is_empty());
6413        assert_eq!(wire.subject.as_ref(), encode_term_bytes(&s).as_slice());
6414        assert_eq!(wire.predicate.as_ref(), encode_term_bytes(&p).as_slice());
6415        assert_eq!(wire.object.as_ref(), encode_term_bytes(&o).as_slice());
6416    }
6417
6418    #[test]
6419    fn frame_packer_default_graph_and_tsg_rows() {
6420        let s = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/s").unwrap());
6421        let o = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/o").unwrap());
6422
6423        // The default graph's zero-length segment stays an empty wire field.
6424        let default_quad = EncodedQuad::new(
6425            s.clone(),
6426            RDF_TYPE.clone(),
6427            o.clone(),
6428            EncodedTerm::DefaultGraph,
6429        );
6430        let wire = packed_wire_quad(&default_quad, IndexPermutation::Spog, false);
6431        assert!(wire.graph_name.is_empty());
6432        assert_eq!(wire.subject.as_ref(), encode_term_bytes(&s).as_slice());
6433        assert_eq!(wire.object.as_ref(), encode_term_bytes(&o).as_slice());
6434
6435        // Tsg keys omit the predicate; the wire field is the constant
6436        // `rdf:type` encoding even though the key order is O‖S‖G.
6437        let g = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/g").unwrap());
6438        let type_quad = EncodedQuad::new(s.clone(), RDF_TYPE.clone(), o.clone(), g.clone());
6439        let wire = packed_wire_quad(&type_quad, IndexPermutation::Tsg, false);
6440        assert_eq!(
6441            wire.predicate.as_ref(),
6442            encode_term_bytes(&RDF_TYPE).as_slice()
6443        );
6444        assert_eq!(wire.subject.as_ref(), encode_term_bytes(&s).as_slice());
6445        assert_eq!(wire.object.as_ref(), encode_term_bytes(&o).as_slice());
6446        assert_eq!(wire.graph_name.as_ref(), encode_term_bytes(&g).as_slice());
6447    }
6448
6449    #[test]
6450    fn frame_packer_keeps_row_order_across_the_buffer() {
6451        let s = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/s").unwrap());
6452        let o1 = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/o1").unwrap());
6453        let o2 = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/o2").unwrap());
6454        let g = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/g").unwrap());
6455        let rdf_type_wire = Bytes::from(encode_term_bytes(&RDF_TYPE));
6456
6457        // Three rows of mixed permutations share one framebuffer.
6458        let rows = [
6459            (
6460                EncodedQuad::new(s.clone(), RDF_TYPE.clone(), o1.clone(), g.clone()),
6461                IndexPermutation::Spog,
6462                false,
6463            ),
6464            (
6465                EncodedQuad::new(s.clone(), RDF_TYPE.clone(), o2.clone(), g.clone()),
6466                IndexPermutation::Tsg,
6467                false,
6468            ),
6469            (
6470                EncodedQuad::new(
6471                    s.clone(),
6472                    RDF_TYPE.clone(),
6473                    o1.clone(),
6474                    EncodedTerm::DefaultGraph,
6475                ),
6476                IndexPermutation::Spog,
6477                true,
6478            ),
6479        ];
6480        let mut packer = FramePacker::with_omitted(waratah_proto::OMIT_NONE);
6481        for (quad, permutation, merge_default_graph) in &rows {
6482            let mut key = encode_index_key(*permutation, quad);
6483            key.extend_from_slice(&CommitTs(7).to_descending_be_bytes());
6484            let row = KeyRow::from_versioned_key(&key, *permutation).unwrap();
6485            packer.push_row(&row, *merge_default_graph, 0);
6486        }
6487        assert_eq!(packer.len(), 3);
6488
6489        let quads = packer.take_frame(false, &rdf_type_wire).quads;
6490        assert_eq!(quads.len(), 3);
6491        let expected = [(&o1, Some(&g)), (&o2, Some(&g)), (&o1, None)];
6492        for (wire, (object, graph)) in quads.iter().zip(expected) {
6493            assert_eq!(wire.subject.as_ref(), encode_term_bytes(&s).as_slice());
6494            assert_eq!(
6495                wire.predicate.as_ref(),
6496                encode_term_bytes(&RDF_TYPE).as_slice()
6497            );
6498            assert_eq!(wire.object.as_ref(), encode_term_bytes(object).as_slice());
6499            match graph {
6500                Some(graph) => {
6501                    assert_eq!(
6502                        wire.graph_name.as_ref(),
6503                        encode_term_bytes(graph).as_slice()
6504                    )
6505                }
6506                None => assert!(wire.graph_name.is_empty()),
6507            }
6508        }
6509    }
6510
6511    #[test]
6512    fn inserts_update_shard_profile() {
6513        let service = PartitionService::memory(PartitionAxis::O);
6514        let quad = waratah_storage::Quad::new(
6515            waratah_storage::NamedNode::new("http://ex/s").unwrap(),
6516            waratah_storage::NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
6517                .unwrap(),
6518            waratah_storage::NamedNode::new("http://ex/Person").unwrap(),
6519            waratah_storage::GraphName::DefaultGraph,
6520        );
6521        let encoded = waratah_storage::encode_quad(&quad).unwrap();
6522        service
6523            .apply_versions(
6524                Some(PartitionAxis::O),
6525                &[QuadVersion {
6526                    quad: encoded,
6527                    commit_ts: waratah_storage::CommitTs(1),
6528                    op: waratah_storage::StorageOp::Put,
6529                    visibility: waratah_storage::VisibilityLabel::default(),
6530                }],
6531            )
6532            .unwrap();
6533        let profile = service.shard_profile().unwrap();
6534        assert_eq!(profile.total_puts, 1);
6535        assert_eq!(
6536            profile
6537                .class_counts
6538                .get(&waratah_storage::StrHash::new("http://ex/Person")),
6539            Some(&1)
6540        );
6541    }
6542
6543    #[test]
6544    fn apply_versions_batch_updates_shard_profile() {
6545        let service = PartitionService::memory(PartitionAxis::S);
6546        let versions: Vec<QuadVersion> = ["http://ex/s1", "http://ex/s2", "http://ex/s3"]
6547            .into_iter()
6548            .map(|subject| {
6549                let quad = waratah_storage::Quad::new(
6550                    waratah_storage::NamedNode::new(subject).unwrap(),
6551                    waratah_storage::NamedNode::new("http://ex/p").unwrap(),
6552                    waratah_storage::Literal::from("o"),
6553                    waratah_storage::GraphName::DefaultGraph,
6554                );
6555                QuadVersion {
6556                    quad: waratah_storage::encode_quad(&quad).unwrap(),
6557                    commit_ts: waratah_storage::CommitTs(1),
6558                    op: waratah_storage::StorageOp::Put,
6559                    visibility: waratah_storage::VisibilityLabel::default(),
6560                }
6561            })
6562            .collect();
6563        assert_eq!(
6564            service
6565                .apply_versions(Some(PartitionAxis::S), &versions)
6566                .unwrap(),
6567            3
6568        );
6569        assert_eq!(service.shard_profile().unwrap().total_puts, 3);
6570        let rows = service
6571            .scan(
6572                None,
6573                &EncodedTriplePattern::default(),
6574                SnapshotId::latest(),
6575                0,
6576            )
6577            .unwrap();
6578        assert_eq!(rows.len(), 3);
6579    }
6580
6581    #[tokio::test]
6582    async fn concurrent_reads_overlap_and_a_write_never_deadlocks() {
6583        let service = PartitionService::memory(PartitionAxis::S);
6584        let versions: Vec<QuadVersion> = (0..32)
6585            .map(|i| {
6586                let quad = waratah_storage::Quad::new(
6587                    waratah_storage::NamedNode::new(format!("http://ex/s{i}")).unwrap(),
6588                    waratah_storage::NamedNode::new("http://ex/p").unwrap(),
6589                    waratah_storage::Literal::from("o"),
6590                    waratah_storage::GraphName::DefaultGraph,
6591                );
6592                QuadVersion {
6593                    quad: waratah_storage::encode_quad(&quad).unwrap(),
6594                    commit_ts: waratah_storage::CommitTs(1),
6595                    op: waratah_storage::StorageOp::Put,
6596                    visibility: waratah_storage::VisibilityLabel::default(),
6597                }
6598            })
6599            .collect();
6600        service
6601            .apply_versions(Some(PartitionAxis::S), &versions)
6602            .unwrap();
6603
6604        // Under the storage RwLock every reader holds a read guard for its
6605        // whole scan, so eight concurrent scans overlap instead of
6606        // serializing, and a writer committing mid-commit completes without
6607        // stalling the readers. The assertion is simply: all of it succeeds
6608        // and every reader still sees its full MVCC snapshot.
6609        let mut readers = Vec::new();
6610        for _ in 0..8 {
6611            let service = service.clone();
6612            readers.push(tokio::task::spawn_blocking(move || {
6613                service
6614                    .scan(
6615                        None,
6616                        &EncodedTriplePattern::default(),
6617                        SnapshotId::latest(),
6618                        0,
6619                    )
6620                    .unwrap()
6621                    .len()
6622            }));
6623        }
6624        let writer = {
6625            let service = service.clone();
6626            let quad = waratah_storage::Quad::new(
6627                waratah_storage::NamedNode::new("http://ex/late").unwrap(),
6628                waratah_storage::NamedNode::new("http://ex/p").unwrap(),
6629                waratah_storage::Literal::from("o"),
6630                waratah_storage::GraphName::DefaultGraph,
6631            );
6632            let extra = QuadVersion {
6633                quad: waratah_storage::encode_quad(&quad).unwrap(),
6634                commit_ts: waratah_storage::CommitTs(2),
6635                op: waratah_storage::StorageOp::Put,
6636                visibility: waratah_storage::VisibilityLabel::default(),
6637            };
6638            tokio::task::spawn_blocking(move || {
6639                service
6640                    .apply_versions(Some(PartitionAxis::S), &[extra])
6641                    .unwrap()
6642            })
6643        };
6644        for handle in readers {
6645            // `SnapshotId::latest()` is sampled per scan: a reader that starts
6646            // after the writer committed sees 33 rows, an earlier one 32.
6647            // Either way the scan is a consistent snapshot.
6648            let seen = handle.await.unwrap();
6649            assert!(
6650                (32..=33).contains(&seen),
6651                "reader saw a partial snapshot: {seen} rows"
6652            );
6653        }
6654        assert_eq!(writer.await.unwrap(), 1);
6655    }
6656
6657    /// Helper used only for tests below.
6658    fn encode_named_spo(subject: &str, predicate: &str, object: &str) -> EncodedQuad {
6659        waratah_storage::encode_quad(&waratah_storage::Quad::new(
6660            waratah_storage::NamedNode::new(subject).unwrap(),
6661            waratah_storage::NamedNode::new(predicate).unwrap(),
6662            waratah_storage::NamedNode::new(object).unwrap(),
6663            waratah_storage::GraphName::DefaultGraph,
6664        ))
6665        .unwrap()
6666    }
6667
6668    /// Helper used only for tests below.
6669    fn put_named_spo(
6670        service: &PartitionService,
6671        axis: PartitionAxis,
6672        subject: &str,
6673        predicate: &str,
6674        object: &str,
6675    ) {
6676        service
6677            .apply_versions(
6678                Some(axis),
6679                &[QuadVersion {
6680                    quad: encode_named_spo(subject, predicate, object),
6681                    commit_ts: waratah_storage::CommitTs(1),
6682                    op: waratah_storage::StorageOp::Put,
6683                    visibility: waratah_storage::VisibilityLabel::default(),
6684                }],
6685            )
6686            .unwrap();
6687    }
6688
6689    /// Helper used only for tests below.
6690    fn knows_pattern() -> EncodedTriplePattern {
6691        EncodedTriplePattern {
6692            subject: None,
6693            predicate: Some(
6694                encode_named_spo("http://ex/alice", "http://ex/knows", "http://ex/bob").predicate,
6695            ),
6696            object: None,
6697            graph_name: Some(EncodedTerm::DefaultGraph),
6698        }
6699    }
6700
6701    /// `verdict_wanted` selects the sink discipline at the page limit. The
6702    /// load-bearing case is the EXACT boundary — a page limit equal to the
6703    /// walk's whole remaining rows: a consumer that declared it will issue
6704    /// another request after a full page (`true`) gets the walk's own
6705    /// terminal verdict (the walk runs past the full page to its exit, so
6706    /// the exact-boundary terminal verdict is a fact, not an inference);
6707    /// a consumer that did not (`false`) gets the historical behavior —
6708    /// the walk stops AT the limit'th row and the response carries no
6709    /// verdict at all (the field is left unset, even for a short page's
6710    /// freely-known completed walk), so an ASK / one-shot slice never
6711    /// pays a look-ahead scan past its last delivered row. Verified on both
6712    /// roads whose verdicts fold honestly: the plain prefix walk and the
6713    /// two-term multi-seek allow-list.
6714    #[test]
6715    fn scan_verdict_wanted_selects_sink_discipline() {
6716        let service = PartitionService::memory(PartitionAxis::S);
6717        for object in ["http://ex/o1", "http://ex/o2", "http://ex/o3"] {
6718            put_named_spo(
6719                &service,
6720                PartitionAxis::S,
6721                "http://ex/alice",
6722                "http://ex/knows",
6723                object,
6724            );
6725        }
6726        let pattern = knows_pattern();
6727
6728        // Plain road: exactly 3 rows under the bound predicate; the page
6729        // limit equals that total (the exact boundary).
6730        for (verdict_wanted, expected) in [
6731            (true, ScanExhaustion::ExhaustedScan),
6732            (false, ScanExhaustion::Limited),
6733        ] {
6734            let (rows, verdict) = service
6735                .scan_filtered(
6736                    None,
6737                    &pattern,
6738                    SnapshotId::latest(),
6739                    3,
6740                    None,
6741                    &[],
6742                    None,
6743                    &[],
6744                    false,
6745                    false,
6746                    IriOnlyMask::NONE,
6747                    verdict_wanted,
6748                )
6749                .unwrap();
6750            assert_eq!(rows.len(), 3);
6751            assert_eq!(
6752                verdict, expected,
6753                "plain road at the exact boundary, verdict_wanted={verdict_wanted}"
6754            );
6755        }
6756
6757        // Multi-seek road: a second subject gives the allow-list two terms
6758        // (alice's 3 rows + bob's 1 = 4); the page limit equals that total.
6759        put_named_spo(
6760            &service,
6761            PartitionAxis::S,
6762            "http://ex/bob",
6763            "http://ex/knows",
6764            "http://ex/o9",
6765        );
6766        let alice = encode_named_spo("http://ex/alice", "http://ex/knows", "http://ex/o1").subject;
6767        let bob = encode_named_spo("http://ex/bob", "http://ex/knows", "http://ex/o9").subject;
6768        let terms = [alice, bob];
6769        for (verdict_wanted, expected) in [
6770            (true, ScanExhaustion::ExhaustedFilterTerms),
6771            (false, ScanExhaustion::Limited),
6772        ] {
6773            let (rows, verdict) = service
6774                .scan_filtered(
6775                    None,
6776                    &pattern,
6777                    SnapshotId::latest(),
6778                    4,
6779                    Some(PatternSlot::Subject),
6780                    &terms,
6781                    None,
6782                    &[],
6783                    false,
6784                    false,
6785                    IriOnlyMask::NONE,
6786                    verdict_wanted,
6787                )
6788                .unwrap();
6789            assert_eq!(rows.len(), 4);
6790            assert_eq!(
6791                verdict, expected,
6792                "multi-seek road at the exact boundary, verdict_wanted={verdict_wanted}"
6793            );
6794        }
6795    }
6796
6797    /// Path hops page filtered scans with `SCAN_BATCH`. If `start_after` were
6798    /// dropped, a page that fills `limit` would repeat forever.
6799    #[test]
6800    fn filtered_scan_start_after_advances_within_one_term() {
6801        let service = PartitionService::memory(PartitionAxis::S);
6802        for object in ["http://ex/o1", "http://ex/o2", "http://ex/o3"] {
6803            put_named_spo(
6804                &service,
6805                PartitionAxis::S,
6806                "http://ex/alice",
6807                "http://ex/knows",
6808                object,
6809            );
6810        }
6811        let alice = encode_named_spo("http://ex/alice", "http://ex/knows", "http://ex/o1").subject;
6812        let pattern = knows_pattern();
6813        let terms = [alice];
6814
6815        let (page1, verdict1) = service
6816            .scan_filtered(
6817                None,
6818                &pattern,
6819                SnapshotId::latest(),
6820                2,
6821                Some(PatternSlot::Subject),
6822                &terms,
6823                None,
6824                &[],
6825                false,
6826                false,
6827                IriOnlyMask::NONE,
6828                true,
6829            )
6830            .unwrap();
6831        assert_eq!(page1.len(), 2);
6832        // Limit 2 cuts INSIDE alice's three-row subtree: the per-term
6833        // walk stopped at the limit and its `Limited` verdict propagates
6834        // through the per-term verdict fold — the outer verdict honestly
6835        // says the page stopped at a demand boundary with more matching
6836        // rows behind it, never a false terminal on a full page.
6837        assert_eq!(verdict1, ScanExhaustion::Limited);
6838
6839        let (page2, verdict2) = service
6840            .scan_filtered(
6841                None,
6842                &pattern,
6843                SnapshotId::latest(),
6844                2,
6845                Some(PatternSlot::Subject),
6846                &terms,
6847                page1.last(),
6848                &[],
6849                false,
6850                false,
6851                IriOnlyMask::NONE,
6852                true,
6853            )
6854            .unwrap();
6855        assert_eq!(page2.len(), 1);
6856        assert_ne!(
6857            page2[0], page1[0],
6858            "filtered start_after must not re-emit the first page"
6859        );
6860        assert_ne!(page2[0], page1[1]);
6861        // The short page's terminal verdict — the distinction the old
6862        // short-page inference could not make: the FILTER TERM LIST is
6863        // what ended (not the scan's range).
6864        assert_eq!(verdict2, ScanExhaustion::ExhaustedFilterTerms);
6865
6866        let (page3, _) = service
6867            .scan_filtered(
6868                None,
6869                &pattern,
6870                SnapshotId::latest(),
6871                2,
6872                Some(PatternSlot::Subject),
6873                &terms,
6874                page2.last(),
6875                &[],
6876                false,
6877                false,
6878                IriOnlyMask::NONE,
6879                true,
6880            )
6881            .unwrap();
6882        assert!(page3.is_empty());
6883    }
6884
6885    #[test]
6886    fn filtered_scan_start_after_skips_completed_filter_terms() {
6887        let service = PartitionService::memory(PartitionAxis::S);
6888        for object in ["http://ex/o1", "http://ex/o2", "http://ex/o3"] {
6889            put_named_spo(
6890                &service,
6891                PartitionAxis::S,
6892                "http://ex/alice",
6893                "http://ex/knows",
6894                object,
6895            );
6896        }
6897        put_named_spo(
6898            &service,
6899            PartitionAxis::S,
6900            "http://ex/bob",
6901            "http://ex/knows",
6902            "http://ex/o4",
6903        );
6904        let alice = encode_named_spo("http://ex/alice", "http://ex/knows", "http://ex/o1").subject;
6905        let bob = encode_named_spo("http://ex/bob", "http://ex/knows", "http://ex/o4").subject;
6906        let pattern = knows_pattern();
6907        let terms = [alice.clone(), bob.clone()];
6908
6909        let (all, _) = service
6910            .scan_filtered(
6911                None,
6912                &pattern,
6913                SnapshotId::latest(),
6914                0,
6915                Some(PatternSlot::Subject),
6916                &terms,
6917                None,
6918                &[],
6919                false,
6920                false,
6921                IriOnlyMask::NONE,
6922                true,
6923            )
6924            .unwrap();
6925        assert_eq!(all.len(), 4);
6926        let mut seen = all.clone();
6927        seen.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}")));
6928        let mut unique = seen.clone();
6929        unique.dedup();
6930        assert_eq!(unique.len(), all.len(), "unlimited scan has no duplicates");
6931
6932        let (page1, _) = service
6933            .scan_filtered(
6934                None,
6935                &pattern,
6936                SnapshotId::latest(),
6937                3,
6938                Some(PatternSlot::Subject),
6939                &terms,
6940                None,
6941                &[],
6942                false,
6943                false,
6944                IriOnlyMask::NONE,
6945                true,
6946            )
6947            .unwrap();
6948        assert_eq!(page1.len(), 3);
6949        let (page2, _) = service
6950            .scan_filtered(
6951                None,
6952                &pattern,
6953                SnapshotId::latest(),
6954                3,
6955                Some(PatternSlot::Subject),
6956                &terms,
6957                page1.last(),
6958                &[],
6959                false,
6960                false,
6961                IriOnlyMask::NONE,
6962                true,
6963            )
6964            .unwrap();
6965        assert_eq!(page2.len(), 1, "second page continues, does not replay");
6966        let mut concatenated = page1.clone();
6967        concatenated.extend(page2);
6968        assert_eq!(concatenated, all);
6969
6970        let mut paged = Vec::new();
6971        let mut cursor = None;
6972        for _ in 0..8 {
6973            let (page, _) = service
6974                .scan_filtered(
6975                    None,
6976                    &pattern,
6977                    SnapshotId::latest(),
6978                    1,
6979                    Some(PatternSlot::Subject),
6980                    &terms,
6981                    cursor.as_ref(),
6982                    &[],
6983                    false,
6984                    false,
6985                    IriOnlyMask::NONE,
6986                    true,
6987                )
6988                .unwrap();
6989            if page.is_empty() {
6990                break;
6991            }
6992            paged.extend(page.clone());
6993            cursor = page.last().cloned();
6994        }
6995        assert_eq!(paged, all);
6996    }
6997
6998    #[test]
6999    fn filtered_scan_unsorted_terms_match_sorted_input() {
7000        let service = PartitionService::memory(PartitionAxis::S);
7001        put_named_spo(
7002            &service,
7003            PartitionAxis::S,
7004            "http://ex/alice",
7005            "http://ex/knows",
7006            "http://ex/o1",
7007        );
7008        put_named_spo(
7009            &service,
7010            PartitionAxis::S,
7011            "http://ex/bob",
7012            "http://ex/knows",
7013            "http://ex/o4",
7014        );
7015        let alice = encode_named_spo("http://ex/alice", "http://ex/knows", "http://ex/o1").subject;
7016        let bob = encode_named_spo("http://ex/bob", "http://ex/knows", "http://ex/o4").subject;
7017        let pattern = knows_pattern();
7018        let (forward, _) = service
7019            .scan_filtered(
7020                None,
7021                &pattern,
7022                SnapshotId::latest(),
7023                0,
7024                Some(PatternSlot::Subject),
7025                &[alice.clone(), bob.clone()],
7026                None,
7027                &[],
7028                false,
7029                false,
7030                IriOnlyMask::NONE,
7031                true,
7032            )
7033            .unwrap();
7034        let (reverse, _) = service
7035            .scan_filtered(
7036                None,
7037                &pattern,
7038                SnapshotId::latest(),
7039                0,
7040                Some(PatternSlot::Subject),
7041                &[bob, alice],
7042                None,
7043                &[],
7044                false,
7045                false,
7046                IriOnlyMask::NONE,
7047                true,
7048            )
7049            .unwrap();
7050        assert_eq!(forward, reverse);
7051        assert_eq!(forward.len(), 2);
7052    }
7053
7054    #[test]
7055    fn filtered_scan_dedups_duplicate_allow_list_terms() {
7056        let service = PartitionService::memory(PartitionAxis::S);
7057        put_named_spo(
7058            &service,
7059            PartitionAxis::S,
7060            "http://ex/alice",
7061            "http://ex/knows",
7062            "http://ex/o1",
7063        );
7064        let alice = encode_named_spo("http://ex/alice", "http://ex/knows", "http://ex/o1").subject;
7065        let pattern = knows_pattern();
7066        let (rows, _) = service
7067            .scan_filtered(
7068                None,
7069                &pattern,
7070                SnapshotId::latest(),
7071                0,
7072                Some(PatternSlot::Subject),
7073                &[alice.clone(), alice.clone()],
7074                None,
7075                &[],
7076                false,
7077                false,
7078                IriOnlyMask::NONE,
7079                true,
7080            )
7081            .unwrap();
7082        assert_eq!(rows.len(), 1);
7083    }
7084
7085    fn put_named(service: &PartitionService, axis: PartitionAxis, commit_ts: u64, subject: &str) {
7086        let quad = waratah_storage::Quad::new(
7087            waratah_storage::NamedNode::new(subject).unwrap(),
7088            waratah_storage::NamedNode::new("http://ex/p").unwrap(),
7089            waratah_storage::Literal::from("o"),
7090            waratah_storage::GraphName::DefaultGraph,
7091        );
7092        let encoded = waratah_storage::encode_quad(&quad).unwrap();
7093        service
7094            .apply_versions(
7095                Some(axis),
7096                &[QuadVersion {
7097                    quad: encoded,
7098                    commit_ts: waratah_storage::CommitTs(commit_ts),
7099                    op: waratah_storage::StorageOp::Put,
7100                    visibility: waratah_storage::VisibilityLabel::default(),
7101                }],
7102            )
7103            .unwrap();
7104    }
7105
7106    fn sst_count(path: &std::path::Path) -> usize {
7107        std::fs::read_dir(path)
7108            .unwrap()
7109            .filter_map(Result::ok)
7110            .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "sst"))
7111            .count()
7112    }
7113
7114    #[test]
7115    fn rocksdb_flush_writes_sst_user_properties_not_sidecar_files() {
7116        let dir = tempfile::tempdir().unwrap();
7117        let path = dir.path().join("s");
7118        let service = PartitionService::open_with_backend(
7119            StorageBackendKind::RocksDb,
7120            &path,
7121            PartitionAxis::S,
7122        )
7123        .unwrap();
7124
7125        put_named(&service, PartitionAxis::S, 1, "http://ex/s");
7126        assert_eq!(service.shard_profile().unwrap().total_puts, 1);
7127
7128        service.flush_memtables().unwrap();
7129        assert!(sst_count(&path) > 0, "expected SST files under {path:?}");
7130        assert!(!path.join("waratah_stats").exists());
7131
7132        let blobs = service
7133            .storage
7134            .stats_property_blobs(STATS_USER_PROPERTY_KEY)
7135            .unwrap();
7136        assert!(
7137            !blobs.is_empty(),
7138            "expected waratah.stats on the canonical CF"
7139        );
7140
7141        let profile = service.shard_profile().unwrap();
7142        assert_eq!(profile.total_puts, 1);
7143        assert!(service.stats.lock().unwrap().open_profile().is_empty());
7144        assert!(service.stats.lock().unwrap().flushing_profile().is_empty());
7145
7146        put_named(&service, PartitionAxis::S, 2, "http://ex/s2");
7147        assert_eq!(service.shard_profile().unwrap().total_puts, 2);
7148
7149        let again = service.shard_profile().unwrap();
7150        assert_eq!(again.total_puts, 2);
7151    }
7152
7153    #[test]
7154    fn rocksdb_flush_keeps_post_flush_open_until_reload_drops_flushing() {
7155        let dir = tempfile::tempdir().unwrap();
7156        let path = dir.path().join("s");
7157        let service = PartitionService::open_with_backend(
7158            StorageBackendKind::RocksDb,
7159            &path,
7160            PartitionAxis::S,
7161        )
7162        .unwrap();
7163
7164        put_named(&service, PartitionAxis::S, 1, "http://ex/s1");
7165        service.flush_memtables().unwrap();
7166        assert_eq!(service.open_total_puts().unwrap(), 0);
7167        assert_eq!(
7168            service.stats.lock().unwrap().flushing_profile().total_puts,
7169            1
7170        );
7171
7172        put_named(&service, PartitionAxis::S, 2, "http://ex/s2");
7173        assert_eq!(service.open_total_puts().unwrap(), 1);
7174        assert_eq!(service.shard_profile().unwrap().total_puts, 2);
7175        assert!(service.stats.lock().unwrap().flushing_profile().is_empty());
7176        assert_eq!(service.open_total_puts().unwrap(), 1);
7177    }
7178
7179    #[test]
7180    fn rocksdb_stats_reload_from_sst_properties_after_reopen() {
7181        let dir = tempfile::tempdir().unwrap();
7182        let path = dir.path().join("s");
7183        {
7184            let service = PartitionService::open_with_backend(
7185                StorageBackendKind::RocksDb,
7186                &path,
7187                PartitionAxis::S,
7188            )
7189            .unwrap();
7190            put_named(&service, PartitionAxis::S, 1, "http://ex/s");
7191            service.flush_memtables().unwrap();
7192            assert_eq!(service.shard_profile().unwrap().total_puts, 1);
7193        }
7194
7195        let reopened = PartitionService::open_with_backend(
7196            StorageBackendKind::RocksDb,
7197            &path,
7198            PartitionAxis::S,
7199        )
7200        .unwrap();
7201        assert_eq!(reopened.shard_profile().unwrap().total_puts, 1);
7202    }
7203
7204    #[test]
7205    fn rocksdb_compaction_reloads_sealed_and_keeps_open() {
7206        let dir = tempfile::tempdir().unwrap();
7207        let path = dir.path().join("s");
7208        let service = PartitionService::open_with_backend(
7209            StorageBackendKind::RocksDb,
7210            &path,
7211            PartitionAxis::S,
7212        )
7213        .unwrap();
7214
7215        put_named(&service, PartitionAxis::S, 1, "http://ex/s1");
7216        service.flush_memtables().unwrap();
7217        put_named(&service, PartitionAxis::S, 2, "http://ex/s2");
7218        service.flush_memtables().unwrap();
7219        assert_eq!(service.shard_profile().unwrap().total_puts, 2);
7220
7221        put_named(&service, PartitionAxis::S, 3, "http://ex/s3");
7222        service.storage.compact_range();
7223        let profile = service.shard_profile().unwrap();
7224        assert_eq!(
7225            profile.total_puts, 3,
7226            "compaction must keep unflushed open overlay"
7227        );
7228    }
7229
7230    fn put_spo_in_graph(
7231        service: &PartitionService,
7232        axis: PartitionAxis,
7233        subject: &str,
7234        predicate: &str,
7235        object: &str,
7236        graph: &str,
7237    ) {
7238        let quad = waratah_storage::Quad::new(
7239            waratah_storage::NamedNode::new(subject).unwrap(),
7240            waratah_storage::NamedNode::new(predicate).unwrap(),
7241            waratah_storage::NamedNode::new(object).unwrap(),
7242            waratah_storage::GraphName::NamedNode(waratah_storage::NamedNode::new(graph).unwrap()),
7243        );
7244        service
7245            .apply_versions(
7246                Some(axis),
7247                &[QuadVersion {
7248                    quad: waratah_storage::encode_quad(&quad).unwrap(),
7249                    commit_ts: waratah_storage::CommitTs(1),
7250                    op: waratah_storage::StorageOp::Put,
7251                    visibility: waratah_storage::VisibilityLabel::default(),
7252                }],
7253            )
7254            .unwrap();
7255    }
7256
7257    #[test]
7258    fn merge_default_graph_collapses_named_graphs_and_rewrites_g_on_every_axis() {
7259        let pattern = EncodedTriplePattern {
7260            subject: Some(encode_named_spo("http://ex/s", "http://ex/p", "http://ex/o").subject),
7261            predicate: Some(
7262                encode_named_spo("http://ex/s", "http://ex/p", "http://ex/o").predicate,
7263            ),
7264            object: Some(encode_named_spo("http://ex/s", "http://ex/p", "http://ex/o").object),
7265            graph_name: None,
7266        };
7267        for axis in [PartitionAxis::S, PartitionAxis::P, PartitionAxis::O] {
7268            let service = PartitionService::memory(axis);
7269            put_spo_in_graph(
7270                &service,
7271                axis,
7272                "http://ex/s",
7273                "http://ex/p",
7274                "http://ex/o",
7275                "http://ex/g1",
7276            );
7277            put_spo_in_graph(
7278                &service,
7279                axis,
7280                "http://ex/s",
7281                "http://ex/p",
7282                "http://ex/o",
7283                "http://ex/g2",
7284            );
7285            put_spo_in_graph(
7286                &service,
7287                axis,
7288                "http://ex/s2",
7289                "http://ex/p",
7290                "http://ex/o",
7291                "http://ex/g1",
7292            );
7293
7294            let (without, _) = service
7295                .scan_filtered(
7296                    None,
7297                    &pattern,
7298                    SnapshotId::latest(),
7299                    0,
7300                    None,
7301                    &[],
7302                    None,
7303                    &[],
7304                    false,
7305                    false,
7306                    IriOnlyMask::NONE,
7307                    true,
7308                )
7309                .unwrap();
7310            assert_eq!(without.len(), 2, "{axis:?} without dedup keeps both graphs");
7311
7312            let (merged, _) = service
7313                .scan_filtered(
7314                    None,
7315                    &pattern,
7316                    SnapshotId::latest(),
7317                    0,
7318                    None,
7319                    &[],
7320                    None,
7321                    &[],
7322                    false,
7323                    true,
7324                    IriOnlyMask::NONE,
7325                    true,
7326                )
7327                .unwrap();
7328            assert_eq!(merged.len(), 1, "{axis:?} dedup emits one triple");
7329            assert_eq!(merged[0].graph_name, EncodedTerm::DefaultGraph);
7330            assert_eq!(merged[0].subject, pattern.subject.clone().unwrap());
7331
7332            let (page1, _) = service
7333                .scan_filtered(
7334                    None,
7335                    &pattern,
7336                    SnapshotId::latest(),
7337                    1,
7338                    None,
7339                    &[],
7340                    None,
7341                    &[],
7342                    false,
7343                    true,
7344                    IriOnlyMask::NONE,
7345                    true,
7346                )
7347                .unwrap();
7348            assert_eq!(page1.len(), 1);
7349            let (page2, _) = service
7350                .scan_filtered(
7351                    None,
7352                    &pattern,
7353                    SnapshotId::latest(),
7354                    0,
7355                    None,
7356                    &[],
7357                    page1.last(),
7358                    &[],
7359                    false,
7360                    true,
7361                    IriOnlyMask::NONE,
7362                    true,
7363                )
7364                .unwrap();
7365            assert!(
7366                page2.is_empty(),
7367                "{axis:?} start_after must skip the whole merged triple, got {page2:?}"
7368            );
7369
7370            let counted = service
7371                .count_filtered(
7372                    None,
7373                    &pattern,
7374                    SnapshotId::latest(),
7375                    0,
7376                    None,
7377                    &[],
7378                    &[],
7379                    false,
7380                    true,
7381                )
7382                .unwrap();
7383            assert_eq!(counted, 1, "{axis:?} count is distinct triples");
7384        }
7385    }
7386
7387    #[test]
7388    fn graph_filter_polarity_empty_block_vs_empty_allow() {
7389        let service = PartitionService::memory(PartitionAxis::S);
7390        put_named_spo(
7391            &service,
7392            PartitionAxis::S,
7393            "http://ex/alice",
7394            "http://ex/p",
7395            "http://ex/o",
7396        );
7397        put_spo_in_graph(
7398            &service,
7399            PartitionAxis::S,
7400            "http://ex/bob",
7401            "http://ex/p",
7402            "http://ex/o",
7403            "http://ex/g1",
7404        );
7405        let pattern = EncodedTriplePattern {
7406            subject: None,
7407            predicate: Some(
7408                encode_named_spo("http://ex/alice", "http://ex/p", "http://ex/o").predicate,
7409            ),
7410            object: None,
7411            graph_name: None,
7412        };
7413        let (unconstrained, _) = service
7414            .scan_filtered(
7415                None,
7416                &pattern,
7417                SnapshotId::latest(),
7418                0,
7419                None,
7420                &[],
7421                None,
7422                &[],
7423                false,
7424                false,
7425                IriOnlyMask::NONE,
7426                true,
7427            )
7428            .unwrap();
7429        assert_eq!(unconstrained.len(), 2, "empty block-list blocks nothing");
7430
7431        let (empty_allow, _) = service
7432            .scan_filtered(
7433                None,
7434                &pattern,
7435                SnapshotId::latest(),
7436                0,
7437                None,
7438                &[],
7439                None,
7440                &[],
7441                true,
7442                false,
7443                IriOnlyMask::NONE,
7444                true,
7445            )
7446            .unwrap();
7447        assert!(
7448            empty_allow.is_empty(),
7449            "empty allow-list allows nothing, got {empty_allow:?}"
7450        );
7451        assert_eq!(
7452            service
7453                .count_filtered(
7454                    None,
7455                    &pattern,
7456                    SnapshotId::latest(),
7457                    0,
7458                    None,
7459                    &[],
7460                    &[],
7461                    true,
7462                    false,
7463                )
7464                .unwrap(),
7465            0
7466        );
7467
7468        let g1 = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/g1").unwrap());
7469        let (allowed, _) = service
7470            .scan_filtered(
7471                None,
7472                &pattern,
7473                SnapshotId::latest(),
7474                0,
7475                None,
7476                &[],
7477                None,
7478                std::slice::from_ref(&g1),
7479                true,
7480                false,
7481                IriOnlyMask::NONE,
7482                true,
7483            )
7484            .unwrap();
7485        assert_eq!(allowed.len(), 1);
7486        assert_eq!(allowed[0].graph_name, g1);
7487
7488        let (blocked_default, _) = service
7489            .scan_filtered(
7490                None,
7491                &pattern,
7492                SnapshotId::latest(),
7493                0,
7494                None,
7495                &[],
7496                None,
7497                &[EncodedTerm::DefaultGraph],
7498                false,
7499                false,
7500                IriOnlyMask::NONE,
7501                true,
7502            )
7503            .unwrap();
7504        assert_eq!(blocked_default.len(), 1);
7505        assert_eq!(blocked_default[0].graph_name, g1);
7506        assert_eq!(
7507            service
7508                .count_filtered(
7509                    None,
7510                    &pattern,
7511                    SnapshotId::latest(),
7512                    0,
7513                    None,
7514                    &[],
7515                    &[EncodedTerm::DefaultGraph],
7516                    false,
7517                    false,
7518                )
7519                .unwrap(),
7520            1,
7521            "count must match the filtered scan, not the unfiltered prefix"
7522        );
7523        assert_eq!(
7524            service
7525                .count_filtered(
7526                    None,
7527                    &pattern,
7528                    SnapshotId::latest(),
7529                    1,
7530                    None,
7531                    &[],
7532                    &[],
7533                    false,
7534                    false,
7535                )
7536                .unwrap(),
7537            1,
7538            "positive count limit stops once that many matches are counted"
7539        );
7540    }
7541
7542    fn put_spo_in_blank_graph(
7543        service: &PartitionService,
7544        axis: PartitionAxis,
7545        subject: &str,
7546        predicate: &str,
7547        object: &str,
7548        blank: &waratah_storage::BlankNode,
7549    ) {
7550        let quad = waratah_storage::Quad::new(
7551            waratah_storage::NamedNode::new(subject).unwrap(),
7552            waratah_storage::NamedNode::new(predicate).unwrap(),
7553            waratah_storage::NamedNode::new(object).unwrap(),
7554            waratah_storage::GraphName::BlankNode(blank.clone()),
7555        );
7556        service
7557            .apply_versions(
7558                Some(axis),
7559                &[QuadVersion {
7560                    quad: waratah_storage::encode_quad(&quad).unwrap(),
7561                    commit_ts: waratah_storage::CommitTs(1),
7562                    op: waratah_storage::StorageOp::Put,
7563                    visibility: waratah_storage::VisibilityLabel::default(),
7564                }],
7565            )
7566            .unwrap();
7567    }
7568
7569    fn p_unbound_g_pattern() -> EncodedTriplePattern {
7570        EncodedTriplePattern {
7571            subject: None,
7572            predicate: Some(
7573                encode_named_spo("http://ex/alice", "http://ex/p", "http://ex/o").predicate,
7574            ),
7575            object: None,
7576            graph_name: None,
7577        }
7578    }
7579
7580    #[test]
7581    fn graph_filter_allow_default_graph_uses_extras() {
7582        let service = PartitionService::memory(PartitionAxis::S);
7583        put_named_spo(
7584            &service,
7585            PartitionAxis::S,
7586            "http://ex/alice",
7587            "http://ex/p",
7588            "http://ex/o",
7589        );
7590        put_spo_in_graph(
7591            &service,
7592            PartitionAxis::S,
7593            "http://ex/bob",
7594            "http://ex/p",
7595            "http://ex/o",
7596            "http://ex/g1",
7597        );
7598        let pattern = p_unbound_g_pattern();
7599        let (allowed, _) = service
7600            .scan_filtered(
7601                None,
7602                &pattern,
7603                SnapshotId::latest(),
7604                0,
7605                None,
7606                &[],
7607                None,
7608                &[EncodedTerm::DefaultGraph],
7609                true,
7610                false,
7611                IriOnlyMask::NONE,
7612                true,
7613            )
7614            .unwrap();
7615        assert_eq!(allowed.len(), 1);
7616        assert_eq!(allowed[0].graph_name, EncodedTerm::DefaultGraph);
7617        assert_eq!(
7618            allowed[0].subject,
7619            encode_named_spo("http://ex/alice", "http://ex/p", "http://ex/o").subject
7620        );
7621    }
7622
7623    #[test]
7624    fn graph_filter_blank_graph_uses_extras() {
7625        let service = PartitionService::memory(PartitionAxis::S);
7626        put_named_spo(
7627            &service,
7628            PartitionAxis::S,
7629            "http://ex/alice",
7630            "http://ex/p",
7631            "http://ex/o",
7632        );
7633        put_spo_in_graph(
7634            &service,
7635            PartitionAxis::S,
7636            "http://ex/bob",
7637            "http://ex/p",
7638            "http://ex/o",
7639            "http://ex/g1",
7640        );
7641        let blank = waratah_storage::BlankNode::new("g").unwrap();
7642        put_spo_in_blank_graph(
7643            &service,
7644            PartitionAxis::S,
7645            "http://ex/carol",
7646            "http://ex/p",
7647            "http://ex/o",
7648            &blank,
7649        );
7650        let pattern = p_unbound_g_pattern();
7651        let encoded_blank = EncodedTerm::from(&blank);
7652        let (allowed, _) = service
7653            .scan_filtered(
7654                None,
7655                &pattern,
7656                SnapshotId::latest(),
7657                0,
7658                None,
7659                &[],
7660                None,
7661                std::slice::from_ref(&encoded_blank),
7662                true,
7663                false,
7664                IriOnlyMask::NONE,
7665                true,
7666            )
7667            .unwrap();
7668        assert_eq!(allowed.len(), 1);
7669        assert_eq!(allowed[0].graph_name, encoded_blank);
7670        assert_eq!(
7671            allowed[0].subject,
7672            encode_named_spo("http://ex/carol", "http://ex/p", "http://ex/o").subject
7673        );
7674
7675        let (blocked, _) = service
7676            .scan_filtered(
7677                None,
7678                &pattern,
7679                SnapshotId::latest(),
7680                0,
7681                None,
7682                &[],
7683                None,
7684                std::slice::from_ref(&encoded_blank),
7685                false,
7686                false,
7687                IriOnlyMask::NONE,
7688                true,
7689            )
7690            .unwrap();
7691        assert_eq!(blocked.len(), 2);
7692        assert!(blocked.iter().all(|quad| quad.graph_name != encoded_blank));
7693
7694        let g1 = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/g1").unwrap());
7695        let (blocked_default_and_g1, _) = service
7696            .scan_filtered(
7697                None,
7698                &pattern,
7699                SnapshotId::latest(),
7700                0,
7701                None,
7702                &[],
7703                None,
7704                &[EncodedTerm::DefaultGraph, g1],
7705                false,
7706                false,
7707                IriOnlyMask::NONE,
7708                true,
7709            )
7710            .unwrap();
7711        assert_eq!(blocked_default_and_g1.len(), 1);
7712        assert_eq!(blocked_default_and_g1[0].graph_name, encoded_blank);
7713    }
7714
7715    #[test]
7716    fn s_axis_insert_and_add_named_graph_catalog() {
7717        let service = PartitionService::memory(PartitionAxis::S);
7718        put_named_spo(
7719            &service,
7720            PartitionAxis::S,
7721            "http://ex/alice",
7722            "http://ex/p",
7723            "http://ex/o",
7724        );
7725        put_spo_in_graph(
7726            &service,
7727            PartitionAxis::S,
7728            "http://ex/bob",
7729            "http://ex/p",
7730            "http://ex/o",
7731            "http://ex/g1",
7732        );
7733        let listed = service.list_named_graphs(SnapshotId::latest()).unwrap();
7734        assert_eq!(listed.len(), 1);
7735        assert_eq!(
7736            listed[0],
7737            EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/g1").unwrap())
7738        );
7739
7740        let empty = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/empty").unwrap());
7741        service
7742            .add_named_graph(&empty, waratah_storage::CommitTs(1))
7743            .unwrap();
7744        let listed = service.list_named_graphs(SnapshotId::latest()).unwrap();
7745        assert_eq!(listed.len(), 2);
7746        assert!(listed.contains(&empty));
7747        assert_eq!(service.shard_profile().unwrap().named_graph_count, 2);
7748        service
7749            .add_named_graph(&empty, waratah_storage::CommitTs(2))
7750            .unwrap();
7751        assert_eq!(
7752            service.shard_profile().unwrap().named_graph_count,
7753            2,
7754            "already-Present add must not increment the count"
7755        );
7756    }
7757
7758    #[test]
7759    fn rocksdb_named_graph_count_survives_flush_compact_and_reopen() {
7760        let dir = tempfile::tempdir().unwrap();
7761        let path = dir.path().join("s");
7762        {
7763            let service = PartitionService::open_with_backend(
7764                StorageBackendKind::RocksDb,
7765                &path,
7766                PartitionAxis::S,
7767            )
7768            .unwrap();
7769            put_spo_in_graph(
7770                &service,
7771                PartitionAxis::S,
7772                "http://ex/s",
7773                "http://ex/p",
7774                "http://ex/o",
7775                "http://ex/g1",
7776            );
7777            let empty =
7778                EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/empty").unwrap());
7779            service
7780                .add_named_graph(&empty, waratah_storage::CommitTs(1))
7781                .unwrap();
7782            assert_eq!(service.shard_profile().unwrap().named_graph_count, 2);
7783            service.flush_memtables().unwrap();
7784            assert_eq!(service.shard_profile().unwrap().named_graph_count, 2);
7785            service.compact_range().unwrap();
7786            assert_eq!(service.shard_profile().unwrap().named_graph_count, 2);
7787        }
7788
7789        let reopened = PartitionService::open_with_backend(
7790            StorageBackendKind::RocksDb,
7791            &path,
7792            PartitionAxis::S,
7793        )
7794        .unwrap();
7795        // Reopen marks the sealed profile stale and empty. Describe must reload
7796        // before reporting the catalog count.
7797        assert_eq!(
7798            reopened
7799                .describe()
7800                .metrics
7801                .expect("describe includes metrics")
7802                .named_graph_count,
7803            Some(2)
7804        );
7805        assert_eq!(reopened.shard_profile().unwrap().named_graph_count, 2);
7806    }
7807
7808    #[test]
7809    fn finish_serialises_the_stamp_on_the_lease_mutex() {
7810        // The M1 window: releasing the lease before the stamp let a peer's
7811        // begin(wipe) take the free lease and delete the documents before
7812        // our stamp landed — a stamped epoch over an emptied index. The fix
7813        // holds the lease mutex across the whole stamp, so NOTHING of the
7814        // finish can run while another thread holds the mutex: while it is
7815        // held here, the finish is blocked and the sidecar epoch must still
7816        // be unset; once it frees, the finish completes and stamps.
7817        let service = PartitionService::memory(PartitionAxis::O)
7818            .with_text_self_create(Some(lease_test_options("text-index-v1;m1-serialise")));
7819        let token = service
7820            .begin_text_rebuild(&lease_test_options("text-index-v1;m1-serialise"), false)
7821            .unwrap()
7822            .expect("the lease is free");
7823        let guard = service.text_rebuild_lease.lock().unwrap();
7824        let finisher = service.clone();
7825        let handle = std::thread::spawn(move || finisher.finish_text_rebuild(token, true));
7826        std::thread::sleep(Duration::from_millis(50));
7827        // The epoch is read from the sidecar meta DIRECTLY — `describe`
7828        // takes the lease mutex (via the liveness probe) and would deadlock
7829        // against this test's own guard.
7830        let sidecar_epoch = || {
7831            service
7832                .text_index_handle()
7833                .ok()
7834                .and_then(|index| index.meta().ok().and_then(|meta| meta.epoch))
7835        };
7836        assert_eq!(
7837            sidecar_epoch(),
7838            None,
7839            "a finish blocked on the lease mutex cannot have stamped yet"
7840        );
7841        drop(guard);
7842        let epoch = handle.join().unwrap().unwrap();
7843        assert!(
7844            sidecar_epoch().is_some(),
7845            "stamped once the mutex freed (epoch {epoch})"
7846        );
7847    }
7848
7849    #[test]
7850    fn a_freed_text_lease_always_carries_a_durable_stamp() {
7851        // The invariant the release-before-stamp window broke, observed in
7852        // the protocol's own terms: once the lease reads FREE, the stamp it
7853        // finished is already durable. Liveness is checked FIRST and the
7854        // epoch SECOND — liveness blocks on the lease mutex while a finish
7855        // holds it, so a false liveness reading means the release already
7856        // happened, and the stamp precedes that release under the same
7857        // hold. (Against the unfixed ordering this test is a probabilistic
7858        // catch — the gap it hunts is real but narrow.)
7859        let service = PartitionService::memory(PartitionAxis::O)
7860            .with_text_self_create(Some(lease_test_options("text-index-v1;m1-freed")));
7861        let token = service
7862            .begin_text_rebuild(&lease_test_options("text-index-v1;m1-freed"), false)
7863            .unwrap()
7864            .expect("the lease is free");
7865        let finisher = service.clone();
7866        let handle = std::thread::spawn(move || finisher.finish_text_rebuild(token, true));
7867        let started = Instant::now();
7868        let sidecar_epoch = || {
7869            service
7870                .text_index_handle()
7871                .ok()
7872                .and_then(|index| index.meta().ok().and_then(|meta| meta.epoch))
7873        };
7874        loop {
7875            assert!(
7876                started.elapsed() < Duration::from_secs(5),
7877                "the finish did not complete within the poll window"
7878            );
7879            if !service.text_rebuild_in_progress() {
7880                assert!(
7881                    sidecar_epoch().is_some(),
7882                    "a free lease must never precede its stamp"
7883                );
7884                break;
7885            }
7886            std::thread::yield_now();
7887        }
7888        assert!(handle.join().unwrap().is_ok());
7889        assert!(sidecar_epoch().is_some(), "the stamping finish stamped");
7890    }
7891
7892    #[test]
7893    fn a_failed_begin_releases_the_lease() {
7894        // The M4 residual: begin takes the lease BEFORE opening the index,
7895        // so an open/wipe failure used to return Err with the lease pinned
7896        // for the rest of its hour — every other driver's begin bounded-
7897        // waited into a refusal for a rebuild that never started. A failed
7898        // begin is not a dead driver: the lease must go back.
7899        let service = PartitionService::memory(PartitionAxis::O)
7900            .with_text_self_create(Some(lease_test_options("text-index-v1;m4-begin")));
7901        FAIL_TEXT_OPEN.with(|slot| slot.set(Some(())));
7902        let error = service
7903            .begin_text_rebuild(&lease_test_options("text-index-v1;m4-begin"), true)
7904            .unwrap_err();
7905        assert!(
7906            error.to_string().contains("injected"),
7907            "the injected failure surfaced: {error}"
7908        );
7909        assert!(
7910            !service.text_rebuild_in_progress(),
7911            "a failed begin must not pin the lease"
7912        );
7913        // The next begin (the next startup's retry, another driver) takes a
7914        // FRESH lease and the whole protocol works from there.
7915        let token = service
7916            .begin_text_rebuild(&lease_test_options("text-index-v1;m4-begin"), false)
7917            .unwrap()
7918            .expect("the released lease is retakeable");
7919        service.finish_text_rebuild(token, false).unwrap();
7920    }
7921
7922    #[test]
7923    fn a_failed_geo_begin_releases_the_lease() {
7924        // Same shape as the text begin's release-on-failure: begin takes
7925        // the lease BEFORE wiping the index, so a wipe failure used to
7926        // return Err with the lease pinned for the rest of its duration —
7927        // every other driver's begin saw a held lease (bounded wait →
7928        // refusal) for a rebuild that never started. A failed begin is not
7929        // a dead driver: the lease must go back.
7930        let service = PartitionService::memory(PartitionAxis::O);
7931        FAIL_GEO_WIPE.with(|slot| slot.set(Some(())));
7932        let error = service.begin_geo_rebuild().unwrap_err();
7933        assert!(
7934            error.to_string().contains("injected"),
7935            "the injected failure surfaced: {error}"
7936        );
7937        assert!(
7938            !service.geo_rebuild_in_progress(),
7939            "the lease is released on the failure path"
7940        );
7941        // The next begin succeeds — no pinning. Finish releases the lease
7942        // this second begin took, leaving the service clean.
7943        assert!(
7944            service.begin_geo_rebuild().unwrap().is_some(),
7945            "a failed begin must not block the next driver"
7946        );
7947        service.finish_geo_rebuild().unwrap();
7948    }
7949
7950    #[test]
7951    fn geo_finish_serialises_the_stamp_on_the_lease_mutex() {
7952        // The release-before-stamp window: releasing the lease before the
7953        // stamp let a peer's begin take the free lease and wipe the index
7954        // before our stamp landed — a stamped epoch over a cleared index.
7955        // The fix holds the lease mutex across the whole stamp, so NOTHING
7956        // of the finish can run while another thread holds the mutex: while
7957        // it is held here, the finish is blocked and the epoch must still
7958        // be unset; once it frees, the finish completes and stamps.
7959        let service = PartitionService::memory(PartitionAxis::O);
7960        service
7961            .begin_geo_rebuild()
7962            .unwrap()
7963            .expect("the lease is free");
7964        // The counter floors the stamp: without a commit the epoch would be
7965        // 0 and unstamped would be indistinguishable from stamped-0.
7966        service
7967            .max_commit_ts
7968            .store(10, std::sync::atomic::Ordering::Relaxed);
7969        let guard = service.geo_rebuild_lease.lock().unwrap();
7970        let finisher = service.clone();
7971        let handle = std::thread::spawn(move || finisher.finish_geo_rebuild());
7972        std::thread::sleep(Duration::from_millis(50));
7973        // The epoch is read from storage DIRECTLY — `describe` takes the
7974        // lease mutex (via the liveness probe) and would deadlock against
7975        // this test's own guard. The liveness-aware reader distinguishes
7976        // unset from stamped.
7977        let epoch_now = || service.storage.as_ref().geo_index_epoch().unwrap();
7978        assert_eq!(
7979            epoch_now(),
7980            None,
7981            "a finish blocked on the lease mutex cannot have stamped yet"
7982        );
7983        drop(guard);
7984        let epoch = handle.join().unwrap().unwrap();
7985        assert_eq!(
7986            epoch_now(),
7987            Some(10),
7988            "stamped once the mutex freed (epoch {epoch})"
7989        );
7990    }
7991
7992    #[test]
7993    fn geo_finish_stamps_under_the_lease_a_peer_begin_cannot_interleave() {
7994        // The deterministic window catch for release-before-stamp: the
7995        // finisher blocks INSIDE the stamp (rendezvous hook), and a peer's
7996        // begin runs against that stamp. The message ORDER on the shared
7997        // channel decides — no timing: with the lease released before the
7998        // stamp, the peer takes the free lease and reports "peer-took"
7999        // BEFORE the finisher's "stamp-written" (the stamp then lands over
8000        // the peer's wipe, while the peer's walk believes it owns the
8001        // rebuild). With the stamp under the lease, the peer's begin blocks
8002        // on the mutex until after "stamp-written" — the stamp is durable
8003        // before any takeover can start.
8004        let service = PartitionService::memory(PartitionAxis::O);
8005        service
8006            .begin_geo_rebuild()
8007            .unwrap()
8008            .expect("the lease is free");
8009        service
8010            .max_commit_ts
8011            .store(10, std::sync::atomic::Ordering::Relaxed);
8012        let (tx, rx) = std::sync::mpsc::channel();
8013        let peer_tx = tx.clone();
8014        let finisher = service.clone();
8015        let handle = std::thread::spawn(move || {
8016            // Arm the hook on the FINISHER thread (thread-local).
8017            BLOCK_GEO_STAMP.with(|slot| slot.set(Some(tx)));
8018            finisher.finish_geo_rebuild()
8019        });
8020        assert_eq!(
8021            rx.recv().unwrap(),
8022            "stamp-begun",
8023            "the finisher reached the stamp"
8024        );
8025        // The stamp is in progress. The peer's begin must only get the lease
8026        // AFTER the stamp landed.
8027        let peer_service = service.clone();
8028        let peer = std::thread::spawn(move || {
8029            let took = peer_service.begin_geo_rebuild().unwrap().is_some();
8030            let _ = peer_tx.send("peer-took");
8031            took
8032        });
8033        let mut stamp_landed_first = false;
8034        for _ in 0..2 {
8035            match rx.recv().unwrap() {
8036                "stamp-written" => stamp_landed_first = true,
8037                "peer-took" => {
8038                    assert!(
8039                        stamp_landed_first,
8040                        "the peer took the lease BEFORE the stamp landed — \
8041                         the release-before-stamp window"
8042                    );
8043                    break;
8044                }
8045                other => panic!("unexpected channel message: {other}"),
8046            }
8047        }
8048        let epoch = handle.join().unwrap().unwrap();
8049        assert_eq!(epoch, 10, "the finisher stamped");
8050        assert!(
8051            peer.join().unwrap(),
8052            "the peer gets the lease once the finish released it"
8053        );
8054        // The peer's takeover holds the lease — release it to leave the
8055        // service clean.
8056        service.finish_geo_rebuild().unwrap();
8057    }
8058
8059    #[test]
8060    fn finish_floors_the_epoch_at_the_previous_stamp() {
8061        // The commit counter is process-local: a freshly opened partition
8062        // reads 0 while the store's rows sit at the timestamps of every
8063        // process that ever wrote them. The stamp must never go DOWN —
8064        // "covered up to 0" over a much-written store is a lie.
8065        let service = PartitionService::memory(PartitionAxis::O);
8066        let options = lease_test_options("text-index-v1;floor-test");
8067        let token = service
8068            .begin_text_rebuild(&options, false)
8069            .unwrap()
8070            .expect("begin takes the lease");
8071        // This process wrote at ts 10 (the counter moves on applies).
8072        service
8073            .max_commit_ts
8074            .store(10, std::sync::atomic::Ordering::Relaxed);
8075        let first = service.finish_text_rebuild(token, true).unwrap();
8076        assert_eq!(first, 10, "the counter stamps when it is the max");
8077
8078        // Restart simulation: a fresh process's counter reads 0, the index
8079        // still carries the previous stamp. The floor keeps the honest
8080        // number; without it the second finish would stamp 0.
8081        let token = service
8082            .begin_text_rebuild(&options, false)
8083            .unwrap()
8084            .expect("the released lease is retaken");
8085        service
8086            .max_commit_ts
8087            .store(0, std::sync::atomic::Ordering::Relaxed);
8088        let second = service.finish_text_rebuild(token, true).unwrap();
8089        assert_eq!(
8090            second, 10,
8091            "the stamp floors at the previously stamped epoch"
8092        );
8093    }
8094
8095    #[test]
8096    fn apply_text_rejects_oversized_lexicals_fail_closed() {
8097        // The wire payload carries the full lexical; a literal above the
8098        // indexed-lexical limit can never be a valid document. The put is
8099        // rejected before the index is even created — the whole insert
8100        // fails loudly (invariant A refuses silently-missing documents).
8101        let service = PartitionService::memory(PartitionAxis::O)
8102            .with_text_self_create(Some(lease_test_options("text-index-v1;oversize")));
8103        let big = "x".repeat(waratah_storage::text_index::MAX_INDEXED_LEXICAL_BYTES + 1);
8104        let error = service.apply_text(&[text_doc(1, &big)]).unwrap_err();
8105        assert!(
8106            error.to_string().contains("indexed-lexical limit"),
8107            "the rejection names the limit: {error}"
8108        );
8109        // Nothing landed: no index was created for the rejected put.
8110        assert_eq!(
8111            service.text_doc_count(),
8112            None,
8113            "no document may land for an oversized lexical"
8114        );
8115    }
8116
8117    #[test]
8118    fn p_and_o_named_graph_catalog_is_unimplemented() {
8119        for axis in [PartitionAxis::P, PartitionAxis::O] {
8120            let service = PartitionService::memory(axis);
8121            let list_err = service.list_named_graphs(SnapshotId::latest()).unwrap_err();
8122            assert_eq!(Status::from(list_err).code(), tonic::Code::Unimplemented);
8123            let add_err = service
8124                .add_named_graph(
8125                    &EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/g").unwrap()),
8126                    waratah_storage::CommitTs(1),
8127                )
8128                .unwrap_err();
8129            assert_eq!(Status::from(add_err).code(), tonic::Code::Unimplemented);
8130        }
8131    }
8132
8133    /// Unique temp dir for RocksDB-backed partition test services.
8134    fn rocks_partition_dir(tag: &str) -> std::path::PathBuf {
8135        std::env::temp_dir().join(format!(
8136            "waratah-partition-{tag}-{}-{}",
8137            std::process::id(),
8138            std::time::SystemTime::now()
8139                .duration_since(std::time::UNIX_EPOCH)
8140                .unwrap()
8141                .as_nanos()
8142        ))
8143    }
8144
8145    /// m2: the partition-side hint seam. `tsg_class_totals_hint` gates the
8146    /// advisory class totals on the TSG full-axis shape (permutation
8147    /// resolves to TSG, subject and object unbound) and feeds the count
8148    /// walk's class-aligned slicing. Nothing previously pinned the gate or
8149    /// the live-hint count path: a wrong gate here silently degrades TSG
8150    /// counts to byte-even shapes, and a broken seam would break exactness.
8151    #[test]
8152    fn tsg_hint_gates_on_shape_and_stays_exact_with_live_hint() {
8153        let dir = rocks_partition_dir("hint");
8154        // TSG rides with the O axis (for_axis(O) = [Opsg, Tsg]), so the
8155        // hint's consumer and the TSG counts live on an O-axis service.
8156        let service =
8157            PartitionService::open_rocksdb(&dir, PartitionAxis::O, RocksDbOpenOptions::default())
8158                .unwrap();
8159        let nn = |iri: &str| EncodedTerm::from(&waratah_storage::NamedNode::new(iri).unwrap());
8160        let mut versions: Vec<QuadVersion> = Vec::new();
8161        let mut push = |subject: &str, predicate: &waratah_storage::NamedNode, object: &str| {
8162            versions.push(QuadVersion {
8163                quad: waratah_storage::encode_quad(&waratah_storage::Quad::new(
8164                    waratah_storage::NamedNode::new(subject).unwrap(),
8165                    predicate.clone(),
8166                    waratah_storage::NamedNode::new(object).unwrap(),
8167                    waratah_storage::GraphName::DefaultGraph,
8168                ))
8169                .unwrap(),
8170                commit_ts: waratah_storage::CommitTs(1),
8171                op: waratah_storage::StorageOp::Put,
8172                visibility: waratah_storage::VisibilityLabel::default(),
8173            });
8174        };
8175        let rdf_type =
8176            waratah_storage::NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
8177                .unwrap();
8178        for class in ["http://ex/C0", "http://ex/C1", "http://ex/C2"] {
8179            for i in 0..4 {
8180                push(&format!("http://ex/s{i}"), &rdf_type, class);
8181            }
8182        }
8183        for i in 0..3 {
8184            push(
8185                &format!("http://ex/s{i}"),
8186                &waratah_storage::NamedNode::new("http://ex/q").unwrap(),
8187                &format!("http://ex/u{i}"),
8188            );
8189        }
8190        service
8191            .apply_versions(Some(PartitionAxis::O), &versions)
8192            .unwrap();
8193
8194        // Seed the open profile with the exact class totals so the hint
8195        // carries the production shapes rather than arbitrary weights.
8196        {
8197            let mut stats = service.stats.lock().unwrap();
8198            let open = stats.open_profile_mut();
8199            for class in ["http://ex/C0", "http://ex/C1", "http://ex/C2"] {
8200                open.class_counts.insert(StrHash::new(class), 4);
8201            }
8202        }
8203
8204        let unbound = EncodedTriplePattern::default();
8205        let hint =
8206            service.tsg_class_totals_hint(Some(IndexPermutation::Tsg), &unbound, PartitionAxis::O);
8207        assert_eq!(
8208            hint.len(),
8209            3,
8210            "full-axis TSG hint carries the seeded classes"
8211        );
8212        assert!(
8213            hint.windows(2).all(|w| w[0].0 < w[1].0),
8214            "hint ascends by StrHash (count_slices_tsg_classes consumes it in order)"
8215        );
8216        assert_eq!(hint.iter().map(|(_, rows)| rows).sum::<u64>(), 12);
8217
8218        // Gate: any shape that cannot slice on class boundaries gets no hint.
8219        let with_subject = EncodedTriplePattern {
8220            subject: Some(nn("http://ex/s0")),
8221            ..unbound.clone()
8222        };
8223        let with_object = EncodedTriplePattern {
8224            object: Some(nn("http://ex/C0")),
8225            ..unbound.clone()
8226        };
8227        assert!(
8228            service
8229                .tsg_class_totals_hint(Some(IndexPermutation::Tsg), &with_subject, PartitionAxis::O)
8230                .is_empty()
8231        );
8232        assert!(
8233            service
8234                .tsg_class_totals_hint(Some(IndexPermutation::Tsg), &with_object, PartitionAxis::O)
8235                .is_empty()
8236        );
8237        assert!(
8238            service
8239                .tsg_class_totals_hint(Some(IndexPermutation::Posg), &unbound, PartitionAxis::O)
8240                .is_empty()
8241        );
8242        // Unresolved permutation: the S axis resolves best_permutation to a
8243        // hexastore index, never TSG.
8244        assert!(
8245            service
8246                .tsg_class_totals_hint(None, &unbound, PartitionAxis::O)
8247                .is_empty()
8248        );
8249
8250        // Live hint vs cleared hint: different slice shapes, identical totals.
8251        let snapshot = SnapshotId::latest();
8252        let counted = |service: &PartitionService| {
8253            service
8254                .count_filtered(
8255                    Some(IndexPermutation::Tsg),
8256                    &unbound,
8257                    snapshot,
8258                    0,
8259                    None,
8260                    &[],
8261                    &[],
8262                    false,
8263                    false,
8264                )
8265                .unwrap()
8266        };
8267        assert_eq!(counted(&service), 12, "TSG count with the live hint");
8268        service
8269            .stats
8270            .lock()
8271            .unwrap()
8272            .open_profile_mut()
8273            .class_counts
8274            .clear();
8275        assert_eq!(
8276            counted(&service),
8277            12,
8278            "TSG count with the hint cleared (byte-even shapes)"
8279        );
8280        // The hexastore index holds all 15 rows; TSG only the 12 type rows.
8281        assert_eq!(
8282            service
8283                .count_filtered(
8284                    Some(IndexPermutation::Opsg),
8285                    &unbound,
8286                    snapshot,
8287                    0,
8288                    None,
8289                    &[],
8290                    &[],
8291                    false,
8292                    false,
8293                )
8294                .unwrap(),
8295            15
8296        );
8297        drop(service);
8298        let _ = std::fs::remove_dir_all(&dir);
8299    }
8300
8301    /// m2: the storage-side serial fallbacks seen end to end. A named-graph
8302    /// window on TSG (the graph term lives inside the TSG key) and
8303    /// `merge_default_graph` (per-walk dedup state) both force the count
8304    /// walk serial at the storage mode gate; through the RPC handler the
8305    /// partition dispatch gate (on-caller vs blocking pool) composes on
8306    /// top. Branch agreement at the dispatch gate itself is pinned by
8307    /// scan_stream_frames_caller_thread_matches_dispatched_rows; here the
8308    /// exact totals through the composed path are the pin.
8309    #[tokio::test]
8310    async fn count_pattern_rpc_storage_serial_fallbacks_stay_exact() {
8311        let dir = rocks_partition_dir("fallback");
8312        // The O axis owns Opsg and Tsg — both fallback cases count on
8313        // those families.
8314        let service =
8315            PartitionService::open_rocksdb(&dir, PartitionAxis::O, RocksDbOpenOptions::default())
8316                .unwrap();
8317        let nn_term = |iri: &str| EncodedTerm::from(&waratah_storage::NamedNode::new(iri).unwrap());
8318        let mut versions: Vec<QuadVersion> = Vec::new();
8319        let push = |versions: &mut Vec<QuadVersion>, quad: &waratah_storage::Quad| {
8320            versions.push(QuadVersion {
8321                quad: waratah_storage::encode_quad(quad).unwrap(),
8322                commit_ts: waratah_storage::CommitTs(1),
8323                op: waratah_storage::StorageOp::Put,
8324                visibility: waratah_storage::VisibilityLabel::default(),
8325            });
8326        };
8327        let rdf_type = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
8328        let dg = |s: &str, p: &str, o: &str| {
8329            waratah_storage::Quad::new(
8330                waratah_storage::NamedNode::new(s).unwrap(),
8331                waratah_storage::NamedNode::new(p).unwrap(),
8332                waratah_storage::NamedNode::new(o).unwrap(),
8333                waratah_storage::GraphName::DefaultGraph,
8334            )
8335        };
8336        let named = |s: &str, p: &str, o: &str, g: &str| {
8337            waratah_storage::Quad::new(
8338                waratah_storage::NamedNode::new(s).unwrap(),
8339                waratah_storage::NamedNode::new(p).unwrap(),
8340                waratah_storage::NamedNode::new(o).unwrap(),
8341                waratah_storage::GraphName::NamedNode(waratah_storage::NamedNode::new(g).unwrap()),
8342            )
8343        };
8344        push(&mut versions, &dg("http://ex/s0", rdf_type, "http://ex/C0"));
8345        push(&mut versions, &dg("http://ex/s1", rdf_type, "http://ex/C0"));
8346        push(&mut versions, &dg("http://ex/s2", rdf_type, "http://ex/C1"));
8347        push(
8348            &mut versions,
8349            &named("http://ex/s3", rdf_type, "http://ex/C0", "http://ex/g0"),
8350        );
8351        push(
8352            &mut versions,
8353            &named("http://ex/s4", rdf_type, "http://ex/C1", "http://ex/g0"),
8354        );
8355        push(
8356            &mut versions,
8357            &dg("http://ex/a", "http://ex/q", "http://ex/b"),
8358        );
8359        push(
8360            &mut versions,
8361            &dg("http://ex/x", "http://ex/px", "http://ex/y"),
8362        );
8363        push(
8364            &mut versions,
8365            &named("http://ex/x", "http://ex/px", "http://ex/y", "http://ex/g0"),
8366        );
8367        service
8368            .apply_versions(Some(PartitionAxis::O), &versions)
8369            .unwrap();
8370        let snapshot = SnapshotId::latest();
8371
8372        // Named-graph window on TSG: the mode gate forces the walk serial;
8373        // the {g0} window selects exactly the two g0 type rows.
8374        let unbound = EncodedTriplePattern::default();
8375        let via_rpc = service
8376            .count_pattern(Request::new(waratah_proto::scan_request_page(
8377                &unbound,
8378                snapshot,
8379                0,
8380                Some(IndexPermutation::Tsg),
8381                None,
8382                &[],
8383                None,
8384                &[nn_term("http://ex/g0")],
8385                true,
8386                false,
8387                IriOnlyMask::NONE,
8388            )))
8389            .await
8390            .unwrap()
8391            .into_inner()
8392            .count;
8393        let via_count_filtered = service
8394            .count_filtered(
8395                Some(IndexPermutation::Tsg),
8396                &unbound,
8397                snapshot,
8398                0,
8399                None,
8400                &[],
8401                &[nn_term("http://ex/g0")],
8402                true,
8403                false,
8404            )
8405            .unwrap();
8406        assert_eq!(
8407            via_rpc, 2,
8408            "TSG count with a g0 window (storage-serial fallback)"
8409        );
8410        assert_eq!(via_count_filtered, via_rpc);
8411
8412        // merge_default_graph: the (x, px, y) triple exists in the default
8413        // graph AND g0; unmerged the bound pattern counts 2, merged it
8414        // counts 1 (merge also forces the walk serial at the mode gate).
8415        let merge_pattern = EncodedTriplePattern {
8416            subject: Some(nn_term("http://ex/x")),
8417            predicate: Some(nn_term("http://ex/px")),
8418            object: Some(nn_term("http://ex/y")),
8419            graph_name: None,
8420        };
8421        let merged = service
8422            .count_pattern(Request::new(waratah_proto::scan_request_page(
8423                &merge_pattern,
8424                snapshot,
8425                0,
8426                Some(IndexPermutation::Opsg),
8427                None,
8428                &[],
8429                None,
8430                &[],
8431                false,
8432                true,
8433                IriOnlyMask::NONE,
8434            )))
8435            .await
8436            .unwrap()
8437            .into_inner()
8438            .count;
8439        let unmerged = service
8440            .count_pattern(Request::new(waratah_proto::scan_request_page(
8441                &merge_pattern,
8442                snapshot,
8443                0,
8444                Some(IndexPermutation::Opsg),
8445                None,
8446                &[],
8447                None,
8448                &[],
8449                false,
8450                false,
8451                IriOnlyMask::NONE,
8452            )))
8453            .await
8454            .unwrap()
8455            .into_inner()
8456            .count;
8457        assert_eq!(unmerged, 2, "both graph variants of the merge-pair triple");
8458        assert_eq!(
8459            merged, 1,
8460            "merge_default_graph collapses graph variants to one"
8461        );
8462        // The dispatch gate's on-caller path forces the walk serial (the
8463        // pool wake would outweigh a µs-scale count); exactness holds there
8464        // too — same answer through count_filtered_on_caller.
8465        let on_caller = service
8466            .count_filtered_on_caller(
8467                Some(IndexPermutation::Opsg),
8468                &merge_pattern,
8469                snapshot,
8470                0,
8471                None,
8472                &[],
8473                &[],
8474                false,
8475                true,
8476            )
8477            .unwrap();
8478        assert_eq!(on_caller, 1, "forced-serial on-caller path");
8479        drop(service);
8480        let _ = std::fs::remove_dir_all(&dir);
8481    }
8482
8483    fn lease_test_options(fingerprint: &str) -> waratah_text_index::TextIndexOptions {
8484        waratah_text_index::TextIndexOptions::new(
8485            waratah_storage::text_index::DEFAULT_ANALYZER,
8486            16,
8487            fingerprint,
8488        )
8489    }
8490
8491    fn text_doc(id: u8, lexical: &str) -> waratah_storage::TextIndexDoc {
8492        waratah_storage::TextIndexDoc::new(vec![id], lexical, None)
8493    }
8494
8495    #[test]
8496    fn resolve_text_subjects_streams_pages_and_stops_when_the_sink_closes() {
8497        let service = PartitionService::memory(PartitionAxis::O)
8498            .with_text_self_create(Some(lease_test_options("text-index-v2;stream-test")));
8499        let object = EncodedTerm::from(&waratah_storage::Literal::from("alpha"));
8500        let predicate =
8501            EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/p1").unwrap());
8502        service
8503            .apply_text(&[waratah_storage::TextIndexDoc::new_with_predicate(
8504                encode_term_bytes(&object),
8505                encode_term_bytes(&predicate),
8506                "alpha",
8507                None,
8508            )])
8509            .unwrap();
8510        // More subjects than one frame, so the sink sees a page WHILE the
8511        // walk runs (the first flush happens inside the storage visit).
8512        let rows = waratah_proto::SCAN_STREAM_FRAME_ROWS + 5;
8513        for index in 0..rows {
8514            service
8515                .storage
8516                .insert_quad(&waratah_storage::Quad::new(
8517                    waratah_storage::NamedNode::new(format!("http://ex/s{index:06}")).unwrap(),
8518                    waratah_storage::NamedNode::new("http://ex/p1").unwrap(),
8519                    waratah_storage::Literal::from("alpha"),
8520                    waratah_storage::GraphName::DefaultGraph,
8521                ))
8522                .unwrap();
8523        }
8524        let request = waratah_storage::text_index::TextSubjectRequest {
8525            mode: waratah_storage::TextCandidateMode::Fts,
8526            query: "alpha".to_owned(),
8527            language: None,
8528            limit: 0,
8529            predicates: vec![predicate],
8530            graph_name: Some(EncodedTerm::DefaultGraph),
8531            graph_filter_terms: Vec::new(),
8532            graph_filter_allow: false,
8533            merge_default_graph: false,
8534            return_graph: false,
8535            subject_equals_graph: false,
8536        };
8537
8538        // Every row is delivered, over two pages (a full frame then the tail).
8539        let mut pages = 0usize;
8540        let mut emitted = 0usize;
8541        service
8542            .resolve_text_subjects(&request, SnapshotId::latest(), &mut |page| {
8543                pages += 1;
8544                emitted += page.len();
8545                Ok(true)
8546            })
8547            .unwrap();
8548        assert_eq!(pages, 2);
8549        assert_eq!(emitted, rows);
8550
8551        // A sink that closes on the first page stops the walk there: the
8552        // remaining rows are never visited, let alone emitted.
8553        let mut pages = 0usize;
8554        let mut emitted = 0usize;
8555        service
8556            .resolve_text_subjects(&request, SnapshotId::latest(), &mut |page| {
8557                pages += 1;
8558                emitted += page.len();
8559                Ok(false)
8560            })
8561            .unwrap();
8562        assert_eq!(pages, 1, "the walk stops at the first page boundary");
8563        assert_eq!(emitted, waratah_proto::SCAN_STREAM_FRAME_ROWS);
8564    }
8565
8566    #[test]
8567    fn resolve_text_subjects_rejects_subject_equals_graph_with_the_default_merge() {
8568        // The merge rewrites every row's graph to the unnamed graph, so no
8569        // subject can ever equal it; the equality filter would drop the whole
8570        // window and the subject form has no residual to recover it. Reject
8571        // the request instead of answering empty.
8572        let service = PartitionService::memory(PartitionAxis::O)
8573            .with_text_self_create(Some(lease_test_options("text-index-v2;invalid-combo")));
8574        let request = waratah_storage::text_index::TextSubjectRequest {
8575            mode: waratah_storage::TextCandidateMode::Fts,
8576            query: "alpha".to_owned(),
8577            language: None,
8578            limit: 0,
8579            predicates: Vec::new(),
8580            graph_name: None,
8581            graph_filter_terms: Vec::new(),
8582            graph_filter_allow: false,
8583            merge_default_graph: true,
8584            return_graph: false,
8585            subject_equals_graph: true,
8586        };
8587        let mut pages = 0usize;
8588        let error = service
8589            .resolve_text_subjects(&request, SnapshotId::latest(), &mut |_| {
8590                pages += 1;
8591                Ok(true)
8592            })
8593            .expect_err("the contradictory pair must be rejected");
8594        assert!(matches!(error, PartitionError::SubjectEqualsGraphWithMerge));
8595        assert_eq!(pages, 0, "rejected before any page");
8596    }
8597
8598    #[test]
8599    fn text_subject_row_frame_marks_the_default_graph_as_present() {
8600        let subject = EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/s1").unwrap());
8601        let with_default_graph = waratah_storage::text_index::TextSubjectRow {
8602            subject: subject.clone(),
8603            graph: Some(EncodedTerm::DefaultGraph),
8604        };
8605        let frame = PartitionService::text_subject_row_to_proto(&with_default_graph);
8606        assert_eq!(
8607            frame.graph.as_deref(),
8608            Some(&[][..]),
8609            "the default graph's encoded term is zero bytes"
8610        );
8611        let without_graph = waratah_storage::text_index::TextSubjectRow {
8612            subject,
8613            graph: None,
8614        };
8615        assert!(
8616            PartitionService::text_subject_row_to_proto(&without_graph)
8617                .graph
8618                .is_none(),
8619            "no graph column means an absent field, not an empty one"
8620        );
8621    }
8622
8623    #[test]
8624    fn text_subject_resolve_returns_distinct_default_graph_subjects() {
8625        let service = PartitionService::memory(PartitionAxis::O)
8626            .with_text_self_create(Some(lease_test_options("text-index-v2;subject-test")));
8627        let object = EncodedTerm::from(&waratah_storage::Literal::from("alpha"));
8628        let predicate =
8629            EncodedTerm::from(&waratah_storage::NamedNode::new("http://ex/p1").unwrap());
8630        let subject = |s: &str| waratah_storage::NamedNode::new(format!("http://ex/{s}")).unwrap();
8631        service
8632            .apply_text(&[waratah_storage::TextIndexDoc::new_with_predicate(
8633                encode_term_bytes(&object),
8634                encode_term_bytes(&predicate),
8635                "alpha",
8636                None,
8637            )])
8638            .unwrap();
8639        for (name, graph) in [
8640            ("s1", waratah_storage::GraphName::DefaultGraph),
8641            (
8642                "s2",
8643                waratah_storage::GraphName::from(
8644                    waratah_storage::NamedNode::new("http://ex/gx").unwrap(),
8645                ),
8646            ),
8647        ] {
8648            service
8649                .storage
8650                .insert_quad(&waratah_storage::Quad::new(
8651                    subject(name),
8652                    waratah_storage::NamedNode::new("http://ex/p1").unwrap(),
8653                    waratah_storage::Literal::from("alpha"),
8654                    graph,
8655                ))
8656                .unwrap();
8657        }
8658        let request = waratah_storage::text_index::TextSubjectRequest {
8659            mode: waratah_storage::TextCandidateMode::Fts,
8660            query: "alpha".to_owned(),
8661            language: None,
8662            limit: 0,
8663            predicates: vec![predicate.clone()],
8664            graph_name: Some(EncodedTerm::DefaultGraph),
8665            graph_filter_terms: Vec::new(),
8666            graph_filter_allow: false,
8667            merge_default_graph: false,
8668            return_graph: false,
8669            subject_equals_graph: false,
8670        };
8671        let mut rows = Vec::new();
8672        service
8673            .resolve_text_subjects(&request, SnapshotId::latest(), &mut |page| {
8674                rows.extend_from_slice(page);
8675                Ok(true)
8676            })
8677            .unwrap();
8678        let subjects: Vec<Vec<u8>> = rows
8679            .iter()
8680            .map(|row| encode_term_bytes(&row.subject))
8681            .collect();
8682        assert_eq!(
8683            subjects,
8684            vec![encode_term_bytes(&EncodedTerm::from(&subject("s1")))]
8685        );
8686        assert!(rows.iter().all(|row| row.graph.is_none()));
8687
8688        // With the graph column requested and no graph window, both subjects
8689        // appear, each with its own graph term.
8690        let mut all = request.clone();
8691        all.graph_name = None;
8692        all.return_graph = true;
8693        let mut rows = Vec::new();
8694        service
8695            .resolve_text_subjects(&all, SnapshotId::latest(), &mut |page| {
8696                rows.extend_from_slice(page);
8697                Ok(true)
8698            })
8699            .unwrap();
8700        assert_eq!(rows.len(), 2);
8701        assert!(rows.iter().all(|row| row.graph.is_some()));
8702
8703        // The guard errors rather than truncating.
8704        let mut guarded = all.clone();
8705        guarded.limit = 1;
8706        assert!(matches!(
8707            service.resolve_text_subjects(&guarded, SnapshotId::latest(), &mut |_page| Ok(true)),
8708            Err(PartitionError::Text(
8709                waratah_text_index::TextIndexError::SubjectLimitExceeded { limit: 1 }
8710            ))
8711        ));
8712
8713        // The graph residual is a FILTER on the walk, not a name: an
8714        // allow-list keeps only its members, a block-list drops them.
8715        let gx = EncodedTerm::from(&waratah_storage::GraphName::from(
8716            waratah_storage::NamedNode::new("http://ex/gx").unwrap(),
8717        ));
8718        let mut allow = all.clone();
8719        allow.graph_filter_terms = vec![gx.clone()];
8720        allow.graph_filter_allow = true;
8721        let mut rows = Vec::new();
8722        service
8723            .resolve_text_subjects(&allow, SnapshotId::latest(), &mut |page| {
8724                rows.extend_from_slice(page);
8725                Ok(true)
8726            })
8727            .unwrap();
8728        assert_eq!(rows.len(), 1);
8729        assert_eq!(rows[0].graph, Some(gx.clone()), "allow-list keeps gx");
8730
8731        let mut block = all.clone();
8732        block.graph_filter_terms = vec![gx];
8733        block.graph_filter_allow = false;
8734        let mut rows = Vec::new();
8735        service
8736            .resolve_text_subjects(&block, SnapshotId::latest(), &mut |page| {
8737                rows.extend_from_slice(page);
8738                Ok(true)
8739            })
8740            .unwrap();
8741        assert_eq!(rows.len(), 1);
8742        assert_eq!(
8743            rows[0].graph,
8744            Some(EncodedTerm::DefaultGraph),
8745            "block-list drops gx"
8746        );
8747    }
8748
8749    #[test]
8750    fn a_subject_resolve_unions_the_named_predicates_and_only_those() {
8751        let service = PartitionService::memory(PartitionAxis::O)
8752            .with_text_self_create(Some(lease_test_options("text-index-v2;subject-union")));
8753        let subject = |s: &str| waratah_storage::NamedNode::new(format!("http://ex/{s}")).unwrap();
8754        let predicate =
8755            |p: &str| waratah_storage::NamedNode::new(format!("http://ex/p{p}")).unwrap();
8756        let literal = waratah_storage::Literal::from("alpha");
8757        // One document per named predicate, plus one under a predicate the
8758        // request does not name. The drain is a single OR, so the union must
8759        // return the p1 and p2 subjects and never the p3 subject.
8760        for (name, p) in [("s1", "p1"), ("s2", "p2"), ("s3", "p3")] {
8761            let predicate_term = EncodedTerm::from(&predicate(p));
8762            service
8763                .apply_text(&[waratah_storage::TextIndexDoc::new_with_predicate(
8764                    encode_term_bytes(&EncodedTerm::from(&literal)),
8765                    encode_term_bytes(&predicate_term),
8766                    "alpha",
8767                    None,
8768                )])
8769                .unwrap();
8770            service
8771                .storage
8772                .insert_quad(&waratah_storage::Quad::new(
8773                    subject(name),
8774                    predicate(p),
8775                    literal.clone(),
8776                    waratah_storage::GraphName::DefaultGraph,
8777                ))
8778                .unwrap();
8779        }
8780        let mut request = waratah_storage::text_index::TextSubjectRequest {
8781            mode: waratah_storage::TextCandidateMode::Fts,
8782            query: "alpha".to_owned(),
8783            language: None,
8784            limit: 0,
8785            predicates: vec![
8786                EncodedTerm::from(&predicate("p1")),
8787                EncodedTerm::from(&predicate("p2")),
8788            ],
8789            graph_name: None,
8790            graph_filter_terms: Vec::new(),
8791            graph_filter_allow: false,
8792            merge_default_graph: false,
8793            return_graph: false,
8794            subject_equals_graph: false,
8795        };
8796        let collect = |request: &waratah_storage::text_index::TextSubjectRequest| {
8797            let mut rows = Vec::new();
8798            service
8799                .resolve_text_subjects(request, SnapshotId::latest(), &mut |page| {
8800                    rows.extend_from_slice(page);
8801                    Ok(true)
8802                })
8803                .unwrap();
8804            // The predicate set is a SET and the walk follows index order, so
8805            // the row order is not a contract; assert on the sorted set.
8806            let mut subjects: Vec<Vec<u8>> = rows
8807                .iter()
8808                .map(|row| encode_term_bytes(&row.subject))
8809                .collect();
8810            subjects.sort();
8811            subjects
8812        };
8813        let mut expected = vec![
8814            encode_term_bytes(&EncodedTerm::from(&subject("s1"))),
8815            encode_term_bytes(&EncodedTerm::from(&subject("s2"))),
8816        ];
8817        expected.sort();
8818        assert_eq!(collect(&request), expected);
8819        // A duplicate literal under two named predicates is one subject row.
8820        let duplicate = waratah_storage::Literal::from("beta");
8821        for p in ["p1", "p2"] {
8822            service
8823                .apply_text(&[waratah_storage::TextIndexDoc::new_with_predicate(
8824                    encode_term_bytes(&EncodedTerm::from(&duplicate)),
8825                    encode_term_bytes(&EncodedTerm::from(&predicate(p))),
8826                    "beta",
8827                    None,
8828                )])
8829                .unwrap();
8830            service
8831                .storage
8832                .insert_quad(&waratah_storage::Quad::new(
8833                    subject("s4"),
8834                    predicate(p),
8835                    duplicate.clone(),
8836                    waratah_storage::GraphName::DefaultGraph,
8837                ))
8838                .unwrap();
8839        }
8840        request.query = "beta".to_owned();
8841        assert_eq!(
8842            collect(&request),
8843            vec![encode_term_bytes(&EncodedTerm::from(&subject("s4")))]
8844        );
8845        // The guard is edge-triggered at the EXACT limit: two distinct rows
8846        // under `limit = 2` is fine, and the third would exceed it.
8847        request.query = "alpha".to_owned();
8848        request.limit = 2;
8849        assert_eq!(collect(&request).len(), 2);
8850        request.limit = 1;
8851        assert!(matches!(
8852            service.resolve_text_subjects(&request, SnapshotId::latest(), &mut |_page| Ok(true)),
8853            Err(PartitionError::Text(
8854                waratah_text_index::TextIndexError::SubjectLimitExceeded { limit: 1 }
8855            ))
8856        ));
8857    }
8858
8859    #[test]
8860    fn subject_equals_graph_keeps_only_rows_whose_subject_is_the_graph() {
8861        // `GRAPH ?s { … }` plus `text:query(?s, …)`: one variable takes one
8862        // value, so a matching row counts only when its subject IS its
8863        // graph. s1 sits in graph s1 (kept); s2's matching row sits in gx
8864        // (dropped), even though s2 is a text-matching subject.
8865        let service = PartitionService::memory(PartitionAxis::O)
8866            .with_text_self_create(Some(lease_test_options("text-index-v2;subject-eq-graph")));
8867        let predicate =
8868            |p: &str| waratah_storage::NamedNode::new(format!("http://ex/p{p}")).unwrap();
8869        let object = waratah_storage::Literal::from("alpha");
8870        service
8871            .apply_text(&[waratah_storage::TextIndexDoc::new_with_predicate(
8872                encode_term_bytes(&EncodedTerm::from(&object)),
8873                encode_term_bytes(&EncodedTerm::from(&predicate("p1"))),
8874                "alpha",
8875                None,
8876            )])
8877            .unwrap();
8878        for (subject_name, graph) in [
8879            (
8880                "s1",
8881                waratah_storage::GraphName::from(
8882                    waratah_storage::NamedNode::new("http://ex/s1").unwrap(),
8883                ),
8884            ),
8885            (
8886                "s2",
8887                waratah_storage::GraphName::from(
8888                    waratah_storage::NamedNode::new("http://ex/gx").unwrap(),
8889                ),
8890            ),
8891        ] {
8892            service
8893                .storage
8894                .insert_quad(&waratah_storage::Quad::new(
8895                    waratah_storage::NamedNode::new(format!("http://ex/{subject_name}")).unwrap(),
8896                    predicate("p1"),
8897                    object.clone(),
8898                    graph,
8899                ))
8900                .unwrap();
8901        }
8902        let request = waratah_storage::text_index::TextSubjectRequest {
8903            mode: waratah_storage::TextCandidateMode::Fts,
8904            query: "alpha".to_owned(),
8905            language: None,
8906            limit: 0,
8907            predicates: vec![EncodedTerm::from(&predicate("p1"))],
8908            graph_name: None,
8909            graph_filter_terms: Vec::new(),
8910            graph_filter_allow: false,
8911            merge_default_graph: false,
8912            return_graph: false,
8913            subject_equals_graph: true,
8914        };
8915        let collect = |request: &waratah_storage::text_index::TextSubjectRequest| {
8916            let mut rows = Vec::new();
8917            service
8918                .resolve_text_subjects(request, SnapshotId::latest(), &mut |page| {
8919                    rows.extend_from_slice(page);
8920                    Ok(true)
8921                })
8922                .unwrap();
8923            rows.iter()
8924                .map(|row| encode_term_bytes(&row.subject))
8925                .collect::<Vec<_>>()
8926        };
8927        assert_eq!(
8928            collect(&request),
8929            vec![encode_term_bytes(&EncodedTerm::from(
8930                &waratah_storage::NamedNode::new("http://ex/s1").unwrap()
8931            ))],
8932            "only the subject that is its own graph survives"
8933        );
8934        // Without the flag both matching subjects are rows: the filter is the
8935        // flag, not the graph window.
8936        let mut plain = request.clone();
8937        plain.subject_equals_graph = false;
8938        assert_eq!(collect(&plain).len(), 2);
8939    }
8940
8941    #[test]
8942    fn the_text_lease_token_proves_ownership() {
8943        let service = PartitionService::memory(PartitionAxis::O);
8944        let options = lease_test_options("text-index-v1;lease-test");
8945        // Take the lease; a second begin sees it fresh and gets nothing.
8946        let token = service
8947            .begin_text_rebuild(&options, false)
8948            .unwrap()
8949            .expect("the first begin takes the lease");
8950        assert_ne!(
8951            token, 0,
8952            "token 0 is reserved for 'not started' on the wire"
8953        );
8954        assert!(
8955            service
8956                .begin_text_rebuild(&options, false)
8957                .unwrap()
8958                .is_none(),
8959            "a fresh lease held elsewhere is not retaken"
8960        );
8961        // A wrong token can neither renew nor finish; the lease survives.
8962        assert!(service.renew_text_rebuild_lease(token + 999).is_err());
8963        assert!(service.finish_text_rebuild(token + 999, true).is_err());
8964        assert!(
8965            service.text_rebuild_in_progress(),
8966            "wrong-token attempts must not release the lease"
8967        );
8968        // The owner renews and finishes; the release is observable.
8969        service.renew_text_rebuild_lease(token).unwrap();
8970        service.finish_text_rebuild(token, true).unwrap();
8971        assert!(!service.text_rebuild_in_progress());
8972        // A released lease cannot be finished again (a stale driver's finish
8973        // after a takeover is rejected the same way).
8974        assert!(service.finish_text_rebuild(token, true).is_err());
8975    }
8976
8977    #[test]
8978    fn the_walkers_own_frames_pass_once_the_wipe_completes() {
8979        // The fence lives on the INDEX and is atomic with the wipe's
8980        // delete — it is NOT the rebuild lease's whole lifetime. The wipe
8981        // runs inside begin(wipe = true), so once begin returns the fence
8982        // is down and the walker's own re-derivation frames land (the old
8983        // lease-long fence rejected the walker through its own door).
8984        let service = PartitionService::memory(PartitionAxis::O);
8985        let options = lease_test_options("text-index-v1;fence-test");
8986        let token = service
8987            .begin_text_rebuild(&options, true)
8988            .unwrap()
8989            .expect("the wipe begin takes the lease");
8990        service
8991            .apply_text(&[text_doc(1, "alpha")])
8992            .expect("the walker's frames land after the wipe completes");
8993        service.finish_text_rebuild(token, false).unwrap();
8994        assert_eq!(service.text_doc_count(), Some(1));
8995
8996        // An ADDITIVE lease does not fence either: a live repair coexists
8997        // with in-progress writes.
8998        let additive = service
8999            .begin_text_rebuild(&options, false)
9000            .unwrap()
9001            .unwrap();
9002        service.apply_text(&[text_doc(2, "beta")]).unwrap();
9003        service.finish_text_rebuild(additive, false).unwrap();
9004        assert_eq!(service.text_doc_count(), Some(2));
9005    }
9006
9007    #[test]
9008    fn apply_text_is_fenced_while_a_wipe_delete_is_in_flight() {
9009        // The atomic fence: with the wipe flag raised (exactly what
9010        // `TextIndex::wipe` holds across its flag-and-delete), a put is
9011        // rejected BEFORE committing — the insert fails loudly and the
9012        // load is rerun, so no document is committed-then-deleted.
9013        // The old check-then-act fence read the rebuild lease before
9014        // taking the writer: a put that passed that check could still
9015        // commit between the flag rising and the delete.
9016        let service = PartitionService::memory(PartitionAxis::O)
9017            .with_text_self_create(Some(lease_test_options("text-index-v1;fence-atomic")));
9018        // Create the index through a first (fence-down) put.
9019        service.apply_text(&[text_doc(1, "alpha")]).unwrap();
9020        service.text_index_handle().unwrap().test_set_wiping(true);
9021        let error = service.apply_text(&[text_doc(2, "beta")]).unwrap_err();
9022        assert!(
9023            error.to_string().contains("wiping"),
9024            "the fence error names the wipe: {error}"
9025        );
9026        assert_eq!(
9027            service.text_doc_count(),
9028            Some(1),
9029            "the fenced put committed nothing"
9030        );
9031        service.text_index_handle().unwrap().test_set_wiping(false);
9032        service.apply_text(&[text_doc(2, "beta")]).unwrap();
9033        assert_eq!(service.text_doc_count(), Some(2));
9034    }
9035
9036    #[test]
9037    fn puts_self_create_the_index_when_the_launcher_configured_it() {
9038        // Launcher-configured: the first put creates the index (no sidecar,
9039        // no rebuild happened) so new rows carry documents; the epoch stays
9040        // unset, so text:query keeps failing until a real walk stamps it.
9041        let service = PartitionService::memory(PartitionAxis::O)
9042            .with_text_self_create(Some(lease_test_options("text-index-v1;self")));
9043        service.apply_text(&[text_doc(1, "alpha")]).unwrap();
9044        let terms = service
9045            .text_candidates(&waratah_storage::text_index::TextSearchRequest::prefix(
9046                "alph",
9047            ))
9048            .unwrap();
9049        assert_eq!(terms, vec![vec![1u8]]);
9050        assert_eq!(
9051            service.text_index_fingerprint().unwrap().as_deref(),
9052            Some("text-index-v1;self")
9053        );
9054        assert_eq!(
9055            service.describe().text_index_epoch,
9056            None,
9057            "a self-created index is untrusted until a walk stamps it"
9058        );
9059
9060        // Without the launcher config: a put before any build fails NotBuilt
9061        // (the pre-self-create behavior, unchanged for unconfigured spawns).
9062        let bare = PartitionService::memory(PartitionAxis::O);
9063        let error = bare.apply_text(&[text_doc(1, "alpha")]).unwrap_err();
9064        assert!(error.to_string().contains("not been built"), "{error}");
9065    }
9066
9067    /// Populate a memory partition with one predicate's rows over several
9068    /// objects, subjects and graphs — enough for the differential matrix to
9069    /// exercise every branch of the unary walk selection.
9070    fn differential_store(service: &PartitionService, axis: PartitionAxis) {
9071        let graph = |iri: Option<&str>| match iri {
9072            Some(iri) => GraphName::from(waratah_storage::NamedNode::new(iri).unwrap()),
9073            None => GraphName::DefaultGraph,
9074        };
9075        let mut quads = Vec::new();
9076        // Two objects x two subjects under one predicate (multi-seek and
9077        // per-term branches), one duplicate triple in a named graph (merge
9078        // collapse), and an unrelated predicate (plain-branch noise).
9079        for (subject, object) in [
9080            ("http://ex/s1", "http://ex/o1"),
9081            ("http://ex/s2", "http://ex/o1"),
9082            ("http://ex/s3", "http://ex/o2"),
9083            ("http://ex/s4", "http://ex/o2"),
9084        ] {
9085            quads.push(waratah_storage::Quad::new(
9086                waratah_storage::NamedNode::new(subject).unwrap(),
9087                waratah_storage::NamedNode::new("http://ex/p").unwrap(),
9088                waratah_storage::NamedNode::new(object).unwrap(),
9089                GraphName::DefaultGraph,
9090            ));
9091        }
9092        // (s1, p, o1) again in a named graph: under merge_default_graph the
9093        // second G-variant of the same triple collapses and G returns as the
9094        // default graph on both paths.
9095        quads.push(waratah_storage::Quad::new(
9096            waratah_storage::NamedNode::new("http://ex/s1").unwrap(),
9097            waratah_storage::NamedNode::new("http://ex/p").unwrap(),
9098            waratah_storage::NamedNode::new("http://ex/o1").unwrap(),
9099            graph(Some("http://ex/g1")),
9100        ));
9101        quads.push(waratah_storage::Quad::new(
9102            waratah_storage::NamedNode::new("http://ex/s5").unwrap(),
9103            waratah_storage::NamedNode::new("http://ex/other").unwrap(),
9104            waratah_storage::NamedNode::new("http://ex/o1").unwrap(),
9105            graph(Some("http://ex/g2")),
9106        ));
9107        let versions: Vec<QuadVersion> = quads
9108            .into_iter()
9109            .map(|quad| QuadVersion {
9110                quad: waratah_storage::encode_quad(&quad).unwrap(),
9111                commit_ts: CommitTs(1),
9112                op: waratah_storage::StorageOp::Put,
9113                visibility: waratah_storage::VisibilityLabel::default(),
9114            })
9115            .collect();
9116        service.apply_versions(Some(axis), &versions).unwrap();
9117    }
9118
9119    /// Decode a packed page with the request's own pattern — the same
9120    /// reassembly the gRPC unary client performs.
9121    fn decode_packed(
9122        page: &pb::ScanPatternResponse,
9123        pattern: &EncodedTriplePattern,
9124        omitted: u8,
9125    ) -> Vec<EncodedQuad> {
9126        page.quads
9127            .iter()
9128            .map(|quad| quad_from_proto_omitting(quad, pattern, omitted).unwrap())
9129            .collect()
9130    }
9131
9132    fn pattern_p(pred: Option<&str>, object: Option<&str>) -> EncodedTriplePattern {
9133        let term = |iri: &str| EncodedTerm::from(&waratah_storage::NamedNode::new(iri).unwrap());
9134        EncodedTriplePattern {
9135            subject: None,
9136            predicate: pred.map(term),
9137            object: object.map(term),
9138            graph_name: None,
9139        }
9140    }
9141
9142    /// The packed unary page and the decoded reference page must return the
9143    /// same rows in the same order on every branch of the unary walk
9144    /// selection — plain, single-term, multi-seek, limit, `start_after`
9145    /// (a limit-k page is a prefix of the unbounded run), default-graph
9146    /// merge, and a bound-slot mask. Only bound masks assert row equality:
9147    /// a dead slot's packed row carries the counted-presence sentinel where
9148    /// the decoded row carries the stored term (asserted separately below),
9149    /// which is exactly why dead bits ride only on cursor-free requests.
9150    #[test]
9151    fn packed_page_matches_the_decoded_page_on_every_walk_branch() {
9152        let service = PartitionService::memory(PartitionAxis::P);
9153        differential_store(&service, PartitionAxis::P);
9154        let snapshot = SnapshotId::latest();
9155
9156        // One case per unary walk branch: name, pattern, filter slot +
9157        // terms, limit, merge_default_graph, omitted mask.
9158        struct Case {
9159            name: &'static str,
9160            pattern: EncodedTriplePattern,
9161            slot: Option<PatternSlot>,
9162            terms: Vec<EncodedTerm>,
9163            limit: u64,
9164            merge: bool,
9165            omitted: u8,
9166        }
9167        let term = |iri: &str| EncodedTerm::from(&waratah_storage::NamedNode::new(iri).unwrap());
9168        let bound_subject = EncodedTriplePattern {
9169            subject: Some(term("http://ex/s1")),
9170            predicate: Some(term("http://ex/p")),
9171            object: None,
9172            graph_name: None,
9173        };
9174        let cases = vec![
9175            Case {
9176                name: "plain",
9177                pattern: pattern_p(Some("http://ex/p"), None),
9178                slot: None,
9179                terms: vec![],
9180                limit: 0,
9181                merge: false,
9182                omitted: OMIT_NONE,
9183            },
9184            Case {
9185                name: "limit",
9186                pattern: pattern_p(Some("http://ex/p"), None),
9187                slot: None,
9188                terms: vec![],
9189                limit: 2,
9190                merge: false,
9191                omitted: OMIT_NONE,
9192            },
9193            Case {
9194                name: "per-term",
9195                pattern: pattern_p(Some("http://ex/p"), None),
9196                slot: Some(PatternSlot::Object),
9197                terms: vec![term("http://ex/o1")],
9198                limit: 0,
9199                merge: false,
9200                omitted: OMIT_NONE,
9201            },
9202            Case {
9203                name: "multi-seek",
9204                pattern: pattern_p(Some("http://ex/p"), None),
9205                slot: Some(PatternSlot::Object),
9206                terms: vec![term("http://ex/o1"), term("http://ex/o2")],
9207                limit: 0,
9208                merge: false,
9209                omitted: OMIT_NONE,
9210            },
9211            Case {
9212                name: "multi-seek-limit",
9213                pattern: pattern_p(Some("http://ex/p"), None),
9214                slot: Some(PatternSlot::Object),
9215                terms: vec![term("http://ex/o1"), term("http://ex/o2")],
9216                limit: 3,
9217                merge: false,
9218                omitted: OMIT_NONE,
9219            },
9220            Case {
9221                name: "bound-mask",
9222                pattern: bound_subject,
9223                slot: None,
9224                terms: vec![],
9225                limit: 0,
9226                merge: false,
9227                omitted: OMIT_SUBJECT,
9228            },
9229            Case {
9230                name: "merge-default",
9231                pattern: pattern_p(Some("http://ex/p"), None),
9232                slot: None,
9233                terms: vec![],
9234                limit: 0,
9235                merge: true,
9236                omitted: OMIT_NONE,
9237            },
9238        ];
9239
9240        for Case {
9241            name,
9242            pattern,
9243            slot,
9244            terms,
9245            limit,
9246            merge,
9247            omitted,
9248        } in &cases
9249        {
9250            let (decoded, _) = service
9251                .scan_filtered(
9252                    None,
9253                    pattern,
9254                    snapshot,
9255                    *limit,
9256                    *slot,
9257                    terms,
9258                    None,
9259                    &[],
9260                    false,
9261                    *merge,
9262                    IriOnlyMask::NONE,
9263                    true,
9264                )
9265                .unwrap_or_else(|e| panic!("{name}: decoded walk failed: {e}"));
9266            let packed = decode_packed(
9267                &service
9268                    .scan_filtered_packed(
9269                        None,
9270                        pattern,
9271                        snapshot,
9272                        *limit,
9273                        *slot,
9274                        terms,
9275                        None,
9276                        &[],
9277                        false,
9278                        *merge,
9279                        IriOnlyMask::NONE,
9280                        &[],
9281                        *omitted,
9282                        true,
9283                    )
9284                    .unwrap_or_else(|e| panic!("{name}: packed walk failed: {e}")),
9285                pattern,
9286                *omitted,
9287            );
9288            assert_eq!(decoded, packed, "{name}: rows must match in order");
9289        }
9290
9291        // start_after resumption: the cursor is a WHOLE-TRIPLE skip (all
9292        // G-variants of the cursor's S/P/O, per the RowMatcher's dedup
9293        // cursor), so the tail is only a clean prefix when the cursor row's
9294        // triple has no other graph variant in the fixture. The last such
9295        // row's tail must be identical on both paths, in order.
9296        let pattern = pattern_p(Some("http://ex/p"), None);
9297        let (full, _) = service
9298            .scan_filtered(
9299                None,
9300                &pattern,
9301                snapshot,
9302                0,
9303                None,
9304                &[],
9305                None,
9306                &[],
9307                false,
9308                false,
9309                IriOnlyMask::NONE,
9310                true,
9311            )
9312            .unwrap();
9313        assert!(full.len() >= 4, "fixture rows missing: {}", full.len());
9314        let triple = |quad: &EncodedQuad| {
9315            (
9316                quad.subject.clone(),
9317                quad.predicate.clone(),
9318                quad.object.clone(),
9319            )
9320        };
9321        let resume_index = full
9322            .iter()
9323            .rposition(|row| {
9324                full.iter()
9325                    .filter(|other| triple(other) == triple(row))
9326                    .count()
9327                    == 1
9328            })
9329            .expect("fixture has a triple-unique row");
9330        let resume_at = full[resume_index].clone();
9331        let (decoded_resume, _) = service
9332            .scan_filtered(
9333                None,
9334                &pattern,
9335                snapshot,
9336                0,
9337                None,
9338                &[],
9339                Some(&resume_at),
9340                &[],
9341                false,
9342                false,
9343                IriOnlyMask::NONE,
9344                true,
9345            )
9346            .unwrap();
9347        let packed_resume = decode_packed(
9348            &service
9349                .scan_filtered_packed(
9350                    None,
9351                    &pattern,
9352                    snapshot,
9353                    0,
9354                    None,
9355                    &[],
9356                    Some(&resume_at),
9357                    &[],
9358                    false,
9359                    false,
9360                    IriOnlyMask::NONE,
9361                    &[],
9362                    OMIT_NONE,
9363                    true,
9364                )
9365                .unwrap(),
9366            &pattern,
9367            OMIT_NONE,
9368        );
9369        assert_eq!(
9370            decoded_resume,
9371            &full[resume_index + 1..],
9372            "decoded page prefix property"
9373        );
9374        assert_eq!(
9375            packed_resume,
9376            &full[resume_index + 1..],
9377            "packed page prefix property"
9378        );
9379    }
9380
9381    /// A masked slot carries no bytes on the wire — the test that fails if
9382    /// the mask is silently ignored. Row equality cannot prove this: a bound
9383    /// slot reassembles to the same term either way.
9384    #[test]
9385    fn packed_masked_page_omits_the_masked_slot_bytes() {
9386        let service = PartitionService::memory(PartitionAxis::P);
9387        differential_store(&service, PartitionAxis::P);
9388        let pattern = pattern_p(Some("http://ex/p"), None);
9389
9390        // Dead subject slot (unbound in the pattern): empty field on the
9391        // wire, sentinel term after decode.
9392        let masked = service
9393            .scan_filtered_packed(
9394                None,
9395                &pattern,
9396                SnapshotId::latest(),
9397                0,
9398                None,
9399                &[],
9400                None,
9401                &[],
9402                false,
9403                false,
9404                IriOnlyMask::NONE,
9405                &[],
9406                OMIT_SUBJECT,
9407                true,
9408            )
9409            .unwrap();
9410        assert!(!masked.quads.is_empty());
9411        for quad in &masked.quads {
9412            assert!(quad.subject.is_empty(), "dead subject must carry no bytes");
9413        }
9414        let decoded = quad_from_proto_omitting(&masked.quads[0], &pattern, OMIT_SUBJECT).unwrap();
9415        assert_eq!(
9416            decoded.subject,
9417            waratah_storage::ENCODED_TERM_TRUE,
9418            "a dead slot reads as the counted-presence sentinel"
9419        );
9420        let wire_bytes: usize = masked
9421            .quads
9422            .iter()
9423            .map(|q| q.subject.len() + q.predicate.len() + q.object.len() + q.graph_name.len())
9424            .sum();
9425        let unmasked = service
9426            .scan_filtered_packed(
9427                None,
9428                &pattern,
9429                SnapshotId::latest(),
9430                0,
9431                None,
9432                &[],
9433                None,
9434                &[],
9435                false,
9436                false,
9437                IriOnlyMask::NONE,
9438                &[],
9439                OMIT_NONE,
9440                true,
9441            )
9442            .unwrap();
9443        let unmasked_bytes: usize = unmasked
9444            .quads
9445            .iter()
9446            .map(|q| q.subject.len() + q.predicate.len() + q.object.len() + q.graph_name.len())
9447            .sum();
9448        assert!(
9449            wire_bytes < unmasked_bytes,
9450            "masked page must be strictly smaller: {wire_bytes} vs {unmasked_bytes}"
9451        );
9452
9453        // The decoded reference path returns the real subject where the
9454        // masked packed path returns the sentinel — the value change that
9455        // forbids dead bits on paged requests.
9456        let (reference, _) = service
9457            .scan_filtered(
9458                None,
9459                &pattern,
9460                SnapshotId::latest(),
9461                0,
9462                None,
9463                &[],
9464                None,
9465                &[],
9466                false,
9467                false,
9468                IriOnlyMask::NONE,
9469                true,
9470            )
9471            .unwrap();
9472        assert_ne!(decoded.subject, reference[0].subject);
9473    }
9474
9475    /// Tsg rows: the packed page synthesises the rdf:type predicate at slice
9476    /// time (`wire_quad`), and a masked Tsg predicate restores from the
9477    /// request's bound term — the same terms the decoded path injects.
9478    #[test]
9479    fn packed_tsg_page_carries_rdf_type_like_the_decoded_page() {
9480        let rdf_type = EncodedTerm::from(
9481            &waratah_storage::NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
9482                .unwrap(),
9483        );
9484        let nn = |iri: &str| EncodedTerm::from(&waratah_storage::NamedNode::new(iri).unwrap());
9485        let service = PartitionService::memory(PartitionAxis::O);
9486        let quads = [
9487            ("http://ex/alice", "http://ex/Person"),
9488            ("http://ex/bob", "http://ex/Person"),
9489        ]
9490        .into_iter()
9491        .map(|(subject, class)| {
9492            waratah_storage::encode_quad(&waratah_storage::Quad::new(
9493                waratah_storage::NamedNode::new(subject).unwrap(),
9494                waratah_storage::NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
9495                    .unwrap(),
9496                waratah_storage::NamedNode::new(class).unwrap(),
9497                GraphName::DefaultGraph,
9498            ))
9499            .unwrap()
9500        })
9501        .map(|quad| QuadVersion {
9502            quad,
9503            commit_ts: CommitTs(1),
9504            op: waratah_storage::StorageOp::Put,
9505            visibility: waratah_storage::VisibilityLabel::default(),
9506        })
9507        .collect::<Vec<_>>();
9508        service
9509            .apply_versions(Some(PartitionAxis::O), &quads)
9510            .unwrap();
9511
9512        let pattern = EncodedTriplePattern {
9513            subject: None,
9514            predicate: Some(rdf_type.clone()),
9515            object: None,
9516            graph_name: None,
9517        };
9518        for omitted in [OMIT_NONE, OMIT_PREDICATE] {
9519            let (decoded, _) = service
9520                .scan_filtered(
9521                    Some(IndexPermutation::Tsg),
9522                    &pattern,
9523                    SnapshotId::latest(),
9524                    0,
9525                    None,
9526                    &[],
9527                    None,
9528                    &[],
9529                    false,
9530                    false,
9531                    IriOnlyMask::NONE,
9532                    true,
9533                )
9534                .unwrap();
9535            let packed = decode_packed(
9536                &service
9537                    .scan_filtered_packed(
9538                        Some(IndexPermutation::Tsg),
9539                        &pattern,
9540                        SnapshotId::latest(),
9541                        0,
9542                        None,
9543                        &[],
9544                        None,
9545                        &[],
9546                        false,
9547                        false,
9548                        IriOnlyMask::NONE,
9549                        &[],
9550                        omitted,
9551                        true,
9552                    )
9553                    .unwrap(),
9554                &pattern,
9555                omitted,
9556            );
9557            assert_eq!(decoded.len(), 2);
9558            assert_eq!(decoded, packed, "omitted={omitted}: Tsg rows must match");
9559            if omitted == OMIT_NONE {
9560                assert_eq!(packed[0].predicate, rdf_type);
9561                assert_eq!(packed[1].predicate, rdf_type);
9562            }
9563            // Key order, not insertion order: alice/bob sort by hash.
9564            let subjects: Vec<_> = packed.iter().map(|q| q.subject.clone()).collect();
9565            assert!(subjects.contains(&nn("http://ex/alice")));
9566            assert!(subjects.contains(&nn("http://ex/bob")));
9567        }
9568    }
9569}