Skip to main content

relate_executor/overlay/
scratch.rs

1//! The per-attempt write buffer (ADR-0016) and its rollback image: the
2//! scratch the [`ExecGraph`](super::ExecGraph) write view overlays on the
3//! committed graph, the one funnel every write posts through
4//! (`push_redo`), and the `CALL { … } IN TRANSACTIONS` per-batch
5//! checkpoint/restore pair.
6
7use std::collections::{HashMap, HashSet};
8use std::mem::size_of;
9use std::sync::atomic::AtomicU64;
10use std::sync::Arc;
11
12use crate::graph::{LabelProbe, QueryStats};
13use crate::redo::RedoOp;
14use relate_core::tokens::WorkspaceCharge;
15use relate_core::{Node, NodeId, RelId, Relationship, Result};
16
17use super::distinct_labels;
18use super::prop_ix::ScratchPropIndex;
19use super::redo_log::RedoLog;
20
21/// The per-batch state (ADR-0210): everything a `CALL { … } IN
22/// TRANSACTIONS` batch's checkpoint captures and a failed batch's
23/// restore puts back — one struct, embedded in [`WriteScratch`], so a
24/// new field joins the rollback vocabulary by construction: the struct
25/// literal itself is the complete capture, where flat fields needed the
26/// same entry hand-synced across the `Clone`, `checkpoint`, and
27/// `restore` lists, and a forgotten entry there was a silent rollback
28/// gap the compiler could not see.
29#[derive(Clone)]
30pub(super) struct PerBatchState {
31    pub(super) snapshot_ts: u64,
32    pub(super) nodes: HashMap<NodeId, Node>,
33    /// Lazy equality index over `nodes`, posted to only by `push_redo`.
34    pub(super) prop_ix: ScratchPropIndex<Node>,
35    pub(super) rels: HashMap<RelId, Relationship>,
36    /// Lazy relationship equality index over `rels`, posted to only by
37    /// `push_redo` (ADR-0185).
38    pub(super) rel_prop_ix: ScratchPropIndex<Relationship>,
39    pub(super) deleted_nodes: HashSet<NodeId>,
40    pub(super) deleted_rels: HashSet<RelId>,
41    pub(super) created_nodes: HashSet<NodeId>,
42    pub(super) created_rels: HashSet<RelId>,
43    pub(super) out_adj: HashMap<NodeId, Vec<RelId>>,
44    pub(super) in_adj: HashMap<NodeId, Vec<RelId>>,
45    /// Per-label probe of what `snapshot_ts` carries, filled lazily by
46    /// `+labels`/`-labels` accounting and shared by clones (ADR-0171).
47    pub(super) label_probe: LabelProbe,
48    /// Net live occupancy vs the snapshot (this statement's creates /
49    /// deletes / SET/REMOVE). `live = snapshot + delta`.
50    pub(super) live_label_delta: HashMap<String, i32>,
51}
52
53/// The statement-spanning scratch state (ADR-0309 counters, ADR-0402 applied
54/// fact): the two facts that outlive one `CALL { … } IN TRANSACTIONS` batch
55/// (ADR-0210). One struct, and one unit on both edges of a batch's life:
56///
57/// - **carried** by [`WriteScratch::rebase`] — a batch commit moves it whole
58///   to the next batch's scratch, so a new statement-spanning field joins the
59///   survivor set by construction, and a rebase cannot carry one field and
60///   drop the next;
61/// - **captured** by [`WriteScratch::checkpoint`] and put back whole by
62///   [`WriteScratch::restore`], so a rolled-back batch's counters and its
63///   applied-change count describe only changes that survived.
64///
65/// The per-batch [`PerBatchState`] is the other half of the rollback image and
66/// is never carried; the redo log is the third (its positional cursor).
67#[derive(Clone, Default)]
68pub(super) struct StatementState {
69    /// The ADR-0309 mutation counters accumulated over the statement's
70    /// batches; handed out as the statement's `QueryStats`.
71    pub(super) stats: QueryStats,
72    /// How many changes the current statement has applied (ADR-0402
73    /// Decision 2's applied fact): zero at statement entry
74    /// ([`WriteScratch::reset_statement`]) and one per change through the
75    /// redo funnel, so the statement's own count *is* the fact — no growth
76    /// baseline has to be threaded beside it. An ADR-0210 batch drain
77    /// (`take_redo`) does not touch it, and it is part of the rollback
78    /// image, so a restored batch leaves it exactly as it was at the
79    /// capture — a batch that rolled back applied nothing.
80    pub(super) applied_ops: u64,
81}
82
83/// Per-attempt write buffer. The shared `Graph` is not mutated until `apply_redo`.
84///
85/// `workspace` is not cloned. A clone keeps the created entities and takes
86/// its own reservation once, at clone time, so dropping the original
87/// releases the original reservation once.
88pub struct WriteScratch {
89    /// The per-batch state — checkpointed, restored, and rebased as one.
90    pub(super) batch: PerBatchState,
91    /// The statement-spanning state — checkpointed and restored with the
92    /// per-batch state as one rollback image, and the only half a batch rebase
93    /// carries forward.
94    pub(super) statement: StatementState,
95    /// The change log, with its catalog positions and validation cursor.
96    pub(super) redo: RedoLog,
97    pub(super) node_id_alloc: Arc<AtomicU64>,
98    pub(super) rel_id_alloc: Arc<AtomicU64>,
99    /// Owned workspace of entities this statement created. Released on drop.
100    pub(super) workspace: relate_core::tokens::WorkspaceCharge,
101}
102
103impl Clone for WriteScratch {
104    fn clone(&self) -> Self {
105        let mut cloned = Self {
106            batch: self.batch.clone(),
107            statement: self.statement.clone(),
108            redo: self.redo.clone(),
109            node_id_alloc: Arc::clone(&self.node_id_alloc),
110            rel_id_alloc: Arc::clone(&self.rel_id_alloc),
111            workspace: relate_core::tokens::WorkspaceCharge::empty(),
112        };
113        // One walk, and only while a ledger is installed. Later writes add
114        // a delta on top of this total.
115        cloned.sync_workspace_best_effort();
116        cloned
117    }
118}
119
120impl WriteScratch {
121    pub fn new(
122        snapshot_ts: u64,
123        node_id_alloc: Arc<AtomicU64>,
124        rel_id_alloc: Arc<AtomicU64>,
125    ) -> Self {
126        Self::with_statement(
127            snapshot_ts,
128            StatementState::default(),
129            node_id_alloc,
130            rel_id_alloc,
131        )
132    }
133
134    /// Build a scratch at `snapshot_ts` carrying `statement` — the one
135    /// constructor [`Self::new`] and [`Self::rebase`] share, so the rebase
136    /// survivor set is exactly the [`StatementState`] handed over here.
137    fn with_statement(
138        snapshot_ts: u64,
139        statement: StatementState,
140        node_id_alloc: Arc<AtomicU64>,
141        rel_id_alloc: Arc<AtomicU64>,
142    ) -> Self {
143        Self {
144            batch: PerBatchState {
145                snapshot_ts,
146                nodes: HashMap::new(),
147                prop_ix: ScratchPropIndex::default(),
148                rels: HashMap::new(),
149                rel_prop_ix: ScratchPropIndex::default(),
150                deleted_nodes: HashSet::new(),
151                deleted_rels: HashSet::new(),
152                created_nodes: HashSet::new(),
153                created_rels: HashSet::new(),
154                out_adj: HashMap::new(),
155                in_adj: HashMap::new(),
156                label_probe: LabelProbe::new(snapshot_ts),
157                live_label_delta: HashMap::new(),
158            },
159            statement,
160            redo: RedoLog::default(),
161            node_id_alloc,
162            rel_id_alloc,
163            workspace: relate_core::tokens::WorkspaceCharge::empty(),
164        }
165    }
166
167    /// Move the workspace reservation onto the created entities currently
168    /// in this scratch. A refusal leaves the previous reservation and sets
169    /// the ledger's sticky error.
170    fn sync_workspace(&mut self) -> Result<()> {
171        let nodes = &self.batch.nodes;
172        let rels = &self.batch.rels;
173        let created_nodes = &self.batch.created_nodes;
174        let created_rels = &self.batch.created_rels;
175        let out_adj = &self.batch.out_adj;
176        let in_adj = &self.batch.in_adj;
177        let redo_bytes = self.redo.reserved_bytes();
178        self.workspace.resize_with(|| {
179            crate::workspace::scratch_created_bytes(
180                nodes,
181                rels,
182                created_nodes,
183                created_rels,
184                out_adj,
185                in_adj,
186                redo_bytes,
187            )
188        })?;
189        relate_core::tokens::peak_hold("create");
190        Ok(())
191    }
192
193    /// The post-mutation workspace sync, best-effort (ADR-0042's token
194    /// ledger): the charge resize for state already installed — a
195    /// clone's created set, a restored checkpoint's entity set. A live
196    /// ledger's admission refusal is deliberately not propagated: the
197    /// state it would charge for is already applied, so failing the call
198    /// would strand half-installed state; the refusal instead sets the
199    /// ledger's sticky error, and the next `tokens::poll()` (the
200    /// engine's per-clause checkpoint) surfaces it as the typed capacity
201    /// error. The one named home of that deferral. The pre-insert
202    /// reservations (`reserve_new_node` / `reserve_new_rel`) are the
203    /// propagating contrast: nothing is applied yet there, so they fail
204    /// closed.
205    fn sync_workspace_best_effort(&mut self) {
206        let _ = self.sync_workspace();
207    }
208
209    /// Add `after - before` to the running workspace total. Best-effort,
210    /// like every post-mutation charge (see
211    /// [`Self::sync_workspace_best_effort`]): the op is already in the
212    /// redo log, so a refusal defers to the ledger's sticky error; the
213    /// high-water mark records only the accepted resize. The
214    /// admission-off gate is the charge API's own
215    /// [`resize_with`](relate_core::tokens::WorkspaceCharge::resize_with)
216    /// — the one home of that early exit, like every charge here.
217    pub(super) fn shift_workspace(&mut self, before: u64, after: u64) {
218        if before == after {
219            return;
220        }
221        let base = self.workspace.bytes();
222        let next = if after > before {
223            base.saturating_add(after - before)
224        } else {
225            base.saturating_sub(before - after)
226        };
227        if self.workspace.resize_with(|| next).is_ok() {
228            relate_core::tokens::peak_hold("create");
229        }
230    }
231
232    /// Reserve the workspace `node` will take before it is inserted. The
233    /// admission-off gate is the charge API's own `resize_with`, the one
234    /// home of that early exit.
235    pub(super) fn reserve_new_node(&mut self, node: &Node) -> Result<()> {
236        let before = self.workspace.bytes();
237        let delta =
238            crate::workspace::created_node_insert_delta(self.batch.created_nodes.len(), node);
239        self.workspace
240            .resize_with(|| before.saturating_add(delta))?;
241        relate_core::tokens::peak_hold("create");
242        Ok(())
243    }
244
245    /// Reserve the workspace `rel` will take, including its adjacency slot,
246    /// before it is inserted. The admission-off gate is the charge API's
247    /// own `resize_with`, the one home of that early exit.
248    pub(super) fn reserve_new_rel(&mut self, rel: &Relationship) -> Result<()> {
249        let before = self.workspace.bytes();
250        let delta = crate::workspace::created_rel_insert_delta(
251            self.batch.created_rels.len(),
252            rel,
253            self.batch.out_adj.get(&rel.start).map(Vec::len),
254            self.batch.in_adj.get(&rel.end).map(Vec::len),
255        );
256        self.workspace
257            .resize_with(|| before.saturating_add(delta))?;
258        relate_core::tokens::peak_hold("create");
259        Ok(())
260    }
261
262    /// True when this overlay created, updated, or deleted a node, so a
263    /// committed range-index cardinality no longer describes the view.
264    pub(crate) fn changes_node_membership(&self) -> bool {
265        !self.batch.nodes.is_empty() || !self.batch.deleted_nodes.is_empty()
266    }
267
268    pub(super) fn live_label_delta(&self, label: &str) -> i64 {
269        i64::from(self.batch.live_label_delta.get(label).copied().unwrap_or(0))
270    }
271
272    fn bump_live_label(&mut self, label: &str, delta: i32) {
273        *self
274            .batch
275            .live_label_delta
276            .entry(label.to_string())
277            .or_insert(0) += delta;
278    }
279
280    pub(super) fn bump_live_labels(&mut self, labels: &[String], delta: i32) {
281        for l in distinct_labels(labels) {
282            self.bump_live_label(l, delta);
283        }
284    }
285
286    /// Net one `label_deltas` outcome into the statement's `+labels` /
287    /// `-labels` counters (ADR-0171): each possibly-negative delta is added
288    /// saturating and the counter clamps at zero, so a statement never
289    /// reports a net-negative count for its own changes. The one home of
290    /// the signed label-stat netting every write verb shares.
291    pub(super) fn net_label_stats(&mut self, labels_added: i64, labels_removed: i64) {
292        self.statement.stats.labels_added = self
293            .statement
294            .stats
295            .labels_added
296            .saturating_add(labels_added)
297            .max(0);
298        self.statement.stats.labels_removed = self
299            .statement
300            .stats
301            .labels_removed
302            .saturating_add(labels_removed)
303            .max(0);
304    }
305
306    pub fn snapshot_ts(&self) -> u64 {
307        self.batch.snapshot_ts
308    }
309
310    /// Per-batch rebase (ADR-0210): reset the per-batch state (redo log,
311    /// entity maps, prop indexes, adjacency, deleted/created sets, label
312    /// probe, live-label delta) at the new snapshot timestamp, keeping the
313    /// statement-spanning [`StatementState`] — the accumulated `stats` and the
314    /// applied-change count — which moves over as one unit. The survivor set
315    /// is decided here, next to the fields, not at the `commit_batch` call
316    /// site.
317    pub(crate) fn rebase(&mut self, new_ts: u64) {
318        let statement = std::mem::take(&mut self.statement);
319        let node_id_alloc = Arc::clone(&self.node_id_alloc);
320        let rel_id_alloc = Arc::clone(&self.rel_id_alloc);
321        *self = Self::with_statement(new_ts, statement, node_id_alloc, rel_id_alloc);
322    }
323
324    pub fn take_redo(&mut self) -> Vec<RedoOp> {
325        self.redo.take()
326    }
327
328    /// Drain the redo and hand its live workspace reservation to the caller.
329    ///
330    /// The scratch's execution allocation is still represented by the redo
331    /// vector while WAL commit serializes and applies it. The caller holds
332    /// this charge through that boundary, then drops it once the commit has
333    /// either been rejected or acknowledged.
334    pub fn take_redo_with_workspace(&mut self) -> Result<(Vec<RedoOp>, WorkspaceCharge)> {
335        // `RedoLog::take` converts its compact live entries into a larger
336        // final `Vec<RedoOp>`. Reserve that vector before allocating it; the
337        // compact source buffer remains live during `collect`, so both
338        // allocations are covered at the conversion peak.
339        let final_redo_bytes = (self.redo.len() as u64).saturating_mul(size_of::<RedoOp>() as u64);
340        self.workspace
341            .resize(self.workspace.bytes().saturating_add(final_redo_bytes))?;
342        let workspace = std::mem::replace(&mut self.workspace, WorkspaceCharge::empty());
343        Ok((self.redo.take(), workspace))
344    }
345
346    /// Borrow the accumulated redo without draining it (see
347    /// [`RedoLog::ops`]); ADR-0210 batch commits hand the sink a clone
348    /// and drain only after the commit succeeds.
349    pub(crate) fn redo_ops(&self) -> Vec<RedoOp> {
350        self.redo.materialize()
351    }
352
353    /// The redo ops at or after `from`: what the statements run since that
354    /// position appended. `None` when `from` is past the end — the log
355    /// shrank under the caller's cursor, which the caller refuses rather
356    /// than reading as nothing. Reads without draining, so a caller
357    /// bounding the transaction's prospective commit measures the same ops
358    /// that commit will.
359    pub fn redo_since(&self, from: usize) -> Option<Vec<RedoOp>> {
360        self.redo.ops_since(from)
361    }
362
363    /// The one funnel every write goes through: post the op to the lazy
364    /// equality indexes, account the ADR-0309 update counters, then append
365    /// it to the redo log.
366    pub fn push_redo(&mut self, op: RedoOp) {
367        self.post_to_indexes(&op);
368        self.account_update_counters(&op);
369        let before = self.redo.reserved_bytes();
370        self.redo.push(op);
371        let after = self.redo.reserved_bytes();
372        self.shift_workspace(before, after);
373        // The one funnel every write posts through also counts the applied
374        // changes the ADR-0402 effect reads — entity, schema and catalog
375        // writes alike, so a catalog-only statement is not "no effect".
376        self.statement.applied_ops += 1;
377    }
378
379    /// How many changes the current statement has applied (ADR-0402
380    /// Decision 2): zero from the statement entry reset and one per change
381    /// through the redo funnel, across ADR-0210 batch drains too.
382    pub(crate) fn applied_ops(&self) -> u64 {
383        self.statement.applied_ops
384    }
385
386    /// The statement-entry reset of the statement-spanning state: the
387    /// ADR-0309 mutation counters and the ADR-0402 applied-change count
388    /// restart together, as one unit, because both describe one statement
389    /// and both survive a batch rebase together. A caller reusing a scratch
390    /// across statements (an explicit transaction, the executor's own tests)
391    /// therefore reads this statement's facts only.
392    pub(crate) fn reset_statement(&mut self) {
393        self.statement = StatementState::default();
394    }
395
396    /// The ADR-0309 update counters, derived from the redo op at the one
397    /// funnel every write goes through: `node_labels_added`/
398    /// `node_labels_removed` count labels per node and `properties_written`
399    /// counts one per property write. Deriving them from the op keeps the
400    /// two counter vocabularies in one accounting site, so a write verb
401    /// cannot bump one and forget the other.
402    fn account_update_counters(&mut self, op: &RedoOp) {
403        match op {
404            RedoOp::CreateNode {
405                labels, properties, ..
406            } => {
407                self.statement.stats.node_labels_added += distinct_labels(labels).len() as i64;
408                self.statement.stats.properties_written += properties.len() as i64;
409            }
410            RedoOp::CreateRel { properties, .. } => {
411                self.statement.stats.properties_written += properties.len() as i64;
412            }
413            RedoOp::AddLabels { labels, .. } => {
414                self.statement.stats.node_labels_added += distinct_labels(labels).len() as i64;
415            }
416            RedoOp::RemoveLabels { labels, .. } => {
417                self.statement.stats.node_labels_removed += distinct_labels(labels).len() as i64;
418            }
419            // One write per pushed property op: `set_prop_core` pushes a
420            // Set op for a non-null value and a Remove op for a null over
421            // an existing key; either is one property write (ADR-0309).
422            RedoOp::SetNodeProp { .. }
423            | RedoOp::RemoveNodeProp { .. }
424            | RedoOp::SetRelProp { .. }
425            | RedoOp::RemoveRelProp { .. } => {
426                self.statement.stats.properties_written += 1;
427            }
428            // Deletions count no property write or label change (ADR-0309);
429            // the catalog ops carry their own counters
430            // (`overlay/catalog.rs`) and the store-level ops touch no
431            // entity.
432            RedoOp::DeleteNode { .. }
433            | RedoOp::DeleteRel { .. }
434            | RedoOp::CreateIndex { .. }
435            | RedoOp::DropIndex { .. }
436            | RedoOp::CreateConstraint { .. }
437            | RedoOp::DropConstraint { .. }
438            | RedoOp::CatalogIndexDetail { .. }
439            | RedoOp::CatalogDerivedConstraint { .. }
440            | RedoOp::PutDatabase { .. }
441            | RedoOp::DropDatabase { .. }
442            | RedoOp::PutGraphType { .. }
443            | RedoOp::SetCurrentGraphType { .. }
444            | RedoOp::PullIdentityPut { .. }
445            | RedoOp::OntologySet { .. }
446            | RedoOp::OntologyDrop { .. } => {}
447        }
448    }
449
450    /// The scratch copy of node `id`. Every `push_redo` producer installs
451    /// into `nodes` before pushing, so a miss is internal-state corruption.
452    fn scratch_node(nodes: &HashMap<NodeId, Node>, id: NodeId) -> &Node {
453        nodes
454            .get(&id)
455            .expect("producer installs into the scratch before push_redo")
456    }
457
458    /// The scratch copy of relationship `id`; same invariant as
459    /// [`Self::scratch_node`].
460    fn scratch_rel(rels: &HashMap<RelId, Relationship>, id: RelId) -> &Relationship {
461        rels.get(&id)
462            .expect("producer installs into the scratch before push_redo")
463    }
464
465    /// Keep `prop_ix` and `rel_prop_ix` current from the redo funnel
466    /// (ADR-0173, ADR-0185): post the `(label, value)` and
467    /// `(rel type, value)` pairings each op introduces. Every arm sources
468    /// from the scratch maps through [`Self::scratch_node`] /
469    /// [`Self::scratch_rel`]. Exhaustive, so a new op must decide here.
470    /// Removals post nothing: both indexes are additions-only and every
471    /// seek re-verifies its ids. A null value posts nothing too — that
472    /// policy is the index API's own ([`ScratchPropIndex::post_value`]'s
473    /// shared core), not re-spelled per arm here.
474    fn post_to_indexes(&mut self, op: &RedoOp) {
475        match op {
476            RedoOp::CreateNode { id, .. } => {
477                let n = Self::scratch_node(&self.batch.nodes, *id);
478                for (key, value) in &*n.properties {
479                    self.batch.prop_ix.post_value(*id, &n.labels, key, value);
480                }
481            }
482            RedoOp::CreateRel { id, .. } => {
483                let r = Self::scratch_rel(&self.batch.rels, *id);
484                for (key, value) in &*r.properties {
485                    self.batch
486                        .rel_prop_ix
487                        .post_value(*id, &r.rel_type, key, value);
488                }
489            }
490            RedoOp::SetNodeProp { id, key, value } => {
491                let n = Self::scratch_node(&self.batch.nodes, *id);
492                self.batch.prop_ix.post_value(*id, &n.labels, key, value);
493            }
494            RedoOp::AddLabels { id, labels } => {
495                let n = Self::scratch_node(&self.batch.nodes, *id);
496                self.batch.prop_ix.post_labels(*id, labels, &n.properties);
497            }
498            RedoOp::SetRelProp { id, key, value } => {
499                let r = Self::scratch_rel(&self.batch.rels, *id);
500                self.batch
501                    .rel_prop_ix
502                    .post_value(*id, &r.rel_type, key, value);
503            }
504            RedoOp::DeleteNode { .. }
505            | RedoOp::DeleteRel { .. }
506            | RedoOp::RemoveNodeProp { .. }
507            | RedoOp::RemoveRelProp { .. }
508            | RedoOp::RemoveLabels { .. }
509            | RedoOp::CreateIndex { .. }
510            | RedoOp::DropIndex { .. }
511            | RedoOp::CreateConstraint { .. }
512            | RedoOp::DropConstraint { .. }
513            | RedoOp::CatalogIndexDetail { .. }
514            | RedoOp::CatalogDerivedConstraint { .. }
515            | RedoOp::PutDatabase { .. }
516            | RedoOp::DropDatabase { .. }
517            | RedoOp::PutGraphType { .. }
518            | RedoOp::SetCurrentGraphType { .. }
519            | RedoOp::PullIdentityPut { .. }
520            | RedoOp::OntologySet { .. }
521            | RedoOp::OntologyDrop { .. } => {}
522        }
523    }
524
525    pub(super) fn alloc_node(&self) -> Result<NodeId> {
526        crate::graph::alloc_exhaustible_id(self.node_id_alloc.as_ref(), "node")
527    }
528
529    pub(super) fn alloc_rel(&self) -> Result<RelId> {
530        crate::graph::alloc_exhaustible_id(self.rel_id_alloc.as_ref(), "relationship")
531    }
532
533    /// Pre-batch state for `CALL { … } IN TRANSACTIONS`. The rollback image is
534    /// the whole scratch state as of here, in three parts: the per-batch maps
535    /// (the one embedded [`PerBatchState`] capture), the statement-spanning
536    /// [`StatementState`] (its ADR-0309 counters **and** its applied-change
537    /// count, so a rolled-back batch restores both), and the redo log
538    /// positionally — a cursor, not a second op vec — so per-batch capture is
539    /// O(1) in the accumulated ops (a by-value copy would be quadratic on the
540    /// no-sink path, where each batch re-captures over an ever-growing log).
541    /// Id allocators stay on the live scratch so a rolled-back batch does not
542    /// hand the same id out again; they are not part of the image.
543    pub(crate) fn checkpoint(&self) -> ScratchCheckpoint {
544        ScratchCheckpoint {
545            batch: self.batch.clone(),
546            statement: self.statement.clone(),
547            redo: self.redo.cursor(),
548        }
549    }
550
551    /// Roll back to a captured [`Self::checkpoint`]: the per-batch state and
552    /// the statement-spanning state restores as one, and the redo log truncates
553    /// to its captured position (the live log's ops stay with the live log).
554    /// Because the applied-change count rides the restored [`StatementState`],
555    /// a batch that rolled back applied nothing — a statement whose every batch
556    /// failed is still a zero-effect write (ADR-0402 Decision 2) — and the
557    /// restore never has to derive that from how many ops the truncation
558    /// dropped.
559    pub(crate) fn restore(&mut self, checkpoint: ScratchCheckpoint) {
560        self.batch = checkpoint.batch;
561        self.statement = checkpoint.statement;
562        self.redo.restore_cursor(checkpoint.redo);
563        self.sync_workspace_best_effort();
564    }
565}
566
567/// Rollback image of a [`WriteScratch`]: its two state halves — the per-batch
568/// state (via the one embedded capture) and the statement-spanning state
569/// ([`StatementState`]: counters and applied count as of the capture) — plus
570/// the redo log's positional cursor. Cloning the maps is shallow once node and
571/// relationship payloads are `Arc`s; the redo ops stay with the live log, and
572/// the id allocators are not captured (they never roll back).
573pub(crate) struct ScratchCheckpoint {
574    batch: PerBatchState,
575    statement: StatementState,
576    redo: super::redo_log::RedoCursor,
577}