relate_executor/overlay/reads.rs
1//! Point reads of one node or relationship through the write overlay: a
2//! scratch deletion hides the element, a scratch copy answers for it, and
3//! otherwise the snapshot at `snapshot_ts` does.
4
5use std::sync::Arc;
6
7use relate_core::{Node, NodeId, RelId, Relationship, Result, Value};
8use relate_ir::Direction;
9use relate_names::Token;
10
11use super::ExecGraph;
12
13/// One candidate node as the scan-predicate check reads it: the write
14/// scratch's materialized copy (string-keyed), or the snapshot's live
15/// record (interned ids). The two arms carry the same facts — labels and
16/// one-slot property reads — each keyed the way its storage is keyed, so
17/// the predicate evaluation is spelled once over both.
18pub(crate) enum ScanNode<'a> {
19 Scratch(&'a Node),
20 Live(&'a crate::store::LiveNode),
21}
22
23impl ScanNode<'_> {
24 /// Whether the node carries `label`, by the interned `lid` on the
25 /// live record and by the string on the scratch copy.
26 pub(crate) fn has_label(&self, label: &str, lid: Option<u32>) -> bool {
27 match self {
28 Self::Scratch(n) => n.labels.iter().any(|l| l == label),
29 Self::Live(live) => lid.is_some_and(|lid| live.has_label(lid)),
30 }
31 }
32
33 /// The node's `key` property, null when absent — the same read
34 /// `eval::prop` makes of a bound node, resolved through the interned
35 /// `kid` on the live record and the string on the scratch copy.
36 pub(crate) fn prop(&self, key: &str, kid: Option<u32>) -> Value {
37 match self {
38 Self::Scratch(n) => n.properties.get(key).cloned().unwrap_or(Value::Null),
39 Self::Live(live) => kid
40 .and_then(|kid| live.props.get(kid))
41 .cloned()
42 .unwrap_or(Value::Null),
43 }
44 }
45
46 /// The node's `key` property by reference, `None` when absent — the
47 /// borrowed form of [`ScanNode::prop`] for the reads that only
48 /// inspect the value (the temporal construction borrows its argument,
49 /// the padded-ISO fast path parses a `&str`), so the per-candidate
50 /// gate never clones the stored string. The caller's `check` closure
51 /// runs inside the one store read the gate opened, so the borrow
52 /// outlives the check.
53 pub(crate) fn prop_value(&self, key: &str, kid: Option<u32>) -> Option<&Value> {
54 match self {
55 Self::Scratch(n) => n.properties.get(key),
56 Self::Live(live) => kid.and_then(|kid| live.props.get(kid)),
57 }
58 }
59}
60
61/// What the overlay scratch says about one element (ADR-0016). Every point
62/// read below starts from this prologue: a scratch deletion hides the
63/// element, a scratch copy answers for it, and scratch silence falls
64/// through to the committed snapshot at `snapshot_ts`.
65enum ScratchAnswer<T> {
66 /// The scratch deleted the element: the read answers "gone".
67 Deleted,
68 /// The scratch holds the element's copy, which answered the read.
69 Answered(T),
70 /// The scratch says nothing: read the snapshot.
71 Snapshot,
72}
73
74impl<T> ScratchAnswer<T> {
75 /// Resolve the prologue into the read's answer: `deleted` when the
76 /// scratch hid the element, the scratch copy's answer when it spoke,
77 /// and `snapshot()` otherwise.
78 fn resolve(self, deleted: T, snapshot: impl FnOnce() -> T) -> T {
79 match self {
80 Self::Deleted => deleted,
81 Self::Answered(answer) => answer,
82 Self::Snapshot => snapshot(),
83 }
84 }
85}
86
87impl ExecGraph<'_> {
88 /// The node side of the visibility prologue: `read` answers from the
89 /// scratch's copy of `id` when it holds one.
90 fn node_prologue<T>(&self, id: NodeId, read: impl FnOnce(&Node) -> T) -> ScratchAnswer<T> {
91 if let Some(cell) = self.scratch {
92 let s = cell.borrow();
93 if s.batch.deleted_nodes.contains(&id) {
94 return ScratchAnswer::Deleted;
95 }
96 if let Some(n) = s.batch.nodes.get(&id) {
97 return ScratchAnswer::Answered(read(n));
98 }
99 }
100 ScratchAnswer::Snapshot
101 }
102
103 /// The relationship side of the visibility prologue: `read` answers
104 /// from the scratch's copy of `id` when it holds one.
105 fn rel_prologue<T>(
106 &self,
107 id: RelId,
108 read: impl FnOnce(&Relationship) -> T,
109 ) -> ScratchAnswer<T> {
110 if let Some(cell) = self.scratch {
111 let s = cell.borrow();
112 if s.batch.deleted_rels.contains(&id) {
113 return ScratchAnswer::Deleted;
114 }
115 if let Some(r) = s.batch.rels.get(&id) {
116 return ScratchAnswer::Answered(read(r));
117 }
118 }
119 ScratchAnswer::Snapshot
120 }
121
122 pub fn node(&self, id: NodeId) -> Option<Node> {
123 self.node_prologue(id, |n| Some(n.clone()))
124 .resolve(None, || self.base.node_at(id, self.snapshot_ts()))
125 }
126
127 /// Existence check without materializing the node. The profiled hot path
128 /// (`node` clones the full `Node` — labels + property map) makes this the
129 /// common-case read in a write statement; callers that only need to know
130 /// a node is present must not pay for its properties.
131 pub fn node_exists(&self, id: NodeId) -> bool {
132 self.node_prologue(id, |_| true)
133 .resolve(false, || self.base.node_visible_at(id, self.snapshot_ts()))
134 }
135
136 /// Label ids without materializing properties. Returns owned label
137 /// strings; callers that only compare labels pay no property map clone.
138 pub fn node_labels(&self, id: NodeId) -> Option<Vec<String>> {
139 self.node_prologue(id, |n| Some((*n.labels).clone()))
140 .resolve(None, || self.base.node_labels_at(id, self.snapshot_ts()))
141 }
142
143 pub fn rel(&self, id: RelId) -> Option<Relationship> {
144 self.rel_prologue(id, |r| Some(r.clone()))
145 .resolve(None, || self.base.rel_at(id, self.snapshot_ts()))
146 }
147
148 pub fn rel_ends(&self, id: RelId) -> Option<(NodeId, NodeId)> {
149 self.rel_prologue(id, |r| Some((r.start, r.end)))
150 .resolve(None, || self.base.rel_ends_at(id, self.snapshot_ts()))
151 }
152
153 pub fn hop(&self, current: NodeId, rid: RelId, dir: Direction) -> Option<NodeId> {
154 let (start, end) = self.rel_ends(rid)?;
155 crate::store::hop_other(current, start, end, dir)
156 }
157
158 /// Plan-time label cardinality estimate (ADR-0218), forwarded for the
159 /// exec layer's pattern-start estimates (ADR-0351).
160 pub fn label_count(&self, label: &str) -> u64 {
161 self.base.label_count(label)
162 }
163
164 /// Existence check without materializing the relationship.
165 pub fn rel_exists(&self, id: RelId) -> bool {
166 self.rel_prologue(id, |_| true)
167 .resolve(false, || self.base.rel_visible_at(id, self.snapshot_ts()))
168 }
169
170 /// The type name shared (`Arc<str>` — one refcount bump off the
171 /// store's interned name; the batch record's copy is the only
172 /// allocation, and only when the rel is scratch). The selector's
173 /// per-walk type reads ride this, never the `String` clone.
174 pub fn rel_type_shared(&self, id: RelId) -> Option<Arc<str>> {
175 self.rel_prologue(id, |r| Some(Arc::from(r.rel_type.as_str())))
176 .resolve(None, || {
177 self.base.rel_type_name_shared(id, self.snapshot_ts())
178 })
179 }
180
181 /// Type name without materializing the relationship's property map.
182 pub fn rel_type(&self, id: RelId) -> Option<String> {
183 self.rel_prologue(id, |r| Some(r.rel_type.clone()))
184 .resolve(None, || {
185 self.base
186 .rel_stub_at(id, self.snapshot_ts())
187 .map(|r| r.rel_type)
188 })
189 }
190
191 pub fn node_stub(&self, id: NodeId) -> Option<Node> {
192 self.node_prologue(id, |n| {
193 Some(Node {
194 id: n.id,
195 labels: n.labels.clone(),
196 properties: crate::store::empty_properties(),
197 })
198 })
199 .resolve(None, || self.base.node_stub_at(id, self.snapshot_ts()))
200 }
201
202 pub fn rel_stub(&self, id: RelId) -> Option<Relationship> {
203 self.rel_prologue(id, |r| {
204 Some(Relationship {
205 id: r.id,
206 start: r.start,
207 end: r.end,
208 rel_type: r.rel_type.clone(),
209 properties: crate::store::empty_properties(),
210 })
211 })
212 .resolve(None, || self.base.rel_stub_at(id, self.snapshot_ts()))
213 }
214
215 pub fn node_prop(&self, id: NodeId, key: &str) -> Option<Value> {
216 self.node_prologue(id, |n| n.properties.get(key).cloned())
217 .resolve(None, || self.base.node_prop_at(id, self.snapshot_ts(), key))
218 }
219
220 /// The plan token as this view must read it — the one rebase policy
221 /// every token domain reads (ADR-0541 × ADR-0210): an `Absent` token
222 /// records a plan-time fact, the store had never interned the name,
223 /// and a `CALL { … } IN TRANSACTIONS` statement's own batch commits
224 /// intern names mid-statement, after the plan resolved them but
225 /// before its later parts read. A scratch rebased past this view's
226 /// admission pin — the state only those mid-statement commits
227 /// produce — therefore turns `Absent` into `Unresolved`, so the
228 /// caller's by-name lookup answers it; every other view keeps the
229 /// plan's answer (a view reading at its own pin cannot see data
230 /// committed after it). `Id` passes through: the interner is
231 /// append-only, so a plan-time id stays the name's id. The label
232 /// twin of this re-check is [`Self::node_has_uninterned_label`].
233 pub(crate) fn live_token(&self, token: Token) -> Token {
234 if token == Token::Absent && self.snapshot_ts() != self.pinned_ts {
235 Token::Unresolved
236 } else {
237 token
238 }
239 }
240
241 /// The store id a plan-resolved property-key token names (ADR-0541):
242 /// the token through [`Self::live_token`]'s rebase policy, then the
243 /// documented `Token::id_or_else` dispatch with the base's by-name
244 /// lookup.
245 pub(crate) fn prop_key_id_resolved(&self, text: &str, token: Token) -> Option<u32> {
246 self.live_token(token)
247 .id_or_else(|| self.base.prop_key_id(text))
248 }
249
250 /// [`Self::node_prop`] reading a plan-resolved key: no interner lookup
251 /// per call on the snapshot arm. An `Unresolved` key resolves by name
252 /// through [`Self::prop_key_id_resolved`] and an `Absent` one answers `None` without a store
253 /// read — unless the scratch was rebased past this view's pin
254 /// ([`Self::prop_key_id_resolved`]); the scratch arm is string-keyed
255 /// either way.
256 pub(crate) fn node_prop_resolved(
257 &self,
258 id: NodeId,
259 (name, token): &relate_names::NamedToken,
260 ) -> Option<Value> {
261 name.with_str(|text| {
262 self.node_prologue(id, |n| n.properties.get(text).cloned())
263 .resolve(None, || {
264 self.prop_key_id_resolved(text, *token)
265 .and_then(|kid| self.node_prop_snapshot(id, kid))
266 })
267 })
268 }
269
270 /// One snapshot property read through the statement-resolved store
271 /// (ADR-0665 A/B): the store handle resolves once per statement, so a
272 /// read pays one `carries` check and one `point` dispatch — the
273 /// per-read gate's resolution is not paid here. The seam's one
274 /// resolution (`point_through`) answers: a declined key and a store
275 /// miss both fall to the compact records.
276 fn node_prop_snapshot(&self, id: NodeId, kid: u32) -> Option<Value> {
277 self.base.point_through(
278 self.resolved_store().map(|store| store.as_ref()),
279 self.snapshot_ts(),
280 id,
281 kid,
282 )
283 }
284
285 /// Batched property read for candidate nodes `ids` and plan-resolved `(name, token)`.
286 ///
287 /// If an uncommitted write overlay exists, reads fall back directly through
288 /// scratch and MVCC row records to ensure uncommitted updates are never bypassed.
289 /// Otherwise dispatches to the resolved attached store when available and carried.
290 pub(crate) fn node_prop_batch(
291 &self,
292 ids: &[NodeId],
293 (name, token): &relate_names::NamedToken,
294 out: &mut [Option<Value>],
295 ) {
296 assert_eq!(
297 ids.len(),
298 out.len(),
299 "ids and out lengths must match for node_prop_batch"
300 );
301 name.with_str(|text| {
302 if self.has_write_overlay() {
303 for (i, &id) in ids.iter().enumerate() {
304 out[i] = self.node_prop(id, text);
305 }
306 return;
307 }
308 if let Some(kid) = self.prop_key_id_resolved(text, *token) {
309 self.base.point_batch_through(
310 self.resolved_store().map(|store| store.as_ref()),
311 self.snapshot_ts(),
312 ids,
313 kid,
314 out,
315 );
316 } else {
317 out.fill(None);
318 }
319 });
320 }
321
322 /// Vectorized range/comparison filter over `ids` and active bits in `mask`.
323 ///
324 /// When an uncommitted write overlay is present or the store declines, returns `None`
325 /// so callers fall back cleanly to `node_prop_batch` and exact Cypher 3VL evaluation.
326 pub(crate) fn node_filter_range(
327 &self,
328 ids: &[NodeId],
329 (name, token): &relate_names::NamedToken,
330 op: relate_ir::BinaryOp,
331 lit: &Value,
332 mask: &mut [u64],
333 ) -> Option<()> {
334 if self.has_write_overlay() {
335 return None;
336 }
337 name.with_str(|text| {
338 let kid = self.prop_key_id_resolved(text, *token)?;
339 self.base.filter_range_through(
340 self.resolved_store().map(|store| store.as_ref()),
341 self.snapshot_ts(),
342 ids,
343 kid,
344 op,
345 lit,
346 mask,
347 )
348 })
349 }
350
351 /// Folds (min/max/count) over `ids` matching active bits in `mask`.
352 /// Declines (`None`) when an uncommitted write overlay is present or the store declines.
353 #[allow(dead_code)]
354 pub(crate) fn node_folds_masked(
355 &self,
356 ids: &[NodeId],
357 mask: &[u64],
358 (name, token): &relate_names::NamedToken,
359 wants: &[crate::graph::PropFold],
360 ) -> Option<Vec<Value>> {
361 if self.has_write_overlay() {
362 return None;
363 }
364 name.with_str(|text| {
365 let kid = self.prop_key_id_resolved(text, *token)?;
366 self.base.folds_masked_through(
367 self.resolved_store().map(|store| store.as_ref()),
368 self.snapshot_ts(),
369 ids,
370 mask,
371 kid,
372 wants,
373 )
374 })
375 }
376
377 /// Grouped frequency counts over `ids` matching active bits in `mask`.
378 /// Declines (`None`) when an uncommitted write overlay is present or the store declines.
379 #[allow(dead_code)]
380 pub(crate) fn node_grouped_counts_masked(
381 &self,
382 ids: &[NodeId],
383 mask: &[u64],
384 (name, token): &relate_names::NamedToken,
385 ) -> Option<Vec<(Value, u64)>> {
386 if self.has_write_overlay() {
387 return None;
388 }
389 name.with_str(|text| {
390 let kid = self.prop_key_id_resolved(text, *token)?;
391 self.base.grouped_counts_masked_through(
392 self.resolved_store().map(|store| store.as_ref()),
393 self.snapshot_ts(),
394 ids,
395 mask,
396 kid,
397 )
398 })
399 }
400
401 /// [`Self::node_prop_resolved`] for a relationship.
402 pub(crate) fn rel_prop_resolved(
403 &self,
404 id: RelId,
405 (name, token): &relate_names::NamedToken,
406 ) -> Option<Value> {
407 name.with_str(|text| {
408 self.rel_prologue(id, |r| r.properties.get(text).cloned())
409 .resolve(None, || {
410 self.prop_key_id_resolved(text, *token)
411 .and_then(|kid| self.base.rel_prop_id_at(id, self.snapshot_ts(), text, kid))
412 })
413 })
414 }
415
416 /// The label check for a name the store never interned (`Absent`, or an
417 /// interned id missing): no committed node carries it, so only a write
418 /// overlay can, by string — `None` for an invisible node.
419 pub(crate) fn node_has_uninterned_label(&self, id: NodeId, label: &str) -> Option<bool> {
420 if self.has_write_overlay() {
421 self.node_has_label(id, label)
422 } else {
423 Some(false)
424 }
425 }
426
427 /// The scan-predicate gate's one candidate read: `check` sees the
428 /// candidate as a [`ScanNode`] — the scratch copy when the overlay
429 /// holds one, else the snapshot's visible live record — and its
430 /// verdict settles the candidate. An invisible or scratch-deleted
431 /// node rejects without `check` running, the same verdict
432 /// `node_exists`-gated paths give.
433 pub(crate) fn node_scan_check(
434 &self,
435 id: NodeId,
436 check: impl Fn(ScanNode<'_>) -> Result<bool>,
437 ) -> Result<bool> {
438 self.node_prologue(id, |n| check(ScanNode::Scratch(n)))
439 .resolve(Ok(false), || {
440 self.base
441 .with_visible_node(id, self.snapshot_ts(), |live| check(ScanNode::Live(live)))
442 .unwrap_or(Ok(false))
443 })
444 }
445
446 pub fn rel_prop(&self, id: RelId, key: &str) -> Option<Value> {
447 self.rel_prologue(id, |r| r.properties.get(key).cloned())
448 .resolve(None, || self.base.rel_prop_at(id, self.snapshot_ts(), key))
449 }
450
451 pub fn node_prop_keys(&self, id: NodeId) -> Vec<String> {
452 self.node_prologue(id, |n| n.properties.keys().cloned().collect())
453 .resolve(Vec::new(), || {
454 self.base.node_prop_keys_at(id, self.snapshot_ts())
455 })
456 }
457
458 pub fn rel_prop_keys(&self, id: RelId) -> Vec<String> {
459 self.rel_prologue(id, |r| r.properties.keys().cloned().collect())
460 .resolve(Vec::new(), || {
461 self.base.rel_prop_keys_at(id, self.snapshot_ts())
462 })
463 }
464}