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