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.base.node_prop_id_at(id, self.snapshot_ts(), kid))
266 })
267 })
268 }
269
270 /// [`Self::node_prop_resolved`] for a relationship.
271 pub(crate) fn rel_prop_resolved(
272 &self,
273 id: RelId,
274 (name, token): &relate_names::NamedToken,
275 ) -> Option<Value> {
276 name.with_str(|text| {
277 self.rel_prologue(id, |r| r.properties.get(text).cloned())
278 .resolve(None, || {
279 self.prop_key_id_resolved(text, *token)
280 .and_then(|kid| self.base.rel_prop_id_at(id, self.snapshot_ts(), text, kid))
281 })
282 })
283 }
284
285 /// The label check for a name the store never interned (`Absent`, or an
286 /// interned id missing): no committed node carries it, so only a write
287 /// overlay can, by string — `None` for an invisible node.
288 pub(crate) fn node_has_uninterned_label(&self, id: NodeId, label: &str) -> Option<bool> {
289 if self.has_write_overlay() {
290 self.node_has_label(id, label)
291 } else {
292 Some(false)
293 }
294 }
295
296 /// The scan-predicate gate's one candidate read: `check` sees the
297 /// candidate as a [`ScanNode`] — the scratch copy when the overlay
298 /// holds one, else the snapshot's visible live record — and its
299 /// verdict settles the candidate. An invisible or scratch-deleted
300 /// node rejects without `check` running, the same verdict
301 /// `node_exists`-gated paths give.
302 pub(crate) fn node_scan_check(
303 &self,
304 id: NodeId,
305 check: impl Fn(ScanNode<'_>) -> Result<bool>,
306 ) -> Result<bool> {
307 self.node_prologue(id, |n| check(ScanNode::Scratch(n)))
308 .resolve(Ok(false), || {
309 self.base
310 .with_visible_node(id, self.snapshot_ts(), |live| check(ScanNode::Live(live)))
311 .unwrap_or(Ok(false))
312 })
313 }
314
315 pub fn rel_prop(&self, id: RelId, key: &str) -> Option<Value> {
316 self.rel_prologue(id, |r| r.properties.get(key).cloned())
317 .resolve(None, || self.base.rel_prop_at(id, self.snapshot_ts(), key))
318 }
319
320 pub fn node_prop_keys(&self, id: NodeId) -> Vec<String> {
321 self.node_prologue(id, |n| n.properties.keys().cloned().collect())
322 .resolve(Vec::new(), || {
323 self.base.node_prop_keys_at(id, self.snapshot_ts())
324 })
325 }
326
327 pub fn rel_prop_keys(&self, id: RelId) -> Vec<String> {
328 self.rel_prologue(id, |r| r.properties.keys().cloned().collect())
329 .resolve(Vec::new(), || {
330 self.base.rel_prop_keys_at(id, self.snapshot_ts())
331 })
332 }
333}