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