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