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 super::declared::intersect_acc;
6use super::*;
7
8enum NodeCandidates {
9 /// No labels and no properties: the caller scans.
10 Unindexed,
11 /// Index postings that still need `node_matches`.
12 Indexed(HashSet<NodeId>),
13 /// A finished id list. Empty means the predicate cannot match.
14 Final(Vec<NodeId>),
15}
16
17impl Graph {
18 /// Approximate number of nodes carrying `label`: the label-index set
19 /// size (ADR-0218). Plan-time estimate only — it is O(1), ignores
20 /// snapshot visibility, and counts every id the index holds; a label
21 /// the store has never interned is 0.
22 pub fn label_count(&self, label: &str) -> u64 {
23 self.interner
24 .get_id(label)
25 .map_or(0, |lid| self.label_count_by_id(lid))
26 }
27
28 /// [`Graph::label_count`] for an already-resolved label token id.
29 pub fn label_count_by_id(&self, lid: u32) -> u64 {
30 self.indexes
31 .label_index
32 .get(&lid)
33 .map_or(0, |ids| ids.len() as u64)
34 }
35
36 pub fn lookup_nodes(
37 &self,
38 labels: &[String],
39 props: &BTreeMap<String, Value>,
40 ) -> Option<Vec<NodeId>> {
41 self.lookup_nodes_at(labels, props, self.read_ts())
42 }
43
44 /// The label/property candidate lookup at `ts`, ascending and
45 /// deduplicated: `None` only for the both-empty `Unindexed` arm —
46 /// the shape the caller scans for instead — a non-empty seek is
47 /// always served.
48 pub fn lookup_nodes_at(
49 &self,
50 labels: &[String],
51 props: &BTreeMap<String, Value>,
52 ts: u64,
53 ) -> Option<Vec<NodeId>> {
54 self.lookup_nodes_upto_at(labels, props, ts, None)
55 }
56
57 /// [`Graph::lookup_nodes_at`] for a caller that only needs to know
58 /// whether more than `cap` nodes match: a residual scan stops once it
59 /// has `cap + 1` matches. An answer of at most `cap` ids is complete,
60 /// ascending and deduplicated; a longer one is an arbitrary
61 /// `cap + 1`-id subset of the matches, meaningful only by its length.
62 /// Index-served arms answer in full (their postings already exist);
63 /// `None` is the both-empty `Unindexed` arm, as for the uncapped form.
64 pub fn lookup_nodes_upto_at(
65 &self,
66 labels: &[String],
67 props: &BTreeMap<String, Value>,
68 ts: u64,
69 cap: Option<usize>,
70 ) -> Option<Vec<NodeId>> {
71 // The label scan's hot shape — one label, no property equality —
72 // is the one canonical label scan ([`node_ids_with_label_at`]):
73 // the bucket's ids copied once under its guard, each probed for
74 // visibility and the interned label id in place. No node is
75 // materialized (the profile-hot `node_at` path builds every
76 // candidate's full property map just to check a label).
77 if labels.len() == 1 && props.is_empty() {
78 return Some(self.node_ids_with_label_at(&labels[0], ts));
79 }
80 match self.node_candidates(labels, props, ts, cap) {
81 NodeCandidates::Unindexed => None,
82 NodeCandidates::Final(ids) => Some(ids),
83 NodeCandidates::Indexed(acc) => {
84 // Each posting is examined by the re-check below.
85 crate::ctx::count_node_reads(acc.len() as u64);
86 // A label-only lookup needs no materialized node: the
87 // id-based label probes answer it, the labels interned
88 // once here instead of per candidate. (The materialized
89 // form built every candidate's property map just to check
90 // labels — ADR-0473's q30 measurement.) An uninterned
91 // label can match nothing (the interner is append-only),
92 // so a miss empties the answer — exactly what a
93 // `node_matches` against no node's label list would do.
94 let mut ids: Vec<_> = if props.is_empty() {
95 let lids: Option<Vec<u32>> =
96 labels.iter().map(|l| self.interner.get_id(l)).collect();
97 match lids {
98 Some(lids) => acc
99 .into_iter()
100 .filter(|&id| {
101 lids.iter()
102 .all(|lid| self.node_carries_label_at(id, *lid, ts))
103 })
104 .collect(),
105 None => Vec::new(),
106 }
107 } else {
108 acc.into_iter()
109 .filter(|id| {
110 self.node_at(*id, ts)
111 .is_some_and(|n| Self::node_matches(&n, labels, props))
112 })
113 .collect()
114 };
115 ids.sort();
116 Some(ids)
117 }
118 }
119 }
120
121 /// The ids posted under every label in `labels`: the label-index
122 /// buckets intersected through `intersect_acc`, the fold every
123 /// multi-set seek uses. A label the store never interned can match
124 /// nothing, so its empty bucket empties the result. Callers route a
125 /// label-less pattern to the full scan — this is only reached with a
126 /// non-empty `labels`.
127 fn intersect_label_ids(&self, labels: &[String]) -> HashSet<NodeId> {
128 let mut acc: Option<HashSet<NodeId>> = None;
129 for label in labels {
130 // An uninterned label can match nothing.
131 let ids = self
132 .interner
133 .get_id(label)
134 .and_then(|lid| self.indexes.label_index.get(&lid).map(|r| r.clone()))
135 .unwrap_or_default();
136 intersect_acc(&mut acc, ids);
137 }
138 acc.unwrap_or_default()
139 }
140
141 /// Index postings for a node lookup, or a finished answer when the
142 /// index cannot serve the predicate.
143 fn node_candidates(
144 &self,
145 labels: &[String],
146 props: &BTreeMap<String, Value>,
147 ts: u64,
148 cap: Option<usize>,
149 ) -> NodeCandidates {
150 if labels.is_empty() && props.is_empty() {
151 return NodeCandidates::Unindexed;
152 }
153 if !labels.is_empty() && props.is_empty() {
154 return NodeCandidates::Indexed(self.intersect_label_ids(labels));
155 }
156 if props.is_empty() || !self.range_serves_equality(labels, props) {
157 return NodeCandidates::Final(self.scan_match(labels, props, ts, cap));
158 }
159 // A capped caller streams the shortest posting instead of
160 // building every posting's id set; a vanished pair (a concurrent
161 // `DROP INDEX`) falls to the scan below.
162 if let Some(cap) = cap {
163 return match self.range_equality_upto(labels, props, ts, cap) {
164 Some(ids) => NodeCandidates::Final(ids),
165 None => NodeCandidates::Final(self.scan_match(labels, props, ts, Some(cap))),
166 };
167 }
168 let mut acc: Option<HashSet<NodeId>> = None;
169 for (key, value) in props {
170 if GroupKey::for_property_index(value).is_none() {
171 return NodeCandidates::Final(Vec::new());
172 }
173 let Some(kid) = self.interner.get_id(key) else {
174 return NodeCandidates::Final(Vec::new());
175 };
176 let mut next: Option<HashSet<NodeId>> = None;
177 for label in labels {
178 let Some(lid) = self.interner.get_id(label) else {
179 continue;
180 };
181 if !self.indexes.range_pairs.contains_key(&(lid, kid)) {
182 continue;
183 }
184 let Some(ids) = self.range_equality_ids(lid, kid, value) else {
185 return NodeCandidates::Final(self.scan_match(labels, props, ts, cap));
186 };
187 intersect_acc(&mut next, ids);
188 }
189 intersect_acc(&mut acc, next.unwrap_or_default());
190 }
191 NodeCandidates::Indexed(acc.unwrap_or_default())
192 }
193
194 /// The canonical node-predicate for a label/property seek: every
195 /// sought label carried, every sought property equal under Cypher
196 /// equality (`1 = 1.0`) — the predicate the base's residual scan
197 /// (`scan_match` and the `Indexed` arm's re-check), the declared
198 /// path's `finish_ids`, and the overlay's scratch merge all apply.
199 /// Hosted here, the lookup/scan file whose module doc claims this
200 /// family — the one home every consumer reads downward.
201 /// Whether a keyed node lookup on `(labels, props)` is served by the
202 /// declared range index — the base half's identity-keyed mode, and
203 /// the mode the overlay's scratch half must match so one lookup's
204 /// two halves answer with one equality relation (LABS-1085 review).
205 /// A scan-served lookup keeps `=` semantics in both halves.
206 pub(crate) fn equality_served_by_index(
207 &self,
208 labels: &[String],
209 props: &BTreeMap<String, Value>,
210 ) -> bool {
211 self.range_serves_equality(labels, props)
212 }
213
214 pub(crate) fn node_matches(
215 n: &Node,
216 labels: &[String],
217 props: &BTreeMap<String, Value>,
218 ) -> bool {
219 // Property comparison is Cypher equality (`1 = 1.0`), matching the
220 // normalized index key that produced the candidate.
221 labels.iter().all(|l| n.labels.iter().any(|x| x == l))
222 && props
223 .iter()
224 .all(|(k, v)| n.properties.get(k).is_some_and(|have| have.eq_non_null(v)))
225 }
226
227 /// Label scan (or a full scan when the pattern has no label) filtered by
228 /// equality. Used when no `RANGE` index serves the properties. With
229 /// `cap`, the scan stops at the first `cap + 1` matches (see
230 /// [`Graph::lookup_nodes_upto_at`]).
231 fn scan_match(
232 &self,
233 labels: &[String],
234 props: &BTreeMap<String, Value>,
235 ts: u64,
236 cap: Option<usize>,
237 ) -> Vec<NodeId> {
238 let (mut matched, mut examined) = (Vec::new(), 0u64);
239 // One probe per examined node: counted, so a scan that finds few
240 // matches in a large bucket reports the reads it performed.
241 let mut visit = |id: NodeId| {
242 examined += 1;
243 let hit = self
244 .node_at(id, ts)
245 .is_some_and(|n| Self::node_matches(&n, labels, props));
246 if hit {
247 matched.push(id);
248 }
249 cap.is_none_or(|cap| matched.len() <= cap)
250 };
251 if labels.is_empty() {
252 for id in self.all_node_ids_at(ts) {
253 if !visit(id) {
254 break;
255 }
256 }
257 } else {
258 // The shortest label bucket: its ids are copied under one short
259 // guard and visited outside it, so the label-index guard is never
260 // held across a node read (the lock order every writer takes is
261 // nodes, then label index). Every pattern label is still checked
262 // per node; a label the store never interned matches nothing.
263 let buckets: Option<Vec<u32>> =
264 labels.iter().map(|l| self.interner.get_id(l)).collect();
265 let shortest = buckets.and_then(|lids| {
266 lids.into_iter()
267 .min_by_key(|lid| self.label_count_by_id(*lid))
268 });
269 if let Some(lid) = shortest {
270 let (ids, _) = self.label_index_copy(lid, usize::MAX);
271 for id in ids {
272 if !visit(id) {
273 break;
274 }
275 }
276 }
277 }
278 crate::ctx::count_node_reads(examined);
279 matched.sort();
280 matched
281 }
282
283 pub fn lookup_string_contains_at(
284 &self,
285 labels: &[String],
286 key: &str,
287 needle: &str,
288 ts: u64,
289 ) -> Option<Vec<NodeId>> {
290 self.lookup_text_contains(labels, key, needle, ts)
291 }
292
293 /// `None` unless a `RANGE` index names the `(label, property)`.
294 /// `STARTS WITH` reads that ordered map; without one the caller scans.
295 pub fn lookup_string_prefix_at(
296 &self,
297 labels: &[String],
298 key: &str,
299 prefix: &str,
300 ts: u64,
301 ) -> Option<Vec<NodeId>> {
302 self.lookup_text_prefix(labels, key, prefix, ts)
303 }
304}