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