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