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::{BTreeMap, HashSet};
8use std::ops::ControlFlow;
9
10use relate_core::{NodeId, Value};
11
12use crate::redo::{IndexDetailSpec, IndexKindSpec};
13
14use super::*;
15
16mod order;
17mod point;
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    /// Labels among `labels` whose pair for `key` exists in `pairs`.
157    /// `None` when none do (the seek must scan). An empty pattern label
158    /// list cannot be served: an index on one label would miss the others.
159    fn indexed_labels<St>(
160        &self,
161        labels: &[String],
162        key: &str,
163        pairs: &CoreMap<(u32, u32), St>,
164    ) -> Option<Vec<u32>> {
165        if labels.is_empty() {
166            return None;
167        }
168        let kid = self.interner.get_id(key)?;
169        let ids: Vec<u32> = labels
170            .iter()
171            .filter_map(|l| self.interner.get_id(l))
172            .filter(|lid| pairs.contains_key(&(*lid, kid)))
173            .collect();
174        (!ids.is_empty()).then_some(ids)
175    }
176
177    /// Build one pair from every version of every node in the label index
178    /// (a superset; the seek re-checks the snapshot, ADR-0018).
179    fn materialize_pair<St: DrainState>(
180        &self,
181        pairs: &CoreMap<(u32, u32), St>,
182        label: &str,
183        property: &str,
184    ) {
185        let (lid, kid) = self.intern_pair(label, property);
186        let mut st = St::default();
187        self.for_each_pair_value(lid, kid, |id, value| st.insert(id, value));
188        // Sealed before publish: a concurrent seek either sees the fully
189        // built pair or none of it.
190        st.seal();
191        pairs.insert((lid, kid), st);
192    }
193
194    pub(super) fn materialize_text_index(&self, label: &str, property: &str) {
195        self.materialize_pair(&self.indexes.gram_pairs, label, property);
196    }
197
198    pub(super) fn materialize_range_index(&self, label: &str, property: &str) {
199        self.materialize_pair(&self.indexes.range_pairs, label, property);
200    }
201
202    pub(super) fn materialize_point_index(&self, label: &str, property: &str) {
203        self.materialize_pair(&self.indexes.point_pairs, label, property);
204    }
205
206    /// Repost every dirty node of one pair. The write guard is held across
207    /// the whole drain, so a concurrent `declared_dirty` lands either before
208    /// the take (reposted here) or after it (kept for the next drain).
209    fn drain_pair<St: DrainState>(&self, pairs: &CoreMap<(u32, u32), St>, lid: u32, kid: u32) {
210        let Some(mut st) = pairs.get_mut(&(lid, kid)) else {
211            return;
212        };
213        if st.dirty().is_empty() {
214            return;
215        }
216        let ids = std::mem::take(st.dirty_mut());
217        for id in ids {
218            st.remove_node(id);
219            self.for_each_node_pair_value(id, lid, kid, |value| st.insert(id, value));
220        }
221    }
222
223    /// The shared seek: drain each indexed label's pair, scan it, intersect
224    /// across labels, and re-check the snapshot. `scan` returns `None` to
225    /// decline (the caller scans), as does a pair that vanished between
226    /// `indexed_labels` and here — a concurrent `DROP INDEX` must not be
227    /// reported as zero rows.
228    fn lookup_indexed<St: DrainState>(
229        &self,
230        pairs: &CoreMap<(u32, u32), St>,
231        labels: &[String],
232        key: &str,
233        ts: u64,
234        scan: impl Fn(&St) -> Option<HashSet<NodeId>>,
235        pred: impl Fn(&Value) -> bool,
236    ) -> Option<Vec<NodeId>> {
237        let lids = self.indexed_labels(labels, key, pairs)?;
238        let kid = self.interner.get_id(key)?;
239        let mut acc: Option<HashSet<NodeId>> = None;
240        for lid in lids {
241            self.drain_pair(pairs, lid, kid);
242            let st = pairs.get(&(lid, kid))?;
243            let next = scan(&st)?;
244            drop(st);
245            intersect_acc(&mut acc, next);
246        }
247        Some(self.finish_ids(acc.into_iter().flatten(), labels, key, ts, pred))
248    }
249
250    pub(super) fn lookup_text_contains(
251        &self,
252        labels: &[String],
253        key: &str,
254        needle: &str,
255        ts: u64,
256    ) -> Option<Vec<NodeId>> {
257        let grams = text::query_grams(needle)?;
258        self.lookup_indexed(
259            &self.indexes.gram_pairs,
260            labels,
261            key,
262            ts,
263            |st| Some(text::intersect_grams(st, &grams)),
264            |v| v.as_string().is_some_and(|s| s.contains(needle)),
265        )
266    }
267
268    pub(super) fn lookup_text_prefix(
269        &self,
270        labels: &[String],
271        key: &str,
272        prefix: &str,
273        ts: u64,
274    ) -> Option<Vec<NodeId>> {
275        self.lookup_indexed(
276            &self.indexes.range_pairs,
277            labels,
278            key,
279            ts,
280            |st| Some(order::prefix_ids(&st.order, prefix)),
281            |v| v.as_string().is_some_and(|s| s.starts_with(prefix)),
282        )
283    }
284
285    pub(crate) fn lookup_range_seek(
286        &self,
287        labels: &[String],
288        key: &str,
289        seek: &RangeSeek,
290        ts: u64,
291    ) -> Option<Vec<NodeId>> {
292        match seek {
293            RangeSeek::Eq(v) => self.lookup_range_values(labels, key, std::slice::from_ref(v), ts),
294            RangeSeek::In(vs) => self.lookup_range_values(labels, key, vs, ts),
295            RangeSeek::Cmp { op, bound } => {
296                order::order_key(bound)?;
297                let op = *op;
298                self.lookup_indexed(
299                    &self.indexes.range_pairs,
300                    labels,
301                    key,
302                    ts,
303                    // A stored temporal outside the order-key window is not
304                    // posted; the index cannot answer a comparison then.
305                    |st| {
306                        st.unbounded
307                            .is_empty()
308                            .then(|| order::range_ids(&st.order, op, bound))
309                    },
310                    |v| order::cmp_holds(v, op, bound),
311                )
312            }
313        }
314    }
315
316    /// Upper bound on the ids [`Self::lookup_range_seek`] would collect from
317    /// the index, counted from posting lengths. `None` when the index cannot
318    /// serve the predicate. A comparison with unbounded temporal postings
319    /// declines, matching the id seek. The bound is not snapshot-filtered.
320    pub(crate) fn range_seek_cardinality(
321        &self,
322        labels: &[String],
323        key: &str,
324        seek: &RangeSeek,
325    ) -> Option<usize> {
326        match seek {
327            RangeSeek::Eq(v) => self.range_values_cardinality(labels, key, std::slice::from_ref(v)),
328            RangeSeek::In(vs) => self.range_values_cardinality(labels, key, vs),
329            RangeSeek::Cmp { op, bound } => {
330                order::order_key(bound)?;
331                let op = *op;
332                self.range_pair_cost(labels, key, |st| {
333                    st.unbounded
334                        .is_empty()
335                        .then(|| order::range_count(&st.order, op, bound))
336                })
337            }
338        }
339    }
340
341    /// Work upper bound for one range seek across the indexed labels. `Some(0)`
342    /// when any label posts nothing, because the label intersection is empty.
343    fn range_pair_cost(
344        &self,
345        labels: &[String],
346        key: &str,
347        count: impl Fn(&order::RangeIndex) -> Option<usize>,
348    ) -> Option<usize> {
349        let lids = self.indexed_labels(labels, key, &self.indexes.range_pairs)?;
350        let kid = self.interner.get_id(key)?;
351        let mut cost = 0usize;
352        for lid in lids {
353            self.drain_pair(&self.indexes.range_pairs, lid, kid);
354            let st = self.indexes.range_pairs.get(&(lid, kid))?;
355            let n = count(&st)?;
356            if n == 0 {
357                return Some(0);
358            }
359            cost = cost.saturating_add(n);
360        }
361        Some(cost)
362    }
363
364    fn range_values_cardinality(
365        &self,
366        labels: &[String],
367        key: &str,
368        values: &[Value],
369    ) -> Option<usize> {
370        let mut total = 0usize;
371        let mut served = false;
372        for value in values {
373            if GroupKey::for_property_index(value).is_none() {
374                continue;
375            }
376            let n =
377                self.range_pair_cost(labels, key, |st| Some(order::equality_count(st, value)))?;
378            served = true;
379            total = total.saturating_add(n);
380        }
381        served.then_some(total)
382    }
383
384    fn lookup_range_values(
385        &self,
386        labels: &[String],
387        key: &str,
388        values: &[Value],
389        ts: u64,
390    ) -> Option<Vec<NodeId>> {
391        let lids = self.indexed_labels(labels, key, &self.indexes.range_pairs)?;
392        let kid = self.interner.get_id(key)?;
393        let mut matched = HashSet::new();
394        for v in values {
395            if GroupKey::for_property_index(v).is_none() {
396                continue;
397            }
398            let mut acc: Option<HashSet<NodeId>> = None;
399            for lid in &lids {
400                let ids = self.range_equality_ids(*lid, kid, v)?;
401                intersect_acc(&mut acc, ids);
402            }
403            if let Some(ids) = acc {
404                matched.extend(ids);
405            }
406        }
407        Some(self.finish_ids(matched, labels, key, ts, |v| {
408            values.iter().any(|b| v.eq_non_null(b))
409        }))
410    }
411
412    /// The capped form of the declared equality seek: the matches of
413    /// `labels` and `props` among the postings of the shortest-posting
414    /// `(label, property)` pair, stopping at `cap + 1` matches. No id set
415    /// is built and no posting is read past the stop; each posting read
416    /// is one node read, counted as examined. Every candidate is checked
417    /// against the snapshot at `ts` with [`Graph::node_matches`], the
418    /// predicate the unbounded seek's re-check applies. `None` when a pair
419    /// vanished (a concurrent `DROP INDEX`): the caller scans instead.
420    pub(super) fn range_equality_upto(
421        &self,
422        labels: &[String],
423        props: &BTreeMap<String, Value>,
424        ts: u64,
425        cap: usize,
426    ) -> Option<Vec<NodeId>> {
427        let mut best: Option<(usize, u32, u32, &Value)> = None;
428        for (key, value) in props {
429            if GroupKey::for_property_index(value).is_none() {
430                return Some(Vec::new());
431            }
432            let Some(kid) = self.interner.get_id(key) else {
433                return Some(Vec::new());
434            };
435            for label in labels {
436                let Some(lid) = self.interner.get_id(label) else {
437                    continue;
438                };
439                if !self.indexes.range_pairs.contains_key(&(lid, kid)) {
440                    continue;
441                }
442                self.drain_pair(&self.indexes.range_pairs, lid, kid);
443                let st = self.indexes.range_pairs.get(&(lid, kid))?;
444                let count = order::equality_count(&st, value);
445                if best.is_none_or(|(least, ..)| count < least) {
446                    best = Some((count, lid, kid, value));
447                }
448            }
449        }
450        let (_, lid, kid, value) = best?;
451        let st = self.indexes.range_pairs.get(&(lid, kid))?;
452        let (mut matched, mut examined) = (Vec::new(), 0u64);
453        order::equality_each(&st, value, |id| {
454            examined += 1;
455            let hit = self
456                .node_at(id, ts)
457                .is_some_and(|n| Self::node_matches(&n, labels, props));
458            if hit {
459                matched.push(id);
460            }
461            if matched.len() > cap {
462                ControlFlow::Break(())
463            } else {
464                ControlFlow::Continue(())
465            }
466        });
467        crate::ctx::count_node_reads(examined);
468        matched.sort_unstable();
469        Some(matched)
470    }
471
472    /// Drain the range pair and read its equality postings. `None` when the
473    /// pair vanished (a concurrent `DROP INDEX`), so the caller scans
474    /// instead of reporting zero rows.
475    pub(super) fn range_equality_ids(
476        &self,
477        lid: u32,
478        kid: u32,
479        value: &Value,
480    ) -> Option<HashSet<NodeId>> {
481        self.drain_pair(&self.indexes.range_pairs, lid, kid);
482        let st = self.indexes.range_pairs.get(&(lid, kid))?;
483        Some(order::equality_ids(&st, value))
484    }
485
486    pub(crate) fn lookup_spatial_seek(
487        &self,
488        labels: &[String],
489        key: &str,
490        seek: &SpatialSeek,
491        ts: u64,
492    ) -> Option<Vec<NodeId>> {
493        self.lookup_indexed(
494            &self.indexes.point_pairs,
495            labels,
496            key,
497            ts,
498            |st| Some(point::spatial_ids(st, seek)),
499            |v| point::spatial_holds(v, seek),
500        )
501    }
502
503    /// Re-check each posted candidate against the snapshot at `ts`: the
504    /// visible version must carry every pattern label and a `key` value
505    /// that satisfies `pred`. Reads the raw version — interned label ids
506    /// and the one-slot `CompactProps::get` — never `node_at`, which
507    /// materializes the full property map per candidate (the profile-hot
508    /// `to_map` path, ADR-0033; LABS-853).
509    fn finish_ids(
510        &self,
511        acc: impl IntoIterator<Item = NodeId>,
512        labels: &[String],
513        key: &str,
514        ts: u64,
515        pred: impl Fn(&Value) -> bool,
516    ) -> Vec<NodeId> {
517        // Every stored label and key was interned before its version
518        // committed, so a pattern label or key the interner never saw is
519        // carried by no node: nothing survives the re-check.
520        let lids: Option<Vec<u32>> = labels.iter().map(|l| self.interner.get_id(l)).collect();
521        let (Some(lids), Some(kid)) = (lids, self.interner.get_id(key)) else {
522            return Vec::new();
523        };
524        let mut ids: Vec<_> = acc
525            .into_iter()
526            .filter(|id| {
527                self.nodes.get(id).is_some_and(|vers| {
528                    visible_version(&vers, ts).is_some_and(|ver| {
529                        ver.live.has_labels(&lids) && ver.live.props.get(kid).is_some_and(&pred)
530                    })
531                })
532            })
533            .collect();
534        ids.sort();
535        ids.dedup();
536        ids
537    }
538
539    /// True when every property has a range index on at least one pattern label.
540    pub(super) fn range_serves_equality(
541        &self,
542        labels: &[String],
543        props: &BTreeMap<String, Value>,
544    ) -> bool {
545        if labels.is_empty() || props.is_empty() {
546            return false;
547        }
548        props.keys().all(|k| {
549            labels.iter().any(|l| {
550                self.string_pair_id(l, k)
551                    .is_some_and(|pk| self.indexes.range_pairs.contains_key(&pk))
552            })
553        })
554    }
555}
556
557/// Intersect `next` into the accumulator: the first set becomes the
558/// accumulator, every later one narrows it. The canonical accumulator fold
559/// for every multi-set seek (declared indexes and equality lookups).
560pub(super) fn intersect_acc(acc: &mut Option<HashSet<NodeId>>, next: HashSet<NodeId>) {
561    *acc = Some(match acc.take() {
562        None => next,
563        Some(prev) => prev.intersection(&next).copied().collect(),
564    });
565}
566
567/// Per-kind byte estimate of the lazily built declared index pairs — the
568/// research-gated census harness's view (ADR-0476 quarantine). Only
569/// the order/by-node arms are counted; the eq-only fallback arms are not.
570/// [`Self::text_bytes`] and [`Self::point_bytes`] are per-posting
571/// estimates (no byte walk); every printed census row is one of these
572/// fields.
573#[cfg(feature = "research")]
574#[derive(Debug, Default, Clone)]
575pub struct DeclaredCensus {
576    pub range_pairs: usize,
577    pub range_order_keys: u64,
578    pub range_posted_ids: u64,
579    pub range_bytes: u64,
580    pub text_pairs: usize,
581    pub text_grams: u64,
582    /// 8 bytes per gram posting.
583    pub text_bytes: u64,
584    pub point_pairs: usize,
585    pub point_entries: u64,
586    /// 40 bytes per posted point.
587    pub point_bytes: u64,
588}
589
590impl Graph {
591    #[cfg(feature = "research")]
592    pub(super) fn declared_index_census(&self) -> DeclaredCensus {
593        use std::mem::size_of;
594
595        use crate::memory::{hashset_i64_bytes, vec_heap, OVERHEAD_MAP_ENTRY};
596
597        let mut c = DeclaredCensus::default();
598        for pair in self.indexes.range_pairs.iter() {
599            c.range_pairs += 1;
600            let st = pair.value();
601            for postings in st.order.values() {
602                c.range_order_keys += 1;
603                c.range_bytes += size_of::<order::OrderKey>() as u64
604                    + size_of::<order::Postings>() as u64
605                    + OVERHEAD_MAP_ENTRY;
606                match postings {
607                    order::Postings::One(_) => c.range_posted_ids += 1,
608                    order::Postings::Many(set) => {
609                        c.range_posted_ids += set.len() as u64;
610                        c.range_bytes += hashset_i64_bytes(set.capacity());
611                    }
612                }
613            }
614            for keys in st.by_node.values() {
615                c.range_bytes +=
616                    OVERHEAD_MAP_ENTRY + size_of::<order::RevKeys<order::OrderKey>>() as u64;
617                if let order::RevKeys::Many(keys) = keys {
618                    c.range_bytes += vec_heap(keys.len(), size_of::<order::OrderKey>() as u64);
619                }
620            }
621            // Both sets are charged by element count: they are transient
622            // and small next to the postings above.
623            c.range_bytes += hashset_i64_bytes(st.dirty.len() + st.unbounded.len());
624        }
625        for pair in self.indexes.gram_pairs.iter() {
626            c.text_pairs += 1;
627            let grams = pair.value().grams.len() as u64;
628            c.text_grams += grams;
629            c.text_bytes += grams * 8;
630        }
631        for pair in self.indexes.point_pairs.iter() {
632            c.point_pairs += 1;
633            let entries = pair.value().pt_count() as u64;
634            c.point_entries += entries;
635            c.point_bytes += entries * 40;
636        }
637        c
638    }
639}
640
641#[cfg(test)]
642mod tests {
643    use super::*;
644
645    #[test]
646    fn order_remove_drops_only_that_node() {
647        let mut st = RangeIndex::default();
648        order::insert_order(&mut st, &Value::Int(1), 10);
649        order::insert_order(&mut st, &Value::Int(2), 11);
650        order::order_remove_node(&mut st, 10);
651        assert!(!st
652            .order
653            .contains_key(&order::order_key(&Value::Int(1)).unwrap()));
654        assert!(st
655            .order
656            .get(&order::order_key(&Value::Int(2)).unwrap())
657            .unwrap()
658            .contains(11));
659    }
660
661    #[test]
662    fn string_order_key_shares_the_value_payload() {
663        let payload: Arc<str> = "Ada".into();
664        let value = Value::String(Arc::clone(&payload));
665        let mut st = RangeIndex::default();
666        order::insert_order(&mut st, &value, 10);
667        order::insert_order(&mut st, &Value::String("Bob".into()), 11);
668        let posted = st.by_node[&10].first().unwrap();
669        assert!(matches!(posted, order::OrderKey::String(s) if Arc::ptr_eq(s, &payload)));
670        assert!(st
671            .order
672            .keys()
673            .any(|k| matches!(k, order::OrderKey::String(s) if Arc::ptr_eq(s, &payload))));
674        assert_eq!(order::prefix_ids(&st.order, "A"), HashSet::from([10]));
675    }
676
677    #[test]
678    fn gram_remove_drops_only_that_node() {
679        let mut st = GramIndex::default();
680        text::gram_insert(&mut st, &Arc::from("abc"), 10);
681        text::gram_insert(&mut st, &Arc::from("zzz"), 11);
682        text::gram_remove_node(&mut st, 10);
683        assert!(st.grams.values().all(|ids| !ids.holds(10)));
684        assert!(st.grams.values().any(|ids| ids.holds(11)));
685    }
686
687    /// `finish_ids` re-checks posted candidates on the raw version (LABS-853):
688    /// a tombstoned node, one missing a pattern label, and one whose visible
689    /// value fails the seek are each dropped exactly as the eager `node_at`
690    /// re-check dropped them — compared against that oracle at both
691    /// snapshots.
692    #[test]
693    fn finish_ids_filters_like_the_eager_node_at_recheck() {
694        let g = Graph::default();
695        let node = |labels: &[&str], x: i64| {
696            g.create_node(
697                labels.iter().map(|l| l.to_string()).collect(),
698                BTreeMap::from([("x".into(), Value::Int(x))]),
699            )
700            .unwrap()
701        };
702        g.begin_write().unwrap();
703        let kept = node(&["N", "M"], 5);
704        let dead = node(&["N", "M"], 6);
705        let unlabeled = node(&["N"], 7);
706        let failing = node(&["N", "M"], 8);
707        g.commit_write();
708        g.materialize_range_index("N", "x");
709        let before = g.commit_ts();
710        g.begin_write().unwrap();
711        g.delete_node(dead, true).unwrap();
712        g.set_property_node(failing, "x", Value::Int(0));
713        g.commit_write();
714        let after = g.commit_ts();
715
716        let op = relate_ir::BinaryOp::Gt;
717        let bound = Value::Int(1);
718        let seek = RangeSeek::Cmp {
719            op,
720            bound: bound.clone(),
721        };
722        let labels = vec!["N".to_string(), "M".to_string()];
723        let eager = |ts: u64| {
724            let mut ids: Vec<_> = [kept, dead, unlabeled, failing]
725                .into_iter()
726                .filter(|id| {
727                    g.node_at(*id, ts).is_some_and(|n| {
728                        Graph::node_matches(&n, &labels, &BTreeMap::new())
729                            && n.properties
730                                .get("x")
731                                .is_some_and(|v| order::cmp_holds(v, op, &bound))
732                    })
733                })
734                .collect();
735            ids.sort();
736            ids
737        };
738        let lazy = |ts: u64| g.lookup_range_seek(&labels, "x", &seek, ts).unwrap();
739
740        assert_eq!(lazy(before), vec![kept, dead, failing]);
741        assert_eq!(lazy(before), eager(before));
742        assert_eq!(lazy(after), vec![kept]);
743        assert_eq!(lazy(after), eager(after));
744        // A pattern label the interner never saw is carried by no node.
745        let ghost = vec!["N".to_string(), "Ghost".to_string()];
746        assert_eq!(g.lookup_range_seek(&ghost, "x", &seek, after), Some(vec![]));
747    }
748}