Skip to main content

waratah_storage/encode/
pattern.rs

1//! Partially-bound encoded triple patterns for storage scans.
2
3use super::binary::{IndexPermutation, QuadSlot, WRITTEN_TERM_MAX_SIZE, write_term};
4use super::encoded_term::{EncodedQuad, EncodedTerm, RDF_TYPE};
5use crate::types::PartitionAxis;
6
7/// Ground or partially-bound encoded triple/quad pattern.
8#[derive(Debug, Clone, PartialEq, Default)]
9pub struct EncodedTriplePattern {
10    /// Bound subject (`None` = variable).
11    pub subject: Option<EncodedTerm>,
12    /// Bound predicate (`None` = variable).
13    pub predicate: Option<EncodedTerm>,
14    /// Bound object (`None` = variable).
15    pub object: Option<EncodedTerm>,
16    /// Bound graph name (`None` = variable; default graph is `Some(DefaultGraph)`).
17    pub graph_name: Option<EncodedTerm>,
18}
19
20impl EncodedTriplePattern {
21    /// Whether `quad` satisfies all bound slots in this pattern.
22    pub fn matches(&self, quad: &EncodedQuad) -> bool {
23        slot_matches(self.subject.as_ref(), &quad.subject)
24            && slot_matches(self.predicate.as_ref(), &quad.predicate)
25            && slot_matches(self.object.as_ref(), &quad.object)
26            && slot_matches(self.graph_name.as_ref(), &quad.graph_name)
27    }
28
29    /// Choose the axis-local permutation for scanning this pattern.
30    ///
31    /// On the O axis, `rdf:type` patterns with a bound class use [`IndexPermutation::Tsg`];
32    /// all other O patterns use [`IndexPermutation::Opsg`]. S/P axes pick the longest
33    /// bound prefix among the two general indexes.
34    pub fn best_permutation(&self, axis: PartitionAxis) -> IndexPermutation {
35        if axis == PartitionAxis::O {
36            if self.predicate.as_ref() == Some(&RDF_TYPE) && self.object.is_some() {
37                return IndexPermutation::Tsg;
38            }
39            return IndexPermutation::Opsg;
40        }
41        let indexes = IndexPermutation::for_axis(axis);
42        let mut best = indexes[0];
43        let mut best_len = self.prefix_bound_len(best);
44        for permutation in indexes.into_iter().skip(1) {
45            let len = self.prefix_bound_len(permutation);
46            if len > best_len {
47                best = permutation;
48                best_len = len;
49            }
50        }
51        best
52    }
53
54    /// Number of leading bound slots in `permutation` order.
55    pub fn prefix_bound_len(&self, permutation: IndexPermutation) -> usize {
56        permutation
57            .slot_order()
58            .iter()
59            .take_while(|slot| self.bound_slot(**slot).is_some())
60            .count()
61    }
62
63    /// Build a RocksDB prefix for `permutation`, encoding consecutive bound slots until the first `None`.
64    pub fn build_scan_prefix_bytes(&self, permutation: IndexPermutation) -> Vec<u8> {
65        let mut sink = Vec::with_capacity(4 * WRITTEN_TERM_MAX_SIZE);
66        for slot in permutation.slot_order() {
67            match self.bound_slot(*slot) {
68                Some(term) => write_term(&mut sink, term),
69                None => break,
70            }
71        }
72        sink
73    }
74
75    /// Bind `term` into `slot` (broadcast allow-list / prefix specialization).
76    pub fn bind_slot(&mut self, slot: QuadSlot, term: EncodedTerm) {
77        match slot {
78            QuadSlot::Subject => self.subject = Some(term),
79            QuadSlot::Predicate => self.predicate = Some(term),
80            QuadSlot::Object => self.object = Some(term),
81            QuadSlot::Graph => self.graph_name = Some(term),
82        }
83    }
84
85    /// Sort+dedup allow-list terms by encoded tight prefix, or `None` when binding
86    /// `slot` does not extend a contiguous `permutation` prefix.
87    ///
88    /// Shared prefix is this pattern with `slot` unbound. Each term's tight
89    /// prefix must start with that shared prefix and be strictly longer, so a
90    /// single iterator over the shared range can `Seek` to each term.
91    pub fn prepare_tight_allow_list(
92        &self,
93        permutation: IndexPermutation,
94        slot: QuadSlot,
95        terms: &[EncodedTerm],
96    ) -> Option<SortedTightAllowList> {
97        let shared_prefix = self.build_scan_prefix_bytes(permutation);
98        let mut entries = Vec::with_capacity(terms.len());
99        for term in terms {
100            let mut bound = self.clone();
101            bound.bind_slot(slot, term.clone());
102            let tight_prefix = bound.build_scan_prefix_bytes(permutation);
103            if !tight_prefix.starts_with(&shared_prefix)
104                || tight_prefix.len() <= shared_prefix.len()
105            {
106                return None;
107            }
108            entries.push((tight_prefix, term.clone()));
109        }
110        entries.sort_by(|a, b| a.0.cmp(&b.0));
111        entries.dedup_by(|a, b| a.0 == b.0);
112        Some(SortedTightAllowList {
113            shared_prefix,
114            terms: entries,
115        })
116    }
117
118    /// Bound term of `slot`, or `None` when the slot is a variable.
119    pub(crate) fn bound_slot(&self, slot: QuadSlot) -> Option<&EncodedTerm> {
120        match slot {
121            QuadSlot::Subject => self.subject.as_ref(),
122            QuadSlot::Predicate => self.predicate.as_ref(),
123            QuadSlot::Object => self.object.as_ref(),
124            QuadSlot::Graph => self.graph_name.as_ref(),
125        }
126    }
127}
128
129/// Sorted unique allow-list terms with encoded prefixes for a multi-seek scan.
130#[derive(Debug, Clone)]
131pub struct SortedTightAllowList {
132    /// RocksDB prefix with the filter slot still unbound (iterator upper bound).
133    pub shared_prefix: Vec<u8>,
134    /// `(tight_prefix, term)` pairs in encoded-prefix order.
135    pub terms: Vec<(Vec<u8>, EncodedTerm)>,
136}
137
138/// Term in `slot` of `quad`.
139pub fn term_in_quad_slot(quad: &EncodedQuad, slot: QuadSlot) -> &EncodedTerm {
140    match slot {
141        QuadSlot::Subject => &quad.subject,
142        QuadSlot::Predicate => &quad.predicate,
143        QuadSlot::Object => &quad.object,
144        QuadSlot::Graph => &quad.graph_name,
145    }
146}
147
148fn slot_matches(expected: Option<&EncodedTerm>, actual: &EncodedTerm) -> bool {
149    expected.is_none_or(|term| term == actual)
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155    use crate::{Literal, NamedNode, Term};
156    use pretty_assertions::assert_eq;
157
158    use super::super::encoded_term::EncodedTerm;
159
160    #[test]
161    fn scan_prefix_stops_at_first_unbound_slot() {
162        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
163        let pattern = EncodedTriplePattern {
164            subject: None,
165            predicate: Some(p.clone()),
166            object: None,
167            graph_name: Some(EncodedTerm::DefaultGraph),
168        };
169
170        // POSG order: P, O, S, G — only P is bound before first gap.
171        let prefix = pattern.build_scan_prefix_bytes(IndexPermutation::Posg);
172        let mut expected = Vec::new();
173        write_term(&mut expected, &p);
174        assert_eq!(prefix, expected);
175    }
176
177    #[test]
178    fn scan_prefix_two_bound_slots_in_permutation_order() {
179        let s = EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap());
180        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
181        let pattern = EncodedTriplePattern {
182            subject: Some(s.clone()),
183            predicate: Some(p.clone()),
184            object: None,
185            graph_name: None,
186        };
187
188        let prefix = pattern.build_scan_prefix_bytes(IndexPermutation::Spog);
189        let mut expected = Vec::new();
190        write_term(&mut expected, &s);
191        write_term(&mut expected, &p);
192        assert_eq!(prefix, expected);
193    }
194
195    #[test]
196    fn bound_object_literal_prefix_for_o_partition() {
197        let sunny_term = Term::from(Literal::from("Sunny"));
198        let sunny = EncodedTerm::from(&sunny_term);
199        let pattern = EncodedTriplePattern {
200            subject: None,
201            predicate: None,
202            object: Some(sunny.clone()),
203            graph_name: Some(EncodedTerm::DefaultGraph),
204        };
205
206        let prefix = pattern.build_scan_prefix_bytes(IndexPermutation::Opsg);
207        let mut expected = Vec::new();
208        write_term(&mut expected, &sunny);
209        assert_eq!(prefix, expected);
210        assert!(matches!(sunny, EncodedTerm::SmallStringLiteral(_)));
211    }
212
213    #[test]
214    fn best_permutation_o_uses_tsg_for_rdf_type() {
215        let class = EncodedTerm::from(&NamedNode::new("http://ex/Person").unwrap());
216        let pattern = EncodedTriplePattern {
217            subject: None,
218            predicate: Some(RDF_TYPE.clone()),
219            object: Some(class),
220            graph_name: Some(EncodedTerm::DefaultGraph),
221        };
222        assert_eq!(
223            pattern.best_permutation(PartitionAxis::O),
224            IndexPermutation::Tsg
225        );
226    }
227
228    #[test]
229    fn best_permutation_o_uses_opsg_for_non_type() {
230        let pattern = EncodedTriplePattern {
231            subject: None,
232            predicate: Some(EncodedTerm::from(
233                &NamedNode::new("http://ex/hasWeather").unwrap(),
234            )),
235            object: Some(EncodedTerm::from(&Term::from(Literal::from("Sunny")))),
236            graph_name: Some(EncodedTerm::DefaultGraph),
237        };
238        assert_eq!(
239            pattern.best_permutation(PartitionAxis::O),
240            IndexPermutation::Opsg
241        );
242    }
243
244    #[test]
245    fn prepare_allow_list_extends_psog_subject_filter() {
246        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
247        let a = EncodedTerm::from(&NamedNode::new("http://ex/a").unwrap());
248        let b = EncodedTerm::from(&NamedNode::new("http://ex/b").unwrap());
249        let pattern = EncodedTriplePattern {
250            subject: None,
251            predicate: Some(p),
252            object: None,
253            graph_name: Some(EncodedTerm::DefaultGraph),
254        };
255        let prepared = pattern
256            .prepare_tight_allow_list(
257                IndexPermutation::Psog,
258                QuadSlot::Subject,
259                &[b.clone(), a.clone(), a],
260            )
261            .expect("P‖S extends P");
262        assert_eq!(prepared.terms.len(), 2, "duplicate a is dropped");
263        assert!(prepared.terms[0].0 < prepared.terms[1].0);
264    }
265
266    #[test]
267    fn prepare_allow_list_rejects_posg_subject_when_object_unbound() {
268        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
269        let s = EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap());
270        let pattern = EncodedTriplePattern {
271            subject: None,
272            predicate: Some(p),
273            object: None,
274            graph_name: Some(EncodedTerm::DefaultGraph),
275        };
276        assert!(
277            pattern
278                .prepare_tight_allow_list(IndexPermutation::Posg, QuadSlot::Subject, &[s])
279                .is_none(),
280            "S is after unbound O on POSG"
281        );
282    }
283}