Skip to main content

relate_executor/overlay/
mod.rs

1//! Private write overlay for optimistic execute (ADR-0016).
2
3use std::cell::{Cell, RefCell};
4use std::collections::HashSet;
5
6use relate_core::{CancelToken, Namespace, NodeId, RelId, Result, Value};
7
8use crate::csv::CsvReader;
9use crate::graph::{Graph, Procedure, QueryStats, SchemaSnapshot};
10
11mod budget;
12mod idlists;
13
14pub use budget::NESTED_EVAL_BUDGET;
15pub(crate) use budget::{ExpressionBudgetCounter, NestedEvalCounter, RetainedTotal};
16pub(crate) use idlists::{intersect_ids, union_ids};
17
18/// The distinct labels of `labels`, in first-occurrence order — the one
19/// dedup every label-accounting walk rides (live-label bumps, net
20/// label-delta accounting, per-node counter accounting). Shared by the
21/// scratch (its label accounting) and the write verbs (`writes.rs`).
22fn distinct_labels(labels: &[String]) -> Vec<&str> {
23    let mut seen = HashSet::new();
24    labels
25        .iter()
26        .map(String::as_str)
27        .filter(|label| seen.insert(*label))
28        .collect()
29}
30
31/// Read view of committed graph plus optional overlay (ADR-0016).
32pub struct ExecGraph<'a> {
33    base: &'a Graph,
34    schema: Option<&'a SchemaSnapshot>,
35    scratch: Option<&'a RefCell<WriteScratch>>,
36    pinned_ts: u64,
37    /// Cooperative cancellation flag for this statement (ADR-0111). `None`
38    /// for views that do not participate in cancellation (tests, diagnostics,
39    /// and the internal write views that never outlive a checked statement).
40    cancel: Option<&'a CancelToken>,
41    /// Statement-wide cancellation sampling window (ADR-0111). One counter
42    /// shared by every hot loop in the statement — scans, folds, and the
43    /// recursive var-length walks — so recursion depth cannot reset the
44    /// window and hide a cancellation. A `Cell` suffices: a statement's
45    /// executor access is single-threaded (the query worker thread), and the
46    /// `&RefCell<WriteScratch>` overlay already makes this view `!Sync`.
47    cancel_ticks: Cell<usize>,
48    /// The per-statement nested-evaluation counter (ADR-0395): one shared
49    /// cell per top-level statement. The view owns it beside
50    /// `cancel_ticks` — every nested entry ticks [`Self::nested_evals`],
51    /// so nesting compounds on one counter and no nested context can
52    /// reset it.
53    nested_evals: NestedEvalCounter,
54    /// The per-statement expression allocation meter (ADR-0463): one
55    /// shared counter per top-level statement, reset at statement entry
56    /// beside the nested-evaluation counter. Every bounded expression
57    /// allocation charges here before it grows, so a single statement
58    /// cannot build an arbitrarily large value through `range`,
59    /// concatenation, comprehensions, accumulators, or the
60    /// collection/string builtins.
61    expression_budget: ExpressionBudgetCounter,
62    /// The per-allocation expression cap this view enforces (ADR-0463):
63    /// inherited from the store's configured limit. `None` is the explicit
64    /// opt-out; otherwise one built value over this many bytes is refused.
65    expression_limit: Option<u64>,
66    /// The store's ontology document as the calling transaction sees it
67    /// (ADR-0121 §3, ADR-0227): per-admission state attached like the
68    /// cancel token ([`Self::with_ontology_document`]), read by the
69    /// `db.ontology.get` / `db.ontology.apply` procedure arms.
70    /// `None` = no ontology set (also every test/diagnostic view).
71    ontology_document: Option<&'a str>,
72    pub(crate) csv: CsvReader<'a>,
73}
74
75/// Sampling mask for cooperative cancellation checks on hot per-row loops
76/// (ADR-0111). `ticks & CANCEL_SAMPLE_MASK == 0` checks the token roughly
77/// once per 1024 iterations, so the atomic load is not paid on every row.
78const CANCEL_SAMPLE_MASK: usize = 1023;
79
80impl<'a> ExecGraph<'a> {
81    /// Schema-less read view of the committed graph. `show_schema` falls back
82    /// to the live committed theater (under its lock); use
83    /// [`Self::with_schema`] when a pinned admission snapshot is
84    /// required. This is the constructor for tests and callers that never
85    /// consult committed SHOW metadata.
86    pub fn read(base: &'a Graph) -> Self {
87        Self::read_at(base, base.commit_ts())
88    }
89    /// The base graph this snapshot reads — estimate-time consumers
90    /// (the live-graph stats, LABS-351) need the base's index counts.
91    pub(crate) fn base(&self) -> &'a Graph {
92        self.base
93    }
94
95    /// The count-only statistics short-circuit's exactness precondition
96    /// (LABS-370 v1 follow-up): this view reads the base's latest
97    /// published state with nothing the base stats cannot see — no
98    /// scratch overlay (an explicit transaction's or write statement's
99    /// own writes live there and the base stats cannot see them), no
100    /// in-flight base write window (`apply_redo` bumps the stats before
101    /// it publishes), and no pinned older snapshot (a concurrent apply
102    /// advances the base stats past an older pin). Any other view
103    /// declines the short-circuit to the scan, which reads its own
104    /// writes. The predicate is checked twice (LABS-370 round 3, F-1-5):
105    /// once up front as a cheap filter, then again under BOTH stats-map
106    /// locks by the reader's consistency window
107    /// (`Graph::windowed_stats_count`) — a write that opens between the
108    /// two checks is closed by the under-lock re-check, so no
109    /// out-of-snapshot write leaks into the count.
110    pub(crate) fn sees_exact_base_stats(&self) -> bool {
111        self.scratch.is_none()
112            && !self.base.in_write_window()
113            && self.pinned_ts == self.base.commit_ts()
114    }
115
116    /// The store's `RELATE_PREVIEW`-resolved set (ADR-0371), the
117    /// executor-side gate the graph-type semantic layer reads for the
118    /// stored-state half of the graph-type trio's gates.
119    pub(crate) fn preview(&self) -> relate_core::PreviewFeatures {
120        self.base.preview()
121    }
122
123    /// The scratch-aware property-defaults gate (CIP-262, ADR-0388
124    /// review F-2-2): the committed theater's cheap answer
125    /// (`Graph::has_property_defaults`), or a `SetCurrentGraphType` in
126    /// this statement's unvalidated redo slice whose body could declare
127    /// or inherit a default (round 5 deleted the `PutGraphType`
128    /// alternative -- the only op that can change the current type). The one yes/no answer
129    /// over both vintages, so the committed-theater half can never miss
130    /// a default this very statement set; the statement boundary's
131    /// default application consults the same gate.
132    pub(crate) fn has_property_defaults(&self) -> bool {
133        if self.base.has_property_defaults() {
134            return true;
135        }
136        self.unvalidated_redo(|ops| {
137            ops.iter().any(|op| match op {
138                // SetCurrentGraphType is the only op that can change the
139                // current graph type property defaults apply from (the
140                // round-5 finding: the PutGraphType alternative never
141                // changes this gate's decision).
142                crate::redo::RedoOp::SetCurrentGraphType { body } => {
143                    crate::graph::spec_has_property_defaults(body)
144                }
145                _ => false,
146            })
147        })
148        .0
149    }
150
151    /// `read` at an explicit snapshot timestamp; same schema-less invariant.
152    pub fn read_at(base: &'a Graph, snapshot_ts: u64) -> Self {
153        Self::new_view(base, snapshot_ts, None)
154    }
155
156    /// Pin a schema snapshot on a view (combinator mirroring
157    /// [`Self::with_cancel`]): `ExecGraph::read_at(base, ts).with_schema(schema)`.
158    pub fn with_schema(mut self, schema: &'a SchemaSnapshot) -> Self {
159        self.schema = Some(schema);
160        self
161    }
162
163    /// Schema-less write view of the committed graph plus overlay.
164    /// `show_schema`/`validate_constraints` fall back to the live committed
165    /// theater, reached in two regimes: the autocommit path reaches it
166    /// while holding the publication read guard, and ADR-0210 batched
167    /// statements (`CALL { … } IN TRANSACTIONS`) reach it unguarded —
168    /// pinned on the graph version but racing a concurrent schema change.
169    /// A caller that needs a pinned admission adds it with
170    /// [`Self::with_schema`].
171    pub fn write(base: &'a Graph, scratch: &'a RefCell<WriteScratch>) -> Self {
172        let pinned_ts = scratch.borrow().snapshot_ts();
173        Self::new_view(base, pinned_ts, Some(scratch))
174    }
175
176    /// The constructor core the two view kinds share: every field but the
177    /// pin and the overlay starts identically (schema-less, cancellation
178    /// unattached, nesting and ontology unset), so a new field joins every
179    /// view by construction instead of being hand-synced across the
180    /// `read_at`/`write` literals.
181    fn new_view(
182        base: &'a Graph,
183        pinned_ts: u64,
184        scratch: Option<&'a RefCell<WriteScratch>>,
185    ) -> Self {
186        Self {
187            base,
188            schema: None,
189            scratch,
190            pinned_ts,
191            cancel: None,
192            cancel_ticks: Cell::new(0),
193            nested_evals: NestedEvalCounter::default(),
194            expression_budget: ExpressionBudgetCounter::default(),
195            expression_limit: base.expression_memory_limit(),
196            ontology_document: None,
197            csv: CsvReader::new(base.csv_policy()),
198        }
199    }
200
201    /// Which fixed namespace of the store the underlying graph is
202    /// (ADR-0116 §1). Used for namespace-qualified element ids (§7).
203    pub(crate) fn namespace(&self) -> Namespace {
204        self.base.namespace()
205    }
206
207    /// Attach a cooperative cancellation flag to this view (ADR-0111).
208    /// Construction sites that do not thread a token leave the view
209    /// uncancellable, which preserves the existing behavior.
210    pub fn with_cancel(mut self, cancel: Option<&'a CancelToken>) -> Self {
211        self.cancel = cancel;
212        self
213    }
214
215    /// Attach the ontology document the calling transaction sees
216    /// (ADR-0121 §3, ADR-0227): the facade's admission-time capture for
217    /// auto-commit statements, the begin-time capture for explicit
218    /// transactions. Per-admission state on the view, like
219    /// [`Self::with_cancel`] (ADR-0111); the `db.ontology.get` /
220    /// `db.ontology.apply` procedure arms read it through
221    /// [`Self::ontology_document`]. A view without one behaves as if the
222    /// store holds no ontology, which preserves test/diagnostic behavior.
223    pub fn with_ontology_document(mut self, document: Option<&'a str>) -> Self {
224        self.ontology_document = document;
225        self
226    }
227
228    /// The ontology document attached by [`Self::with_ontology_document`].
229    pub(crate) fn ontology_document(&self) -> Option<&'a str> {
230        self.ontology_document
231    }
232
233    /// Check the attached [`CancelToken`], returning
234    /// `Error::Cancelled` (`query cancelled`) once it is cancelled. Called at
235    /// row-production points and inside long loops; a view without a token is
236    /// never cancelled. See ADR-0111.
237    #[inline]
238    pub(crate) fn check_cancelled(&self) -> Result<()> {
239        match self.cancel {
240            Some(token) if token.is_cancelled() => Err(relate_core::Error::cancelled()),
241            _ => Ok(()),
242        }
243    }
244
245    /// Sample one hot-loop iteration against the statement-wide cancellation
246    /// window (ADR-0111).
247    ///
248    /// This is the single home of the sampling policy: cancellation is
249    /// checked at statement entry, at the top of every clause, and — via
250    /// this method — inside sampled hot loops, once every
251    /// [`CANCEL_SAMPLE_MASK`] + 1 ticks. The counter lives on the statement's
252    /// view, not on the call site, so recursive walks (var-length expansion
253    /// in `exec/expand.rs`, `eval_walk/pattern.rs`, `exec/gpm.rs`) accumulate
254    /// ticks across frames: a fresh per-frame window would let a
255    /// bounded-degree `()-[*1..n]->()` walk explore combinatorially many
256    /// frames that each stay under the window and never observe
257    /// cancellation. The counter wraps so an unbounded loop is safe; every
258    /// `CANCEL_SAMPLE_MASK + 1`th tick calls [`Self::check_cancelled`],
259    /// which surfaces the typed `Error::Cancelled` (`query cancelled`) once
260    /// the token is cancelled.
261    #[inline]
262    pub(crate) fn cancel_tick(&self) -> Result<()> {
263        relate_core::tokens::poll()?;
264        let ticks = self.cancel_ticks.get().wrapping_add(1);
265        self.cancel_ticks.set(ticks);
266        if ticks & CANCEL_SAMPLE_MASK == 0 {
267            self.check_cancelled()?;
268        }
269        Ok(())
270    }
271
272    /// The per-statement nested-evaluation counter (ADR-0395): the one
273    /// cell every nested entry ticks — the seeded statement engine and
274    /// the direct clause-engine paths alike — so all nesting compounds
275    /// on the statement's single budget.
276    pub(crate) fn nested_evals(&self) -> &NestedEvalCounter {
277        &self.nested_evals
278    }
279
280    /// Overlay scratch adj is unordered (ADR-0031 / ADR-0035).
281    pub(crate) fn has_write_overlay(&self) -> bool {
282        self.scratch.is_some()
283    }
284
285    pub(crate) fn overlay_changes_node_membership(&self) -> bool {
286        self.scratch
287            .is_some_and(|cell| cell.borrow().changes_node_membership())
288    }
289
290    fn snapshot_ts(&self) -> u64 {
291        self.scratch
292            .map(|s| s.borrow().snapshot_ts())
293            .unwrap_or(self.pinned_ts)
294    }
295
296    fn scratch_mut(&self) -> std::cell::RefMut<'_, WriteScratch> {
297        self.scratch
298            .expect("write on read-only ExecGraph")
299            .borrow_mut()
300    }
301
302    /// The one per-statement reset of the statement's own facts: the
303    /// ADR-0309 mutation counters and the ADR-0402 applied-change count
304    /// restart together at statement entry, so a view reused across
305    /// statements reports this statement's counters and its own applied count
306    /// — never the previous statement's. A read view carries no scratch and
307    /// has nothing to reset.
308    pub(crate) fn reset_statement(&self) {
309        if let Some(scratch) = self.scratch {
310            scratch.borrow_mut().reset_statement();
311        }
312    }
313
314    /// One statement's entry reset: the CSV memo, the statement-spanning
315    /// scratch state (the ADR-0309 counters and the ADR-0402 applied count in
316    /// one scratch reset), the ADR-0395 nested-evaluation budget and the
317    /// ADR-0463 expression-build meter restart together. Every statement
318    /// entry calls this and nothing else.
319    pub(crate) fn begin_statement(&self) {
320        self.csv.begin_statement();
321        self.reset_statement();
322        self.nested_evals().reset();
323        self.expression_budget.reset();
324    }
325
326    pub fn stats(&self) -> QueryStats {
327        self.scratch
328            .map(|s| s.borrow().statement.stats.clone())
329            .unwrap_or_default()
330    }
331
332    /// How many changes the current statement has applied so far
333    /// (ADR-0402 Decision 2): the count the statement entry reset zeroed and
334    /// every redo push grows, so a non-zero count is the statement's applied
335    /// fact. A read view applies nothing and reads zero.
336    pub(crate) fn applied_ops(&self) -> u64 {
337        self.scratch.map(|s| s.borrow().applied_ops()).unwrap_or(0)
338    }
339
340    pub(crate) fn scratch_snapshot(&self) -> Option<ScratchCheckpoint> {
341        self.scratch.map(|scratch| scratch.borrow().checkpoint())
342    }
343
344    /// Roll the scratch back to a captured [`Self::scratch_snapshot`]:
345    /// symmetric with the capture — a read view (no scratch) or a `None`
346    /// snapshot (a failed batch on a read view) is the same no-op, handled
347    /// once at this layer instead of re-decided at every caller.
348    pub(crate) fn restore_scratch(&self, snapshot: Option<ScratchCheckpoint>) {
349        if let (Some(scratch), Some(snapshot)) = (self.scratch, snapshot) {
350            scratch.borrow_mut().restore(snapshot);
351        }
352    }
353
354    /// ADR-0210 per-batch commit for `CALL { … } IN TRANSACTIONS`: hand the
355    /// current batch's redo ops to the durable-commit sink, then
356    /// [`WriteScratch::rebase`] the scratch at the new commit timestamp so
357    /// live overlay state stays bounded by one batch while the
358    /// statement-spanning state (stats, id allocators) carries over. A
359    /// read view (no scratch) or an empty batch (no ops) is a no-op.
360    pub(crate) fn commit_batch(&self, sink: &dyn crate::ctx::BatchCommit) -> Result<()> {
361        let Some(scratch) = self.scratch else {
362            return Ok(());
363        };
364        let (ops, ts) = {
365            let s = scratch.borrow();
366            (s.redo_ops(), s.snapshot_ts())
367        };
368        if ops.is_empty() {
369            return Ok(());
370        }
371        // The redo is drained only as part of the post-commit rebase
372        // below: a failed commit must leave the scratch (entity maps +
373        // redo) intact for the caller's abort/restore path, not
374        // half-updated with the redo gone.
375        let commit_ts = sink.commit_batch(ops, ts)?;
376        scratch.borrow_mut().rebase(commit_ts);
377        Ok(())
378    }
379
380    pub fn procedure(&self, name: &str) -> Option<Procedure> {
381        self.base.procedure(name)
382    }
383
384    /// Materialize a node as a `Value` for result rows and entity builtins
385    /// (`startNode()`/`endNode()`). Falls back to the virtual-node side
386    /// table (`virtual_nodes`, CIP-257) when the store/overlay lookup
387    /// misses, so endpoints of synthesized visualization relationships
388    /// resolve without a store backing. This is the one graph-level lookup
389    /// shared by the entity builtins and the visualization rows. Unlike
390    /// [`Self::node`], which write paths use and which must keep missing on
391    /// virtual ids (CIP-257 "Write behavior on virtual entities"), this
392    /// read-path materialization is the only place the fallback is
393    /// consulted.
394    pub fn node_value(&self, id: NodeId) -> Value {
395        if let Some(node) = self.node(id) {
396            return Value::from_node(node);
397        }
398        if let Some(value @ relate_model::CypherValue::Node { .. }) = lookup_virtual_node(id) {
399            return relate_core::cypher_to_value(&value);
400        }
401        Value::Null
402    }
403
404    pub fn rel_value(&self, id: RelId) -> Value {
405        self.rel(id)
406            .map(Value::from_relationship)
407            .unwrap_or(Value::Null)
408    }
409
410    pub fn is_deleted_node(&self, id: NodeId) -> bool {
411        self.scratch
412            .map(|s| s.borrow().batch.deleted_nodes.contains(&id))
413            .unwrap_or(false)
414    }
415
416    pub fn is_deleted_rel(&self, id: RelId) -> bool {
417        self.scratch
418            .map(|s| s.borrow().batch.deleted_rels.contains(&id))
419            .unwrap_or(false)
420    }
421
422    /// Every live node id, ascending: the snapshot's ids minus the scratch's
423    /// deletions plus its creations (ADR-0173). A copy-on-write entry was
424    /// read from the snapshot, so it is a snapshot id already, and a delete
425    /// drops the id from `created_nodes`. The two sets meet only if an
426    /// allocator handed out a committed id; `dedup` keeps that to one entry.
427    pub fn all_node_ids(&self) -> Vec<NodeId> {
428        let mut ids = self.base.all_node_ids_at(self.snapshot_ts());
429        if let Some(cell) = self.scratch {
430            let s = cell.borrow();
431            ids.retain(|id| !s.batch.deleted_nodes.contains(id));
432            ids.extend(s.batch.created_nodes.iter().copied());
433            ids.sort_unstable();
434            ids.dedup();
435        }
436        ids
437    }
438
439    /// Every live relationship id, ascending; built like
440    /// [`Self::all_node_ids`] from `deleted_rels` and `created_rels`.
441    pub fn all_rel_ids(&self) -> Vec<RelId> {
442        let mut ids = self.base.all_rel_ids_at(self.snapshot_ts());
443        if let Some(cell) = self.scratch {
444            let s = cell.borrow();
445            ids.retain(|id| !s.batch.deleted_rels.contains(id));
446            ids.extend(s.batch.created_rels.iter().copied());
447            ids.sort_unstable();
448            ids.dedup();
449        }
450        ids
451    }
452}
453
454mod adjacency;
455mod catalog;
456mod label_probe;
457mod materialize;
458mod prop_ix;
459mod reads;
460mod redo_log;
461mod rel_seek;
462mod scratch;
463mod seek;
464mod validation;
465mod virtual_nodes;
466mod writes;
467
468pub(crate) use materialize::MaterializeCache;
469pub(crate) use reads::ScanNode;
470pub(crate) use redo_log::ValidatedCatalog;
471pub(crate) use virtual_nodes::{lookup_virtual_node, register_virtual_node};
472
473use scratch::ScratchCheckpoint;
474pub use scratch::WriteScratch;
475
476#[cfg(test)]
477mod adjacency_tests;
478#[cfg(test)]
479mod allocator_exhaustion_tests;
480#[cfg(test)]
481pub(crate) mod batch_commit_tests;
482#[cfg(test)]
483mod budget_tests;
484#[cfg(test)]
485mod materialize_tests;
486#[cfg(test)]
487mod payload_sharing_tests;
488#[cfg(test)]
489mod query_semantics_tests;
490#[cfg(test)]
491mod read_projection_tests;
492#[cfg(test)]
493mod seek_merge_tests;
494#[cfg(test)]
495mod test_support;
496#[cfg(test)]
497mod validation_cursor_tests;
498#[cfg(test)]
499mod workspace_peak_tests;
500#[cfg(test)]
501mod write_stat_tests;