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