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 order;
16mod point;
17mod seek;
18mod text;
19
20pub(super) use order::RangeIndex;
21pub(crate) use order::{RangeSeek, SpatialSeek};
22pub(crate) use point::spatial_holds;
23pub(super) use point::PointIndex;
24/// Profile-only: the bench harness drives the point backend directly
25/// (the R-tree vs. grid comparison of record lives there).
26#[cfg(test)]
27pub(super) use point::{point_insert, spatial_ids};
28pub(crate) use text::trigram_count;
29pub(super) use text::GramIndex;
30
31/// One declared index's postings for a `(label, property)` pair. The
32/// graph wiring below is written once against this trait.
33pub(super) trait DrainState: Default {
34    fn dirty(&self) -> &HashSet<NodeId>;
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    fn drain_pair<St: DrainState>(&self, pairs: &CoreMap<(u32, u32), St>, lid: u32, kid: u32) {
211        let Some(mut st) = pairs.get_mut(&(lid, kid)) else {
212            return;
213        };
214        if st.dirty().is_empty() {
215            return;
216        }
217        let ids = std::mem::take(st.dirty_mut());
218        for id in ids {
219            st.remove_node(id);
220            self.for_each_node_pair_value(id, lid, kid, |value| st.insert(id, value));
221        }
222    }
223}
224
225/// Intersect `next` into the accumulator: the first set becomes the
226/// accumulator, every later one narrows it. The canonical accumulator fold
227/// for every multi-set seek (declared indexes and equality lookups).
228pub(super) fn intersect_acc(acc: &mut Option<HashSet<NodeId>>, next: HashSet<NodeId>) {
229    *acc = Some(match acc.take() {
230        None => next,
231        Some(prev) => prev.intersection(&next).copied().collect(),
232    });
233}
234
235/// Per-kind byte estimate of the lazily built declared index pairs — the
236/// research-gated census harness's view (ADR-0476 quarantine). Only
237/// the order/by-node arms are counted; the eq-only fallback arms are not.
238/// [`Self::text_bytes`] and [`Self::point_bytes`] are per-posting
239/// estimates (no byte walk); every printed census row is one of these
240/// fields.
241#[cfg(feature = "research")]
242#[derive(Debug, Default, Clone)]
243pub struct DeclaredCensus {
244    pub range_pairs: usize,
245    pub range_order_keys: u64,
246    pub range_posted_ids: u64,
247    pub range_bytes: u64,
248    pub text_pairs: usize,
249    pub text_grams: u64,
250    /// 8 bytes per gram posting.
251    pub text_bytes: u64,
252    pub point_pairs: usize,
253    pub point_entries: u64,
254    /// 40 bytes per posted point.
255    pub point_bytes: u64,
256}
257
258impl Graph {
259    #[cfg(feature = "research")]
260    pub(super) fn declared_index_census(&self) -> DeclaredCensus {
261        use std::mem::size_of;
262
263        use crate::memory::{hashset_i64_bytes, vec_heap, OVERHEAD_MAP_ENTRY};
264
265        let mut c = DeclaredCensus::default();
266        for pair in self.indexes.range_pairs.iter() {
267            c.range_pairs += 1;
268            let st = pair.value();
269            for postings in st.order.values() {
270                c.range_order_keys += 1;
271                c.range_bytes += size_of::<order::OrderKey>() as u64
272                    + size_of::<order::Postings>() as u64
273                    + OVERHEAD_MAP_ENTRY;
274                match postings {
275                    order::Postings::One(_) => c.range_posted_ids += 1,
276                    order::Postings::Many(set) => {
277                        c.range_posted_ids += set.len() as u64;
278                        c.range_bytes += hashset_i64_bytes(set.capacity());
279                    }
280                }
281            }
282            for keys in st.by_node.values() {
283                c.range_bytes +=
284                    OVERHEAD_MAP_ENTRY + size_of::<order::RevKeys<order::OrderKey>>() as u64;
285                if let order::RevKeys::Many(keys) = keys {
286                    c.range_bytes += vec_heap(keys.len(), size_of::<order::OrderKey>() as u64);
287                }
288            }
289            // Both sets are charged by element count: they are transient
290            // and small next to the postings above.
291            c.range_bytes += hashset_i64_bytes(st.dirty.len() + st.unbounded.len());
292        }
293        for pair in self.indexes.gram_pairs.iter() {
294            c.text_pairs += 1;
295            let grams = pair.value().grams.len() as u64;
296            c.text_grams += grams;
297            c.text_bytes += grams * 8;
298        }
299        for pair in self.indexes.point_pairs.iter() {
300            c.point_pairs += 1;
301            let entries = pair.value().pt_count() as u64;
302            c.point_entries += entries;
303            c.point_bytes += entries * 40;
304        }
305        c
306    }
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312
313    #[test]
314    fn order_remove_drops_only_that_node() {
315        let mut st = RangeIndex::default();
316        order::insert_order(&mut st, &Value::Int(1), 10);
317        order::insert_order(&mut st, &Value::Int(2), 11);
318        order::order_remove_node(&mut st, 10);
319        assert!(!st
320            .order
321            .contains_key(&order::order_key(&Value::Int(1)).unwrap()));
322        assert!(st
323            .order
324            .get(&order::order_key(&Value::Int(2)).unwrap())
325            .unwrap()
326            .contains(11));
327    }
328
329    #[test]
330    fn string_order_key_shares_the_value_payload() {
331        let payload: Arc<str> = "Ada".into();
332        let value = Value::String(Arc::clone(&payload));
333        let mut st = RangeIndex::default();
334        order::insert_order(&mut st, &value, 10);
335        order::insert_order(&mut st, &Value::String("Bob".into()), 11);
336        let posted = st.by_node[&10].first().unwrap();
337        assert!(matches!(posted, order::OrderKey::String(s) if Arc::ptr_eq(s, &payload)));
338        assert!(st
339            .order
340            .keys()
341            .any(|k| matches!(k, order::OrderKey::String(s) if Arc::ptr_eq(s, &payload))));
342        assert_eq!(order::prefix_ids(&st.order, "A"), HashSet::from([10]));
343    }
344
345    #[test]
346    fn gram_remove_drops_only_that_node() {
347        let mut st = GramIndex::default();
348        text::gram_insert(&mut st, &Arc::from("abc"), 10);
349        text::gram_insert(&mut st, &Arc::from("zzz"), 11);
350        text::gram_remove_node(&mut st, 10);
351        assert!(st.grams.values().all(|ids| !ids.holds(10)));
352        assert!(st.grams.values().any(|ids| ids.holds(11)));
353    }
354
355    /// `finish_ids` re-checks posted candidates on the raw version (LABS-853):
356    /// a tombstoned node, one missing a pattern label, and one whose visible
357    /// value fails the seek are each dropped exactly as the eager `node_at`
358    /// re-check dropped them — compared against that oracle at both
359    /// snapshots.
360    #[test]
361    fn finish_ids_filters_like_the_eager_node_at_recheck() {
362        let g = Graph::default();
363        let node = |labels: &[&str], x: i64| {
364            g.create_node(
365                labels.iter().map(|l| l.to_string()).collect(),
366                BTreeMap::from([("x".into(), Value::Int(x))]),
367            )
368            .unwrap()
369        };
370        g.begin_write().unwrap();
371        let kept = node(&["N", "M"], 5);
372        let dead = node(&["N", "M"], 6);
373        let unlabeled = node(&["N"], 7);
374        let failing = node(&["N", "M"], 8);
375        g.commit_write();
376        g.materialize_range_index("N", "x");
377        let before = g.commit_ts();
378        g.begin_write().unwrap();
379        g.delete_node(dead, true).unwrap();
380        g.set_property_node(failing, "x", Value::Int(0));
381        g.commit_write();
382        let after = g.commit_ts();
383
384        let op = relate_ir::BinaryOp::Gt;
385        let bound = Value::Int(1);
386        let seek = RangeSeek::Cmp {
387            op,
388            bound: bound.clone(),
389        };
390        let labels = vec!["N".to_string(), "M".to_string()];
391        let eager = |ts: u64| {
392            let mut ids: Vec<_> = [kept, dead, unlabeled, failing]
393                .into_iter()
394                .filter(|id| {
395                    g.node_at(*id, ts).is_some_and(|n| {
396                        Graph::node_matches(&n, &labels, &BTreeMap::new())
397                            && n.properties
398                                .get("x")
399                                .is_some_and(|v| order::cmp_holds(v, op, &bound))
400                    })
401                })
402                .collect();
403            ids.sort();
404            ids
405        };
406        let lazy = |ts: u64| g.lookup_range_seek(&labels, "x", &seek, ts).unwrap();
407
408        assert_eq!(lazy(before), vec![kept, dead, failing]);
409        assert_eq!(lazy(before), eager(before));
410        assert_eq!(lazy(after), vec![kept]);
411        assert_eq!(lazy(after), eager(after));
412        // A pattern label the interner never saw is carried by no node.
413        let ghost = vec!["N".to_string(), "Ghost".to_string()];
414        assert_eq!(g.lookup_range_seek(&ghost, "x", &seek, after), Some(vec![]));
415    }
416}