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