Skip to main content

relate_executor/overlay/
mod.rs

1//! Private write overlay for optimistic execute (ADR-0016).
2
3use std::borrow::Cow;
4use std::cell::{Cell, RefCell};
5use std::collections::HashSet;
6
7use relate_core::{CancelToken, Namespace, NodeId, RelId, Result, TransactionClock, Value};
8use relate_planner::LogicalPlan;
9
10use crate::csv::CsvReader;
11use crate::exec::kernels::construct_memo::ConstructMemos;
12use crate::graph::{Graph, Procedure, QueryStats, SchemaSnapshot};
13use crate::row::Row;
14
15mod budget;
16mod idlists;
17mod spelled;
18
19pub(crate) use spelled::is_internal_column;
20
21pub use budget::NESTED_EVAL_BUDGET;
22pub(crate) use budget::{
23    memo_table_ceiling, ExpressionBudgetCounter, MemoLive, NestedEvalCounter, RetainedTotal,
24    SeatShape,
25};
26pub(crate) use idlists::{intersect_ids, union_ids};
27use spelled::SpelledNames;
28
29/// The distinct labels of `labels`, in first-occurrence order — the one
30/// dedup every label-accounting walk rides (live-label bumps, net
31/// label-delta accounting, per-node counter accounting). Shared by the
32/// scratch (its label accounting) and the write verbs (`writes.rs`).
33fn distinct_labels(labels: &[String]) -> Vec<&str> {
34    let mut seen = HashSet::new();
35    labels
36        .iter()
37        .map(String::as_str)
38        .filter(|label| seen.insert(*label))
39        .collect()
40}
41
42/// Read view of committed graph plus optional overlay (ADR-0016).
43pub struct ExecGraph<'a> {
44    base: &'a Graph,
45    schema: Option<&'a SchemaSnapshot>,
46    scratch: Option<&'a RefCell<WriteScratch>>,
47    pinned_ts: u64,
48    /// Cooperative cancellation flag for this statement (ADR-0111). `None`
49    /// for views that do not participate in cancellation (tests, diagnostics,
50    /// and the internal write views that never outlive a checked statement).
51    cancel: Option<&'a CancelToken>,
52    /// Statement-wide cancellation sampling window (ADR-0111). One counter
53    /// shared by every hot loop in the statement — scans, folds, and the
54    /// recursive var-length walks — so recursion depth cannot reset the
55    /// window and hide a cancellation. A `Cell` suffices: a statement's
56    /// executor access is single-threaded (the query worker thread), and the
57    /// `&RefCell<WriteScratch>` overlay already makes this view `!Sync`.
58    cancel_ticks: Cell<usize>,
59    /// The per-statement nested-evaluation counter (ADR-0395): one shared
60    /// cell per top-level statement. The view owns it beside
61    /// `cancel_ticks` — every nested entry ticks [`Self::nested_evals`],
62    /// so nesting compounds on one counter and no nested context can
63    /// reset it.
64    nested_evals: NestedEvalCounter,
65    /// The per-statement expression allocation meter (ADR-0463): one
66    /// shared counter per top-level statement, reset at statement entry
67    /// beside the nested-evaluation counter. Every bounded expression
68    /// allocation charges here before it grows, so a single statement
69    /// cannot build an arbitrarily large value through `range`,
70    /// concatenation, comprehensions, accumulators, or the
71    /// collection/string builtins.
72    expression_budget: ExpressionBudgetCounter,
73    /// The per-allocation expression cap this view enforces (ADR-0463):
74    /// inherited from the store's configured limit. `None` is the explicit
75    /// opt-out; otherwise one built value over this many bytes is refused.
76    expression_limit: Option<u64>,
77    /// Live bytes of every stage memo in this statement (LABS-1478): one
78    /// shared counter the memos reserve from and return on drop, so the
79    /// query's memo footprint is bounded as a whole.
80    memo_live: MemoLive,
81    /// The statement's hashed-value memos over `datetime(text)`
82    /// (ADR-0640): a pure parse, so it carries across the statement's stages.
83    construct_memos: ConstructMemos,
84    /// The store's ontology document as the calling transaction sees it
85    /// (ADR-0121 §3, ADR-0227): per-admission state attached like the
86    /// cancel token ([`Self::with_ontology_document`]), read by the
87    /// `db.ontology.get` / `db.ontology.apply` procedure arms.
88    /// `None` = no ontology set (also every test/diagnostic view).
89    ontology_document: Option<&'a str>,
90    /// The instant the calling explicit transaction began at, so every
91    /// statement's clock pin reads one `<kind>.transaction()` instant
92    /// ([`Self::with_transaction_clock`]); `None` = autocommit.
93    transaction_clock: Option<TransactionClock>,
94    pub(crate) csv: CsvReader<'a>,
95    /// The `__`-prefixed names this statement declares itself, so the
96    /// executor's synthetic columns can be told from a user's binding
97    /// that spells the same prefix (REL8-1732).
98    spelled: SpelledNames,
99    /// The attached property store resolved for this statement (ADR-0665
100    /// A/B, the per-read chain's one resolution): filled by the first
101    /// property read and reused for the statement's lifetime — the
102    /// statement's read guard pins the publication epoch, so the store's
103    /// answers cannot move while the statement runs (ADR-0508's placement
104    /// argument). `None` inside the cell = no store serves this snapshot,
105    /// and the compact records answer as before. A cell like its
106    /// neighbours: single-threaded executor access.
107    serving_store: std::cell::OnceCell<Option<std::sync::Arc<dyn crate::graph::PropStore>>>,
108}
109
110/// Sampling mask for cooperative cancellation checks on hot per-row loops
111/// (ADR-0111). `ticks & CANCEL_SAMPLE_MASK == 0` checks the token roughly
112/// once per 1024 iterations, so the atomic load is not paid on every row.
113const CANCEL_SAMPLE_MASK: usize = 1023;
114
115/// Ticks between two token reads: the sampling interval the mask encodes.
116#[cfg(test)]
117pub(crate) const CANCEL_SAMPLE_INTERVAL: usize = CANCEL_SAMPLE_MASK + 1;
118
119impl<'a> ExecGraph<'a> {
120    /// Schema-less read view of the committed graph. `show_schema` falls back
121    /// to the live committed theater (under its lock); use
122    /// [`Self::with_schema`] when a pinned admission snapshot is
123    /// required. This is the constructor for tests and callers that never
124    /// consult committed SHOW metadata.
125    pub fn read(base: &'a Graph) -> Self {
126        Self::read_at(base, base.commit_ts())
127    }
128    /// The base graph this snapshot reads — estimate-time consumers
129    /// (the live-graph stats, LABS-351) need the base's index counts.
130    pub(crate) fn base(&self) -> &'a Graph {
131        self.base
132    }
133
134    /// The count-only statistics short-circuit's exactness precondition
135    /// (LABS-370 v1 follow-up): this view reads the base's latest
136    /// published state with nothing the base stats cannot see — no
137    /// scratch overlay carrying changes (an explicit transaction's or write
138    /// statement's own writes live there and the base stats cannot see
139    /// them; a scratch that has logged nothing yet is invisible to them
140    /// and passes, ADR-0689), no
141    /// in-flight base write window (`apply_redo` bumps the stats before
142    /// it publishes), and no pinned older snapshot (a concurrent apply
143    /// advances the base stats past an older pin). Any other view
144    /// declines the short-circuit to the scan, which reads its own
145    /// writes. The predicate is checked twice (LABS-370 round 3, F-1-5):
146    /// once up front as a cheap filter, then again under BOTH stats-map
147    /// locks by the reader's consistency window
148    /// (`Graph::windowed_stats_count`) — a write that opens between the
149    /// two checks is closed by the under-lock re-check, so no
150    /// out-of-snapshot write leaks into the count.
151    pub(crate) fn sees_exact_base_stats(&self) -> bool {
152        self.has_no_pending_writes()
153            && !self.base.in_write_window()
154            && self.pinned_ts == self.base.commit_ts()
155    }
156
157    /// Whether this view reads its committed snapshot unchanged: no write
158    /// scratch, or one with no changes yet (an explicit transaction always
159    /// carries a scratch, even when it only reads). The vector matrix
160    /// (ADR-0705) serves only such views; a view with its own uncommitted
161    /// writes scans `Value`s, which read those writes.
162    pub(crate) fn has_no_pending_writes(&self) -> bool {
163        self.scratch
164            .is_none_or(|scratch| scratch.borrow().has_no_changes())
165    }
166
167    /// The store's `RELATE_PREVIEW`-resolved set (ADR-0371), the
168    /// executor-side gate the graph-type semantic layer reads for the
169    /// stored-state half of the graph-type trio's gates.
170    pub(crate) fn preview(&self) -> relate_core::PreviewFeatures {
171        self.base.preview()
172    }
173
174    /// Whether `name`'s index was created inside the current write
175    /// scratch — an explicit transaction's or a write statement's own
176    /// uncommitted `CREATE INDEX`. A SEARCH over such an index is the
177    /// still-populating rejection (ADR-0678): the index becomes part of a
178    /// committed, scannable state only when the transaction commits. An
179    /// `IF NOT EXISTS` create over an already-committed index records no
180    /// create op, so it stays searchable.
181    pub(crate) fn index_created_in_scratch(&self, name: &str) -> bool {
182        self.scratch.is_some_and(|scratch| {
183            scratch.borrow().redo.catalog_ops().any(|op| {
184                matches!(
185                    op,
186                    crate::redo::RedoOp::CreateIndex { name: created, .. } if created == name
187                )
188            })
189        })
190    }
191
192    /// The scratch-aware property-defaults gate (CIP-262, ADR-0388
193    /// review F-2-2): the committed theater's cheap answer
194    /// (`Graph::has_property_defaults`), or a `SetCurrentGraphType` in
195    /// this statement's unvalidated redo slice whose body could declare
196    /// or inherit a default (round 5 deleted the `PutGraphType`
197    /// alternative -- the only op that can change the current type). The one yes/no answer
198    /// over both vintages, so the committed-theater half can never miss
199    /// a default this very statement set; the statement boundary's
200    /// default application consults the same gate.
201    pub(crate) fn has_property_defaults(&self) -> bool {
202        if self.base.has_property_defaults() {
203            return true;
204        }
205        self.unvalidated_redo(|ops| {
206            ops.iter().any(|op| match op {
207                // SetCurrentGraphType is the only op that can change the
208                // current graph type property defaults apply from (the
209                // round-5 finding: the PutGraphType alternative never
210                // changes this gate's decision).
211                crate::redo::RedoOp::SetCurrentGraphType { body } => {
212                    crate::graph::spec_has_property_defaults(body)
213                }
214                _ => false,
215            })
216        })
217        .0
218    }
219
220    /// `read` at an explicit snapshot timestamp; same schema-less invariant.
221    pub fn read_at(base: &'a Graph, snapshot_ts: u64) -> Self {
222        Self::new_view(base, snapshot_ts, None)
223    }
224
225    /// Pin a schema snapshot on a view (combinator mirroring
226    /// [`Self::with_cancel`]): `ExecGraph::read_at(base, ts).with_schema(schema)`.
227    pub fn with_schema(mut self, schema: &'a SchemaSnapshot) -> Self {
228        self.schema = Some(schema);
229        self
230    }
231
232    /// Schema-less write view of the committed graph plus overlay.
233    /// `show_schema`/`validate_constraints` fall back to the live committed
234    /// theater, reached in two regimes: the autocommit path reaches it
235    /// while holding the publication read guard, and ADR-0210 batched
236    /// statements (`CALL { … } IN TRANSACTIONS`) reach it unguarded —
237    /// pinned on the graph version but racing a concurrent schema change.
238    /// A caller that needs a pinned admission adds it with
239    /// [`Self::with_schema`].
240    pub fn write(base: &'a Graph, scratch: &'a RefCell<WriteScratch>) -> Self {
241        let pinned_ts = scratch.borrow().snapshot_ts();
242        Self::new_view(base, pinned_ts, Some(scratch))
243    }
244
245    /// The constructor core the two view kinds share: every field but the
246    /// pin and the overlay starts identically (schema-less, cancellation
247    /// unattached, nesting and ontology unset), so a new field joins every
248    /// view by construction instead of being hand-synced across the
249    /// `read_at`/`write` literals.
250    fn new_view(
251        base: &'a Graph,
252        pinned_ts: u64,
253        scratch: Option<&'a RefCell<WriteScratch>>,
254    ) -> Self {
255        let memo_live = MemoLive::new(base.memo_budget_bytes());
256        Self {
257            base,
258            schema: None,
259            scratch,
260            pinned_ts,
261            cancel: None,
262            cancel_ticks: Cell::new(0),
263            nested_evals: NestedEvalCounter::new(base.nested_eval_budget()),
264            expression_budget: ExpressionBudgetCounter::default(),
265            expression_limit: base.expression_memory_limit(),
266            construct_memos: ConstructMemos::new(memo_live.clone()),
267            memo_live,
268            ontology_document: None,
269            transaction_clock: None,
270            csv: CsvReader::new(base.csv_policy()),
271            spelled: SpelledNames::default(),
272            serving_store: std::cell::OnceCell::new(),
273        }
274    }
275
276    /// Which fixed namespace of the store the underlying graph is
277    /// (ADR-0116 §1). Used for namespace-qualified element ids (§7).
278    pub(crate) fn namespace(&self) -> Namespace {
279        self.base.namespace()
280    }
281
282    /// Attach a cooperative cancellation flag to this view (ADR-0111).
283    /// Construction sites that do not thread a token leave the view
284    /// uncancellable, which preserves the existing behavior.
285    pub fn with_cancel(mut self, cancel: Option<&'a CancelToken>) -> Self {
286        self.cancel = cancel;
287        self
288    }
289
290    /// Attach the ontology document the calling transaction sees
291    /// (ADR-0121 §3, ADR-0227): the facade's admission-time capture for
292    /// auto-commit statements, the begin-time capture for explicit
293    /// transactions. Per-admission state on the view, like
294    /// [`Self::with_cancel`] (ADR-0111); the `db.ontology.get` /
295    /// `db.ontology.apply` procedure arms read it through
296    /// [`Self::effective_ontology_document`], which overlays the write
297    /// log's pending ontology op on it. A view without one behaves as if
298    /// the store holds no ontology, which preserves test/diagnostic
299    /// behavior.
300    pub fn with_ontology_document(mut self, document: Option<&'a str>) -> Self {
301        self.ontology_document = document;
302        self
303    }
304
305    /// Attach the explicit transaction's begin-time clock: per-admission
306    /// state like [`Self::with_cancel`]. A view without one is an autocommit
307    /// statement, whose own instant is its transaction's.
308    pub fn with_transaction_clock(mut self, clock: TransactionClock) -> Self {
309        self.transaction_clock = Some(clock);
310        self
311    }
312
313    /// The transaction clock attached by [`Self::with_transaction_clock`].
314    pub(crate) fn transaction_clock(&self) -> Option<TransactionClock> {
315        self.transaction_clock
316    }
317
318    /// The ontology document this view's readers must serve (ADR-0667):
319    /// the write overlay's pending state when the statement or transaction
320    /// pushed an ontology op — the log's last op wins, exactly as the
321    /// commit pipeline's own last-op-wins rule — else the attached capture.
322    /// This is the read-own-writes fact: a `get` after a `set` in the same
323    /// transaction sees the pending document, and a rollback (the scratch
324    /// discarded) returns every later read to the committed capture.
325    pub(crate) fn effective_ontology_document(&self) -> Option<Cow<'a, str>> {
326        if let Some(cell) = self.scratch {
327            let scratch = cell.borrow();
328            match scratch.redo.last_ontology_op() {
329                Some(crate::redo::OntologyOp::Set(spec)) => {
330                    return Some(Cow::Owned(spec.to_string()));
331                }
332                // A pending drop hides the committed document.
333                Some(crate::redo::OntologyOp::Drop) => return None,
334                None => {}
335            }
336        }
337        self.ontology_document.map(Cow::Borrowed)
338    }
339
340    /// Check the attached [`CancelToken`], returning
341    /// `Error::Cancelled` (`query cancelled`) once it is cancelled. Called at
342    /// row-production points and inside long loops; a view without a token is
343    /// never cancelled. See ADR-0111.
344    #[inline]
345    pub(crate) fn check_cancelled(&self) -> Result<()> {
346        match self.cancel {
347            Some(token) if token.is_cancelled() => Err(relate_core::Error::cancelled()),
348            _ => Ok(()),
349        }
350    }
351
352    /// Sample one hot-loop iteration against the statement-wide cancellation
353    /// window (ADR-0111).
354    ///
355    /// This is the single home of the sampling policy: cancellation is
356    /// checked at statement entry, at the top of every clause, and — via
357    /// this method — inside sampled hot loops, once every
358    /// [`CANCEL_SAMPLE_MASK`] + 1 ticks. The counter lives on the statement's
359    /// view, not on the call site, so recursive walks (var-length expansion
360    /// in `exec/expand.rs`, `eval_walk/pattern.rs`, `exec/gpm.rs`) accumulate
361    /// ticks across frames: a fresh per-frame window would let a
362    /// bounded-degree `()-[*1..n]->()` walk explore combinatorially many
363    /// frames that each stay under the window and never observe
364    /// cancellation. The counter wraps so an unbounded loop is safe; every
365    /// `CANCEL_SAMPLE_MASK + 1`th tick calls [`Self::check_cancelled`],
366    /// which surfaces the typed `Error::Cancelled` (`query cancelled`) once
367    /// the token is cancelled.
368    #[inline]
369    pub(crate) fn cancel_tick(&self) -> Result<()> {
370        relate_core::tokens::poll()?;
371        let ticks = self.cancel_ticks.get().wrapping_add(1);
372        self.cancel_ticks.set(ticks);
373        if ticks & CANCEL_SAMPLE_MASK == 0 {
374            self.check_cancelled()?;
375        }
376        Ok(())
377    }
378
379    /// The per-statement nested-evaluation counter (ADR-0395): the one
380    /// cell every nested entry ticks — the seeded statement engine and
381    /// the direct clause-engine paths alike — so all nesting compounds
382    /// on the statement's single budget.
383    pub(crate) fn nested_evals(&self) -> &NestedEvalCounter {
384        &self.nested_evals
385    }
386
387    /// Overlay scratch adj is unordered (ADR-0031 / ADR-0035).
388    pub(crate) fn has_write_overlay(&self) -> bool {
389        self.scratch.is_some()
390    }
391
392    pub(crate) fn overlay_changes_node_membership(&self) -> bool {
393        self.scratch
394            .is_some_and(|cell| cell.borrow().changes_node_membership())
395    }
396
397    pub(crate) fn snapshot_ts(&self) -> u64 {
398        self.scratch
399            .map(|s| s.borrow().snapshot_ts())
400            .unwrap_or(self.pinned_ts)
401    }
402
403    /// The attached property store serving this statement's snapshot,
404    /// resolved once per statement (ADR-0665 A/B): every property read
405    /// below the overlay dispatches through this handle instead of
406    /// re-resolving per read. `None` when no store is attached or the
407    /// attached one serves a different snapshot — the compact records
408    /// answer, exactly the per-read gate's own decline.
409    pub(crate) fn resolved_store(&self) -> Option<&std::sync::Arc<dyn crate::graph::PropStore>> {
410        self.serving_store
411            .get_or_init(|| self.base.serving_store_handle(self.snapshot_ts()))
412            .as_ref()
413    }
414
415    fn scratch_mut(&self) -> std::cell::RefMut<'_, WriteScratch> {
416        self.scratch
417            .expect("write on read-only ExecGraph")
418            .borrow_mut()
419    }
420
421    /// The one per-statement reset of the statement's own facts: the
422    /// ADR-0309 mutation counters and the ADR-0402 applied-change count
423    /// restart together at statement entry, so a view reused across
424    /// statements reports this statement's counters and its own applied count
425    /// — never the previous statement's. A read view carries no scratch and
426    /// has nothing to reset.
427    pub(crate) fn reset_statement(&self) {
428        if let Some(scratch) = self.scratch {
429            scratch.borrow_mut().reset_statement();
430        }
431    }
432
433    /// One statement's entry: the CSV memo, the statement-spanning scratch
434    /// state (the ADR-0309 counters and the ADR-0402 applied count in one
435    /// scratch reset), the ADR-0395 nested-evaluation budget, the
436    /// ADR-0463 expression-build meter and the declared-name set restart
437    /// together, and the declared-name set is re-seeded from `plan` in the
438    /// same call — so no entry can produce a reset-but-undeclared
439    /// statement. Every statement entry calls this and nothing else; the
440    /// budget tests call it with an empty plan for the reset alone.
441    ///
442    /// The returned row is the statement's single root seed — the row its
443    /// driving operator starts from, minted here so both entries take it from
444    /// one home instead of fabricating it inline. A statement root drives
445    /// exactly one row (ADR-0687 decision 6), which is why the plan grade
446    /// measures store reads per execution and divides by no input count.
447    pub(crate) fn begin_statement(&self, plan: &LogicalPlan) -> Row {
448        self.csv.begin_statement();
449        self.reset_statement();
450        self.nested_evals().reset();
451        self.expression_budget.reset();
452        self.spelled.reset();
453        crate::exec::declare_plan_names(self, plan);
454        Row::new()
455    }
456
457    /// Record names the statement declares: the `__`-prefixed ones are the
458    /// statement's own, not the executor's. Called only by the statement-entry
459    /// plan walk ([`crate::exec::scope::declare_plan_names`]).
460    pub(crate) fn declare_names<'n>(&self, names: impl IntoIterator<Item = &'n str>) {
461        for name in names {
462            self.spelled.declare(name);
463        }
464    }
465
466    /// Whether `key` is a column the executor synthesized: in the `__`
467    /// namespace and not declared by this statement. The one typed
468    /// internality test every row-scanning consumer asks.
469    pub(crate) fn is_internal_key(&self, key: &str) -> bool {
470        spelled::is_internal_column(key) && !self.spelled.contains(key)
471    }
472
473    /// The statement's anonymous-seat prefixes, resolved once per
474    /// statement and cached (see [`SpelledNames`]) — the data the
475    /// pattern-walk schema builders take instead of the live view.
476    pub(crate) fn seat_prefixes(&self) -> std::sync::Arc<crate::pattern_walk::SeatPrefixes> {
477        self.spelled.seat_prefixes()
478    }
479
480    /// The statement's synthetic `__` prefix for `base`, lengthened past
481    /// `names` and every declared name (see [`SpelledNames`]).
482    pub(crate) fn uncolliding_prefix<'n>(
483        &self,
484        base: &str,
485        names: impl IntoIterator<Item = &'n str>,
486    ) -> String {
487        self.spelled.uncolliding_prefix(base, names)
488    }
489
490    pub fn stats(&self) -> QueryStats {
491        self.scratch
492            .map(|s| s.borrow().statement.stats.clone())
493            .unwrap_or_default()
494    }
495
496    /// How many changes the current statement has applied so far
497    /// (ADR-0402 Decision 2): the count the statement entry reset zeroed and
498    /// every redo push grows, so a non-zero count is the statement's applied
499    /// fact. A read view applies nothing and reads zero.
500    pub(crate) fn applied_ops(&self) -> u64 {
501        self.scratch.map(|s| s.borrow().applied_ops()).unwrap_or(0)
502    }
503
504    pub(crate) fn scratch_snapshot(&self) -> Option<ScratchCheckpoint> {
505        self.scratch.map(|scratch| scratch.borrow().checkpoint())
506    }
507
508    /// The current batch's created bytes for PROFILE (REL8-2047): the
509    /// `IN TRANSACTIONS` arm's per-batch scratch figure, read before the
510    /// batch commits or rolls back. A read view reads zero — the same
511    /// fold every sibling read on this graph makes.
512    pub(crate) fn scratch_created_bytes(&self) -> u64 {
513        self.scratch
514            .map(|scratch| scratch.borrow().scratch_created_bytes())
515            .unwrap_or(0)
516    }
517
518    /// The current batch's redo-log bytes for PROFILE (REL8-2047) — the
519    /// WAL payload its commit writes, the arm's per-batch WAL figure. A
520    /// read view reads zero.
521    pub(crate) fn redo_reserved_bytes(&self) -> u64 {
522        self.scratch
523            .map(|scratch| scratch.borrow().redo_reserved_bytes())
524            .unwrap_or(0)
525    }
526
527    /// Roll the scratch back to a captured [`Self::scratch_snapshot`]:
528    /// symmetric with the capture — a read view (no scratch) or a `None`
529    /// snapshot (a failed batch on a read view) is the same no-op, handled
530    /// once at this layer instead of re-decided at every caller.
531    pub(crate) fn restore_scratch(&self, snapshot: Option<ScratchCheckpoint>) {
532        if let (Some(scratch), Some(snapshot)) = (self.scratch, snapshot) {
533            scratch.borrow_mut().restore(snapshot);
534        }
535    }
536
537    /// ADR-0210 per-batch commit for `CALL { … } IN TRANSACTIONS`: hand the
538    /// current batch's redo ops to the durable-commit sink, then
539    /// [`WriteScratch::rebase`] the scratch at the new commit timestamp so
540    /// live overlay state stays bounded by one batch while the
541    /// statement-spanning state (stats, id allocators) carries over. A
542    /// read view (no scratch) or an empty batch (no ops) is a no-op.
543    pub(crate) fn commit_batch(&self, sink: &dyn crate::ctx::BatchCommit) -> Result<()> {
544        let Some(scratch) = self.scratch else {
545            return Ok(());
546        };
547        let (ops, ts) = {
548            let s = scratch.borrow();
549            (s.redo_ops(), s.snapshot_ts())
550        };
551        if ops.is_empty() {
552            return Ok(());
553        }
554        // The redo is drained only as part of the post-commit rebase
555        // below: a failed commit must leave the scratch (entity maps +
556        // redo) intact for the caller's abort/restore path, not
557        // half-updated with the redo gone.
558        let commit_ts = sink.commit_batch(ops, ts)?;
559        scratch.borrow_mut().rebase(commit_ts);
560        Ok(())
561    }
562
563    pub fn procedure(&self, name: &str) -> Option<Procedure> {
564        self.base.procedure(name)
565    }
566
567    /// Materialize a node as a `Value` for result rows and entity builtins
568    /// (`startNode()`/`endNode()`). Falls back to the virtual-node side
569    /// table (`virtual_nodes`, CIP-257) when the store/overlay lookup
570    /// misses, so endpoints of synthesized visualization relationships
571    /// resolve without a store backing. This is the one graph-level lookup
572    /// shared by the entity builtins and the visualization rows. Unlike
573    /// [`Self::node`], which write paths use and which must keep missing on
574    /// virtual ids (CIP-257 "Write behavior on virtual entities"), this
575    /// read-path materialization is the only place the fallback is
576    /// consulted.
577    pub fn node_value(&self, id: NodeId) -> Value {
578        if let Some(node) = self.node(id) {
579            return Value::from_node(node);
580        }
581        if let Some(value @ relate_model::CypherValue::Node { .. }) = lookup_virtual_node(id) {
582            return relate_core::cypher_to_value(&value);
583        }
584        Value::Null
585    }
586
587    pub fn rel_value(&self, id: RelId) -> Value {
588        self.rel(id)
589            .map(Value::from_relationship)
590            .unwrap_or(Value::Null)
591    }
592
593    pub fn is_deleted_node(&self, id: NodeId) -> bool {
594        self.scratch
595            .map(|s| s.borrow().batch.deleted_nodes.contains(&id))
596            .unwrap_or(false)
597    }
598
599    pub fn is_deleted_rel(&self, id: RelId) -> bool {
600        self.scratch
601            .map(|s| s.borrow().batch.deleted_rels.contains(&id))
602            .unwrap_or(false)
603    }
604
605    /// One past the largest node id this view can show: committed ids are
606    /// below the graph's counter, and a write view's scratch-created ids
607    /// come from the scratch's own counter (seeded from the graph's, then
608    /// advanced independently), so the bound is the larger of the two. A
609    /// dense per-node table sized to it never misses a node.
610    pub(crate) fn node_id_bound(&self) -> NodeId {
611        let committed = self.base.next_node_id();
612        match self.scratch {
613            None => committed,
614            Some(cell) => {
615                let scratch = cell
616                    .borrow()
617                    .node_id_alloc
618                    .load(std::sync::atomic::Ordering::Relaxed);
619                committed.max(
620                    NodeId::try_from(scratch).expect("the scratch id counter stops at i64::MAX"),
621                )
622            }
623        }
624    }
625
626    /// Every live node id, ascending: the snapshot's ids minus the scratch's
627    /// deletions plus its creations (ADR-0173). A copy-on-write entry was
628    /// read from the snapshot, so it is a snapshot id already, and a delete
629    /// drops the id from `created_nodes`. The two sets meet only if an
630    /// allocator handed out a committed id; `dedup` keeps that to one entry.
631    pub fn all_node_ids(&self) -> Vec<NodeId> {
632        let mut ids = self.base.all_node_ids_at(self.snapshot_ts());
633        if let Some(cell) = self.scratch {
634            let s = cell.borrow();
635            ids.retain(|id| !s.batch.deleted_nodes.contains(id));
636            ids.extend(s.batch.created_nodes.iter().copied());
637            ids.sort_unstable();
638            ids.dedup();
639        }
640        ids
641    }
642
643    /// Every live relationship id, ascending; built like
644    /// [`Self::all_node_ids`] from `deleted_rels` and `created_rels`.
645    pub fn all_rel_ids(&self) -> Vec<RelId> {
646        let mut ids = self.base.all_rel_ids_at(self.snapshot_ts());
647        if let Some(cell) = self.scratch {
648            let s = cell.borrow();
649            ids.retain(|id| !s.batch.deleted_rels.contains(id));
650            ids.extend(s.batch.created_rels.iter().copied());
651            ids.sort_unstable();
652            ids.dedup();
653        }
654        ids
655    }
656}
657
658mod adjacency;
659mod catalog;
660mod label_probe;
661mod materialize;
662mod prop_ix;
663mod reads;
664mod redo_log;
665mod rel_seek;
666mod scratch;
667mod seek;
668mod validation;
669mod virtual_nodes;
670mod writes;
671
672pub(crate) use materialize::MaterializeCache;
673pub(crate) use reads::ScanNode;
674pub(crate) use redo_log::ValidatedCatalog;
675pub(crate) use virtual_nodes::{lookup_virtual_node, register_virtual_node};
676
677pub use scratch::{ScratchCheckpoint, StatementMark, WriteScratch};
678
679#[cfg(test)]
680mod adjacency_tests;
681#[cfg(test)]
682mod allocator_exhaustion_tests;
683#[cfg(test)]
684pub(crate) mod batch_commit_tests;
685#[cfg(test)]
686mod budget_tests;
687#[cfg(test)]
688mod materialize_tests;
689#[cfg(test)]
690mod payload_sharing_tests;
691#[cfg(test)]
692mod query_semantics_tests;
693#[cfg(test)]
694mod read_projection_tests;
695#[cfg(test)]
696mod seek_merge_tests;
697#[cfg(test)]
698mod test_support;
699#[cfg(test)]
700mod validation_cursor_tests;
701#[cfg(test)]
702mod workspace_peak_tests;
703#[cfg(test)]
704mod write_stat_tests;