Skip to main content

relate_executor/graph/
index_lookup.rs

1//! The index-backed lookup and scan planning (ADR-0218, ADR-0063): the
2//! label/equality candidate sets, the residual scan, and the plan-time
3//! cardinality reads. A sibling of `index.rs`.
4
5use std::ops::ControlFlow;
6
7use super::declared::intersect_acc;
8use super::index_postings::EqualityRoute;
9use super::*;
10
11/// The fixed half of an equality re-check walk — what every examined
12/// candidate is re-verified against, and the cap contract — bundled so
13/// the walk ([`RecheckWalk`]) reads one context per candidate.
14pub(in crate::graph) struct RecheckSpec<'a> {
15    /// Every pattern label and property, re-applied per candidate by
16    /// [`Graph::node_matches`].
17    pub(in crate::graph) labels: &'a [String],
18    pub(in crate::graph) props: &'a BTreeMap<String, Value>,
19    /// The snapshot the re-check verifies against.
20    pub(in crate::graph) ts: u64,
21    /// The capped contract's stop: `Break` at the first `cap + 1`
22    /// matches ([`Graph::lookup_nodes_upto_at`]); `None` never breaks.
23    pub(in crate::graph) cap: Option<usize>,
24}
25
26/// One equality re-check walk over an id stream: the hits and the
27/// examined count, carrying the shared per-candidate body (count the
28/// read, re-verify the snapshot with the canonical node predicate,
29/// record the hit, stop at the cap) and the closing count-and-sort.
30/// The caller supplies only the stream — a label bucket, a declared
31/// posting walk, or a lazy posting bucket — visiting each id through
32/// [`Self::visit`] and taking the answer from [`Self::finish`].
33pub(in crate::graph) struct RecheckWalk<'a, 'g> {
34    graph: &'g Graph,
35    spec: &'a RecheckSpec<'a>,
36    matched: Vec<NodeId>,
37    examined: u64,
38}
39
40impl RecheckWalk<'_, '_> {
41    /// One examined candidate — the shared body; `Break` at the cap.
42    pub(in crate::graph) fn visit(&mut self, id: NodeId) -> ControlFlow<()> {
43        self.examined += 1;
44        let hit = self
45            .graph
46            .node_at(id, self.spec.ts)
47            .is_some_and(|n| Graph::node_matches(&n, self.spec.labels, self.spec.props));
48        if hit {
49            self.matched.push(id);
50        }
51        if self.spec.cap.is_some_and(|cap| self.matched.len() > cap) {
52            ControlFlow::Break(())
53        } else {
54            ControlFlow::Continue(())
55        }
56    }
57
58    /// The closing half: count the reads, sort the hits.
59    pub(in crate::graph) fn finish(self) -> Vec<NodeId> {
60        crate::ctx::count_node_reads(self.examined);
61        let mut matched = self.matched;
62        matched.sort_unstable();
63        matched
64    }
65}
66
67/// Whether a candidate resolution consults the attached store: the
68/// ordinary path consults ([`StoreConsult::Consult`]); the equality
69/// serve's per-value fallback rides [`StoreConsult::Bypass`] because its
70/// one whole-list consult already asked and was declined — a typed
71/// policy, not a caller's bare bool.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73enum StoreConsult {
74    Consult,
75    Bypass,
76}
77
78impl Graph {
79    /// Approximate number of nodes carrying `label`: the label-index set
80    /// size (ADR-0218). Plan-time estimate only — it is O(1), ignores
81    /// snapshot visibility, and counts every id the index holds; a label
82    /// the store has never interned is 0.
83    pub fn label_count(&self, label: &str) -> u64 {
84        self.interner
85            .get_id(label)
86            .map_or(0, |lid| self.label_count_by_id(lid))
87    }
88
89    /// [`Graph::label_count`] for an already-resolved label token id.
90    pub fn label_count_by_id(&self, lid: u32) -> u64 {
91        self.indexes
92            .label_index
93            .get(&lid)
94            .map_or(0, |ids| ids.len() as u64)
95    }
96
97    pub fn lookup_nodes(
98        &self,
99        labels: &[String],
100        props: &BTreeMap<String, Value>,
101    ) -> Option<Vec<NodeId>> {
102        self.lookup_nodes_at(labels, props, self.read_ts())
103    }
104
105    /// The label/property candidate lookup at `ts`, ascending and
106    /// deduplicated: `None` only for the both-empty `Unindexed` arm —
107    /// the shape the caller scans for instead — a non-empty seek is
108    /// always served.
109    pub fn lookup_nodes_at(
110        &self,
111        labels: &[String],
112        props: &BTreeMap<String, Value>,
113        ts: u64,
114    ) -> Option<Vec<NodeId>> {
115        self.lookup_nodes_upto_at(labels, props, ts, None)
116    }
117
118    /// [`Graph::lookup_nodes_at`] for a caller that only needs to know
119    /// whether more than `cap` nodes match: a residual scan stops once it
120    /// has `cap + 1` matches. An answer of at most `cap` ids is complete,
121    /// ascending and deduplicated; a longer one is an arbitrary
122    /// `cap + 1`-id subset of the matches, meaningful only by its length.
123    /// Index-served arms answer in full (their postings already exist);
124    /// `None` is the both-empty `Unindexed` arm, as for the uncapped form.
125    pub fn lookup_nodes_upto_at(
126        &self,
127        labels: &[String],
128        props: &BTreeMap<String, Value>,
129        ts: u64,
130        cap: Option<usize>,
131    ) -> Option<Vec<NodeId>> {
132        self.lookup_nodes_at_with(labels, props, ts, cap, StoreConsult::Consult)
133    }
134
135    fn lookup_nodes_at_with(
136        &self,
137        labels: &[String],
138        props: &BTreeMap<String, Value>,
139        ts: u64,
140        cap: Option<usize>,
141        consult: StoreConsult,
142    ) -> Option<Vec<NodeId>> {
143        // The label scan's hot shape — one label, no property equality —
144        // is the one canonical label scan ([`node_ids_with_label_at`]):
145        // the bucket's ids copied once under its guard, each probed for
146        // visibility and the interned label id in place. No node is
147        // materialized (the profile-hot `node_at` path builds every
148        // candidate's full property map just to check a label). ADR-0665
149        // A/B: the store's label arm does not preempt this — the CI
150        // interleave measured the bitset arm at 1.5-2.2x on the pure
151        // label-scan pattern queries (q8/q30) while helping none.
152        if labels.len() == 1 && props.is_empty() {
153            return Some(self.node_ids_with_label_at(&labels[0], ts));
154        }
155        self.node_candidates(labels, props, ts, cap, consult)
156    }
157
158    /// The capped `=` / `IN` point seek over one property: the ids whose
159    /// `key` equals any of `values` and that carry every label, stopping
160    /// once more than `cap` distinct ids match. Each value rides the
161    /// capped keyed lookup ([`Graph::lookup_nodes_upto_at`]) — the
162    /// shortest posting streamed through the shared re-check walk, never
163    /// the whole posting list built into an id set — so a non-unique
164    /// value matching a large store reads `cap + 1` postings, not every
165    /// match. `None` only when a per-value keyed lookup declines
166    /// (a vanished pair under a concurrent `DROP INDEX`). An
167    /// answer of at most `cap` ids is complete, ascending and
168    /// deduplicated; a longer one is an arbitrary subset meaningful only
169    /// by its length. A value with no property-index key (a NaN)
170    /// matches nothing.
171    pub(crate) fn lookup_equality_upto(
172        &self,
173        labels: &[String],
174        key: &str,
175        values: &[Value],
176        ts: u64,
177        cap: usize,
178    ) -> Option<Vec<NodeId>> {
179        let probe = |value: &Value| BTreeMap::from([(key.to_string(), value.clone())]);
180        // The one route decision the uncapped serve reads
181        // ([`Graph::lookup_range_seek`]). ADR-0665 A/B (measured
182        // warm/cold ordering): behind the declared arm the attached
183        // experimental store's sorted `(key,row)` side-file serves the
184        // capped seek ahead of a COLD lazy pair only — a warm pair's
185        // probe beats the side-file seek, so it keeps the engine arm.
186        // The store is consulted ONCE for the whole list (the `IN` shape
187        // its sorted pass answers in one seek); the fallback loop below
188        // rides a store-free keyed lookup, so a cold-pair decline is not
189        // re-asked per value, and a Scan route the store declined answers
190        // `None` for the CALLER's one scan — the per-value loop would
191        // turn it into one full scan per list member (the regression the
192        // store arm introduced; the pre-store pre-check declined exactly
193        // here).
194        // The one route match answers both questions — whether the store
195        // is consulted for the whole list, and whether a store decline
196        // hands the CALLER the single scan — never a bool beside a
197        // re-test of the same enum.
198        match self.values_equality_route(labels, key, values) {
199            EqualityRoute::Scan => {
200                if let Some(ids) = self.prop_store_equality(labels, key, values, ts, Some(cap)) {
201                    return Some(ids);
202                }
203                // No index route and no store answer: the caller's single
204                // scan is the shape.
205                return None;
206            }
207            // A declared pair always outranks the store (ADR-0614's
208            // declared-then-postings precedence, unchanged).
209            EqualityRoute::Declared => {}
210            EqualityRoute::Postings => {
211                if !self.postings_pair_ready(labels, key) {
212                    if let Some(ids) = self.prop_store_equality(labels, key, values, ts, Some(cap))
213                    {
214                        return Some(ids);
215                    }
216                }
217            }
218        }
219        let mut found = std::collections::BTreeSet::new();
220        for value in values
221            .iter()
222            .filter(|v| GroupKey::for_property_index(v).is_some())
223        {
224            // `None` is the keyed lookup's decline: propagated, so the
225            // serve declines with it.
226            found.extend(self.lookup_nodes_at_with(
227                labels,
228                &probe(value),
229                ts,
230                Some(cap),
231                // Bypass: the whole-list consult above already asked and
232                // the store declined — the per-value fallback builds the
233                // route's own postings answer, never a second consult.
234                StoreConsult::Bypass,
235            )?);
236            if found.len() > cap {
237                break;
238            }
239        }
240        Some(found.into_iter().collect())
241    }
242
243    /// The ids posted under every label in `labels`: the label-index
244    /// buckets intersected through `intersect_acc`, the fold every
245    /// multi-set seek uses. A label the store never interned can match
246    /// nothing, so its empty bucket empties the result. Callers route a
247    /// label-less pattern to the full scan — this is only reached with a
248    /// non-empty `labels`.
249    fn intersect_label_ids(&self, labels: &[String]) -> HashSet<NodeId> {
250        let mut acc: Option<HashSet<NodeId>> = None;
251        for label in labels {
252            // An uninterned label can match nothing.
253            let ids = self
254                .interner
255                .get_id(label)
256                .and_then(|lid| self.indexes.label_index.get(&lid).map(|r| r.clone()))
257                .unwrap_or_default();
258            intersect_acc(&mut acc, ids);
259        }
260        acc.unwrap_or_default()
261    }
262
263    /// Index postings for a node lookup, or a finished answer when the
264    /// index cannot serve the predicate.
265    fn node_candidates(
266        &self,
267        labels: &[String],
268        props: &BTreeMap<String, Value>,
269        ts: u64,
270        cap: Option<usize>,
271        consult: StoreConsult,
272    ) -> Option<Vec<NodeId>> {
273        if labels.is_empty() && props.is_empty() {
274            return None;
275        }
276        if !labels.is_empty() && props.is_empty() {
277            // The label bucket intersection finished here: the id-based
278            // label probes answer it, the labels interned once — no node
279            // materialized (the materialized form built every candidate's
280            // property map just to check labels, ADR-0473's q30
281            // measurement). An uninterned label can match nothing (the
282            // interner is append-only), so a miss empties the answer.
283            let acc = self.intersect_label_ids(labels);
284            // Each posting is examined by the probe below.
285            crate::ctx::count_node_reads(acc.len() as u64);
286            // The probe filters in HashSet order; the arm's ascending
287            // contract (which `union_ids` merges on and `far_probe`
288            // assumes) needs the closing sort — the walk branch's
289            // `finish` sorts itself.
290            let mut probed: Vec<_> = match self.intern_labels(labels) {
291                Some(lids) => acc
292                    .into_iter()
293                    .filter(|&id| {
294                        lids.iter()
295                            .all(|lid| self.node_carries_label_at(id, *lid, ts))
296                    })
297                    .collect(),
298                None => Vec::new(),
299            };
300            probed.sort_unstable();
301            return Some(probed);
302        }
303        // The props-non-empty shapes from here (the two guards above own
304        // the empty-props ones). The route decides once (ADR-0614): a
305        // declared RANGE pair, the lazy equality postings, or the scan —
306        // the one three-way decision the id seek, the cardinality, this
307        // arm, and the overlay's scratch-mode flag all read.
308        let route = self.map_equality_route(labels, props);
309        // No declared pair covers the lookup. ADR-0665 A/B (measured
310        // warm/cold ordering): the attached experimental store's sorted
311        // side-file preempts a COLD lazy pair — its build was paid at
312        // attach, the postings' build is paid at first serve — but a WARM
313        // pair's probe beats the side-file seek (the CI interleave measured
314        // the store ahead of warm postings as a regression on repeated
315        // serves), so the engine arm keeps it. The route's decline cases
316        // (a label-less pattern, a value whose identity is narrower than
317        // its `=` class) are `Scan` here — the store arm serves them
318        // unconditionally (exact side-file match), with the full scan
319        // behind it. A declared pair always outranks the store
320        // (ADR-0614's declared-then-postings precedence, unchanged).
321        let store_first = match route {
322            EqualityRoute::Declared => false,
323            EqualityRoute::Scan => true,
324            EqualityRoute::Postings => !self.postings_pair_ready(
325                labels,
326                props
327                    .first_key_value()
328                    .expect("a props-non-empty candidate carries a first key")
329                    .0,
330            ),
331        };
332        if consult == StoreConsult::Consult && store_first && props.len() == 1 {
333            // One-property shapes only (the exact side-file match);
334            // multi-property patterns stay on the index routes, and the
335            // label-only shape never reaches here (the canonical label
336            // route above owns it).
337            let (key, value) = props
338                .first_key_value()
339                .expect("a one-property candidate carries a first key");
340            if let Some(ids) =
341                self.prop_store_equality(labels, key, std::slice::from_ref(value), ts, cap)
342            {
343                return Some(ids);
344            }
345        }
346        match route {
347            EqualityRoute::Postings => {
348                return Some(self.equality_postings_upto(labels, props, ts, cap));
349            }
350            EqualityRoute::Scan => {
351                return Some(self.scan_match(labels, props, ts, cap));
352            }
353            // A declared RANGE pair covers every sought property: the
354            // capped stream or the intersect loop below answers it.
355            EqualityRoute::Declared => {}
356        }
357        // A capped caller streams the shortest posting instead of
358        // building every posting's id set; a vanished pair (a concurrent
359        // `DROP INDEX`) falls to the scan below.
360        if let Some(cap) = cap {
361            return match self.range_equality_upto(labels, props, ts, cap) {
362                Some(ids) => Some(ids),
363                None => Some(self.scan_match(labels, props, ts, Some(cap))),
364            };
365        }
366        let mut acc: Option<HashSet<NodeId>> = None;
367        for (key, value) in props {
368            if GroupKey::for_property_index(value).is_none() {
369                return Some(Vec::new());
370            }
371            let Some(kid) = self.interner.get_id(key) else {
372                return Some(Vec::new());
373            };
374            let mut next: Option<HashSet<NodeId>> = None;
375            for label in labels {
376                let Some(lid) = self.interner.get_id(label) else {
377                    continue;
378                };
379                if !self.indexes.range_pairs.contains_key(&(lid, kid)) {
380                    continue;
381                }
382                let Some(ids) = self.range_equality_ids(lid, kid, value) else {
383                    return Some(self.scan_match(labels, props, ts, cap));
384                };
385                intersect_acc(&mut next, ids);
386            }
387            intersect_acc(&mut acc, next.unwrap_or_default());
388        }
389        // The declared pairs' accumulated postings, finished here: the
390        // shared re-check walk verifies each against the full predicate —
391        // the walk counts each examined posting itself, no cap on this
392        // arm (`cap: None` makes the walk's `Break` unreachable — the
393        // discard states it).
394        let spec = RecheckSpec {
395            labels,
396            props,
397            ts,
398            cap: None,
399        };
400        let mut walk = self.recheck_walk(&spec);
401        for id in acc.unwrap_or_default() {
402            let _ = walk.visit(id);
403        }
404        Some(walk.finish())
405    }
406
407    /// Whether a keyed node lookup on `(labels, props)` is answered by
408    /// an identity-keyed structure — a declared range pair, or, when
409    /// none covers the pair, the lazy equality postings (ADR-0614) —
410    /// the base half's mode, and the mode the overlay's scratch half
411    /// must match so one lookup's two halves answer with one equality
412    /// relation (LABS-1085 review). A scan-served lookup — a declined
413    /// value, a label-less pattern — keeps `=` semantics in both
414    /// halves.
415    pub(crate) fn equality_served_by_index(
416        &self,
417        labels: &[String],
418        props: &BTreeMap<String, Value>,
419    ) -> bool {
420        !matches!(self.map_equality_route(labels, props), EqualityRoute::Scan)
421    }
422
423    /// The label half of [`Self::node_matches`]: the node carries every one
424    /// of `labels`. The overlay's scratch merge asks it too, so one
425    /// containment rule serves the committed and the scratch side.
426    pub(crate) fn node_carries_labels(n: &Node, labels: &[String]) -> bool {
427        labels.iter().all(|l| n.labels.iter().any(|x| x == l))
428    }
429
430    /// The canonical node-predicate for a label/property seek: every
431    /// sought label carried, every sought property equal under Cypher
432    /// equality (`1 = 1.0`) — the predicate the base's residual scan
433    /// (`scan_match` and the `Indexed` arm's re-check), the declared
434    /// path's `finish_ids`, the lazy postings' serve (ADR-0614), and
435    /// the overlay's scratch merge all apply. Hosted here, the
436    /// lookup/scan file whose module doc claims this family — the one
437    /// home every consumer reads downward.
438    pub(crate) fn node_matches(
439        n: &Node,
440        labels: &[String],
441        props: &BTreeMap<String, Value>,
442    ) -> bool {
443        // Property comparison is Cypher equality (`1 = 1.0`), matching the
444        // normalized index key that produced the candidate.
445        Self::node_carries_labels(n, labels)
446            && props
447                .iter()
448                .all(|(k, v)| n.properties.get(k).is_some_and(|have| have.eq_non_null(v)))
449    }
450
451    /// Begin one equality re-check walk over `spec` — the shared
452    /// per-candidate body and the closing count-and-sort behind
453    /// [`RecheckWalk`], the form every re-checking site (the scan tail,
454    /// both equality serves, the `Indexed` arm's posting re-check)
455    /// reads.
456    pub(in crate::graph) fn recheck_walk<'a>(
457        &self,
458        spec: &'a RecheckSpec<'a>,
459    ) -> RecheckWalk<'a, '_> {
460        RecheckWalk {
461            graph: self,
462            spec,
463            matched: Vec::new(),
464            examined: 0,
465        }
466    }
467
468    /// The interned pattern label with the smallest label-index bucket —
469    /// the one bucket a label-conjunction scan or a postings serve
470    /// streams, so a serve never examines more nodes than the scan it
471    /// replaces. `None` when any pattern label was never interned (the
472    /// fail-closed rule: no node carries it, so the whole label
473    /// conjunction matches nothing) or `labels` is empty — the answer
474    /// both shapes give then.
475    pub(in crate::graph) fn smallest_interned_bucket(&self, labels: &[String]) -> Option<u32> {
476        self.intern_labels(labels)?
477            .into_iter()
478            .min_by_key(|lid| self.label_count_by_id(*lid))
479    }
480
481    /// Every pattern label's interned id, fail-closed: `None` when any
482    /// label was never interned — no node carries it, so the whole
483    /// label conjunction matches nothing. The one spelling of the rule
484    /// the keyed lookup's label-only arm, the shortest-bucket choice,
485    /// and `finish_ids`' re-check all read.
486    fn intern_labels(&self, labels: &[String]) -> Option<Vec<u32>> {
487        labels.iter().map(|l| self.interner.get_id(l)).collect()
488    }
489
490    /// Re-check each posted candidate against the snapshot at `ts`: the
491    /// visible version must carry every pattern label and a `key` value
492    /// that satisfies `pred`. Reads the raw version — interned label ids
493    /// and the one-slot `CompactProps::get` — never `node_at`, which
494    /// materializes the full property map per candidate (the profile-hot
495    /// `to_map` path, ADR-0033; LABS-853). The raw-version member of the
496    /// recheck family (beside [`RecheckWalk`]'s materializing form): the
497    /// declared seek family and the lazy
498    /// postings' single-key serve (ADR-0614) re-check through this same
499    /// filter, so both answer exactly the same candidates.
500    pub(in crate::graph) fn finish_ids(
501        &self,
502        acc: impl IntoIterator<Item = NodeId>,
503        labels: &[String],
504        key: &str,
505        ts: u64,
506        pred: impl Fn(&Value) -> bool,
507    ) -> Vec<NodeId> {
508        // Every stored label and key was interned before its version
509        // committed, so a pattern label or key the interner never saw is
510        // carried by no node: nothing survives the re-check.
511        let (Some(lids), Some(kid)) = (self.intern_labels(labels), self.interner.get_id(key))
512        else {
513            return Vec::new();
514        };
515        let mut ids: Vec<_> = acc
516            .into_iter()
517            .filter(|id| {
518                self.nodes.get(id).is_some_and(|vers| {
519                    visible_version(&vers, ts).is_some_and(|ver| {
520                        ver.live.has_labels(&lids) && ver.live.props.get(kid).is_some_and(&pred)
521                    })
522                })
523            })
524            .collect();
525        ids.sort_unstable();
526        ids.dedup();
527        ids
528    }
529
530    /// Label scan (or a full scan when the pattern has no label) filtered by
531    /// equality. Used when no `RANGE` index serves the properties and the
532    /// lazy equality postings declined (ADR-0614: a label-less pattern, or
533    /// a value whose identity is narrower than its `=` class). With
534    /// `cap`, the scan stops at the first `cap + 1` matches (see
535    /// [`Graph::lookup_nodes_upto_at`]).
536    fn scan_match(
537        &self,
538        labels: &[String],
539        props: &BTreeMap<String, Value>,
540        ts: u64,
541        cap: Option<usize>,
542    ) -> Vec<NodeId> {
543        // One probe per examined node: counted, so a scan that finds few
544        // matches in a large bucket reports the reads it performed —
545        // the shared walk body ([`Self::recheck_walk`]).
546        let spec = RecheckSpec {
547            labels,
548            props,
549            ts,
550            cap,
551        };
552        let mut walk = self.recheck_walk(&spec);
553        // The id stream, one shape for both patterns: every node for a
554        // label-less pattern, else the shortest interned label bucket —
555        // its ids copied under one short guard and visited outside it,
556        // so the label-index guard is never held across a node read (the
557        // lock order every writer takes is nodes, then label index).
558        // Fail-closed: no bucket when a pattern label was never interned,
559        // so the conjunction matches nothing
560        // ([`Self::smallest_interned_bucket`]'s rule).
561        let ids = if labels.is_empty() {
562            self.all_node_ids_at(ts)
563        } else {
564            self.smallest_interned_bucket(labels)
565                .map_or_else(Vec::new, |lid| self.label_index_copy(lid, usize::MAX).0)
566        };
567        for id in ids {
568            if walk.visit(id).is_break() {
569                break;
570            }
571        }
572        walk.finish()
573    }
574
575    pub fn lookup_string_contains_at(
576        &self,
577        labels: &[String],
578        key: &str,
579        needle: &str,
580        ts: u64,
581    ) -> Option<Vec<NodeId>> {
582        self.lookup_text_contains(labels, key, needle, ts)
583    }
584
585    /// `None` unless a `RANGE` index names the `(label, property)`.
586    /// `STARTS WITH` reads that ordered map; without one the caller scans.
587    pub fn lookup_string_prefix_at(
588        &self,
589        labels: &[String],
590        key: &str,
591        prefix: &str,
592        ts: u64,
593    ) -> Option<Vec<NodeId>> {
594        self.lookup_text_prefix(labels, key, prefix, ts)
595    }
596}