Skip to main content

waratah_storage/encode/
key_matcher.rs

1//! Decode-free pattern-scan row matching over raw hexastore keys.
2//!
3//! The partition walk used to decode every visited row into an
4//! [`EncodedQuad`] just to decide visibility and pattern fit. Here the same
5//! decisions run on raw bytes: slot offsets come from the [`TERM_WIDTH`]
6//! width table ([`super::binary::term_width_at`]), bound-slot checks are
7//! slice compares against pre-encoded expectation bytes, and graph
8//! membership runs on the raw graph segment. Wire rows are emitted as
9//! [`KeyRow`] slices of the key buffer — callers decode (unary paths) or
10//! copy slices (streaming) only after a row has passed every check.
11
12use super::binary::{
13    IndexPermutation, QuadSlot, TYPE_NAMED_NODE_ID, WRITTEN_TERM_MAX_SIZE, encode_term_bytes,
14    term_width_at, write_term,
15};
16use super::encoded_term::{EncodedQuad, EncodedTerm, RDF_TYPE};
17use super::pattern::{EncodedTriplePattern, term_in_quad_slot};
18use super::str_hash::{StrHash, StrHashSet, new_str_hash_set};
19use super::versioned::{COMMIT_TS_LEN, STORAGE_VALUE_LEN, SnapshotScanState, decode_storage_value};
20use crate::StorageError;
21use crate::types::{CommitTs, SnapshotId, StorageOp};
22
23/// IRI-only slot flags pushed by the planner (`FILTER(isIRI(?x))` pushdown).
24///
25/// Subject/object only: the predicate slot can only ever begin with the
26/// NamedNode marker, and the graph slot is not pushed (compute filters G
27/// itself). The SPARQL filter stays in the plan as the source of truth; this
28/// mask is a partition-side pre-filter, not a semantic replacement.
29#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
30pub struct IriOnlyMask {
31    /// Subject segments must begin with the NamedNode marker.
32    pub subject: bool,
33    /// Object segments must begin with the NamedNode marker.
34    pub object: bool,
35}
36
37impl IriOnlyMask {
38    /// No pushdown: every segment kind is accepted.
39    pub const NONE: Self = Self {
40        subject: false,
41        object: false,
42    };
43
44    /// Key-position indexes (into `slot_order`) whose segment's first byte
45    /// must be [`TYPE_NAMED_NODE_ID`]. Slots the pattern already binds
46    /// exactly are skipped: a prefix-enforced slot cannot violate the mask,
47    /// and a residual bound slot gets a full byte compare anyway.
48    fn compile_checks(
49        self,
50        pattern: &EncodedTriplePattern,
51        order: &[QuadSlot],
52        enforced: usize,
53    ) -> Vec<usize> {
54        let mut checks = Vec::new();
55        for (index, slot) in order.iter().enumerate().skip(enforced) {
56            let masked = match slot {
57                QuadSlot::Subject => self.subject,
58                QuadSlot::Object => self.object,
59                QuadSlot::Predicate | QuadSlot::Graph => false,
60            };
61            if masked && pattern.bound_slot(*slot).is_none() {
62                checks.push(index);
63            }
64        }
65        checks
66    }
67}
68
69/// Byte-level residual graph-membership window (twin of the old decoded-term
70/// `GraphMembership`).
71///
72/// Compiled once per scan from the request's graph-filter terms and polarity;
73/// evaluated per row on the raw graph segment (empty = default graph).
74#[derive(Debug, Clone)]
75pub enum GByteFilter {
76    /// Empty block-list: no graph constraint at all.
77    Unconstrained,
78    /// Empty allow-list: no graph can match; the scan is trivially empty.
79    EmptyWindow,
80    /// Constrained window over named IRIs, the default graph, and other
81    /// (blank / literal) graph terms compared as full encoded slices.
82    Window {
83        /// `true` = allow-list (keep members); `false` = block-list (drop members).
84        allow: bool,
85        /// Named-node graphs by IRI hash (identity lookup, no second SipHash).
86        named: StrHashSet,
87        /// Whether the RDF default graph participates in the window.
88        default_graph: bool,
89        /// Blank-node (and any non-named) graph terms as encoded byte strings.
90        extras: Vec<Vec<u8>>,
91    },
92}
93
94impl GByteFilter {
95    /// Compile the byte-level window from graph-filter terms and polarity.
96    ///
97    /// Empty terms: `allow = false` is [`GByteFilter::Unconstrained`] (a
98    /// block-list that blocks nothing), `allow = true` is
99    /// [`GByteFilter::EmptyWindow`] (an allow-list that allows nothing).
100    pub fn compile(terms: &[EncodedTerm], allow: bool) -> Self {
101        if terms.is_empty() {
102            return if allow {
103                Self::EmptyWindow
104            } else {
105                Self::Unconstrained
106            };
107        }
108        let mut named = new_str_hash_set();
109        let mut extras = Vec::new();
110        let mut default_graph = false;
111        for term in terms {
112            match term {
113                EncodedTerm::NamedNode { iri_id } => {
114                    named.insert(*iri_id);
115                }
116                EncodedTerm::DefaultGraph => {
117                    default_graph = true;
118                }
119                other => {
120                    let bytes = encode_term_bytes(other);
121                    if !extras.contains(&bytes) {
122                        extras.push(bytes);
123                    }
124                }
125            }
126        }
127        Self::Window {
128            allow,
129            named,
130            default_graph,
131            extras,
132        }
133    }
134
135    /// `true` for [`GByteFilter::EmptyWindow`] (no row can pass).
136    pub fn empty_window(&self) -> bool {
137        matches!(self, Self::EmptyWindow)
138    }
139
140    /// `true` for [`GByteFilter::Unconstrained`] (no row is filtered).
141    pub fn unconstrained(&self) -> bool {
142        matches!(self, Self::Unconstrained)
143    }
144
145    /// Membership on a raw graph segment (empty = default graph).
146    ///
147    /// Segments are width-walked before this runs, so a named-node segment is
148    /// exactly `1 ‖ 16 hash bytes`.
149    pub fn keeps_segment(&self, graph: &[u8]) -> bool {
150        let (allow, named, default_graph, extras) = match self {
151            Self::Unconstrained => return true,
152            Self::EmptyWindow => return false,
153            Self::Window {
154                allow,
155                named,
156                default_graph,
157                extras,
158            } => (*allow, named, *default_graph, extras),
159        };
160        let member = if graph.is_empty() {
161            default_graph
162        } else if graph.len() == 17 && graph[0] == TYPE_NAMED_NODE_ID {
163            let iri_id = StrHash::from_be_bytes(
164                graph[1..17]
165                    .try_into()
166                    .expect("segment length checked above"),
167            );
168            named.contains(&iri_id)
169        } else {
170            extras.iter().any(|extra| extra.as_slice() == graph)
171        };
172        member == allow
173    }
174
175    /// Membership on a decoded graph term (unary paths that already decoded).
176    pub fn keeps_term(&self, graph: &EncodedTerm) -> bool {
177        match graph {
178            EncodedTerm::DefaultGraph => self.keeps_segment(&[]),
179            EncodedTerm::NamedNode { iri_id } => {
180                let mut segment = [0u8; 17];
181                segment[0] = TYPE_NAMED_NODE_ID;
182                segment[1..].copy_from_slice(&iri_id.to_be_bytes());
183                self.keeps_segment(&segment)
184            }
185            other => self.keeps_segment(&encode_term_bytes(other)),
186        }
187    }
188}
189
190/// One raw versioned hexastore row handed to a scan's emit callback.
191///
192/// `key` is `slot_order(permutation)` terms concatenated plus the 8-byte
193/// descending `commit_ts` trailer; `seg_starts[i]` is the byte offset of key
194/// slot `i` in [`IndexPermutation::slot_order`] order. On
195/// [`IndexPermutation::Tsg`] (three slots) `seg_starts[3]` is the end of the
196/// term prefix. Rows borrow the iterator's buffer — copy out before the walk
197/// advances.
198#[derive(Debug, Clone, Copy)]
199pub struct KeyRow<'k> {
200    /// Full versioned key (term bytes ‖ descending `commit_ts`).
201    pub key: &'k [u8],
202    /// Index permutation this row was walked in.
203    pub permutation: IndexPermutation,
204    /// Start offset of each key slot (see the struct docs).
205    pub seg_starts: [usize; 4],
206    /// Commit timestamp from the fixed key trailer.
207    pub commit_ts: CommitTs,
208}
209
210impl<'k> KeyRow<'k> {
211    /// Walk a versioned key (slot terms ‖ descending `commit_ts` trailer)
212    /// and build the borrowing row view. A re-encoded row (no natural
213    /// trailer) appends any 8 bytes — the timestamp is only read by the
214    /// MVCC walk, never by wire emission.
215    ///
216    /// Errors with [`StorageError::Corrupt`] on a short trailer, an unknown
217    /// type byte, or a term prefix that does not exactly cover the key.
218    pub fn from_versioned_key(
219        key: &'k [u8],
220        permutation: IndexPermutation,
221    ) -> Result<KeyRow<'k>, StorageError> {
222        if key.len() < COMMIT_TS_LEN {
223            return Err(StorageError::Corrupt(format!(
224                "versioned key too short: {} bytes",
225                key.len()
226            )));
227        }
228        let term_len = key.len() - COMMIT_TS_LEN;
229        let trailer: [u8; COMMIT_TS_LEN] = key[term_len..]
230            .try_into()
231            .expect("trailer length checked above");
232        Ok(KeyRow {
233            key,
234            permutation,
235            seg_starts: walk_slot_starts(&key[..term_len], permutation)?,
236            commit_ts: CommitTs::from_descending_be_bytes(trailer),
237        })
238    }
239
240    /// Term bytes without the `commit_ts` trailer (the MVCC logical key).
241    pub fn logical(&self) -> &[u8] {
242        &self.key[..self.key.len() - COMMIT_TS_LEN]
243    }
244
245    /// Raw bytes of the key slot at `index` in `slot_order` order.
246    pub fn slot_bytes_at(&self, index: usize) -> &[u8] {
247        let order_len = self.permutation.slot_order().len();
248        let end = if index + 1 < order_len {
249            self.seg_starts[index + 1]
250        } else {
251            self.logical().len()
252        };
253        &self.key[self.seg_starts[index]..end]
254    }
255
256    /// Raw bytes of a quad slot; `None` when the permutation omits it (the
257    /// Tsg predicate, implicit `rdf:type`). An empty slice is the default
258    /// graph's zero-length encoding.
259    pub fn slot_bytes(&self, slot: QuadSlot) -> Option<&[u8]> {
260        self.permutation
261            .slot_order()
262            .iter()
263            .position(|s| *s == slot)
264            .map(|index| self.slot_bytes_at(index))
265    }
266
267    /// Raw bytes of the graph segment (empty = default graph).
268    ///
269    /// Every permutation ends with the graph slot.
270    pub fn graph_segment(&self) -> &[u8] {
271        self.slot_bytes(QuadSlot::Graph)
272            .expect("every permutation ends with the graph slot")
273    }
274
275    /// All slots before the graph (the S‖P‖O identity in key order).
276    ///
277    /// Equal triples have equal prefixes: slot encodings are fixed-size per
278    /// type byte, so byte equality of the prefix is [`EncodedQuad::same_triple`]
279    /// without decoding. On Tsg the prefix is O‖S (the predicate is constant).
280    pub fn triple_prefix(&self) -> &[u8] {
281        let order = self.permutation.slot_order();
282        &self.key[..self.seg_starts[order.len() - 1]]
283    }
284}
285
286/// Verdict of [`RowMatcher::matches_row`] for one visited row.
287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288pub enum MatchDecision {
289    /// Not a visible Put for this scan; the walk moves on.
290    Skip,
291    /// A visible Put for this scan; the walked slot starts locate every
292    /// segment for the emitter.
293    Emit {
294        /// Start offset of each key slot (see [`KeyRow::seg_starts`]).
295        slot_starts: [usize; 4],
296        /// Commit timestamp from the key trailer.
297        commit_ts: CommitTs,
298    },
299}
300
301/// Compiled per-scan row matcher replacing per-row key decoding.
302///
303/// One matcher per iterator walk (one per tight prefix on multi-seek scans).
304/// `matches_row` runs the exact pipeline of the retired
305/// `visible_matching_put` + `pattern.matches` + graph filter + dedup:
306///
307/// 1. `commit_ts` from the fixed trailer; the logical key is the term prefix.
308/// 2. MVCC collapse via [`SnapshotScanState::consider_slice`] (reusable
309///    buffer) — before any term work.
310/// 3. `op == Put` from the fixed 5-byte value.
311/// 4. Width-table slot walk, then residual bound-slot checks, graph
312///    membership, dedup cursor and whole-triple collapse — all on raw bytes.
313pub struct RowMatcher {
314    permutation: IndexPermutation,
315    /// Slot index (in `slot_order`) of the graph segment.
316    g_index: usize,
317    /// `(slot index, expected bytes)` for bound slots the iterator range does
318    /// not already enforce, in key order.
319    checks: Vec<(usize, Vec<u8>)>,
320    /// The pattern contradicts the index (bound predicate on Tsg that is not
321    /// `rdf:type`): no key can ever match.
322    impossible: bool,
323    /// Residual graph-membership window.
324    g_filter: GByteFilter,
325    /// Emit only the first visible row of each S‖P‖O prefix
326    /// (`merge_default_graph` merge-default scans).
327    merge_default_graph: bool,
328    /// While set (`merge_default_graph` + `start_after`): rows whose triple prefix
329    /// equals the cursor's are skipped until the first differing row.
330    cursor_triple: Option<Vec<u8>>,
331    /// Triple prefix of the previously emitted row (`merge_default_graph` state).
332    last_triple: Vec<u8>,
333    /// Key-position indexes (into `slot_order`) whose segment's first byte
334    /// must be [`TYPE_NAMED_NODE_ID`] (IRI-only pushdown).
335    iri_only_checks: Vec<usize>,
336}
337
338impl RowMatcher {
339    /// Compile the matcher for one scan.
340    ///
341    /// `start_after` is the exclusive resume cursor; its whole-triple skip is
342    /// byte-level ([`KeyRow::triple_prefix`]) because a merged-default cursor
343    /// (G rewritten to DefaultGraph) cannot be compared as a raw key.
344    pub fn compile(
345        pattern: &EncodedTriplePattern,
346        permutation: IndexPermutation,
347        g_filter: GByteFilter,
348        merge_default_graph: bool,
349        start_after: Option<&EncodedQuad>,
350        iri_only: IriOnlyMask,
351    ) -> Self {
352        let order = permutation.slot_order();
353        let mut enforced = pattern.prefix_bound_len(permutation);
354        // DefaultGraph writes zero prefix bytes: a bound default-graph slot
355        // inside the prefix count contributes nothing to the iterator range,
356        // which keeps matching every named graph of the same triple. Demote
357        // it to a residual check (G is always the last slot).
358        if enforced > 0
359            && order[enforced - 1] == QuadSlot::Graph
360            && pattern.bound_slot(QuadSlot::Graph) == Some(&EncodedTerm::DefaultGraph)
361        {
362            enforced -= 1;
363        }
364        let mut checks = Vec::new();
365        for (index, slot) in order.iter().enumerate().skip(enforced) {
366            if let Some(term) = pattern.bound_slot(*slot) {
367                checks.push((index, encode_term_bytes(term)));
368            }
369        }
370        // Tsg keys omit the predicate: `rdf:type` is implicit in every row.
371        // A bound predicate that is not `rdf:type` can never match.
372        let impossible = permutation == IndexPermutation::Tsg
373            && pattern
374                .predicate
375                .as_ref()
376                .is_some_and(|term| term != &RDF_TYPE);
377        let cursor_triple = if merge_default_graph {
378            start_after.map(|quad| triple_prefix_bytes(quad, permutation))
379        } else {
380            None
381        };
382        Self {
383            permutation,
384            g_index: order.len() - 1,
385            checks,
386            impossible,
387            g_filter,
388            merge_default_graph,
389            cursor_triple,
390            last_triple: Vec::new(),
391            iri_only_checks: iri_only.compile_checks(pattern, order, enforced),
392        }
393    }
394
395    /// Match one versioned row (key ‖ trailer, 5-byte value) under `snapshot`.
396    ///
397    /// See the struct docs for the per-row pipeline. On [`MatchDecision::Emit`]
398    /// the walked slot starts are returned so the caller can build a
399    /// [`KeyRow`] without re-walking the key.
400    pub fn matches_row(
401        &mut self,
402        key: &[u8],
403        value: &[u8],
404        snapshot: SnapshotId,
405        state: &mut SnapshotScanState,
406    ) -> Result<MatchDecision, StorageError> {
407        if self.impossible {
408            return Ok(MatchDecision::Skip);
409        }
410        if key.len() < COMMIT_TS_LEN {
411            return Err(StorageError::Corrupt(format!(
412                "versioned key too short: {} bytes",
413                key.len()
414            )));
415        }
416        let term_len = key.len() - COMMIT_TS_LEN;
417        let trailer: [u8; COMMIT_TS_LEN] = key[term_len..]
418            .try_into()
419            .expect("trailer length checked above");
420        let commit_ts = CommitTs::from_descending_be_bytes(trailer);
421        let logical = &key[..term_len];
422        // MVCC collapse before any term work: superseded versions and
423        // versions newer than the snapshot pay one buffer compare.
424        if !state.consider_slice(logical, commit_ts, snapshot.0) {
425            return Ok(MatchDecision::Skip);
426        }
427        if value.len() != STORAGE_VALUE_LEN {
428            return Err(StorageError::Corrupt(format!(
429                "storage value must be {STORAGE_VALUE_LEN} bytes, got {}",
430                value.len()
431            )));
432        }
433        let (op, _visibility) = decode_storage_value(value)?;
434        if op != StorageOp::Put {
435            return Ok(MatchDecision::Skip);
436        }
437        let seg_starts = walk_slot_starts(logical, self.permutation)?;
438        // IRI-only pushdown: the planner proved the query's FILTER(isIRI(?x))
439        // conjuncts make these slots NamedNode-valued, so a non-NamedNode
440        // marker byte rejects the row before any decode work.
441        for &index in &self.iri_only_checks {
442            if logical[seg_starts[index]] != TYPE_NAMED_NODE_ID {
443                return Ok(MatchDecision::Skip);
444            }
445        }
446        // Bound slots after the first unbound one (or after a zero-length
447        // default-graph slot): direct slice compares.
448        for (index, expected) in &self.checks {
449            if slot_segment(logical, &seg_starts, self.permutation, *index) != expected.as_slice() {
450                return Ok(MatchDecision::Skip);
451            }
452        }
453        // Residual graph membership on the raw graph segment.
454        let graph = slot_segment(logical, &seg_starts, self.permutation, self.g_index);
455        if !self.g_filter.keeps_segment(graph) {
456            return Ok(MatchDecision::Skip);
457        }
458        let triple = &logical[..seg_starts[self.g_index]];
459        if self.cursor_triple.as_deref() == Some(triple) {
460            return Ok(MatchDecision::Skip);
461        }
462        self.cursor_triple = None;
463        if self.merge_default_graph {
464            if self.last_triple.as_slice() == triple {
465                return Ok(MatchDecision::Skip);
466            }
467            self.last_triple.clear();
468            self.last_triple.extend_from_slice(triple);
469        }
470        Ok(MatchDecision::Emit {
471            slot_starts: seg_starts,
472            commit_ts,
473        })
474    }
475}
476
477/// Byte offset where each key slot starts in `logical`, walking
478/// variable-width terms via the width table.
479///
480/// On three-slot permutations (Tsg) `starts[3]` is the end of the term
481/// prefix. Errors with [`StorageError::Corrupt`] on unknown type bytes or a
482/// term prefix that does not exactly cover `logical`.
483fn walk_slot_starts(
484    logical: &[u8],
485    permutation: IndexPermutation,
486) -> Result<[usize; 4], StorageError> {
487    let order = permutation.slot_order();
488    let mut starts = [0usize; 4];
489    let mut offset = 0usize;
490    for (index, slot) in order.iter().enumerate() {
491        starts[index] = offset;
492        if *slot == QuadSlot::Graph && offset == logical.len() {
493            // DefaultGraph encodes as zero bytes: the term prefix ends here.
494            break;
495        }
496        offset += term_width_at(logical, offset)?;
497    }
498    if offset > logical.len() {
499        return Err(StorageError::Corrupt(
500            "encoded term extends past the end of the key".to_owned(),
501        ));
502    }
503    if offset != logical.len() {
504        return Err(StorageError::Corrupt(format!(
505            "hexastore key has {} trailing byte(s) after the last slot",
506            logical.len() - offset
507        )));
508    }
509    if order.len() == 3 {
510        starts[3] = logical.len();
511    }
512    Ok(starts)
513}
514
515/// Raw bytes of key slot `index` from pre-walked starts.
516fn slot_segment<'a>(
517    logical: &'a [u8],
518    seg_starts: &[usize; 4],
519    permutation: IndexPermutation,
520    index: usize,
521) -> &'a [u8] {
522    let order_len = permutation.slot_order().len();
523    let end = if index + 1 < order_len {
524        seg_starts[index + 1]
525    } else {
526        logical.len()
527    };
528    &logical[seg_starts[index]..end]
529}
530
531/// Triple-prefix bytes of `quad` in `permutation` key order (all slots
532/// before the graph).
533fn triple_prefix_bytes(quad: &EncodedQuad, permutation: IndexPermutation) -> Vec<u8> {
534    let mut sink = Vec::with_capacity(3 * WRITTEN_TERM_MAX_SIZE);
535    for slot in permutation.slot_order() {
536        if *slot == QuadSlot::Graph {
537            break;
538        }
539        write_term(&mut sink, term_in_quad_slot(quad, *slot));
540    }
541    sink
542}
543
544#[cfg(test)]
545mod tests {
546    use super::*;
547    use crate::Term;
548    use crate::encode::binary::{decode_index_key, encode_index_key as encode_key};
549    use crate::encode::versioned::{
550        decode_versioned_key, encode_storage_value, encode_versioned_key, versioned_key_term_prefix,
551    };
552    use crate::{BlankNode, Literal, NamedNode, VisibilityLabel};
553    use pretty_assertions::assert_eq;
554
555    fn named(iri: &str) -> EncodedTerm {
556        EncodedTerm::from(&NamedNode::new(iri).unwrap())
557    }
558
559    /// Representative terms covering every width class (1 / 5 / 9 / 17 / 19 /
560    /// 25 / 33 bytes) plus blanks — the variable-width slot population.
561    fn object_terms() -> Vec<EncodedTerm> {
562        vec![
563            named("http://ex/o"),
564            EncodedTerm::SmallStringLiteral("Sunny".try_into().unwrap()),
565            EncodedTerm::BooleanLiteral(true.into()),
566            EncodedTerm::FloatLiteral("1.5".parse().unwrap()),
567            EncodedTerm::IntegerLiteral("42".parse().unwrap()),
568            EncodedTerm::DateTimeLiteral("2010-06-21T11:28:01Z".parse().unwrap()),
569            EncodedTerm::DurationLiteral("P1Y2M3DT10H30M".parse().unwrap()),
570            EncodedTerm::SmallSmallLangStringLiteral {
571                value: "chat".try_into().unwrap(),
572                language: "en".try_into().unwrap(),
573            },
574            EncodedTerm::BigTypedLiteral {
575                value_id: StrHash::new("a typed literal value far longer than sixteen bytes"),
576                datatype_id: StrHash::new("http://www.w3.org/2001/XMLSchema#date"),
577            },
578        ]
579    }
580
581    /// Deterministic corpus: one quad per width-class object, blank subjects,
582    /// rdf:type rows, named/blank/literal graphs, and a default-graph triple
583    /// duplicated across named graphs (`merge_default_graph` fodder).
584    fn corpus() -> Vec<EncodedQuad> {
585        let p1 = named("http://ex/p");
586        let rdf_type = RDF_TYPE.clone();
587        let s_iri = named("http://ex/s");
588        let s2 = named("http://ex/s2");
589        let s3 = named("http://ex/s3");
590        let default = EncodedTerm::DefaultGraph;
591        let g1 = named("http://ex/g1");
592        let g2 = named("http://ex/g2");
593        let g_blank = EncodedTerm::from(&BlankNode::new("g").unwrap());
594        let g_lit = EncodedTerm::SmallStringLiteral("graph".try_into().unwrap());
595        let s_small = EncodedTerm::SmallBlankNode("sb".try_into().unwrap());
596        let s_big = EncodedTerm::BigBlankNode {
597            id_id: StrHash::new("a big blank node id far longer than sixteen bytes"),
598        };
599        let s_num = EncodedTerm::NumericalBlankNode {
600            id: 0x100a_u128.to_be_bytes(),
601        };
602        let sunny = || EncodedTerm::SmallStringLiteral("Sunny".try_into().unwrap());
603
604        let mut quads = Vec::new();
605        for object in object_terms() {
606            quads.push(EncodedQuad::new(
607                s_iri.clone(),
608                p1.clone(),
609                object,
610                default.clone(),
611            ));
612        }
613        for subject in [&s_small, &s_big, &s_num] {
614            quads.push(EncodedQuad::new(
615                subject.clone(),
616                p1.clone(),
617                sunny(),
618                default.clone(),
619            ));
620        }
621        // rdf:type rows (Tsg fodder), incl. a named-graph copy.
622        quads.push(EncodedQuad::new(
623            s_iri.clone(),
624            rdf_type.clone(),
625            named("http://ex/Person"),
626            default.clone(),
627        ));
628        quads.push(EncodedQuad::new(
629            s_iri.clone(),
630            rdf_type,
631            named("http://ex/Person"),
632            g1.clone(),
633        ));
634        // One triple across default + named + blank + literal graphs.
635        quads.push(EncodedQuad::new(
636            s2.clone(),
637            p1.clone(),
638            named("http://ex/o"),
639            g1.clone(),
640        ));
641        quads.push(EncodedQuad::new(
642            s2.clone(),
643            p1.clone(),
644            named("http://ex/o"),
645            g2.clone(),
646        ));
647        quads.push(EncodedQuad::new(
648            s2.clone(),
649            p1.clone(),
650            named("http://ex/o"),
651            g_blank,
652        ));
653        quads.push(EncodedQuad::new(
654            s2.clone(),
655            p1.clone(),
656            named("http://ex/o"),
657            g_lit,
658        ));
659        // Default-graph triple with named-graph copies (merge-default fodder).
660        for graph in [default, g1.clone(), g2.clone()] {
661            quads.push(EncodedQuad::new(s3.clone(), p1.clone(), sunny(), graph));
662        }
663        quads
664    }
665
666    /// Versioned (key, value) rows for `quads` in lexicographic key order,
667    /// with put/delete/re-put version chains and a delete-only quad.
668    fn versioned_rows(
669        permutation: IndexPermutation,
670        quads: &[EncodedQuad],
671    ) -> Vec<(Vec<u8>, Vec<u8>)> {
672        let mut rows: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
673        let value = |op| encode_storage_value(op, VisibilityLabel::default()).to_vec();
674        for (i, quad) in quads.iter().enumerate() {
675            match i % 7 {
676                // Put, Delete, re-Put: exercises MVCC collapse at snapshots 1/2/3.
677                0 => {
678                    for (ts, op) in [
679                        (1, StorageOp::Put),
680                        (2, StorageOp::Delete),
681                        (3, StorageOp::Put),
682                    ] {
683                        rows.push((
684                            encode_versioned_key(permutation, quad, CommitTs(ts)),
685                            value(op),
686                        ));
687                    }
688                }
689                // Delete-only: never visible at any snapshot.
690                5 => {
691                    rows.push((
692                        encode_versioned_key(permutation, quad, CommitTs(1)),
693                        value(StorageOp::Delete),
694                    ));
695                }
696                _ => {
697                    rows.push((
698                        encode_versioned_key(permutation, quad, CommitTs(1)),
699                        value(StorageOp::Put),
700                    ));
701                }
702            }
703        }
704        rows.sort_by(|a, b| a.0.cmp(&b.0));
705        rows
706    }
707
708    fn pattern_of(
709        subject: Option<EncodedTerm>,
710        predicate: Option<EncodedTerm>,
711        object: Option<EncodedTerm>,
712        graph_name: Option<EncodedTerm>,
713    ) -> EncodedTriplePattern {
714        EncodedTriplePattern {
715            subject,
716            predicate,
717            object,
718            graph_name,
719        }
720    }
721
722    /// Patterns: unbound, each slot bound, every multi-bound shape, bound G
723    /// as DefaultGraph and named, plus a never-matching predicate (the Tsg
724    /// contradiction).
725    fn pattern_list() -> Vec<EncodedTriplePattern> {
726        let s = named("http://ex/s");
727        let s3 = named("http://ex/s3");
728        let s_blank = EncodedTerm::SmallBlankNode("sb".try_into().unwrap());
729        let p1 = named("http://ex/p");
730        let rdf_type = RDF_TYPE.clone();
731        let other_p = named("http://ex/other");
732        let o_iri = named("http://ex/o");
733        let o_str = EncodedTerm::SmallStringLiteral("Sunny".try_into().unwrap());
734        let dg = || EncodedTerm::DefaultGraph;
735        let g1 = named("http://ex/g1");
736        vec![
737            pattern_of(None, None, None, None),
738            pattern_of(Some(s.clone()), None, None, None),
739            pattern_of(Some(s_blank), None, None, None),
740            pattern_of(None, Some(p1.clone()), None, None),
741            pattern_of(None, Some(rdf_type.clone()), None, None),
742            pattern_of(None, None, Some(o_iri.clone()), None),
743            pattern_of(None, None, Some(o_str.clone()), None),
744            pattern_of(None, None, None, Some(dg())),
745            pattern_of(None, None, None, Some(g1.clone())),
746            pattern_of(Some(s.clone()), Some(p1.clone()), None, None),
747            pattern_of(Some(s.clone()), None, Some(o_iri.clone()), None),
748            pattern_of(None, Some(p1.clone()), Some(o_str.clone()), None),
749            pattern_of(None, Some(p1.clone()), None, Some(dg())),
750            pattern_of(None, Some(p1.clone()), None, Some(g1.clone())),
751            pattern_of(Some(s.clone()), None, None, Some(dg())),
752            pattern_of(None, None, Some(o_iri.clone()), Some(g1.clone())),
753            pattern_of(Some(s.clone()), Some(p1.clone()), Some(o_iri.clone()), None),
754            pattern_of(Some(s.clone()), Some(p1.clone()), None, Some(dg())),
755            pattern_of(
756                None,
757                Some(p1.clone()),
758                Some(o_str.clone()),
759                Some(g1.clone()),
760            ),
761            pattern_of(Some(s3.clone()), None, Some(o_str.clone()), Some(dg())),
762            // Fully bound with a default-graph G over a triple that also
763            // exists in named graphs: the zero-byte G slot must stay a
764            // residual check even though the prefix count covers it.
765            pattern_of(
766                Some(s3.clone()),
767                Some(p1.clone()),
768                Some(o_str.clone()),
769                Some(dg()),
770            ),
771            pattern_of(
772                Some(s.clone()),
773                Some(p1.clone()),
774                Some(o_str.clone()),
775                Some(dg()),
776            ),
777            // A predicate that matches nothing — on Tsg this is the
778            // contradiction case (rdf:type is implicit in every key).
779            pattern_of(Some(s.clone()), Some(other_p), None, None),
780        ]
781    }
782
783    /// Graph-filter windows: unconstrained, empty allow, block default,
784    /// block set, allow set, allow-with-default, allow blanks.
785    fn filter_sets() -> Vec<(bool, Vec<EncodedTerm>)> {
786        let g1 = named("http://ex/g1");
787        let g_blank = EncodedTerm::from(&BlankNode::new("g").unwrap());
788        vec![
789            (false, vec![]),
790            (true, vec![]),
791            (false, vec![EncodedTerm::DefaultGraph]),
792            (false, vec![g1.clone()]),
793            (false, vec![EncodedTerm::DefaultGraph, g1.clone()]),
794            (true, vec![g1.clone()]),
795            (true, vec![EncodedTerm::DefaultGraph, g1.clone()]),
796            (true, vec![g_blank]),
797        ]
798    }
799
800    /// The retired decoded-term pipeline: `decode_versioned_key` + MVCC +
801    /// `pattern.matches` + graph membership + cursor / dedup — the reference
802    /// `matches_row` must agree with this verdict for every row.
803    struct ReferenceWalk {
804        permutation: IndexPermutation,
805        pattern: EncodedTriplePattern,
806        filter_terms: Vec<EncodedTerm>,
807        filter_allow: bool,
808        dedup: bool,
809        cursor: Option<EncodedQuad>,
810        dont_skip: bool,
811        last_triple: Option<EncodedQuad>,
812        state: SnapshotScanState,
813    }
814
815    impl ReferenceWalk {
816        fn verdict(
817            &mut self,
818            key: &[u8],
819            value: &[u8],
820            snapshot: SnapshotId,
821        ) -> Result<Option<EncodedQuad>, crate::StorageError> {
822            let (quad, ts) = decode_versioned_key(self.permutation, key)?;
823            let logical = versioned_key_term_prefix(key)?;
824            if !self.state.consider_slice(logical, ts, snapshot.0) {
825                return Ok(None);
826            }
827            let (op, _) = decode_storage_value(value)?;
828            if op != StorageOp::Put {
829                return Ok(None);
830            }
831            if !self.pattern.matches(&quad) {
832                return Ok(None);
833            }
834            let member = self.filter_terms.iter().any(|t| t == &quad.graph_name);
835            if member != self.filter_allow {
836                return Ok(None);
837            }
838            if !self.dont_skip {
839                if self.cursor.as_ref().is_some_and(|c| quad.same_triple(c)) {
840                    return Ok(None);
841                }
842                self.dont_skip = true;
843            }
844            if self.dedup {
845                if self
846                    .last_triple
847                    .as_ref()
848                    .is_some_and(|prev| prev.same_triple(&quad))
849                {
850                    return Ok(None);
851                }
852                self.last_triple = Some(quad.clone());
853            }
854            Ok(Some(quad))
855        }
856    }
857
858    /// Drive one (permutation, pattern, filter, dedup, cursor, snapshot)
859    /// config over the shared row list and assert the matcher's emitted
860    /// sequence equals the decoded reference's.
861    #[allow(clippy::too_many_arguments)]
862    fn assert_parity(
863        permutation: IndexPermutation,
864        pattern: &EncodedTriplePattern,
865        filter_terms: &[EncodedTerm],
866        filter_allow: bool,
867        dedup: bool,
868        cursor: Option<&EncodedQuad>,
869        snapshot: SnapshotId,
870        rows: &[(Vec<u8>, Vec<u8>)],
871    ) -> usize {
872        let matcher_filter = GByteFilter::compile(filter_terms, filter_allow);
873        let mut matcher = RowMatcher::compile(
874            pattern,
875            permutation,
876            matcher_filter,
877            dedup,
878            cursor,
879            IriOnlyMask::NONE,
880        );
881        let mut reference = ReferenceWalk {
882            permutation,
883            pattern: pattern.clone(),
884            filter_terms: filter_terms.to_vec(),
885            filter_allow,
886            dedup,
887            cursor: cursor.cloned(),
888            // `dont_skip` only engages for merge-default cursors.
889            dont_skip: cursor.is_none() || !dedup,
890            last_triple: None,
891            state: SnapshotScanState::default(),
892        };
893        let mut matcher_state = SnapshotScanState::default();
894        let cursor_key = cursor.map(|quad| encode_key(permutation, quad));
895        let prefix = pattern.build_scan_prefix_bytes(permutation);
896        let mut matcher_out: Vec<EncodedQuad> = Vec::new();
897        let mut reference_out: Vec<EncodedQuad> = Vec::new();
898        for (key, value) in rows {
899            if key.as_slice() < prefix.as_slice() {
900                continue; // iterator Seek lands on the prefix region
901            }
902            if !key.starts_with(&prefix) {
903                break;
904            }
905            if let Some(cursor_key) = &cursor_key {
906                let logical = versioned_key_term_prefix(key).unwrap();
907                if logical <= cursor_key.as_slice() {
908                    continue;
909                }
910            }
911            match matcher
912                .matches_row(key, value, snapshot, &mut matcher_state)
913                .unwrap()
914            {
915                MatchDecision::Skip => {}
916                MatchDecision::Emit { slot_starts, .. } => {
917                    let row = KeyRow {
918                        key,
919                        permutation,
920                        seg_starts: slot_starts,
921                        commit_ts: CommitTs(0),
922                    };
923                    // The walked graph segment must decode to the same G the
924                    // reference sees.
925                    let decoded = decode_index_key(permutation, row.logical()).unwrap();
926                    assert_eq!(
927                        row.graph_segment(),
928                        crate::encode::encode_term_bytes(&decoded.graph_name),
929                        "graph segment of {permutation:?} row must match decoded G"
930                    );
931                    assert_eq!(
932                        row.triple_prefix().len(),
933                        row.logical().len() - row.graph_segment().len(),
934                    );
935                    matcher_out.push(decoded);
936                }
937            }
938            if let Some(quad) = reference.verdict(key, value, snapshot).unwrap() {
939                reference_out.push(quad);
940            }
941        }
942        assert_eq!(
943            matcher_out,
944            reference_out,
945            "matcher diverged from the decoded reference for {permutation:?} {pattern:?} \
946             filter_allow={filter_allow} terms={} dedup={dedup} cursor={cursor:?} snapshot={:?}",
947            filter_terms.len(),
948            snapshot.0,
949        );
950        matcher_out.len()
951    }
952
953    #[test]
954    fn matcher_matches_decoded_reference_over_full_corpus() {
955        let quads = corpus();
956        let patterns = pattern_list();
957        let filters = filter_sets();
958        // Merge-default cursor shape: a named-graph copy with G rewritten to
959        // DefaultGraph (what compute sends back after a dedup scan).
960        let merged_cursor = EncodedQuad {
961            graph_name: EncodedTerm::DefaultGraph,
962            ..quads[quads.len() - 2].clone()
963        };
964        let cursors_template: Vec<Option<EncodedQuad>> =
965            vec![None, Some(quads[0].clone()), Some(merged_cursor)];
966
967        let mut emitted_somewhere = 0usize;
968        for permutation in IndexPermutation::ALL {
969            let rows = versioned_rows(permutation, &quads);
970            // Real resume cursors are previous pages' last emitted rows. On
971            // Tsg every emitted row has the implicit rdf:type predicate, so a
972            // Tsg cursor always carries rdf:type on the wire.
973            let cursors: Vec<Option<EncodedQuad>> = cursors_template
974                .iter()
975                .map(|cursor| {
976                    cursor.as_ref().map(|quad| {
977                        let mut quad = quad.clone();
978                        if permutation == IndexPermutation::Tsg {
979                            quad.predicate = RDF_TYPE.clone();
980                        }
981                        quad
982                    })
983                })
984                .collect();
985            for pattern in &patterns {
986                for (allow, terms) in &filters {
987                    for dedup in [false, true] {
988                        for cursor in &cursors {
989                            for snapshot in [SnapshotId(1), SnapshotId(3)] {
990                                emitted_somewhere += assert_parity(
991                                    permutation,
992                                    pattern,
993                                    terms,
994                                    *allow,
995                                    dedup,
996                                    cursor.as_ref(),
997                                    snapshot,
998                                    &rows,
999                                );
1000                            }
1001                        }
1002                    }
1003                }
1004            }
1005        }
1006        assert!(
1007            emitted_somewhere > 1000,
1008            "the corpus must exercise real emissions, got {emitted_somewhere}"
1009        );
1010    }
1011
1012    #[test]
1013    fn gbyte_filter_segment_semantics() {
1014        let g1 = named("http://ex/g1");
1015        let g1_bytes = crate::encode::encode_term_bytes(&g1);
1016        let g_blank = EncodedTerm::from(&BlankNode::new("g").unwrap());
1017        let g_blank_bytes = crate::encode::encode_term_bytes(&g_blank);
1018
1019        // Unconstrained passes everything; empty allow passes nothing.
1020        assert!(GByteFilter::compile(&[], false).keeps_segment(&g1_bytes));
1021        assert!(GByteFilter::compile(&[], false).keeps_segment(&[]));
1022        assert!(!GByteFilter::compile(&[], true).keeps_segment(&g1_bytes));
1023        assert!(!GByteFilter::compile(&[], true).keeps_segment(&[]));
1024
1025        // Default graph: zero-length rule, both polarities.
1026        assert!(!GByteFilter::compile(&[EncodedTerm::DefaultGraph], false).keeps_segment(&[]));
1027        assert!(GByteFilter::compile(&[EncodedTerm::DefaultGraph], false).keeps_segment(&g1_bytes));
1028        assert!(GByteFilter::compile(&[EncodedTerm::DefaultGraph], true).keeps_segment(&[]));
1029        assert!(!GByteFilter::compile(&[EncodedTerm::DefaultGraph], true).keeps_segment(&g1_bytes));
1030
1031        // Named graphs hash-lookup from the segment; blanks compare bytes.
1032        assert!(!GByteFilter::compile(std::slice::from_ref(&g1), false).keeps_segment(&g1_bytes));
1033        assert!(GByteFilter::compile(std::slice::from_ref(&g1), true).keeps_segment(&g1_bytes));
1034        assert!(
1035            GByteFilter::compile(std::slice::from_ref(&g_blank), true)
1036                .keeps_segment(&g_blank_bytes)
1037        );
1038        assert!(
1039            !GByteFilter::compile(std::slice::from_ref(&g_blank), false)
1040                .keeps_segment(&g_blank_bytes)
1041        );
1042
1043        // Decoded-term membership agrees with segment membership.
1044        let filter = GByteFilter::compile(&[g1.clone(), EncodedTerm::DefaultGraph], true);
1045        assert!(filter.keeps_term(&g1));
1046        assert!(filter.keeps_term(&EncodedTerm::DefaultGraph));
1047        assert!(!filter.keeps_term(&named("http://ex/g2")));
1048        let unconstrained = GByteFilter::compile(&[], false);
1049        assert!(unconstrained.keeps_term(&g1));
1050        assert!(unconstrained.keeps_term(&EncodedTerm::DefaultGraph));
1051    }
1052
1053    #[test]
1054    fn row_slot_helpers_locate_segments() {
1055        // Spog key: S‖P‖O‖G‖ts with a 33-byte object and a named graph.
1056        let quad = EncodedQuad::new(
1057            named("http://ex/s"),
1058            named("http://ex/p"),
1059            EncodedTerm::SmallSmallLangStringLiteral {
1060                value: "chat".try_into().unwrap(),
1061                language: "en".try_into().unwrap(),
1062            },
1063            named("http://ex/g1"),
1064        );
1065        let key = encode_key(IndexPermutation::Spog, &quad);
1066        let mut versioned_key = key.clone();
1067        versioned_key.extend_from_slice(&CommitTs(9).to_descending_be_bytes());
1068        // The walk runs on the term prefix; the trailer is read separately.
1069        let logical = &versioned_key[..versioned_key.len() - COMMIT_TS_LEN];
1070        let seg_starts = walk_slot_starts(logical, IndexPermutation::Spog).unwrap();
1071        let row = KeyRow {
1072            key: &versioned_key,
1073            permutation: IndexPermutation::Spog,
1074            seg_starts,
1075            commit_ts: CommitTs(9),
1076        };
1077        assert_eq!(row.commit_ts, CommitTs(9));
1078        assert_eq!(row.slot_bytes(QuadSlot::Subject).unwrap(), &key[0..17]);
1079        assert_eq!(row.slot_bytes(QuadSlot::Predicate).unwrap(), &key[17..34]);
1080        assert_eq!(row.slot_bytes(QuadSlot::Object).unwrap(), &key[34..67]);
1081        assert_eq!(row.slot_bytes(QuadSlot::Graph).unwrap(), &key[67..84]);
1082        assert_eq!(row.graph_segment(), &key[67..84]);
1083        assert_eq!(row.triple_prefix(), &key[..67]);
1084        assert_eq!(row.logical(), &key[..]);
1085        // DefaultGraph: the graph segment is empty, trailer follows O.
1086        let default_quad = EncodedQuad {
1087            graph_name: EncodedTerm::DefaultGraph,
1088            ..quad.clone()
1089        };
1090        let default_key = encode_key(IndexPermutation::Spog, &default_quad);
1091        let mut default_versioned = default_key.clone();
1092        default_versioned.extend_from_slice(&CommitTs(9).to_descending_be_bytes());
1093        let default_logical = &default_versioned[..default_versioned.len() - COMMIT_TS_LEN];
1094        let starts = walk_slot_starts(default_logical, IndexPermutation::Spog).unwrap();
1095        let default_row = KeyRow {
1096            key: &default_versioned,
1097            permutation: IndexPermutation::Spog,
1098            seg_starts: starts,
1099            commit_ts: CommitTs(9),
1100        };
1101        assert!(default_row.graph_segment().is_empty());
1102        assert_eq!(default_row.triple_prefix(), &default_versioned[..67]);
1103        // Tsg: three slots, seg_starts[3] is the term-prefix end.
1104        let tsg_key = encode_key(IndexPermutation::Tsg, &default_quad);
1105        let mut tsg_versioned = tsg_key.clone();
1106        tsg_versioned.extend_from_slice(&CommitTs(9).to_descending_be_bytes());
1107        let tsg_logical = &tsg_versioned[..tsg_versioned.len() - COMMIT_TS_LEN];
1108        let tsg_starts = walk_slot_starts(tsg_logical, IndexPermutation::Tsg).unwrap();
1109        let tsg_row = KeyRow {
1110            key: &tsg_versioned,
1111            permutation: IndexPermutation::Tsg,
1112            seg_starts: tsg_starts,
1113            commit_ts: CommitTs(9),
1114        };
1115        assert_eq!(tsg_row.slot_bytes(QuadSlot::Predicate), None);
1116        assert_eq!(tsg_row.graph_segment().len(), 0);
1117        assert_eq!(tsg_row.logical().len(), tsg_starts[3]);
1118        // Literal object width drives the O segment length (33).
1119        assert_eq!(term_width_at(row.logical(), 34).unwrap(), 33);
1120    }
1121
1122    #[test]
1123    fn walk_slot_starts_rejects_corrupt_keys() {
1124        // Unknown type byte after a valid 17-byte subject.
1125        let mut bad = vec![1u8; 17];
1126        bad.push(0xFF);
1127        assert!(walk_slot_starts(&bad, IndexPermutation::Opsg).is_err());
1128        // Truncated prefix (no object bytes at all).
1129        assert!(walk_slot_starts(&[1u8; 5], IndexPermutation::Opsg).is_err());
1130        // Trailing garbage after a complete slot sequence.
1131        let mut trailing = Vec::new();
1132        trailing.extend_from_slice(&encode_key(
1133            IndexPermutation::Spog,
1134            &EncodedQuad::new(
1135                named("http://ex/s"),
1136                named("http://ex/p"),
1137                named("http://ex/o"),
1138                EncodedTerm::DefaultGraph,
1139            ),
1140        ));
1141        let complete_len = trailing.len();
1142        trailing.push(0);
1143        assert!(walk_slot_starts(&trailing, IndexPermutation::Spog).is_err());
1144        assert!(walk_slot_starts(&trailing[..complete_len], IndexPermutation::Spog).is_ok());
1145    }
1146
1147    #[test]
1148    fn literal_object_round_trip_fixture() {
1149        // Guards the corpus fixture: oxsdatatypes parse paths used above.
1150        let literal = Literal::from("Sunny");
1151        assert_eq!(
1152            EncodedTerm::from(&Term::from(literal)),
1153            EncodedTerm::SmallStringLiteral("Sunny".try_into().unwrap())
1154        );
1155    }
1156}