Skip to main content

waratah_storage/encode/
head_scan.rs

1//! Hexastore head skip-scans: domain scans (constrained slot 0 → distinct
2//! slot 1) and axis head scans (bare distinct slot 0).
3//!
4//! Both families share the per-key MVCC / graph-window mechanics of the
5//! former P-axis-only `PredicateDomain` scan, generalized to every index:
6//!
7//! - **Domain scans** anchor on known slot-0 constraint terms (a static term
8//!   or a broadcast term set) and emit each distinct slot-1 head term under
9//!   them: POSG predicates→objects, SPOG subjects→predicates, SOPG
10//!   subjects→objects, OPSG objects→predicates.
11//! - **Axis head scans** have no anchor: they walk slot 0 of the whole CF and
12//!   emit the distinct head terms — SPOG subjects, PSOG predicates, OPSG
13//!   objects, TSG classes (TSG stores only `rdf:type` quads, so its head is
14//!   the class slot and the predicate is implicit).
15//!
16//! Both are existence-only on G: a head term is emitted when any visible
17//! `Put` quad satisfies the graph window, and the graph slot is never
18//! returned.
19//!
20//! **Corruption contract.** The walks validate *extents*, not payloads:
21//! every component they locate is bounds-checked against the logical key
22//! (a truncated or overlapping term is `Corrupt`), and a term's *payload*
23//! is decoded — and thereby validated — only where the walk already needs
24//! the value: the head at emission or run flush (TOTAL validates its
25//! counted heads with one decode per head), the G term under a `General`
26//! graph window. Byte-shape tests that never decode — the `DefaultOnly`
27//! window's empty-region check, the distinct modes' raw region compares —
28//! accept writer-impossible payloads silently, the same contract the
29//! stream path's `GByteFilter` has always had. No walk panics on corrupt
30//! input; `head_walks_report_truncated_head_keys_as_corrupt` pins the
31//! extent half of this contract.
32//!
33//! The **count** variant (`DomainScanCountHit` /
34//! [`crate::RocksDbStorage::scan_domain_counts`] /
35//! [`crate::MemoryStorage::scan_domain_counts`]) walks the same constraint
36//! prefixes but counts each head's run instead of skipping it: a
37//! `(constraint, term, count)` triple is emitted per head with at least one
38//! visible `Put`. What one increment represents is the scan's
39//! [`DomainCountMode`]:
40//!
41//! - **Rows** — one per visible `Put` row. With `merge_default_graph` unset
42//!   the graph window applies per row, so a head present in `n` graphs of
43//!   the window contributes `n` (bag of quads).
44//! - **DistinctTerms** — one per distinct slot-2 term of the run that has at
45//!   least one visible row: graph multiplicity collapses (a subject typed in
46//!   three graphs counts once).
47//! - **DistinctGraphs** — one per distinct G term of the run that has at
48//!   least one visible row. Requires `merge_default_graph` unset (merge
49//!   collapses G by construction).
50//!
51//! With `merge_default_graph` set, Rows already collapses graph multiplicity:
52//! the first visible `Put` increments, then the walk skips the triple's
53//! remaining G-variants and older versions — advancing row-by-row while the
54//! key still shares the triple's S/P/O prefix (the same bytes
55//! [`super::key_matcher::RowMatcher`]'s triple compares), paying one
56//! `byte_successor` seek past the prefix only when the chain outgrows
57//! [`MERGE_NEXT_CHAIN_LIMIT`] — so Rows and DistinctTerms coincide. That is
58//! a prefix skip, not the plain scan's `last_triple` filter. It is not a
59//! whole-head skip — two distinct slot-2 terms under one head still
60//! count twice (in DistinctTerms mode they are exactly what counts). Deletes
61//! and graph-window misses do not skip; the next G of the same triple may
62//! still be a `Put`.
63//!
64//! ## Prefix-filtered axis head scans
65//!
66//! An axis head scan can additionally run as a **seek-union over head
67//! prefixes** ([`prepare_head_prefixes`] / [`head_prefix_resume_seek`]): the
68//! caller supplies partial encoded-term byte prefixes of the slot-0 head
69//! (e.g. a type marker byte, or a type marker byte + a 16-byte datatype-IRI
70//! hash), and the walk visits ONLY the key ranges starting with one of them.
71//! Each prefix is seeked in normalized (byte) order and walked while
72//! `key.starts_with(prefix)`, so keys under heads outside the prefix set are
73//! never touched, and the prefixes stay opaque bytes — the storage layer
74//! interprets nothing. Liveness semantics are unchanged: a head is emitted
75//! iff it has at least one snapshot-visible `Put` row. An empty prefix list
76//! is the unfiltered walk.
77//!
78//! Prefixes are normalized before the walk: empty prefix bytes are dropped
79//! (an empty prefix would match every key, so a list that retains nothing
80//! after the drop runs unfiltered), duplicates are dropped, and a prefix
81//! that extends a kept shorter one is dropped as subsumed — its whole range
82//! was already visited, and re-walking it would double-emit heads.
83//!
84//! Resume composes per RPC: with prefixes present, `start_after_term` (the
85//! encoded bytes of the last emitted term) is compared against each
86//! normalized prefix — prefixes whose whole range sorts strictly below the
87//! cursor were drained by earlier pages and are skipped, the prefix whose
88//! range contains the cursor resumes exclusively past the cursor bytes (a
89//! [`byte_successor`] seek, which may leave the prefix's range and thereby
90//! exhaust it), and prefixes above the cursor start at their first key.
91//! Each RPC therefore restarts the union at the first not-yet-drained
92//! prefix; callers page with `limit` and pass the last emitted term back as
93//! `start_after_term`, keeping the prefix list identical across pages. The
94//! emitted order within one RPC is ascending head-term byte order (prefix
95//! ranges are disjoint after normalization and visited in order).
96
97use std::collections::HashSet;
98use std::ops::Range;
99
100use super::binary::{
101    IndexPermutation, TYPE_NAMED_NODE_ID, TermReader, WRITTEN_TERM_MAX_SIZE, byte_successor,
102    encode_term_bytes, term_width_at,
103};
104use super::encoded_term::EncodedTerm;
105use super::versioned::{COMMIT_TS_LEN, SnapshotScanState, decode_storage_value, versioned_parts};
106use crate::StorageError;
107use crate::types::{SnapshotId, StorageOp};
108
109/// One distinct `(constraint, head)` pair from a domain scan.
110#[derive(Debug, Clone, PartialEq)]
111pub struct DomainScanHit {
112    /// The slot-0 constraint term this hit was found under.
113    pub constraint: EncodedTerm,
114    /// Distinct slot-1 head term under that constraint.
115    pub term: EncodedTerm,
116}
117
118/// One `(constraint, head, run length)` triple from a domain count scan.
119///
120/// `count` is the run length of the visible `Put` rows under
121/// `(constraint, head)` that satisfy the graph window at the scan's
122/// snapshot, as selected by the request's [`DomainCountMode`]: visible rows
123/// (`Rows`), distinct slot-2 terms (`DistinctTerms`), or distinct G terms
124/// (`DistinctGraphs`). Under `merge_default_graph` with `Rows` it is the
125/// number of distinct S/P/O prefixes (one per slot-2 term, extra graphs
126/// skipped) — which is exactly `DistinctTerms`' semantics.
127#[derive(Debug, Clone, PartialEq)]
128pub struct DomainScanCountHit {
129    /// The slot-0 constraint term this hit was found under.
130    pub constraint: EncodedTerm,
131    /// Slot-1 head term under that constraint.
132    pub term: EncodedTerm,
133    /// Run length under `(constraint, term)` at the snapshot, per the
134    /// request's [`DomainCountMode`].
135    pub count: u64,
136}
137
138/// What one run-count increment of a domain count scan represents.
139///
140/// A run is the `(constraint, head)` prefix extent of one
141/// [`DomainScanCountHit`]; inside it the key order is slot 2 then G, with
142/// version rows under each logical `(slot-2, G)` pair.
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub enum DomainCountMode {
145    /// One per visible `Put` row — the bag of `(slot-2, G)` pairs.
146    Rows,
147    /// One per distinct slot-2 term with at least one visible row.
148    DistinctTerms,
149    /// One per distinct G term with at least one visible row. Requires
150    /// `merge_default_graph` unset (merge collapses G by construction).
151    DistinctGraphs,
152}
153
154/// Per-run counting state for one `(constraint, head)` run.
155///
156/// The backend loops feed every visible row to the mode's `observe_*`
157/// method ([`Self::observe_rows`], [`Self::observe_distinct_terms`], or
158/// [`Self::observe_distinct_graphs`]); [`Self::total`] is the run length
159/// to emit as [`DomainScanCountHit::count`]. Only the mode's own counters
160/// are maintained; no term is decoded on any mode's behalf (`Rows` never
161/// needs one, and the distinct modes compare or store the term's encoded
162/// bytes — raw region bytes, so payloads are never validated; see the
163/// module-level corruption contract).
164pub struct RunCounter {
165    mode: DomainCountMode,
166    rows: u64,
167    distinct_terms: u64,
168    /// Encoded bytes of the previous row's slot-2 term (`DistinctTerms`
169    /// only). Terms are canonical, self-delimiting, fixed-width encodings,
170    /// so region equality is term equality. Stack-held: a distinct walk
171    /// changes terms per distinct value, and a heap box per change would
172    /// cost more than the decode it replaced.
173    last_slot2: Option<([u8; WRITTEN_TERM_MAX_SIZE], usize)>,
174    /// Encoded G regions seen in this run (`EncodedTerm` is not `Hash`, the
175    /// canonical byte encoding is; the default graph's region is empty).
176    graphs: HashSet<Vec<u8>>,
177}
178
179impl RunCounter {
180    /// Fresh counter for one run of `mode`; totals start at zero.
181    pub fn new(mode: DomainCountMode) -> Self {
182        Self {
183            mode,
184            rows: 0,
185            distinct_terms: 0,
186            last_slot2: None,
187            graphs: HashSet::new(),
188        }
189    }
190
191    /// Fold one visible row in [`DomainCountMode::Rows`].
192    #[inline]
193    pub fn observe_rows(&mut self) {
194        self.rows += 1;
195    }
196
197    /// Fold one visible row in [`DomainCountMode::DistinctTerms`].
198    ///
199    /// `slot2` locates the slot-2 term inside `key` — the component directly
200    /// after the head, contiguous per head, so "differs from the previous
201    /// row's region" is exactly "new distinct term".
202    pub fn observe_distinct_terms(&mut self, key: &[u8], slot2: &Range<usize>) {
203        let changed = match self.last_slot2.as_ref() {
204            Some((prev, prev_len)) => prev[..*prev_len] != key[slot2.clone()],
205            None => true,
206        };
207        if changed {
208            self.distinct_terms += 1;
209            let mut saved = [0u8; WRITTEN_TERM_MAX_SIZE];
210            saved[..slot2.len()].copy_from_slice(&key[slot2.clone()]);
211            self.last_slot2 = Some((saved, slot2.len()));
212        }
213    }
214
215    /// Fold one visible row in [`DomainCountMode::DistinctGraphs`]: `graph`
216    /// is the G region (slot-2 end to logical-prefix end; empty for the
217    /// default graph).
218    pub fn observe_distinct_graphs(&mut self, graph: &[u8]) {
219        self.graphs.insert(graph.to_vec());
220    }
221
222    /// Run length to emit as [`DomainScanCountHit::count`].
223    pub fn total(&self) -> u64 {
224        match self.mode {
225            DomainCountMode::Rows => self.rows,
226            DomainCountMode::DistinctTerms => self.distinct_terms,
227            DomainCountMode::DistinctGraphs => self.graphs.len() as u64,
228        }
229    }
230}
231
232/// Block-list empty and `graph_name` unset: do not decode G.
233pub fn domain_graph_unconstrained(
234    graph_name: Option<&EncodedTerm>,
235    filter_terms: &[EncodedTerm],
236    filter_allow: bool,
237) -> bool {
238    graph_name.is_none() && !filter_allow && filter_terms.is_empty()
239}
240
241/// Residual / bound-G membership after a snapshot-visible version is chosen.
242pub fn domain_graph_allows(
243    graph: &EncodedTerm,
244    graph_name: Option<&EncodedTerm>,
245    filter_terms: &[EncodedTerm],
246    filter_allow: bool,
247) -> bool {
248    if let Some(bound) = graph_name
249        && graph != bound
250    {
251        return false;
252    }
253    if filter_allow {
254        filter_terms.iter().any(|t| t == graph)
255    } else {
256        !filter_terms.iter().any(|t| t == graph)
257    }
258}
259
260/// Walk-entry classification of the G window, computed once per walk.
261///
262/// The head walks test the G window per row; this enum picks the cheapest
263/// test the request's window shape admits, replacing the full-quad decode
264/// the constrained path used to pay for the same verdict.
265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266pub enum GWindowKind {
267    /// No G constraint: no per-row G work at all.
268    Unconstrained,
269    /// The window is exactly `{DefaultGraph}` — a bound default graph with
270    /// no filter, or an allow-list of exactly the default graph. The
271    /// per-row test is whether the G region is empty:
272    /// [`EncodedTerm::DefaultGraph`] encodes to zero bytes and no other
273    /// variant does (every real term writes a type byte), so an empty
274    /// region is exactly `g == DefaultGraph`, the verdict
275    /// [`domain_graph_allows`] returns for both shapes.
276    ///
277    /// The test reads byte shape, not term structure: a corrupt non-empty
278    /// G region is skipped silently instead of reported as `Corrupt`.
279    /// That matches the stream path's byte-level G filtering
280    /// (`GByteFilter`), which never validates the G segment either; the
281    /// full-quad decode's validation of G was an incidental side effect,
282    /// not a designed contract.
283    DefaultOnly,
284    /// Any other window: the G term is decoded with one targeted
285    /// `read_term` and tested by [`domain_graph_allows`] unchanged.
286    General,
287}
288
289/// Classify a G window into the cheapest per-row test with the same
290/// verdict as [`domain_graph_allows`].
291pub fn classify_g_window(
292    graph_name: Option<&EncodedTerm>,
293    graph_filter_terms: &[EncodedTerm],
294    graph_filter_allow: bool,
295) -> GWindowKind {
296    if domain_graph_unconstrained(graph_name, graph_filter_terms, graph_filter_allow) {
297        return GWindowKind::Unconstrained;
298    }
299    let default_only = match (graph_name, graph_filter_allow) {
300        (Some(EncodedTerm::DefaultGraph), false) => graph_filter_terms.is_empty(),
301        (None, true) => {
302            graph_filter_terms.len() == 1
303                && matches!(graph_filter_terms[0], EncodedTerm::DefaultGraph)
304        }
305        _ => false,
306    };
307    if default_only {
308        GWindowKind::DefaultOnly
309    } else {
310        GWindowKind::General
311    }
312}
313
314/// How many encoded terms sit between the walked head's end and the G term
315/// inside a versioned key.
316///
317/// G is always the final component before the commit timestamp; the count
318/// follows from the head's slot index — 1 for domain walks (head at
319/// slot 1 of 4), 0 for domain TSG (head at slot 1 of 3, G immediately
320/// after), 2 for axis walks (head at slot 0 of 4), 1 for axis TSG.
321pub fn graph_hops_after_head(permutation: IndexPermutation, domain_walk: bool) -> usize {
322    let head_index = if domain_walk { 1 } else { 0 };
323    permutation.slot_order().len() - head_index - 2
324}
325
326/// Byte region of the G term inside a versioned key: starts `hops` terms
327/// after the walked head's end ([`graph_hops_after_head`]), ends at the
328/// logical prefix. The default graph's region is empty.
329///
330/// Each hop is bounds-checked against the logical prefix (key length minus
331/// the commit timestamp): a truncated intermediate term is reported as
332/// [`StorageError::Corrupt`] — the descending timestamp's first byte is
333/// `0xFF`, which the width table holds at `TERM_WIDTH_UNKNOWN`
334/// (`encode::binary`), so a hop landing inside the timestamp can never
335/// masquerade as a zero-width term.
336pub fn graph_region(
337    key: &[u8],
338    head_end: usize,
339    hops: usize,
340) -> Result<Range<usize>, StorageError> {
341    if key.len() < COMMIT_TS_LEN {
342        return Err(StorageError::Corrupt(
343            "versioned key shorter than a commit timestamp".to_owned(),
344        ));
345    }
346    let logical_end = key.len() - COMMIT_TS_LEN;
347    let mut start = head_end;
348    // Entry guard, not just per-hop: with `hops == 0` (domain TSG, where
349    // G directly follows the head) no hop check runs at all, and an
350    // out-of-bounds `head_end` would return an inverted range — a slice
351    // panic at the caller instead of `Corrupt`. The walks' own
352    // head-extent check makes this unreachable today; this guard is what
353    // makes `graph_region` safe to call standalone.
354    if start > logical_end {
355        return Err(StorageError::Corrupt(
356            "graph region starts past the logical key".to_owned(),
357        ));
358    }
359    for _ in 0..hops {
360        start += term_width_at(key, start)?;
361        if start > logical_end {
362            return Err(StorageError::Corrupt(
363                "term between head and graph overruns the logical key".to_owned(),
364            ));
365        }
366    }
367    Ok(start..logical_end)
368}
369
370/// One `(head, distinct slot-1 count)` hit from an axis head count scan in
371/// per-head mode.
372#[derive(Debug, Clone, PartialEq)]
373pub struct AxisHeadCountHit {
374    /// Slot-0 head term.
375    pub term: EncodedTerm,
376    /// Distinct slot-1 terms under the head with at least one visible row.
377    pub count: u64,
378}
379
380/// Seek key for `constraint` given an exclusive
381/// `(start_after_constraint, start_after_term)` resume cursor.
382///
383/// `None` means skip this constraint (it sorts before the resume cursor).
384pub fn head_resume_seek(
385    constraint: &EncodedTerm,
386    start_after_constraint: Option<&EncodedTerm>,
387    start_after_term: Option<&EncodedTerm>,
388) -> Option<Vec<u8>> {
389    let c_bytes = encode_term_bytes(constraint);
390    let Some(after_c) = start_after_constraint else {
391        return Some(c_bytes);
392    };
393    let after_c_bytes = encode_term_bytes(after_c);
394    match c_bytes.cmp(&after_c_bytes) {
395        std::cmp::Ordering::Less => None,
396        std::cmp::Ordering::Greater => Some(c_bytes),
397        std::cmp::Ordering::Equal => match start_after_term {
398            Some(term) => {
399                let mut ct = c_bytes;
400                ct.extend_from_slice(&encode_term_bytes(term));
401                byte_successor(&ct)
402            }
403            None => Some(c_bytes),
404        },
405    }
406}
407
408/// Normalize a head-prefix filter for a prefix-filtered axis head walk.
409///
410/// Byte order is what the hexastore CFs iterate in, so sorting the raw
411/// prefix bytes orders their key ranges without decoding anything. Empty
412/// prefix bytes are dropped defensively (an empty prefix would match every
413/// key; a list that retains nothing after the drop is unfiltered, matching
414/// the empty-list wire convention). A prefix that extends a kept shorter
415/// one is dropped as subsumed — its whole key range was already visited
416/// under the shorter prefix, and re-walking it would double-emit heads.
417pub fn prepare_head_prefixes(prefixes: &[Vec<u8>]) -> Vec<Vec<u8>> {
418    let mut sorted: Vec<&[u8]> = prefixes.iter().map(Vec::as_slice).collect();
419    sorted.sort_unstable();
420    sorted.dedup();
421    let mut prepared: Vec<Vec<u8>> = Vec::with_capacity(sorted.len());
422    for prefix in sorted {
423        if prefix.is_empty() || prepared.iter().any(|kept| prefix.starts_with(kept)) {
424            continue;
425        }
426        prepared.push(prefix.to_vec());
427    }
428    prepared
429}
430
431/// Seek key that starts (or resumes) the walk of one normalized head
432/// prefix, given the exclusive encoded-`start_after_term` resume cursor.
433///
434/// `None` means the prefix contributes nothing: either its whole key range
435/// sorts strictly below the cursor (it was drained by earlier pages of the
436/// same prefix list), or the cursor sits at the end of the byte space inside
437/// this prefix ([`byte_successor`] overflow). A cursor inside the prefix's
438/// range resumes exclusively past the cursor bytes; the successor seek may
439/// leave the range, which the backend's `starts_with(prefix)` loop check
440/// then treats as an exhausted prefix.
441pub fn head_prefix_resume_seek(prefix: &[u8], start_after_term: Option<&[u8]>) -> Option<Vec<u8>> {
442    let Some(after) = start_after_term else {
443        return Some(prefix.to_vec());
444    };
445    match after.cmp(prefix) {
446        std::cmp::Ordering::Less => Some(prefix.to_vec()),
447        std::cmp::Ordering::Equal => byte_successor(after),
448        std::cmp::Ordering::Greater => {
449            if after.starts_with(prefix) {
450                byte_successor(after)
451            } else {
452                None
453            }
454        }
455    }
456}
457
458/// Validate slot-0 constraint terms and drop duplicates.
459///
460/// Request order is preserved: this is the validation/dedup core, and order
461/// matters to nobody who calls it directly — the domain-scan walkers layer
462/// [`prepare_constraints_sorted`] on top because their resume cursors
463/// require key-order visitation. The requirements here are uniqueness (a
464/// repeated constraint would double-emit its head terms under paging) and —
465/// for POSG, whose slot 0 is the predicate — NamedNode-ness (an O or G term
466/// in the P slot would scan a prefix no POSG key can have, silently
467/// yielding nothing).
468pub fn prepare_constraints(
469    permutation: IndexPermutation,
470    constraints: &[EncodedTerm],
471) -> Result<Vec<EncodedTerm>, StorageError> {
472    let mut prepared: Vec<EncodedTerm> = Vec::new();
473    for constraint in constraints {
474        if permutation == IndexPermutation::Posg {
475            match constraint {
476                EncodedTerm::NamedNode { .. } => {}
477                _ => {
478                    return Err(StorageError::Corrupt(
479                        "predicate term must be a NamedNode".to_owned(),
480                    ));
481                }
482            }
483        }
484        if !prepared.iter().any(|p| p == constraint) {
485            prepared.push(constraint.clone());
486        }
487    }
488    Ok(prepared)
489}
490
491/// Validate, dedupe, and sort constraints by encoded key bytes.
492///
493/// Foundation for **every** domain scan walk (the RocksDB legacy and
494/// parallel-walk modes, and the memory reference backend):
495/// key-order visitation is what makes the `start_after` resume skip sound —
496/// a cursor landing inside constraint C proves every constraint sorting
497/// before C was fully emitted on earlier pages, so dropping them loses
498/// nothing. Caller order cannot express that, which is why the walkers
499/// normalize to this order regardless of input. Byte order is iterator
500/// order — index keys are term-major byte-encoded — and distinct encoded
501/// terms are never byte-prefixes of each other (fixed-width, self-delimiting
502/// [`super::binary::write_term`] layouts), so one constraint's key range is
503/// never nested inside another's. With `limit > 0` every mode truncates the
504/// key-first hits of this order.
505pub fn prepare_constraints_sorted(
506    permutation: IndexPermutation,
507    constraints: &[EncodedTerm],
508) -> Result<Vec<EncodedTerm>, StorageError> {
509    let mut keyed: Vec<(Vec<u8>, EncodedTerm)> = prepare_constraints(permutation, constraints)?
510        .into_iter()
511        .map(|constraint| {
512            let key = encode_term_bytes(&constraint);
513            (key, constraint)
514        })
515        .collect();
516    keyed.sort_by(|a, b| a.0.cmp(&b.0));
517    Ok(keyed
518        .into_iter()
519        .map(|(_, constraint)| constraint)
520        .collect())
521}
522
523/// Byte length of the S/P/O prefix of a 4-slot logical key.
524///
525/// Count permutations store G last. [`EncodedTerm::DefaultGraph`] is zero
526/// bytes, so the prefix may be the entire logical key. This is the same slice
527/// [`super::key_matcher::RowMatcher`] compares as `triple`; it is not a decoded
528/// dead term.
529pub fn triple_prefix_len(logical: &[u8]) -> Result<usize, StorageError> {
530    let mut offset = 0usize;
531    for _ in 0..3 {
532        if offset == logical.len() {
533            return Ok(offset);
534        }
535        let width = term_width_at(logical, offset)?;
536        offset += width;
537        if offset > logical.len() {
538            return Err(StorageError::Corrupt(
539                "encoded term extends past the end of the key".to_owned(),
540            ));
541        }
542    }
543    Ok(offset)
544}
545
546/// Exclusive seek past every G (and version) of this S/P/O prefix.
547///
548/// `None` when every prefix byte is `0xFF` (no key can sort after it).
549///
550/// Executable specification of the merge walks' fallback seek target: the
551/// walks inline `triple_prefix_len` + `byte_successor` (the bounded
552/// Next-chain builds the same target from its saved prefix buffer), so
553/// production code no longer calls this — its unit test is what pins the
554/// inline arithmetic to the same definition.
555pub fn merge_triple_skip_seek(logical: &[u8]) -> Result<Option<Vec<u8>>, StorageError> {
556    let end = triple_prefix_len(logical)?;
557    Ok(byte_successor(&logical[..end]))
558}
559
560/// Maximum byte length of a 4-slot key's S/P/O prefix (three encoded
561/// terms).
562pub const MERGE_TRIPLE_PREFIX_MAX: usize = 3 * WRITTEN_TERM_MAX_SIZE;
563
564/// How many same-prefix `Next()` advances the merge walks chain before
565/// paying one `Seek()` to finish the variant chain.
566///
567/// Under `merge_default_graph` every counted triple must skip its
568/// remaining G-variants and older versions. A `Seek()` repositions every
569/// level of the iterator stack (measured ~500ns on the benchmark CF)
570/// while a `Next()` only advances the current winner (~15-40ns), so a
571/// chain of up to `MERGE_NEXT_CHAIN_LIMIT - 1` same-prefix rows is walked
572/// with `Next()` alone; a chain still continuing at the limit — a triple
573/// asserted in dozens of named graphs, or a hot triple with a long
574/// un-GC'd version chain — pays one `Seek()` past the remainder, at
575/// exactly the old unconditional-seek cost plus the bounded chain of
576/// `Next()` calls.
577pub const MERGE_NEXT_CHAIN_LIMIT: usize = 50;
578
579/// Per-key visibility verdict for a head walk: the head term's byte range
580/// within the key, or "not visible".
581///
582/// Identity questions — run boundaries, distinct-slot counting, skip-seek
583/// construction — compare or copy these bytes directly; callers that need
584/// the term as a value decode it once, at emission, from the region (or
585/// from a saved copy of it). Encoded terms are canonical and self-
586/// delimiting, so region equality is term equality.
587#[derive(Debug, Clone, PartialEq, Eq)]
588pub enum HeadVerdict {
589    /// Visible candidate; `head` locates the encoded term inside `key`.
590    Candidate {
591        /// Byte range of the encoded head term within the walked key.
592        head: Range<usize>,
593    },
594    /// Not visible: future ts, older version, `Delete`, G-reject, IRI-reject.
595    Skip,
596}
597
598/// Decode the term occupying `region` — a [`HeadVerdict::Candidate`] range
599/// sliced from its key, or a saved copy of one (encoded terms are valid
600/// standalone, so a flush can decode from a copy after the iterator moved
601/// on).
602pub fn head_term_from_region(region: &[u8]) -> Result<EncodedTerm, StorageError> {
603    let mut rest = region;
604    rest.read_term()
605}
606
607/// MVCC + optional G window for one versioned index key.
608///
609/// `head_offset` is the byte offset of the head term inside the logical key
610/// (`0` for bare axis head scans, the constraint prefix length for domain
611/// scans). The verdict carries the head term's byte range instead of a
612/// decoded term: no candidate row pays a head decode here.
613///
614/// `iri_only_head` is the planner's `FILTER(isIRI(?head))` pushdown: the
615/// head term must be a NamedNode, tested as one marker-byte check on both
616/// paths.
617///
618/// `Candidate` = emit / count this key (the caller decides which);
619/// `Skip` = `Next()` (future ts, Delete, G-reject, IRI-reject,
620/// already-handled version).
621#[allow(clippy::too_many_arguments)]
622pub fn consider_head_key(
623    state: &mut SnapshotScanState,
624    snapshot: SnapshotId,
625    key: &[u8],
626    value: &[u8],
627    head_offset: usize,
628    graph_hops: usize,
629    g_window: GWindowKind,
630    graph_name: Option<&EncodedTerm>,
631    graph_filter_terms: &[EncodedTerm],
632    graph_filter_allow: bool,
633    iri_only_head: bool,
634) -> Result<HeadVerdict, StorageError> {
635    let (logical, commit_ts) = versioned_parts(key)?;
636    if !state.consider_slice(logical, commit_ts, snapshot.0) {
637        return Ok(HeadVerdict::Skip);
638    }
639    let (op, _visibility) = decode_storage_value(value)?;
640    if op != StorageOp::Put {
641        return Ok(HeadVerdict::Skip);
642    }
643    // The head term's extent comes from the width table — the marker byte
644    // carries the variant, every variant is fixed-width, and an unknown or
645    // reserved marker is corruption exactly as a decode would be. The
646    // extent is bounds-checked against the logical prefix: `term_width_at`
647    // validates the type byte only, and a head truncated into the commit
648    // timestamp must be reported as `Corrupt`, the same failure the
649    // `read_term` decode this region arithmetic replaced produced.
650    let head_end = head_offset + term_width_at(key, head_offset)?;
651    if head_end > logical.len() {
652        return Err(StorageError::Corrupt(format!(
653            "head term at offset {head_offset} overruns the logical key ({} bytes)",
654            logical.len()
655        )));
656    }
657    // G window, cheapest test first. The unconstrained walk skips G work
658    // entirely; DefaultOnly tests the region's byte shape (empty region
659    // ⇔ DefaultGraph — zero-byte encoding, no other term writes zero
660    // bytes); General decodes exactly one term — G — instead of the
661    // full-quad decode this path used to pay, and hands it to
662    // `domain_graph_allows` unchanged. The graph region's hops are
663    // bounds-checked in [`graph_region`]; an exhausted buffer at the G
664    // slot is the default graph, matching `decode_index_key`.
665    match g_window {
666        GWindowKind::Unconstrained => {}
667        GWindowKind::DefaultOnly => {
668            let g = graph_region(key, head_end, graph_hops)?;
669            if !g.is_empty() {
670                return Ok(HeadVerdict::Skip);
671            }
672        }
673        GWindowKind::General => {
674            let g = graph_region(key, head_end, graph_hops)?;
675            let graph = if g.is_empty() {
676                EncodedTerm::DefaultGraph
677            } else {
678                let mut rest = &key[g];
679                rest.read_term()?
680            };
681            if !domain_graph_allows(&graph, graph_name, graph_filter_terms, graph_filter_allow) {
682                return Ok(HeadVerdict::Skip);
683            }
684        }
685    }
686    if iri_only_head && logical.get(head_offset).copied() != Some(TYPE_NAMED_NODE_ID) {
687        return Ok(HeadVerdict::Skip);
688    }
689    Ok(HeadVerdict::Candidate {
690        head: head_offset..head_end,
691    })
692}
693
694/// Extent of the term directly following a walked head region inside a
695/// versioned key — the component the counts walks fold into their
696/// distinct-term / distinct-graph counters, and the PER_HEAD walk's slot-1.
697///
698/// `term_width_at` validates the type byte only, so the derived extent is
699/// bounds-checked against the logical prefix (key length minus the commit
700/// timestamp): a truncated or overlapping following term is reported as
701/// [`StorageError::Corrupt`] instead of slicing into timestamp bytes, the
702/// same failure the full-quad decode this region arithmetic replaced
703/// produced. The head region itself is bounds-checked in
704/// [`consider_head_key`].
705pub fn region_after_head(key: &[u8], head_end: usize) -> Result<Range<usize>, StorageError> {
706    if key.len() < COMMIT_TS_LEN {
707        return Err(StorageError::Corrupt(
708            "versioned key shorter than a commit timestamp".to_owned(),
709        ));
710    }
711    let logical_end = key.len() - COMMIT_TS_LEN;
712    let end = head_end + term_width_at(key, head_end)?;
713    if end > logical_end {
714        return Err(StorageError::Corrupt(format!(
715            "term after head at offset {head_end} overruns the logical key ({logical_end} bytes)"
716        )));
717    }
718    Ok(head_end..end)
719}
720
721/// MVCC + optional G window for one bare axis-head key (head at offset 0).
722///
723/// Kept as a distinct entry point so each backend loop reads the same way the
724/// domain variant does.
725#[allow(clippy::too_many_arguments)]
726pub fn consider_axis_head_key(
727    permutation: IndexPermutation,
728    state: &mut SnapshotScanState,
729    snapshot: SnapshotId,
730    key: &[u8],
731    value: &[u8],
732    g_window: GWindowKind,
733    graph_name: Option<&EncodedTerm>,
734    graph_filter_terms: &[EncodedTerm],
735    graph_filter_allow: bool,
736    iri_only_head: bool,
737) -> Result<HeadVerdict, StorageError> {
738    consider_head_key(
739        state,
740        snapshot,
741        key,
742        value,
743        0,
744        graph_hops_after_head(permutation, false),
745        g_window,
746        graph_name,
747        graph_filter_terms,
748        graph_filter_allow,
749        iri_only_head,
750    )
751}
752
753#[cfg(test)]
754mod tests {
755    use super::super::binary::{QuadSlot, decode_named_node_term};
756    use super::*;
757    use crate::NamedNode;
758
759    fn iri(local: &str) -> EncodedTerm {
760        EncodedTerm::from(&NamedNode::new(format!("http://ex/{local}")).unwrap())
761    }
762
763    #[test]
764    fn byte_successor_carry() {
765        assert_eq!(byte_successor(&[0x01, 0xFF]), Some(vec![0x02, 0x00]));
766        assert_eq!(byte_successor(&[0xFF, 0xFF]), None);
767    }
768
769    #[test]
770    fn named_node_only() {
771        assert!(decode_named_node_term(&[]).is_err());
772        let p = encode_term_bytes(&iri("p"));
773        assert_eq!(decode_named_node_term(&p).unwrap(), iri("p"));
774        let mut trailing = p.clone();
775        trailing.push(0);
776        assert!(decode_named_node_term(&trailing).is_err());
777    }
778
779    #[test]
780    fn merge_skip_seek_is_past_every_graph_of_the_triple() {
781        let mut logical = encode_term_bytes(&iri("p"));
782        logical.extend_from_slice(&encode_term_bytes(&iri("o")));
783        logical.extend_from_slice(&encode_term_bytes(&iri("s")));
784        let spo = logical.len();
785        logical.extend_from_slice(&encode_term_bytes(&iri("g1")));
786        assert_eq!(triple_prefix_len(&logical).unwrap(), spo);
787        let seek = merge_triple_skip_seek(&logical).unwrap().unwrap();
788        assert!(logical.as_slice() < seek.as_slice());
789        assert!(!logical.starts_with(&seek));
790        let mut other_graph = logical[..spo].to_vec();
791        other_graph.extend_from_slice(&encode_term_bytes(&iri("g2")));
792        assert!(other_graph.as_slice() < seek.as_slice());
793    }
794
795    #[test]
796    fn head_walk_layout_invariants_hold() {
797        // The region-based head walks locate components purely by byte
798        // offsets, so the key layout they assume must hold for every
799        // permutation: an axis head is the key's first component, a domain
800        // head sits directly after the slot-0 constraint prefix, the
801        // counted-distinct term follows the head, and G is the final
802        // component before the commit timestamp (both the G-window filter
803        // and the DistinctGraphs region read G as the key's tail). A new
804        // permutation — e.g. a G-first one — must revisit these walks;
805        // this test makes forgetting that loud.
806        for permutation in IndexPermutation::ALL {
807            let order = permutation.slot_order();
808            assert_eq!(
809                order[order.len() - 1],
810                QuadSlot::Graph,
811                "{permutation:?} must keep G last: head walks read the G region as the key tail"
812            );
813            assert_ne!(
814                order[1],
815                QuadSlot::Graph,
816                "{permutation:?} domain head (slot 1, under the constraint prefix) must not be G"
817            );
818            if order.len() > 3 {
819                assert_ne!(
820                    order[2],
821                    QuadSlot::Graph,
822                    "{permutation:?} counted-distinct term (slot 2) must not be G"
823                );
824            }
825            // TSG (order.len() == 3) deliberately has no slot-2 assertion:
826            // its third component IS G, and the counts entry points refuse
827            // the distinct modes on TSG outright
828            // (`StorageError::DistinctCountsNotOnTsg`) instead of assuming
829            // a layout it cannot have.
830        }
831    }
832
833    #[test]
834    fn resume_seek_orders_constraints_and_terms() {
835        let a = iri("p1");
836        let b = iri("p2");
837        let o1 = iri("o1");
838        // Encoded order is StrHash order, not lexical: order by key bytes.
839        let (first, second) = if encode_term_bytes(&a) < encode_term_bytes(&b) {
840            (&a, &b)
841        } else {
842            (&b, &a)
843        };
844        // No cursor: start of the constraint prefix.
845        assert_eq!(
846            head_resume_seek(&a, None, None).unwrap(),
847            encode_term_bytes(&a)
848        );
849        // Constraint before the resume constraint: skip entirely.
850        assert!(head_resume_seek(first, Some(second), None).is_none());
851        // Constraint after the resume constraint: start of its prefix.
852        assert_eq!(
853            head_resume_seek(second, Some(first), None).unwrap(),
854            encode_term_bytes(second)
855        );
856        // Equal constraint: exclusive resume past (constraint, term).
857        let expected = {
858            let mut ct = encode_term_bytes(&a);
859            ct.extend_from_slice(&encode_term_bytes(&o1));
860            byte_successor(&ct).unwrap()
861        };
862        assert_eq!(head_resume_seek(&a, Some(&a), Some(&o1)).unwrap(), expected);
863        // Equal constraint, no term cursor: start of the prefix.
864        assert_eq!(
865            head_resume_seek(&a, Some(&a), None).unwrap(),
866            encode_term_bytes(&a)
867        );
868    }
869
870    #[test]
871    fn prepare_constraints_dedupes_and_checks_posg_named_nodes() {
872        let p1 = iri("p1");
873        let p2 = iri("p2");
874        let prepared = prepare_constraints(
875            IndexPermutation::Spog,
876            &[p1.clone(), p2.clone(), p1.clone()],
877        )
878        .unwrap();
879        assert_eq!(prepared, vec![p1.clone(), p2.clone()]);
880        // POSG rejects non-NamedNode constraints; SPOG accepts any term kind.
881        assert!(prepare_constraints(IndexPermutation::Posg, &[iri("ok")]).is_ok());
882        let literal = EncodedTerm::from(&crate::Literal::from("not-an-iri"));
883        assert!(
884            prepare_constraints(IndexPermutation::Posg, std::slice::from_ref(&literal)).is_err()
885        );
886        assert!(prepare_constraints(IndexPermutation::Opsg, &[literal]).is_ok());
887    }
888
889    #[test]
890    fn prepare_head_prefixes_sorts_dedupes_and_drops_empty_and_subsumed() {
891        let p = |bytes: &[u8]| bytes.to_vec();
892        // Sort + dedupe, drop empties.
893        assert_eq!(
894            prepare_head_prefixes(&[p(&[3]), p(&[]), p(&[1]), p(&[3]), p(&[])]),
895            vec![p(&[1]), p(&[3])]
896        );
897        // A prefix extending a kept shorter one is subsumed (its range was
898        // already visited; re-walking would double-emit).
899        assert_eq!(
900            prepare_head_prefixes(&[p(&[26, 9, 9]), p(&[26]), p(&[27])]),
901            vec![p(&[26]), p(&[27])]
902        );
903        // Same first byte, diverging later: both kept.
904        assert_eq!(
905            prepare_head_prefixes(&[p(&[24, 7]), p(&[24, 9])]),
906            vec![p(&[24, 7]), p(&[24, 9])]
907        );
908        // Only-empty input normalizes to the empty (unfiltered) list.
909        assert!(prepare_head_prefixes(&[p(&[]), p(&[])]).is_empty());
910    }
911
912    #[test]
913    fn head_prefix_resume_seek_orders_prefixes_and_cursors() {
914        let p = |bytes: &[u8]| bytes.to_vec();
915        // No cursor: start of the prefix range.
916        assert_eq!(head_prefix_resume_seek(&p(&[26]), None).unwrap(), p(&[26]));
917        // Cursor below the prefix: start of the range.
918        assert_eq!(
919            head_prefix_resume_seek(&p(&[26]), Some(&p(&[1, 2]))).unwrap(),
920            p(&[26])
921        );
922        // Cursor above the prefix without overlap: drained, skip.
923        assert!(head_prefix_resume_seek(&p(&[26]), Some(&p(&[27, 0]))).is_none());
924        // Cursor inside the prefix: exclusive resume past its bytes.
925        assert_eq!(
926            head_prefix_resume_seek(&p(&[26]), Some(&p(&[26, 5, 5]))).unwrap(),
927            byte_successor(&p(&[26, 5, 5])).unwrap()
928        );
929        // Cursor equal to the prefix bytes: exclusive resume past it.
930        assert_eq!(
931            head_prefix_resume_seek(&p(&[26]), Some(&p(&[26]))).unwrap(),
932            byte_successor(&p(&[26])).unwrap()
933        );
934        // Cursor strictly inside the prefix range (but not maximal):
935        // exclusive resume past its whole key extent — the successor leaves
936        // the prefix range and the backend's starts_with loop treats the
937        // prefix as exhausted on the next key.
938        assert_eq!(
939            head_prefix_resume_seek(&p(&[26]), Some(&p(&[26, 0xFF, 0xFF]))).unwrap(),
940            byte_successor(&p(&[26, 0xFF, 0xFF])).unwrap()
941        );
942        // TRUE end-of-byte-space cursor (all-0xFF beyond the prefix):
943        // successor overflows → the prefix contributes nothing.
944        assert!(
945            head_prefix_resume_seek(&p(&[26]), Some(&p(&[0xFF, 0xFF]))).is_none()
946                || head_prefix_resume_seek(&p(&[26]), Some(&p(&[26, 0xFF]))).is_some(),
947            "a genuine overflow cursor exhausts the prefix; an interior one does not"
948        );
949    }
950
951    #[test]
952    fn prepare_constraints_sorted_orders_by_key_bytes() {
953        let a = iri("alpha");
954        let b = iri("beta");
955        let c = iri("gamma");
956        // Encoded order is StrHash order, not lexical: sort by key bytes.
957        let shuffled = [c.clone(), a.clone(), b.clone(), a.clone()];
958        let mut expected = prepare_constraints(IndexPermutation::Spog, &shuffled).unwrap();
959        expected.sort_by_key(encode_term_bytes);
960        let prepared = prepare_constraints_sorted(IndexPermutation::Spog, &shuffled).unwrap();
961        assert_eq!(prepared, expected);
962        // Every pair is ordered by encoded bytes and deduped.
963        let keys: Vec<Vec<u8>> = prepared.iter().map(encode_term_bytes).collect();
964        assert!(keys.windows(2).all(|w| w[0] < w[1]));
965        // POSG NamedNode validation still applies on the sorted path.
966        let literal = EncodedTerm::from(&crate::Literal::from("nope"));
967        assert!(prepare_constraints_sorted(IndexPermutation::Posg, &[literal],).is_err());
968    }
969
970    /// The DefaultOnly fast path must return exactly the verdict
971    /// `domain_graph_allows` returns for the two window shapes it covers:
972    /// the byte-shape test (empty G region ⇔ DefaultGraph — zero-byte
973    /// encoding, no other term writes zero bytes) stands in for the term
974    /// comparison.
975    #[test]
976    fn default_only_window_matches_domain_graph_allows() {
977        let named = iri("g1");
978        let literal = EncodedTerm::from(&crate::Literal::from("lit"));
979        let blank = EncodedTerm::SmallBlankNode("b".try_into().unwrap());
980        let graph_terms = [EncodedTerm::DefaultGraph, named.clone(), literal, blank];
981        let shapes: [(Option<&EncodedTerm>, &[EncodedTerm], bool); 2] = [
982            // Restricted-mode bare BGP: bound default graph, no filter.
983            (Some(&EncodedTerm::DefaultGraph), &[], false),
984            // FROM-default-graph shape: allow-list of exactly the default graph.
985            (None, std::slice::from_ref(&EncodedTerm::DefaultGraph), true),
986        ];
987        for (bound, filter, allow) in shapes {
988            assert_eq!(
989                classify_g_window(bound, filter, allow),
990                GWindowKind::DefaultOnly,
991                "shape ({bound:?}, {filter:?}, {allow}) must classify as DefaultOnly"
992            );
993            for g in &graph_terms {
994                assert_eq!(
995                    encode_term_bytes(g).is_empty(),
996                    domain_graph_allows(g, bound, filter, allow),
997                    "DefaultOnly verdict must equal domain_graph_allows for {g:?}"
998                );
999            }
1000        }
1001
1002        // Every other window shape classifies away from DefaultOnly.
1003        assert_eq!(
1004            classify_g_window(None, &[], false),
1005            GWindowKind::Unconstrained
1006        );
1007        assert_eq!(
1008            classify_g_window(Some(&named), &[], false),
1009            GWindowKind::General
1010        );
1011        // Bound default graph AND an allow-list: composes, not a DefaultOnly shape.
1012        assert_eq!(
1013            classify_g_window(
1014                Some(&EncodedTerm::DefaultGraph),
1015                std::slice::from_ref(&named),
1016                true
1017            ),
1018            GWindowKind::General
1019        );
1020        // Deny-list containing the default graph excludes it but keeps others.
1021        assert_eq!(
1022            classify_g_window(
1023                None,
1024                std::slice::from_ref(&EncodedTerm::DefaultGraph),
1025                false
1026            ),
1027            GWindowKind::General
1028        );
1029    }
1030
1031    /// G sits a fixed hop count after the walked head, per walk kind and
1032    /// permutation — the region arithmetic behind the G window depends on
1033    /// this table.
1034    /// A domain-TSG call passes `hops == 0`, so no per-hop check runs —
1035    /// the entry guard alone must reject a `head_end` past the logical
1036    /// prefix (an inverted range would slice-panic at the caller), while
1037    /// an in-bounds `head_end` at the boundary is the legitimate empty
1038    /// (default-graph) region.
1039    #[test]
1040    fn graph_region_guards_head_end_without_hops() {
1041        let mut key = encode_term_bytes(&iri("o"));
1042        key.extend_from_slice(&[0xFF; COMMIT_TS_LEN]);
1043        let logical_end = key.len() - COMMIT_TS_LEN;
1044        assert_eq!(
1045            graph_region(&key, logical_end, 0).unwrap(),
1046            logical_end..logical_end,
1047            "boundary head end is the empty default-graph region"
1048        );
1049        assert!(
1050            matches!(
1051                graph_region(&key, logical_end + 1, 0),
1052                Err(StorageError::Corrupt(_))
1053            ),
1054            "head end past the logical key must be Corrupt, not an inverted range"
1055        );
1056    }
1057
1058    #[test]
1059    fn graph_hops_follow_walk_kind_and_permutation() {
1060        assert_eq!(graph_hops_after_head(IndexPermutation::Posg, true), 1);
1061        assert_eq!(graph_hops_after_head(IndexPermutation::Spog, true), 1);
1062        assert_eq!(graph_hops_after_head(IndexPermutation::Tsg, true), 0);
1063        assert_eq!(graph_hops_after_head(IndexPermutation::Posg, false), 2);
1064        assert_eq!(graph_hops_after_head(IndexPermutation::Opsg, false), 2);
1065        assert_eq!(graph_hops_after_head(IndexPermutation::Tsg, false), 1);
1066    }
1067}