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 ids posted under every label in `labels`: the label-index
193    /// buckets intersected through `intersect_acc`, the fold every
194    /// multi-set seek uses. A label the store never interned can match
195    /// nothing, so its empty bucket empties the result. Callers route a
196    /// label-less pattern to the full scan — this is only reached with a
197    /// non-empty `labels`.
198    fn intersect_label_ids(&self, labels: &[String]) -> HashSet<NodeId> {
199        let mut acc: Option<HashSet<NodeId>> = None;
200        for label in labels {
201            // An uninterned label can match nothing.
202            let ids = self
203                .interner
204                .get_id(label)
205                .and_then(|lid| self.indexes.label_index.get(&lid).map(|r| r.clone()))
206                .unwrap_or_default();
207            intersect_acc(&mut acc, ids);
208        }
209        acc.unwrap_or_default()
210    }
211
212    /// Index postings for a node lookup, or a finished answer when the
213    /// index cannot serve the predicate.
214    fn node_candidates(
215        &self,
216        labels: &[String],
217        props: &BTreeMap<String, Value>,
218        ts: u64,
219        cap: Option<usize>,
220    ) -> NodeCandidates {
221        if labels.is_empty() && props.is_empty() {
222            return NodeCandidates::Unindexed;
223        }
224        if !labels.is_empty() && props.is_empty() {
225            return NodeCandidates::Indexed(self.intersect_label_ids(labels));
226        }
227        // The props-non-empty shapes from here (the two guards above own
228        // the empty-props ones). The route decides once (ADR-0614): a
229        // declared RANGE pair, the lazy equality postings, or the scan —
230        // the one three-way decision the id seek, the cardinality, this
231        // arm, and the overlay's scratch-mode flag all read.
232        match self.map_equality_route(labels, props) {
233            // No declared pair covers the lookup: the lazy equality
234            // postings serve it — a one-time O(label) pair build, then
235            // O(dirty) catch-up per seek. The route's decline cases (a
236            // label-less pattern, a value whose identity is narrower
237            // than its `=` class) are `Scan` here.
238            EqualityRoute::Postings => {
239                return NodeCandidates::Final(self.equality_postings_upto(labels, props, ts, cap));
240            }
241            EqualityRoute::Scan => {
242                return NodeCandidates::Final(self.scan_match(labels, props, ts, cap));
243            }
244            // A declared RANGE pair covers every sought property: the
245            // capped stream or the intersect loop below answers it.
246            EqualityRoute::Declared => {}
247        }
248        // A capped caller streams the shortest posting instead of
249        // building every posting's id set; a vanished pair (a concurrent
250        // `DROP INDEX`) falls to the scan below.
251        if let Some(cap) = cap {
252            return match self.range_equality_upto(labels, props, ts, cap) {
253                Some(ids) => NodeCandidates::Final(ids),
254                None => NodeCandidates::Final(self.scan_match(labels, props, ts, Some(cap))),
255            };
256        }
257        let mut acc: Option<HashSet<NodeId>> = None;
258        for (key, value) in props {
259            if GroupKey::for_property_index(value).is_none() {
260                return NodeCandidates::Final(Vec::new());
261            }
262            let Some(kid) = self.interner.get_id(key) else {
263                return NodeCandidates::Final(Vec::new());
264            };
265            let mut next: Option<HashSet<NodeId>> = None;
266            for label in labels {
267                let Some(lid) = self.interner.get_id(label) else {
268                    continue;
269                };
270                if !self.indexes.range_pairs.contains_key(&(lid, kid)) {
271                    continue;
272                }
273                let Some(ids) = self.range_equality_ids(lid, kid, value) else {
274                    return NodeCandidates::Final(self.scan_match(labels, props, ts, cap));
275                };
276                intersect_acc(&mut next, ids);
277            }
278            intersect_acc(&mut acc, next.unwrap_or_default());
279        }
280        NodeCandidates::Indexed(acc.unwrap_or_default())
281    }
282
283    /// Whether a keyed node lookup on `(labels, props)` is answered by
284    /// an identity-keyed structure — a declared range pair, or, when
285    /// none covers the pair, the lazy equality postings (ADR-0614) —
286    /// the base half's mode, and the mode the overlay's scratch half
287    /// must match so one lookup's two halves answer with one equality
288    /// relation (LABS-1085 review). A scan-served lookup — a declined
289    /// value, a label-less pattern — keeps `=` semantics in both
290    /// halves.
291    pub(crate) fn equality_served_by_index(
292        &self,
293        labels: &[String],
294        props: &BTreeMap<String, Value>,
295    ) -> bool {
296        !matches!(self.map_equality_route(labels, props), EqualityRoute::Scan)
297    }
298
299    /// The label half of [`Self::node_matches`]: the node carries every one
300    /// of `labels`. The overlay's scratch merge asks it too, so one
301    /// containment rule serves the committed and the scratch side.
302    pub(crate) fn node_carries_labels(n: &Node, labels: &[String]) -> bool {
303        labels.iter().all(|l| n.labels.iter().any(|x| x == l))
304    }
305
306    /// The canonical node-predicate for a label/property seek: every
307    /// sought label carried, every sought property equal under Cypher
308    /// equality (`1 = 1.0`) — the predicate the base's residual scan
309    /// (`scan_match` and the `Indexed` arm's re-check), the declared
310    /// path's `finish_ids`, the lazy postings' serve (ADR-0614), and
311    /// the overlay's scratch merge all apply. Hosted here, the
312    /// lookup/scan file whose module doc claims this family — the one
313    /// home every consumer reads downward.
314    pub(crate) fn node_matches(
315        n: &Node,
316        labels: &[String],
317        props: &BTreeMap<String, Value>,
318    ) -> bool {
319        // Property comparison is Cypher equality (`1 = 1.0`), matching the
320        // normalized index key that produced the candidate.
321        Self::node_carries_labels(n, labels)
322            && props
323                .iter()
324                .all(|(k, v)| n.properties.get(k).is_some_and(|have| have.eq_non_null(v)))
325    }
326
327    /// Begin one equality re-check walk over `spec` — the shared
328    /// per-candidate body and the closing count-and-sort behind
329    /// [`RecheckWalk`], the form every re-checking site (the scan tail,
330    /// both equality serves, the `Indexed` arm's posting re-check)
331    /// reads.
332    pub(in crate::graph) fn recheck_walk<'a>(
333        &self,
334        spec: &'a RecheckSpec<'a>,
335    ) -> RecheckWalk<'a, '_> {
336        RecheckWalk {
337            graph: self,
338            spec,
339            matched: Vec::new(),
340            examined: 0,
341        }
342    }
343
344    /// The interned pattern label with the smallest label-index bucket —
345    /// the one bucket a label-conjunction scan or a postings serve
346    /// streams, so a serve never examines more nodes than the scan it
347    /// replaces. `None` when any pattern label was never interned (the
348    /// fail-closed rule: no node carries it, so the whole label
349    /// conjunction matches nothing) or `labels` is empty — the answer
350    /// both shapes give then.
351    pub(in crate::graph) fn smallest_interned_bucket(&self, labels: &[String]) -> Option<u32> {
352        self.intern_labels(labels)?
353            .into_iter()
354            .min_by_key(|lid| self.label_count_by_id(*lid))
355    }
356
357    /// Every pattern label's interned id, fail-closed: `None` when any
358    /// label was never interned — no node carries it, so the whole
359    /// label conjunction matches nothing. The one spelling of the rule
360    /// the keyed lookup's label-only arm, the shortest-bucket choice,
361    /// and `finish_ids`' re-check all read.
362    fn intern_labels(&self, labels: &[String]) -> Option<Vec<u32>> {
363        labels.iter().map(|l| self.interner.get_id(l)).collect()
364    }
365
366    /// Re-check each posted candidate against the snapshot at `ts`: the
367    /// visible version must carry every pattern label and a `key` value
368    /// that satisfies `pred`. Reads the raw version — interned label ids
369    /// and the one-slot `CompactProps::get` — never `node_at`, which
370    /// materializes the full property map per candidate (the profile-hot
371    /// `to_map` path, ADR-0033; LABS-853). The raw-version member of the
372    /// recheck family (beside [`RecheckWalk`]'s materializing form): the
373    /// declared seek family and the lazy
374    /// postings' single-key serve (ADR-0614) re-check through this same
375    /// filter, so both answer exactly the same candidates.
376    pub(in crate::graph) fn finish_ids(
377        &self,
378        acc: impl IntoIterator<Item = NodeId>,
379        labels: &[String],
380        key: &str,
381        ts: u64,
382        pred: impl Fn(&Value) -> bool,
383    ) -> Vec<NodeId> {
384        // Every stored label and key was interned before its version
385        // committed, so a pattern label or key the interner never saw is
386        // carried by no node: nothing survives the re-check.
387        let (Some(lids), Some(kid)) = (self.intern_labels(labels), self.interner.get_id(key))
388        else {
389            return Vec::new();
390        };
391        let mut ids: Vec<_> = acc
392            .into_iter()
393            .filter(|id| {
394                self.nodes.get(id).is_some_and(|vers| {
395                    visible_version(&vers, ts).is_some_and(|ver| {
396                        ver.live.has_labels(&lids) && ver.live.props.get(kid).is_some_and(&pred)
397                    })
398                })
399            })
400            .collect();
401        ids.sort_unstable();
402        ids.dedup();
403        ids
404    }
405
406    /// Label scan (or a full scan when the pattern has no label) filtered by
407    /// equality. Used when no `RANGE` index serves the properties and the
408    /// lazy equality postings declined (ADR-0614: a label-less pattern, or
409    /// a value whose identity is narrower than its `=` class). With
410    /// `cap`, the scan stops at the first `cap + 1` matches (see
411    /// [`Graph::lookup_nodes_upto_at`]).
412    fn scan_match(
413        &self,
414        labels: &[String],
415        props: &BTreeMap<String, Value>,
416        ts: u64,
417        cap: Option<usize>,
418    ) -> Vec<NodeId> {
419        // One probe per examined node: counted, so a scan that finds few
420        // matches in a large bucket reports the reads it performed —
421        // the shared walk body ([`Self::recheck_walk`]).
422        let spec = RecheckSpec {
423            labels,
424            props,
425            ts,
426            cap,
427        };
428        let mut walk = self.recheck_walk(&spec);
429        // The id stream, one shape for both patterns: every node for a
430        // label-less pattern, else the shortest interned label bucket —
431        // its ids copied under one short guard and visited outside it,
432        // so the label-index guard is never held across a node read (the
433        // lock order every writer takes is nodes, then label index).
434        // Fail-closed: no bucket when a pattern label was never interned,
435        // so the conjunction matches nothing
436        // ([`Self::smallest_interned_bucket`]'s rule).
437        let ids = if labels.is_empty() {
438            self.all_node_ids_at(ts)
439        } else {
440            self.smallest_interned_bucket(labels)
441                .map_or_else(Vec::new, |lid| self.label_index_copy(lid, usize::MAX).0)
442        };
443        for id in ids {
444            if walk.visit(id).is_break() {
445                break;
446            }
447        }
448        walk.finish()
449    }
450
451    pub fn lookup_string_contains_at(
452        &self,
453        labels: &[String],
454        key: &str,
455        needle: &str,
456        ts: u64,
457    ) -> Option<Vec<NodeId>> {
458        self.lookup_text_contains(labels, key, needle, ts)
459    }
460
461    /// `None` unless a `RANGE` index names the `(label, property)`.
462    /// `STARTS WITH` reads that ordered map; without one the caller scans.
463    pub fn lookup_string_prefix_at(
464        &self,
465        labels: &[String],
466        key: &str,
467        prefix: &str,
468        ts: u64,
469    ) -> Option<Vec<NodeId>> {
470        self.lookup_text_prefix(labels, key, prefix, ts)
471    }
472}