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