Skip to main content

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_string_lookup(
137            labels,
138            key,
139            |n| n.as_string().is_some_and(|s| s.contains(needle)),
140            || {
141                self.base
142                    .lookup_string_contains_at(labels, key, needle, self.snapshot_ts())
143            },
144        )
145    }
146
147    /// `None` when no `RANGE` index serves the prefix: the caller scans.
148    pub fn lookup_string_prefix(
149        &self,
150        labels: &[String],
151        key: &str,
152        prefix: &str,
153    ) -> Option<Vec<NodeId>> {
154        self.merge_string_lookup(
155            labels,
156            key,
157            |n| n.as_string().is_some_and(|s| s.starts_with(prefix)),
158            || {
159                self.base
160                    .lookup_string_prefix_at(labels, key, prefix, self.snapshot_ts())
161            },
162        )
163    }
164
165    pub(crate) fn lookup_range(
166        &self,
167        labels: &[String],
168        key: &str,
169        seek: &RangeSeek,
170    ) -> Option<Vec<NodeId>> {
171        self.merge_string_lookup(
172            labels,
173            key,
174            |v| Self::range_overlay_pred(v, seek),
175            || {
176                self.base
177                    .lookup_range_seek(labels, key, seek, self.snapshot_ts())
178            },
179        )
180    }
181
182    /// Upper bound on [`Self::lookup_range`], counted from posting lengths.
183    /// `None` when the index cannot serve the predicate or the write overlay
184    /// has created, updated, or deleted a node: the committed postings are
185    /// then an incomplete description of this view, and the caller keeps the
186    /// eager probe.
187    pub(crate) fn lookup_range_cardinality(
188        &self,
189        labels: &[String],
190        key: &str,
191        seek: &RangeSeek,
192    ) -> Option<usize> {
193        if self.overlay_changes_node_membership() {
194            return None;
195        }
196        self.base.range_seek_cardinality(labels, key, seek)
197    }
198
199    pub(crate) fn lookup_spatial(
200        &self,
201        labels: &[String],
202        key: &str,
203        seek: &SpatialSeek,
204    ) -> Option<Vec<NodeId>> {
205        self.merge_string_lookup(
206            labels,
207            key,
208            |v| spatial_holds(v, seek),
209            || {
210                self.base
211                    .lookup_spatial_seek(labels, key, seek, self.snapshot_ts())
212            },
213        )
214    }
215
216    fn range_overlay_pred(v: &Value, seek: &RangeSeek) -> bool {
217        match seek {
218            RangeSeek::Eq(b) => v.eq_non_null(b),
219            RangeSeek::In(xs) => xs.iter().any(|b| v.eq_non_null(b)),
220            RangeSeek::Cmp { op, bound } => {
221                // Superset of the committed comparison. An incomparable value
222                // or an unexpected operator stays in the candidate set; the
223                // residual predicate in expand rechecks it.
224                let Some(ord) = v.compare(bound) else {
225                    return true;
226                };
227                match op {
228                    relate_ir::BinaryOp::Lt => ord.is_lt(),
229                    relate_ir::BinaryOp::Gt => ord.is_gt(),
230                    relate_ir::BinaryOp::Lte => ord.is_le(),
231                    relate_ir::BinaryOp::Gte => ord.is_ge(),
232                    _ => true,
233                }
234            }
235        }
236    }
237
238    fn merge_string_lookup(
239        &self,
240        labels: &[String],
241        key: &str,
242        pred: impl Fn(&Value) -> bool,
243        base: impl FnOnce() -> Option<Vec<NodeId>>,
244    ) -> Option<Vec<NodeId>> {
245        let mut ids = base()?;
246        ids.retain(|id| self.node_exists(*id));
247        if let Some(cell) = self.scratch {
248            // Read the scratch copy in place — `self.node` would clone its
249            // whole property map per scratch node; `node_exists` keeps the
250            // one visibility prologue (a scratch deletion hides the copy).
251            let scratch = cell.borrow();
252            for (id, n) in &scratch.batch.nodes {
253                if ids.contains(id) || !self.node_exists(*id) {
254                    continue;
255                }
256                if labels.iter().all(|l| n.labels.iter().any(|x| x == l))
257                    && n.properties.get(key).is_some_and(&pred)
258                {
259                    ids.push(*id);
260                }
261            }
262        }
263        ids.sort();
264        Some(ids)
265    }
266}
267
268fn scratch_lookup_adds(
269    cell: &RefCell<WriteScratch>,
270    labels: &[String],
271    props: &BTreeMap<String, Value>,
272    by_index: bool,
273) -> Vec<NodeId> {
274    // One candidate resolution — `NodeId`s in both arms (the index seek
275    // returns ids; the scan walks the map in place, never a per-node
276    // clone) — then one application of the canonical `node_matches`. The
277    // keyed arm needs the mutable borrow first (the seek builds its pair
278    // lazily); the filter runs under the shared borrow after it.
279    let keyed = match props.first_key_value() {
280        Some((key, value)) if by_index => {
281            let mut s = cell.borrow_mut();
282            let batch = &mut s.batch;
283            // One label narrows the candidates (every match carries all
284            // of `labels`); none seeks the any-label bucket.
285            let seek_labels = &labels[..labels.len().min(1)];
286            Some(
287                batch
288                    .prop_ix
289                    .seek(&batch.nodes, seek_labels, key, value)
290                    .into_iter()
291                    .collect::<Vec<_>>(),
292            )
293        }
294        // A scan-served probe (no index serves the pair): the base half
295        // scans with `=` — the scratch half scans the same way, so a
296        // zoned-DateTime DST-overlap twin is found in either half.
297        _ => None,
298    };
299    let mut adds: Vec<NodeId> = match keyed {
300        Some(ids) => {
301            let s = cell.borrow();
302            ids.into_iter()
303                .filter(|id| {
304                    s.batch
305                        .nodes
306                        .get(id)
307                        .is_some_and(|n| Graph::node_matches(n, labels, props))
308                })
309                .collect()
310        }
311        None => {
312            let s = cell.borrow();
313            s.batch
314                .nodes
315                .iter()
316                .filter(|(_, n)| Graph::node_matches(n, labels, props))
317                .map(|(id, _)| *id)
318                .collect()
319        }
320    };
321    adds.sort_unstable();
322    adds
323}