relate_executor/overlay/seek.rs
1//! Index seeks over the overlay: the base graph's answer at the snapshot,
2//! minus scratch deletions, plus scratch nodes that satisfy the predicate.
3
4use std::cell::RefCell;
5use std::collections::{BTreeMap, HashSet};
6
7use relate_core::{Node, NodeId, Value};
8
9use crate::graph::{spatial_holds, Graph, RangeSeek, SpatialSeek};
10
11use super::{union_ids, ExecGraph, WriteScratch};
12
13impl<'a> ExecGraph<'a> {
14 /// The label/property candidate lookup at the snapshot, ascending
15 /// and deduplicated: `None` only when both `labels` and `props` are
16 /// empty — the shape the caller scans for instead — a non-empty
17 /// seek is always served.
18 pub fn lookup_nodes(
19 &self,
20 labels: &[String],
21 props: &BTreeMap<String, Value>,
22 ) -> Option<Vec<NodeId>> {
23 self.lookup_nodes_upto(labels, props, None)
24 }
25
26 /// [`ExecGraph::lookup_nodes`] for a caller that only needs to know
27 /// whether more than `cap` nodes match ([`Graph::lookup_nodes_upto_at`]
28 /// carries the contract: at most `cap` ids is the complete answer, a
29 /// longer one only its length). A view with write scratch answers in
30 /// full: a truncated base subset could lose members to the scratch's
31 /// deletions and read as complete.
32 pub fn lookup_nodes_upto(
33 &self,
34 labels: &[String],
35 props: &BTreeMap<String, Value>,
36 cap: Option<usize>,
37 ) -> Option<Vec<NodeId>> {
38 let ts = self.snapshot_ts();
39 // The base's own answer carries the both-empty policy (its only
40 // `None` is the `Unindexed` arm), so the overlay propagates it
41 // instead of re-checking the fact beside a handled form of it.
42 let Some(cell) = self.scratch else {
43 // The read-only view: the base answer is already
44 // visibility-filtered at the snapshot and nothing merges into
45 // it, so the capped answer is the view's own.
46 return self.base.lookup_nodes_upto_at(labels, props, ts, cap);
47 };
48 // A view with write scratch asks the base uncapped: a truncated
49 // base subset could lose members to the scratch's deletions.
50 let mut ids = self.base.lookup_nodes_upto_at(labels, props, ts, None)?;
51 // Only the scratch's deletions can hide more of the base answer.
52 // Existence check is clone-free (node_exists, not node()).
53 ids.retain(|id| self.node_exists(*id));
54 // This lookup's scratch additions merge through the ascending-list
55 // algebra (LABS-803): [`scratch_lookup_adds`] answers the family's
56 // ascending contract on its own, and union_ids merges it with the
57 // ascending base — no duplicate guard, no closing re-sort — the
58 // same algebra the string, range and spatial lookups merge through
59 // ([`Self::merge_scratch_lookup`]).
60 //
61 // The scratch half runs in the base half's own equality mode: an
62 // index-served probe seeks the scratch's identity-keyed index
63 // (ADR-0446 both halves), a scan-served probe scans the scratch
64 // with `=` — one lookup, one relation, however the base is served
65 // (LABS-1085 review).
66 let by_index = self.base.equality_served_by_index(labels, props);
67 Some(union_ids(
68 ids,
69 scratch_lookup_adds(cell, labels, props, by_index),
70 ))
71 }
72
73 /// Committed postings plus the scratch's, for one equality probe
74 /// (ADR-0172 §3, ADR-0185): ascending, deduplicated. A superset — the
75 /// caller re-verifies every id on this view.
76 pub(super) fn merged_candidates<Id: Ord + Copy>(
77 &self,
78 committed: Vec<Id>,
79 scratch: impl FnOnce(&mut WriteScratch) -> HashSet<Id>,
80 ) -> Vec<Id> {
81 let mut ids = committed;
82 if let Some(cell) = self.scratch {
83 let s = &mut *cell.borrow_mut();
84 ids.extend(scratch(s));
85 }
86 ids.sort_unstable();
87 ids.dedup();
88 ids
89 }
90
91 /// Committed bucket length plus the scratch's, both counted in place
92 /// (ADR-0184): a composite uniqueness probe compares these sizes
93 /// without materializing any candidate list.
94 pub(super) fn merged_len(
95 &self,
96 committed: usize,
97 scratch: impl FnOnce(&mut WriteScratch) -> usize,
98 ) -> usize {
99 committed
100 + self.scratch.map_or(0, |cell| {
101 let s = &mut *cell.borrow_mut();
102 scratch(s)
103 })
104 }
105
106 /// Candidate ids for a node uniqueness probe on `(label, key) = value`
107 /// (ADR-0172 §3), ascending and deduplicated: the committed graph's lazy
108 /// equality postings for the pair plus the scratch's `prop_ix` seek.
109 /// A superset — the caller re-verifies every id on this view. Empty when
110 /// `value` has no property-index key (it contains a NaN).
111 pub(crate) fn equality_candidates(&self, label: &str, key: &str, value: &Value) -> Vec<NodeId> {
112 self.merged_candidates(self.base.equality_postings(label, key, value), |s| {
113 s.batch.prop_ix.seek(&s.batch.nodes, &[label], key, value)
114 })
115 }
116
117 /// The size of the committed plus scratch equality bucket for
118 /// `(label, key) = value` (ADR-0184), counted in place: the pair
119 /// selection of a composite uniqueness probe compares these sizes
120 /// without materializing any candidate list. Zero when `value` has no
121 /// property-index key (it contains a NaN).
122 pub(crate) fn equality_bucket_len(&self, label: &str, key: &str, value: &Value) -> usize {
123 self.merged_len(self.base.equality_postings_len(label, key, value), |s| {
124 s.batch.prop_ix.seek_len(&s.batch.nodes, label, key, value)
125 })
126 }
127
128 /// `None` when the base index cannot serve the needle (the gram index
129 /// rejects empty needles): the caller falls back to a full scan, exactly
130 /// like the `lookup_nodes` path, rather than matching nothing.
131 pub fn lookup_string_contains(
132 &self,
133 labels: &[String],
134 key: &str,
135 needle: &str,
136 ) -> Option<Vec<NodeId>> {
137 self.merge_scratch_lookup(
138 labels,
139 key,
140 |n| n.as_string().is_some_and(|s| s.contains(needle)),
141 self.base
142 .lookup_string_contains_at(labels, key, needle, self.snapshot_ts()),
143 )
144 }
145
146 /// `None` when no `RANGE` index serves the prefix: the caller scans.
147 pub fn lookup_string_prefix(
148 &self,
149 labels: &[String],
150 key: &str,
151 prefix: &str,
152 ) -> Option<Vec<NodeId>> {
153 self.merge_scratch_lookup(
154 labels,
155 key,
156 |n| n.as_string().is_some_and(|s| s.starts_with(prefix)),
157 self.base
158 .lookup_string_prefix_at(labels, key, prefix, self.snapshot_ts()),
159 )
160 }
161
162 pub(crate) fn lookup_range(
163 &self,
164 labels: &[String],
165 key: &str,
166 seek: &RangeSeek,
167 ) -> Option<Vec<NodeId>> {
168 self.merge_scratch_lookup(
169 labels,
170 key,
171 |v| Self::range_overlay_pred(v, seek),
172 self.base
173 .lookup_range_seek(labels, key, seek, self.snapshot_ts()),
174 )
175 }
176
177 /// [`Self::lookup_range`] for the `=` / `IN` point seek when the
178 /// caller only needs to know whether more than `cap` nodes match
179 /// ([`Graph::lookup_equality_upto`] carries the contract). A view
180 /// with write scratch answers in full: a truncated base subset could
181 /// lose members to the scratch's deletions and read as complete
182 /// ([`Self::lookup_nodes_upto`]'s rule). `None`: the seek is not an
183 /// equality, or the equality route is the scan.
184 pub(crate) fn lookup_point_upto(
185 &self,
186 labels: &[String],
187 key: &str,
188 seek: &RangeSeek,
189 cap: usize,
190 ) -> Option<Vec<NodeId>> {
191 if self.scratch.is_some() {
192 return self.lookup_range(labels, key, seek);
193 }
194 // A comparison window is no point seek: declined, as documented.
195 let values = match seek {
196 RangeSeek::Eq(v) => std::slice::from_ref(v),
197 RangeSeek::In(vs) => vs.as_slice(),
198 RangeSeek::Cmp { .. } => return None,
199 };
200 self.base
201 .lookup_equality_upto(labels, key, values, self.snapshot_ts(), cap)
202 }
203
204 /// Upper bound on [`Self::lookup_range`], counted from posting lengths.
205 /// `None` when the index cannot serve the predicate or the write overlay
206 /// has created, updated, or deleted a node: the committed postings are
207 /// then an incomplete description of this view, and the caller keeps the
208 /// eager probe.
209 pub(crate) fn lookup_range_cardinality(
210 &self,
211 labels: &[String],
212 key: &str,
213 seek: &RangeSeek,
214 ) -> Option<usize> {
215 if self.overlay_changes_node_membership() {
216 return None;
217 }
218 self.base.range_seek_cardinality(labels, key, seek)
219 }
220
221 pub(crate) fn lookup_spatial(
222 &self,
223 labels: &[String],
224 key: &str,
225 seek: &SpatialSeek,
226 ) -> Option<Vec<NodeId>> {
227 self.merge_scratch_lookup(
228 labels,
229 key,
230 |v| spatial_holds(v, seek),
231 self.base
232 .lookup_spatial_seek(labels, key, seek, self.snapshot_ts()),
233 )
234 }
235
236 fn range_overlay_pred(v: &Value, seek: &RangeSeek) -> bool {
237 match seek {
238 RangeSeek::Eq(b) => v.eq_non_null(b),
239 RangeSeek::In(xs) => xs.iter().any(|b| v.eq_non_null(b)),
240 RangeSeek::Cmp { op, bound } => {
241 // Superset of the committed comparison. An incomparable value
242 // or an unexpected operator stays in the candidate set; the
243 // residual predicate in expand rechecks it.
244 let Some(ord) = v.compare(bound) else {
245 return true;
246 };
247 match op {
248 relate_ir::BinaryOp::Lt => ord.is_lt(),
249 relate_ir::BinaryOp::Gt => ord.is_gt(),
250 relate_ir::BinaryOp::Lte => ord.is_le(),
251 relate_ir::BinaryOp::Gte => ord.is_ge(),
252 _ => true,
253 }
254 }
255 }
256 }
257
258 fn merge_scratch_lookup(
259 &self,
260 labels: &[String],
261 key: &str,
262 pred: impl Fn(&Value) -> bool,
263 base: Option<Vec<NodeId>>,
264 ) -> Option<Vec<NodeId>> {
265 let mut ids = base?;
266 ids.retain(|id| self.node_exists(*id));
267 if let Some(cell) = self.scratch {
268 // The same ascending-list merge `lookup_nodes_upto` reads: the
269 // scratch's matches come back ascending and `union_ids` merges
270 // them with the ascending base — no duplicate guard, no closing
271 // re-sort. `node_exists` keeps the one visibility prologue (a
272 // scratch deletion hides the copy).
273 let mut adds = scratch_adds(cell, |n| {
274 Graph::node_carries_labels(n, labels) && n.properties.get(key).is_some_and(&pred)
275 });
276 adds.retain(|id| self.node_exists(*id));
277 ids = union_ids(ids, adds);
278 }
279 Some(ids)
280 }
281}
282
283fn scratch_lookup_adds(
284 cell: &RefCell<WriteScratch>,
285 labels: &[String],
286 props: &BTreeMap<String, Value>,
287 by_index: bool,
288) -> Vec<NodeId> {
289 // One candidate resolution — `NodeId`s in both arms (the index seek
290 // returns ids; the scan walks the map in place, never a per-node
291 // clone) — then one application of the canonical `node_matches`. The
292 // keyed arm needs the mutable borrow first (the seek builds its pair
293 // lazily); the filter runs under the shared borrow after it.
294 let keyed = match props.first_key_value() {
295 Some((key, value)) if by_index => {
296 let mut s = cell.borrow_mut();
297 let batch = &mut s.batch;
298 // One label narrows the candidates (every match carries all
299 // of `labels`); none seeks the any-label bucket.
300 let seek_labels = &labels[..labels.len().min(1)];
301 Some(
302 batch
303 .prop_ix
304 .seek(&batch.nodes, seek_labels, key, value)
305 .into_iter()
306 .collect::<Vec<_>>(),
307 )
308 }
309 // A scan-served probe (no index serves the pair): the base half
310 // scans with `=` — the scratch half scans the same way, so a
311 // zoned-DateTime DST-overlap twin is found in either half.
312 _ => None,
313 };
314 let mut adds: Vec<NodeId> = match keyed {
315 Some(ids) => {
316 let s = cell.borrow();
317 ids.into_iter()
318 .filter(|id| {
319 s.batch
320 .nodes
321 .get(id)
322 .is_some_and(|n| Graph::node_matches(n, labels, props))
323 })
324 .collect()
325 }
326 None => scratch_adds(cell, |n| Graph::node_matches(n, labels, props)),
327 };
328 adds.sort_unstable();
329 adds
330}
331
332/// The scratch nodes satisfying `pred`, ascending: the scratch map read in
333/// place — never a per-node clone — the one scan every scratch merge of the
334/// seek family answers its additions through.
335fn scratch_adds(cell: &RefCell<WriteScratch>, pred: impl Fn(&Node) -> bool) -> Vec<NodeId> {
336 let s = cell.borrow();
337 let mut adds: Vec<NodeId> = s
338 .batch
339 .nodes
340 .iter()
341 .filter(|(_, n)| pred(n))
342 .map(|(id, _)| *id)
343 .collect();
344 adds.sort_unstable();
345 adds
346}