Skip to main content

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    /// [`Self::node_prop`] reading a plan-resolved key: no interner lookup
221    /// per call on the snapshot arm. An `Unresolved` key falls back to the
222    /// string lookup and an `Absent` one answers `None` without a store
223    /// read; the scratch arm is string-keyed either way.
224    pub(crate) fn node_prop_resolved(
225        &self,
226        id: NodeId,
227        (name, token): &relate_names::NamedToken,
228    ) -> Option<Value> {
229        name.with_str(|text| {
230            if *token == Token::Unresolved {
231                return self.node_prop(id, text);
232            }
233            self.node_prologue(id, |n| n.properties.get(text).cloned())
234                .resolve(None, || {
235                    token
236                        .id()
237                        .and_then(|kid| self.base.node_prop_id_at(id, self.snapshot_ts(), kid))
238                })
239        })
240    }
241
242    /// [`Self::node_prop_resolved`] for a relationship.
243    pub(crate) fn rel_prop_resolved(
244        &self,
245        id: RelId,
246        (name, token): &relate_names::NamedToken,
247    ) -> Option<Value> {
248        name.with_str(|text| {
249            if *token == Token::Unresolved {
250                return self.rel_prop(id, text);
251            }
252            self.rel_prologue(id, |r| r.properties.get(text).cloned())
253                .resolve(None, || {
254                    token
255                        .id()
256                        .and_then(|kid| self.base.rel_prop_id_at(id, self.snapshot_ts(), text, kid))
257                })
258        })
259    }
260
261    /// The label check for a name the store never interned (`Absent`, or an
262    /// interned id missing): no committed node carries it, so only a write
263    /// overlay can, by string — `None` for an invisible node.
264    pub(crate) fn node_has_uninterned_label(&self, id: NodeId, label: &str) -> Option<bool> {
265        if self.has_write_overlay() {
266            self.node_has_label(id, label)
267        } else {
268            Some(false)
269        }
270    }
271
272    /// The scan-predicate gate's one candidate read: `check` sees the
273    /// candidate as a [`ScanNode`] — the scratch copy when the overlay
274    /// holds one, else the snapshot's visible live record — and its
275    /// verdict settles the candidate. An invisible or scratch-deleted
276    /// node rejects without `check` running, the same verdict
277    /// `node_exists`-gated paths give.
278    pub(crate) fn node_scan_check(
279        &self,
280        id: NodeId,
281        check: impl Fn(ScanNode<'_>) -> Result<bool>,
282    ) -> Result<bool> {
283        self.node_prologue(id, |n| check(ScanNode::Scratch(n)))
284            .resolve(Ok(false), || {
285                self.base
286                    .with_visible_node(id, self.snapshot_ts(), |live| check(ScanNode::Live(live)))
287                    .unwrap_or(Ok(false))
288            })
289    }
290
291    pub fn rel_prop(&self, id: RelId, key: &str) -> Option<Value> {
292        self.rel_prologue(id, |r| r.properties.get(key).cloned())
293            .resolve(None, || self.base.rel_prop_at(id, self.snapshot_ts(), key))
294    }
295
296    pub fn node_prop_keys(&self, id: NodeId) -> Vec<String> {
297        self.node_prologue(id, |n| n.properties.keys().cloned().collect())
298            .resolve(Vec::new(), || {
299                self.base.node_prop_keys_at(id, self.snapshot_ts())
300            })
301    }
302
303    pub fn rel_prop_keys(&self, id: RelId) -> Vec<String> {
304        self.rel_prologue(id, |r| r.properties.keys().cloned().collect())
305            .resolve(Vec::new(), || {
306                self.base.rel_prop_keys_at(id, self.snapshot_ts())
307            })
308    }
309}