Skip to main content

relate_executor/graph/declared/
mod.rs

1//! `CREATE TEXT INDEX`, `CREATE RANGE INDEX`, and `CREATE POINT INDEX`
2//! access methods. Each structure exists only for a catalog pair and is
3//! built on create, on startup (`rebuild_indexes`), and incrementally on
4//! later writes. A seek with no matching index returns `None` so the
5//! caller scans the label and evaluates the predicate.
6
7use std::collections::HashSet;
8
9use relate_core::{NodeId, Value};
10
11use crate::redo::{IndexDetailSpec, IndexKindSpec};
12
13use super::*;
14
15mod aggregate;
16mod order;
17mod point;
18mod seek;
19mod text;
20
21pub(super) use order::RangeIndex;
22pub(crate) use order::{Extremum, RangeSeek, SpatialSeek};
23pub(crate) use point::spatial_holds;
24pub(super) use point::PointIndex;
25/// Profile-only: the bench harness drives the point backend directly
26/// (the R-tree vs. grid comparison of record lives there).
27#[cfg(test)]
28pub(super) use point::{point_insert, spatial_ids};
29pub(crate) use text::trigram_count;
30pub(super) use text::GramIndex;
31
32/// One declared index's postings for a `(label, property)` pair. The
33/// graph wiring below is written once against this trait.
34pub(super) trait DrainState: Default {
35    fn dirty_mut(&mut self) -> &mut HashSet<NodeId>;
36    /// Post one version's value for `id`. A value of another type posts
37    /// nothing.
38    fn insert(&mut self, id: NodeId, value: &Value);
39    /// Drop every posting of `id`.
40    fn remove_node(&mut self, id: NodeId);
41    /// Finalize a full local build (create, reopen rebuild) before the
42    /// pair is published: a seek never observes an unsealed pair. The
43    /// default is nothing to do.
44    fn seal(&mut self) {}
45}
46
47impl Graph {
48    pub(super) fn declared_dirty(&self, lid: u32, kid: u32, id: NodeId) {
49        Self::mark_dirty(&self.indexes.gram_pairs, lid, kid, id);
50        Self::mark_dirty(&self.indexes.range_pairs, lid, kid, id);
51        Self::mark_dirty(&self.indexes.point_pairs, lid, kid, id);
52    }
53
54    fn mark_dirty<St: DrainState>(pairs: &CoreMap<(u32, u32), St>, lid: u32, kid: u32, id: NodeId) {
55        if let Some(mut st) = pairs.get_mut(&(lid, kid)) {
56            st.dirty_mut().insert(id);
57        }
58    }
59
60    /// `(gram entries, dirty ids)` when a text index has materialized this pair.
61    #[cfg(test)]
62    pub(super) fn gram_pair_state(&self, label: &str, key: &str) -> Option<(usize, usize)> {
63        let pk = self.string_pair_id(label, key)?;
64        self.indexes
65            .gram_pairs
66            .get(&pk)
67            .map(|st| (st.grams.len(), st.dirty.len()))
68    }
69
70    pub(super) fn materialize_detail(&self, detail: &IndexDetailSpec) {
71        for (label, property, kind) in detail.covered_pairs() {
72            match kind {
73                IndexKindSpec::Text => self.materialize_text_index(label, property),
74                IndexKindSpec::Range => self.materialize_range_index(label, property),
75                IndexKindSpec::Point => self.materialize_point_index(label, property),
76                _ => {}
77            }
78        }
79    }
80
81    pub(super) fn drop_detail(&self, detail: &IndexDetailSpec) {
82        let remaining: Vec<IndexDetailSpec> = self
83            .theater
84            .lock()
85            .unwrap()
86            .index_details
87            .values()
88            .cloned()
89            .collect();
90        for (label, property, kind) in detail.covered_pairs() {
91            let still = remaining.iter().any(|other| {
92                other
93                    .covered_pairs()
94                    .iter()
95                    .any(|(l, p, k)| *l == label && *p == property && *k == kind)
96            });
97            if still {
98                continue;
99            }
100            let Some(pk) = self.string_pair_id(label, property) else {
101                continue;
102            };
103            match kind {
104                IndexKindSpec::Text => {
105                    self.indexes.gram_pairs.remove(&pk);
106                }
107                IndexKindSpec::Range => {
108                    self.indexes.range_pairs.remove(&pk);
109                }
110                IndexKindSpec::Point => {
111                    self.indexes.point_pairs.remove(&pk);
112                }
113                _ => {}
114            }
115        }
116    }
117
118    pub(super) fn rebuild_declared_indexes(&self) {
119        self.indexes.gram_pairs.clear();
120        self.indexes.range_pairs.clear();
121        self.indexes.point_pairs.clear();
122        let details: Vec<IndexDetailSpec> = self
123            .theater
124            .lock()
125            .unwrap()
126            .index_details
127            .values()
128            .cloned()
129            .collect();
130        for detail in details {
131            self.materialize_detail(&detail);
132        }
133    }
134
135    /// The node `(label, property)` pairs the store's RANGE indexes serve an
136    /// equality seek on, read from the typed catalog details
137    /// ([`IndexDetailSpec::range_seek_pairs`]) rather than re-parsed from the
138    /// rendered `:Label(property)` text: every component of a composite range
139    /// index is covered, a relationship index contributes no node pair, and a
140    /// comma-bearing property name stays one name.
141    pub fn range_indexed_node_properties(&self) -> Vec<(String, String)> {
142        self.theater
143            .lock()
144            .unwrap()
145            .index_details
146            .values()
147            .flat_map(IndexDetailSpec::range_seek_pairs)
148            .map(|(label, property)| (label.to_string(), property.to_string()))
149            .collect()
150    }
151
152    fn intern_pair(&self, label: &str, key: &str) -> (u32, u32) {
153        (self.interner.intern(label), self.interner.intern(key))
154    }
155
156    /// `key`'s interned id and the labels among `labels` whose pair for it
157    /// exists in `pairs`. `None` when none do (the seek must scan). An empty
158    /// pattern label list cannot be served: an index on one label would miss
159    /// the others.
160    fn indexed_labels<St>(
161        &self,
162        labels: &[String],
163        key: &str,
164        pairs: &CoreMap<(u32, u32), St>,
165    ) -> Option<(u32, Vec<u32>)> {
166        if labels.is_empty() {
167            return None;
168        }
169        let kid = self.interner.get_id(key)?;
170        let ids: Vec<u32> = labels
171            .iter()
172            .filter_map(|l| self.interner.get_id(l))
173            .filter(|lid| pairs.contains_key(&(*lid, kid)))
174            .collect();
175        (!ids.is_empty()).then_some((kid, ids))
176    }
177
178    /// Build one pair from every version of every node in the label index
179    /// (a superset; the seek re-checks the snapshot, ADR-0018).
180    fn materialize_pair<St: DrainState>(
181        &self,
182        pairs: &CoreMap<(u32, u32), St>,
183        label: &str,
184        property: &str,
185    ) {
186        let (lid, kid) = self.intern_pair(label, property);
187        let mut st = St::default();
188        self.for_each_pair_value(lid, kid, |id, value| st.insert(id, value));
189        // Sealed before publish: a concurrent seek either sees the fully
190        // built pair or none of it.
191        st.seal();
192        pairs.insert((lid, kid), st);
193    }
194
195    pub(super) fn materialize_text_index(&self, label: &str, property: &str) {
196        self.materialize_pair(&self.indexes.gram_pairs, label, property);
197    }
198
199    pub(super) fn materialize_range_index(&self, label: &str, property: &str) {
200        self.materialize_pair(&self.indexes.range_pairs, label, property);
201    }
202
203    pub(super) fn materialize_point_index(&self, label: &str, property: &str) {
204        self.materialize_pair(&self.indexes.point_pairs, label, property);
205    }
206
207    /// Repost every dirty node of one pair. The write guard is held across
208    /// the whole drain, so a concurrent `declared_dirty` lands either before
209    /// the take (reposted here) or after it (kept for the next drain).
210    /// Drains the pair's dirty postings and reports whether the pair
211    /// exists — the one presence spelling, so a caller asking "is this
212    /// pair declared, and current?" never restates the guard beside it.
213    fn drain_pair<St: DrainState>(
214        &self,
215        pairs: &CoreMap<(u32, u32), St>,
216        lid: u32,
217        kid: u32,
218    ) -> bool {
219        let Some(mut st) = pairs.get_mut(&(lid, kid)) else {
220            return false;
221        };
222        let ids = std::mem::take(st.dirty_mut());
223        for id in ids {
224            st.remove_node(id);
225            self.for_each_node_pair_value(id, lid, kid, |value| st.insert(id, value));
226        }
227        true
228    }
229}
230
231/// Intersect `next` into the accumulator: the first set becomes the
232/// accumulator, every later one narrows it. The canonical accumulator fold
233/// for every multi-set seek (declared indexes and equality lookups).
234pub(super) fn intersect_acc(acc: &mut Option<HashSet<NodeId>>, next: HashSet<NodeId>) {
235    *acc = Some(match acc.take() {
236        None => next,
237        Some(prev) => prev.intersection(&next).copied().collect(),
238    });
239}
240
241/// Per-kind byte estimate of the lazily built declared index pairs — the
242/// research-gated census harness's view (ADR-0476 quarantine). Only
243/// the order/by-node arms are counted; the eq-only fallback arms are not.
244/// [`Self::text_bytes`] and [`Self::point_bytes`] are per-posting
245/// estimates (no byte walk); every printed census row is one of these
246/// fields.
247#[cfg(feature = "research")]
248#[derive(Debug, Default, Clone)]
249pub struct DeclaredCensus {
250    pub range_pairs: usize,
251    pub range_order_keys: u64,
252    pub range_posted_ids: u64,
253    pub range_bytes: u64,
254    pub text_pairs: usize,
255    pub text_grams: u64,
256    /// 8 bytes per gram posting.
257    pub text_bytes: u64,
258    pub point_pairs: usize,
259    pub point_entries: u64,
260    /// 40 bytes per posted point.
261    pub point_bytes: u64,
262}
263
264impl Graph {
265    #[cfg(feature = "research")]
266    pub(super) fn declared_index_census(&self) -> DeclaredCensus {
267        use std::mem::size_of;
268
269        use crate::memory::{hashset_i64_bytes, vec_heap, OVERHEAD_MAP_ENTRY};
270
271        let mut c = DeclaredCensus::default();
272        for pair in self.indexes.range_pairs.iter() {
273            c.range_pairs += 1;
274            let st = pair.value();
275            for postings in st.order.values() {
276                c.range_order_keys += 1;
277                c.range_bytes += size_of::<order::OrderKey>() as u64
278                    + size_of::<order::Postings>() as u64
279                    + OVERHEAD_MAP_ENTRY;
280                match postings {
281                    order::Postings::One(_) => c.range_posted_ids += 1,
282                    order::Postings::Many(set) => {
283                        c.range_posted_ids += set.len() as u64;
284                        c.range_bytes += hashset_i64_bytes(set.capacity());
285                    }
286                }
287            }
288            for keys in st.by_node.values() {
289                c.range_bytes +=
290                    OVERHEAD_MAP_ENTRY + size_of::<order::RevKeys<order::OrderKey>>() as u64;
291                if let order::RevKeys::Many(keys) = keys {
292                    c.range_bytes += vec_heap(keys.len(), size_of::<order::OrderKey>() as u64);
293                }
294            }
295            // The per-id sets are charged by element count: the transient
296            // dirty queue, and the retained `unbounded` temporals and
297            // `unposted` NaN values — small next to the postings above.
298            c.range_bytes +=
299                hashset_i64_bytes(st.dirty.len() + st.unbounded.len() + st.unposted.len());
300        }
301        for pair in self.indexes.gram_pairs.iter() {
302            c.text_pairs += 1;
303            let grams = pair.value().grams.len() as u64;
304            c.text_grams += grams;
305            c.text_bytes += grams * 8;
306        }
307        for pair in self.indexes.point_pairs.iter() {
308            c.point_pairs += 1;
309            let entries = pair.value().pt_count() as u64;
310            c.point_entries += entries;
311            c.point_bytes += entries * 40;
312        }
313        c
314    }
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    #[test]
322    fn order_remove_drops_only_that_node() {
323        let mut st = RangeIndex::default();
324        order::insert_order(&mut st, &Value::Int(1), 10);
325        order::insert_order(&mut st, &Value::Int(2), 11);
326        order::order_remove_node(&mut st, 10);
327        assert!(!st
328            .order
329            .contains_key(&order::order_key(&Value::Int(1)).unwrap()));
330        assert!(st
331            .order
332            .get(&order::order_key(&Value::Int(2)).unwrap())
333            .unwrap()
334            .contains(11));
335    }
336
337    #[test]
338    fn string_order_key_shares_the_value_payload() {
339        let payload: Arc<str> = "Ada".into();
340        let value = Value::String(Arc::clone(&payload));
341        let mut st = RangeIndex::default();
342        order::insert_order(&mut st, &value, 10);
343        order::insert_order(&mut st, &Value::String("Bob".into()), 11);
344        let posted = st.by_node[&10].first().unwrap();
345        assert!(matches!(posted, order::OrderKey::String(s) if Arc::ptr_eq(s, &payload)));
346        assert!(st
347            .order
348            .keys()
349            .any(|k| matches!(k, order::OrderKey::String(s) if Arc::ptr_eq(s, &payload))));
350        assert_eq!(order::prefix_ids(&st.order, "A"), HashSet::from([10]));
351    }
352
353    #[test]
354    fn gram_remove_drops_only_that_node() {
355        let mut st = GramIndex::default();
356        text::gram_insert(&mut st, &Arc::from("abc"), 10);
357        text::gram_insert(&mut st, &Arc::from("zzz"), 11);
358        text::gram_remove_node(&mut st, 10);
359        assert!(st.grams.values().all(|ids| !ids.holds(10)));
360        assert!(st.grams.values().any(|ids| ids.holds(11)));
361    }
362
363    /// `finish_ids` re-checks posted candidates on the raw version (LABS-853):
364    /// a tombstoned node, one missing a pattern label, and one whose visible
365    /// value fails the seek are each dropped exactly as the eager `node_at`
366    /// re-check dropped them — compared against that oracle at both
367    /// snapshots.
368    #[test]
369    fn finish_ids_filters_like_the_eager_node_at_recheck() {
370        let g = Graph::default();
371        let node = |labels: &[&str], x: i64| {
372            g.create_node(
373                labels.iter().map(|l| l.to_string()).collect(),
374                BTreeMap::from([("x".into(), Value::Int(x))]),
375            )
376            .unwrap()
377        };
378        g.begin_write().unwrap();
379        let kept = node(&["N", "M"], 5);
380        let dead = node(&["N", "M"], 6);
381        let unlabeled = node(&["N"], 7);
382        let failing = node(&["N", "M"], 8);
383        g.commit_write();
384        g.materialize_range_index("N", "x");
385        let before = g.commit_ts();
386        g.begin_write().unwrap();
387        g.delete_node(dead, true).unwrap();
388        g.set_property_node(failing, "x", Value::Int(0));
389        g.commit_write();
390        let after = g.commit_ts();
391
392        let op = relate_ir::BinaryOp::Gt;
393        let bound = Value::Int(1);
394        let seek = RangeSeek::Cmp {
395            op,
396            bound: bound.clone(),
397        };
398        let labels = vec!["N".to_string(), "M".to_string()];
399        let eager = |ts: u64| {
400            let mut ids: Vec<_> = [kept, dead, unlabeled, failing]
401                .into_iter()
402                .filter(|id| {
403                    g.node_at(*id, ts).is_some_and(|n| {
404                        Graph::node_matches(&n, &labels, &BTreeMap::new())
405                            && n.properties
406                                .get("x")
407                                .is_some_and(|v| order::cmp_holds(v, op, &bound))
408                    })
409                })
410                .collect();
411            ids.sort();
412            ids
413        };
414        let lazy = |ts: u64| g.lookup_range_seek(&labels, "x", &seek, ts).unwrap();
415
416        assert_eq!(lazy(before), vec![kept, dead, failing]);
417        assert_eq!(lazy(before), eager(before));
418        assert_eq!(lazy(after), vec![kept]);
419        assert_eq!(lazy(after), eager(after));
420        // A pattern label the interner never saw is carried by no node.
421        let ghost = vec!["N".to_string(), "Ghost".to_string()];
422        assert_eq!(g.lookup_range_seek(&ghost, "x", &seek, after), Some(vec![]));
423    }
424}