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::{EntityId, 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
53impl PerBatchState {
54    /// Undo one created node (ADR-0642's per-statement rollback): the inverse
55    /// of the batch entries the create path makes, stated on the state that
56    /// owns them — so the rollback vocabulary lives once, and a field added
57    /// here is a compile error at its inverse rather than a silent gap.
58    pub(super) fn uncreate_node(&mut self, id: NodeId) {
59        let node = self
60            .nodes
61            .remove(&id)
62            .expect("a batched CREATE's node is live in the batch");
63        self.bump_live_labels(&node.labels, -1);
64        self.created_nodes.remove(&id);
65    }
66
67    /// The relationship half of [`Self::uncreate_node`]. Both endpoints'
68    /// adjacency lists are cleared separately, in one bulk pass over the
69    /// statement's dropped ids ([`Self::drop_adjacency`]) — not a scan per
70    /// id, so a statement that created many relationships on one endpoint
71    /// rolls back in O(adjacency) instead of O(creates × list).
72    pub(super) fn uncreate_rel(&mut self, id: RelId) {
73        self.rels
74            .remove(&id)
75            .expect("a batched CREATE's relationship is live in the batch");
76        self.created_rels.remove(&id);
77    }
78
79    /// Take the statement's dropped relationship ids back off both endpoint
80    /// adjacency lists — one retain pass per map, the bulk inverse of the
81    /// push each create made. Called once per rolled-back statement, before
82    /// the per-entity undo.
83    pub(super) fn drop_adjacency(&mut self, dropped: &HashSet<RelId>) {
84        for adj in [&mut self.out_adj, &mut self.in_adj] {
85            adj.retain(|_, list| {
86                list.retain(|id| !dropped.contains(id));
87                !list.is_empty()
88            });
89        }
90    }
91
92    /// Net `delta` onto each distinct label's live-carrier count. The one
93    /// home of the accounting: every write verb and the rollback consult it.
94    pub(super) fn bump_live_labels(&mut self, labels: &[String], delta: i32) {
95        for label in distinct_labels(labels) {
96            *self.live_label_delta.entry(label.to_string()).or_insert(0) += delta;
97        }
98    }
99}
100
101/// The statement-spanning scratch state (ADR-0309 counters, ADR-0402 applied
102/// fact, REL8-1188 statement-local created sets): the four facts that outlive
103/// one `CALL { … } IN TRANSACTIONS` batch (ADR-0210). One struct, and one
104/// unit on both edges of a batch's life:
105///
106/// - **carried** by [`WriteScratch::rebase`] — a batch commit moves it whole
107///   to the next batch's scratch, so a new statement-spanning field joins the
108///   survivor set by construction, and a rebase cannot carry one field and
109///   drop the next;
110/// - **captured** by [`WriteScratch::checkpoint`] and put back whole by
111///   [`WriteScratch::restore`], so a rolled-back batch's counters and its
112///   applied-change count describe only changes that survived.
113///
114/// The per-batch [`PerBatchState`] is the other half of the rollback image and
115/// is never carried; the redo log is the third (its positional cursor).
116#[derive(Clone, Default)]
117pub(super) struct StatementState {
118    /// The ADR-0309 mutation counters accumulated over the statement's
119    /// batches; handed out as the statement's `QueryStats`.
120    pub(super) stats: QueryStats,
121    /// How many changes the current statement has applied (ADR-0402
122    /// Decision 2's applied fact): zero at statement entry
123    /// ([`WriteScratch::reset_statement`]) and one per change through the
124    /// redo funnel, so the statement's own count *is* the fact — no growth
125    /// baseline has to be threaded beside it. An ADR-0210 batch drain
126    /// (`take_redo`) does not touch it, and it is part of the rollback
127    /// image, so a restored batch leaves it exactly as it was at the
128    /// capture — a batch that rolled back applied nothing.
129    pub(super) applied_ops: u64,
130    /// The node ids *this statement* created through the redo funnel: the
131    /// statement-local twin of [`PerBatchState::created_nodes`], which
132    /// additionally spans the earlier statements of the transaction. Delete
133    /// accounting nets a create only against the statement that counted it —
134    /// a delete of a node an earlier statement of the transaction created
135    /// counts as this statement's delete, never as a negative create
136    /// (REL8-1188). The node and rel twins are filled at the one funnel and
137    /// cleared at a statement entry and a batch rebase, so each holds exactly
138    /// its statement's creates inside the current batch — never more ids than
139    /// the workspace-charged batch twin, whose size the charge measures.
140    pub(super) created_nodes: HashSet<NodeId>,
141    /// The relationship ids *this statement* created: the rel half of
142    /// [`Self::created_nodes`]'s rule.
143    pub(super) created_rels: HashSet<RelId>,
144}
145
146/// Per-attempt write buffer. The shared `Graph` is not mutated until `apply_redo`.
147///
148/// `workspace` is not cloned. A clone keeps the created entities and takes
149/// its own reservation once, at clone time, so dropping the original
150/// releases the original reservation once.
151pub struct WriteScratch {
152    /// The per-batch state — checkpointed, restored, and rebased as one.
153    pub(super) batch: PerBatchState,
154    /// The statement-spanning state — checkpointed and restored with the
155    /// per-batch state as one rollback image, and the only half a batch rebase
156    /// carries forward.
157    pub(super) statement: StatementState,
158    /// The change log, with its catalog positions and validation cursor.
159    pub(super) redo: RedoLog,
160    pub(super) node_id_alloc: Arc<AtomicU64>,
161    pub(super) rel_id_alloc: Arc<AtomicU64>,
162    /// Owned workspace of entities this statement created. Released on drop.
163    pub(super) workspace: relate_core::tokens::WorkspaceCharge,
164}
165
166impl Clone for WriteScratch {
167    fn clone(&self) -> Self {
168        let mut cloned = Self {
169            batch: self.batch.clone(),
170            statement: self.statement.clone(),
171            redo: self.redo.clone(),
172            node_id_alloc: Arc::clone(&self.node_id_alloc),
173            rel_id_alloc: Arc::clone(&self.rel_id_alloc),
174            workspace: relate_core::tokens::WorkspaceCharge::empty(),
175        };
176        // One walk, and only while a ledger is installed. Later writes add
177        // a delta on top of this total.
178        cloned.sync_workspace_best_effort();
179        cloned
180    }
181}
182
183impl WriteScratch {
184    pub fn new(
185        snapshot_ts: u64,
186        node_id_alloc: Arc<AtomicU64>,
187        rel_id_alloc: Arc<AtomicU64>,
188    ) -> Self {
189        Self::with_statement(
190            snapshot_ts,
191            StatementState::default(),
192            node_id_alloc,
193            rel_id_alloc,
194        )
195    }
196
197    /// Build a scratch at `snapshot_ts` carrying `statement` — the one
198    /// constructor [`Self::new`] and [`Self::rebase`] share, so the rebase
199    /// survivor set is exactly the [`StatementState`] handed over here.
200    fn with_statement(
201        snapshot_ts: u64,
202        statement: StatementState,
203        node_id_alloc: Arc<AtomicU64>,
204        rel_id_alloc: Arc<AtomicU64>,
205    ) -> Self {
206        Self {
207            batch: PerBatchState {
208                snapshot_ts,
209                nodes: HashMap::new(),
210                prop_ix: ScratchPropIndex::default(),
211                rels: HashMap::new(),
212                rel_prop_ix: ScratchPropIndex::default(),
213                deleted_nodes: HashSet::new(),
214                deleted_rels: HashSet::new(),
215                created_nodes: HashSet::new(),
216                created_rels: HashSet::new(),
217                out_adj: HashMap::new(),
218                in_adj: HashMap::new(),
219                label_probe: LabelProbe::new(snapshot_ts),
220                live_label_delta: HashMap::new(),
221            },
222            statement,
223            redo: RedoLog::default(),
224            node_id_alloc,
225            rel_id_alloc,
226            workspace: relate_core::tokens::WorkspaceCharge::empty(),
227        }
228    }
229
230    /// Move the workspace reservation onto the created entities currently
231    /// in this scratch. A refusal leaves the previous reservation and sets
232    /// the ledger's sticky error.
233    fn sync_workspace(&mut self) -> Result<()> {
234        let nodes = &self.batch.nodes;
235        let rels = &self.batch.rels;
236        let created_nodes = &self.batch.created_nodes;
237        let created_rels = &self.batch.created_rels;
238        let out_adj = &self.batch.out_adj;
239        let in_adj = &self.batch.in_adj;
240        let redo_bytes = self.redo.reserved_bytes();
241        self.workspace.resize_with(|| {
242            crate::workspace::scratch_created_bytes(
243                nodes,
244                rels,
245                created_nodes,
246                created_rels,
247                out_adj,
248                in_adj,
249                redo_bytes,
250            )
251        })?;
252        relate_core::tokens::peak_hold("create");
253        Ok(())
254    }
255
256    /// The post-mutation workspace sync, best-effort (ADR-0042's token
257    /// ledger): the charge resize for state already installed — a
258    /// clone's created set, a restored checkpoint's entity set. A live
259    /// ledger's admission refusal is deliberately not propagated: the
260    /// state it would charge for is already applied, so failing the call
261    /// would strand half-installed state; the refusal instead sets the
262    /// ledger's sticky error, and the next `tokens::poll()` (the
263    /// engine's per-clause checkpoint) surfaces it as the typed capacity
264    /// error. The one named home of that deferral. The pre-insert
265    /// reservations (`reserve_new_node` / `reserve_new_rel`) are the
266    /// propagating contrast: nothing is applied yet there, so they fail
267    /// closed.
268    fn sync_workspace_best_effort(&mut self) {
269        let _ = self.sync_workspace();
270    }
271
272    /// Add `after - before` to the running workspace total. Best-effort,
273    /// like every post-mutation charge (see
274    /// [`Self::sync_workspace_best_effort`]): the op is already in the
275    /// redo log, so a refusal defers to the ledger's sticky error; the
276    /// high-water mark records only the accepted resize. The
277    /// admission-off gate is the charge API's own
278    /// [`resize_with`](relate_core::tokens::WorkspaceCharge::resize_with)
279    /// — the one home of that early exit, like every charge here.
280    pub(super) fn shift_workspace(&mut self, before: u64, after: u64) {
281        if before == after {
282            return;
283        }
284        let base = self.workspace.bytes();
285        let next = if after > before {
286            base.saturating_add(after - before)
287        } else {
288            base.saturating_sub(before - after)
289        };
290        if self.workspace.resize_with(|| next).is_ok() {
291            relate_core::tokens::peak_hold("create");
292        }
293    }
294
295    /// Reserve the workspace `node` will take before it is inserted. The
296    /// admission-off gate is the charge API's own `resize_with`, the one
297    /// home of that early exit.
298    pub(super) fn reserve_new_node(&mut self, node: &Node) -> Result<()> {
299        let before = self.workspace.bytes();
300        let delta =
301            crate::workspace::created_node_insert_delta(self.batch.created_nodes.len(), node);
302        self.workspace
303            .resize_with(|| before.saturating_add(delta))?;
304        relate_core::tokens::peak_hold("create");
305        Ok(())
306    }
307
308    /// Reserve the workspace `rel` will take, including its adjacency slot,
309    /// before it is inserted. The admission-off gate is the charge API's
310    /// own `resize_with`, the one home of that early exit.
311    pub(super) fn reserve_new_rel(&mut self, rel: &Relationship) -> Result<()> {
312        let before = self.workspace.bytes();
313        let delta = crate::workspace::created_rel_insert_delta(
314            self.batch.created_rels.len(),
315            rel,
316            self.batch.out_adj.get(&rel.start).map(Vec::len),
317            self.batch.in_adj.get(&rel.end).map(Vec::len),
318        );
319        self.workspace
320            .resize_with(|| before.saturating_add(delta))?;
321        relate_core::tokens::peak_hold("create");
322        Ok(())
323    }
324
325    /// True when this overlay created, updated, or deleted a node, so a
326    /// committed range-index cardinality no longer describes the view.
327    pub(crate) fn changes_node_membership(&self) -> bool {
328        !self.batch.nodes.is_empty() || !self.batch.deleted_nodes.is_empty()
329    }
330
331    pub(super) fn live_label_delta(&self, label: &str) -> i64 {
332        i64::from(self.batch.live_label_delta.get(label).copied().unwrap_or(0))
333    }
334
335    /// Net one `label_deltas` outcome into the statement's `+labels` /
336    /// `-labels` counters (ADR-0171): each possibly-negative delta is added
337    /// saturating and the counter clamps at zero, so a statement never
338    /// reports a net-negative count for its own changes. The one home of
339    /// the signed label-stat netting every write verb shares.
340    pub(super) fn net_label_stats(&mut self, labels_added: i64, labels_removed: i64) {
341        self.statement.stats.labels_added = self
342            .statement
343            .stats
344            .labels_added
345            .saturating_add(labels_added)
346            .max(0);
347        self.statement.stats.labels_removed = self
348            .statement
349            .stats
350            .labels_removed
351            .saturating_add(labels_removed)
352            .max(0);
353    }
354
355    pub fn snapshot_ts(&self) -> u64 {
356        self.batch.snapshot_ts
357    }
358
359    /// Per-batch rebase (ADR-0210): reset the per-batch state (redo log,
360    /// entity maps, prop indexes, adjacency, deleted/created sets, label
361    /// probe, live-label delta) at the new snapshot timestamp, keeping the
362    /// statement-spanning [`StatementState`] — the accumulated `stats` and the
363    /// applied-change count — which moves over as one unit. Its created-id
364    /// sets are the one exception, cleared here with the batch's own created
365    /// sets: an id nets a create only inside the batch that counted it
366    /// (REL8-1188), so a carried id would only grow the sets past the bytes
367    /// the workspace charge measures. The survivor set is decided here, next
368    /// to the fields, not at the `commit_batch` call site.
369    pub(crate) fn rebase(&mut self, new_ts: u64) {
370        let mut statement = std::mem::take(&mut self.statement);
371        statement.created_nodes.clear();
372        statement.created_rels.clear();
373        let node_id_alloc = Arc::clone(&self.node_id_alloc);
374        let rel_id_alloc = Arc::clone(&self.rel_id_alloc);
375        *self = Self::with_statement(new_ts, statement, node_id_alloc, rel_id_alloc);
376    }
377
378    pub fn take_redo(&mut self) -> Vec<RedoOp> {
379        self.redo.take()
380    }
381
382    /// Drain the redo and hand its live workspace reservation to the caller.
383    ///
384    /// The scratch's execution allocation is still represented by the redo
385    /// vector while WAL commit serializes and applies it. The caller holds
386    /// this charge through that boundary, then drops it once the commit has
387    /// either been rejected or acknowledged.
388    pub fn take_redo_with_workspace(&mut self) -> Result<(Vec<RedoOp>, WorkspaceCharge)> {
389        // `RedoLog::take` converts its compact live entries into a larger
390        // final `Vec<RedoOp>`. Reserve that vector before allocating it; the
391        // compact source buffer remains live during `collect`, so both
392        // allocations are covered at the conversion peak.
393        let final_redo_bytes = (self.redo.len() as u64).saturating_mul(size_of::<RedoOp>() as u64);
394        self.workspace
395            .resize(self.workspace.bytes().saturating_add(final_redo_bytes))?;
396        let workspace = std::mem::replace(&mut self.workspace, WorkspaceCharge::empty());
397        Ok((self.redo.take(), workspace))
398    }
399
400    /// Borrow the accumulated redo without draining it (see
401    /// [`RedoLog::ops`]); ADR-0210 batch commits hand the sink a clone
402    /// and drain only after the commit succeeds.
403    pub(crate) fn redo_ops(&self) -> Vec<RedoOp> {
404        self.redo.materialize()
405    }
406
407    /// The redo ops at or after `from`: what the statements run since that
408    /// position appended. `None` when `from` is past the end — the log
409    /// shrank under the caller's cursor, which the caller refuses rather
410    /// than reading as nothing. Reads without draining, so a caller
411    /// bounding the transaction's prospective commit measures the same ops
412    /// that commit will.
413    pub fn redo_since(&self, from: usize) -> Option<Vec<RedoOp>> {
414        self.redo.ops_since(from)
415    }
416
417    /// The one funnel every write goes through: post the op to the lazy
418    /// equality indexes, account the ADR-0309 update counters, then append
419    /// it to the redo log.
420    pub fn push_redo(&mut self, op: RedoOp) {
421        self.post_to_indexes(&op);
422        self.account_update_counters(&op);
423        let before = self.redo.reserved_bytes();
424        self.redo.push(op);
425        let after = self.redo.reserved_bytes();
426        self.shift_workspace(before, after);
427        // The one funnel every write posts through also counts the applied
428        // changes the ADR-0402 effect reads — entity, schema and catalog
429        // writes alike, so a catalog-only statement is not "no effect".
430        self.statement.applied_ops += 1;
431    }
432
433    /// How many changes the current statement has applied (ADR-0402
434    /// Decision 2): zero from the statement entry reset and one per change
435    /// through the redo funnel, across ADR-0210 batch drains too.
436    pub(crate) fn applied_ops(&self) -> u64 {
437        self.statement.applied_ops
438    }
439
440    /// The statement-entry reset of the statement-spanning state: the
441    /// ADR-0309 mutation counters and the ADR-0402 applied-change count
442    /// restart together, as one unit, because both describe one statement
443    /// and both survive a batch rebase together. A caller reusing a scratch
444    /// across statements (an explicit transaction, the executor's own tests)
445    /// therefore reads this statement's facts only.
446    pub(crate) fn reset_statement(&mut self) {
447        self.statement = StatementState::default();
448    }
449
450    /// The ADR-0309 update counters, derived from the redo op at the one
451    /// funnel every write goes through: `node_labels_added`/
452    /// `node_labels_removed` count labels per node and `properties_written`
453    /// counts one per property write. Deriving them from the op keeps the
454    /// two counter vocabularies in one accounting site, so a write verb
455    /// cannot bump one and forget the other. The same match records which
456    /// entities were created — the statement-local set ([`StatementState::
457    /// created_nodes`] / `created_rels`) and its transaction-spanning batch
458    /// twin ([`PerBatchState::created_nodes`] / `created_rels`) in the same
459    /// arm, so the two registration sites cannot drift — the fact the delete
460    /// verbs' net-or-count decision reads (REL8-1188).
461    fn account_update_counters(&mut self, op: &RedoOp) {
462        match op {
463            RedoOp::CreateNode {
464                id,
465                labels,
466                properties,
467                ..
468            } => {
469                self.statement.stats.node_labels_added += distinct_labels(labels).len() as i64;
470                self.statement.stats.properties_written += properties.len() as i64;
471                self.statement.created_nodes.insert(*id);
472                self.batch.created_nodes.insert(*id);
473            }
474            RedoOp::CreateRel { id, properties, .. } => {
475                self.statement.stats.properties_written += properties.len() as i64;
476                self.statement.created_rels.insert(*id);
477                self.batch.created_rels.insert(*id);
478            }
479            RedoOp::AddLabels { labels, .. } => {
480                self.statement.stats.node_labels_added += distinct_labels(labels).len() as i64;
481            }
482            RedoOp::RemoveLabels { labels, .. } => {
483                self.statement.stats.node_labels_removed += distinct_labels(labels).len() as i64;
484            }
485            // One write per pushed property op: `set_prop_core` pushes a
486            // Set op for a non-null value and a Remove op for a null over
487            // an existing key; either is one property write (ADR-0309).
488            RedoOp::SetNodeProp { .. }
489            | RedoOp::RemoveNodeProp { .. }
490            | RedoOp::SetRelProp { .. }
491            | RedoOp::RemoveRelProp { .. } => {
492                self.statement.stats.properties_written += 1;
493            }
494            // Deletions count no property write or label change (ADR-0309);
495            // the catalog ops carry their own counters
496            // (`overlay/catalog.rs`) and the store-level ops touch no
497            // entity.
498            RedoOp::DeleteNode { .. }
499            | RedoOp::DeleteRel { .. }
500            | RedoOp::CreateIndex { .. }
501            | RedoOp::DropIndex { .. }
502            | RedoOp::CreateConstraint { .. }
503            | RedoOp::DropConstraint { .. }
504            | RedoOp::CatalogIndexDetail { .. }
505            | RedoOp::CatalogDerivedConstraint { .. }
506            | RedoOp::PutDatabase { .. }
507            | RedoOp::DropDatabase { .. }
508            | RedoOp::PutGraphType { .. }
509            | RedoOp::SetCurrentGraphType { .. }
510            | RedoOp::PullIdentityPut { .. }
511            | RedoOp::OntologySet { .. }
512            | RedoOp::OntologyDrop { .. } => {}
513        }
514    }
515
516    /// The scratch copy of node `id`. Every `push_redo` producer installs
517    /// into `nodes` before pushing, so a miss is internal-state corruption.
518    fn scratch_node(nodes: &HashMap<NodeId, Node>, id: NodeId) -> &Node {
519        nodes
520            .get(&id)
521            .expect("producer installs into the scratch before push_redo")
522    }
523
524    /// The scratch copy of relationship `id`; same invariant as
525    /// [`Self::scratch_node`].
526    fn scratch_rel(rels: &HashMap<RelId, Relationship>, id: RelId) -> &Relationship {
527        rels.get(&id)
528            .expect("producer installs into the scratch before push_redo")
529    }
530
531    /// Keep `prop_ix` and `rel_prop_ix` current from the redo funnel
532    /// (ADR-0173, ADR-0185): post the `(label, value)` and
533    /// `(rel type, value)` pairings each op introduces. Every arm sources
534    /// from the scratch maps through [`Self::scratch_node`] /
535    /// [`Self::scratch_rel`]. Exhaustive, so a new op must decide here.
536    /// Removals post nothing: both indexes are additions-only and every
537    /// seek re-verifies its ids. A null value posts nothing too — that
538    /// policy is the index API's own ([`ScratchPropIndex::post_value`]'s
539    /// shared core), not re-spelled per arm here.
540    fn post_to_indexes(&mut self, op: &RedoOp) {
541        match op {
542            RedoOp::CreateNode { id, .. } => {
543                let n = Self::scratch_node(&self.batch.nodes, *id);
544                for (key, value) in &*n.properties {
545                    self.batch.prop_ix.post_value(*id, &n.labels, key, value);
546                }
547            }
548            RedoOp::CreateRel { id, .. } => {
549                let r = Self::scratch_rel(&self.batch.rels, *id);
550                for (key, value) in &*r.properties {
551                    self.batch
552                        .rel_prop_ix
553                        .post_value(*id, &r.rel_type, key, value);
554                }
555            }
556            RedoOp::SetNodeProp { id, key, value } => {
557                let n = Self::scratch_node(&self.batch.nodes, *id);
558                self.batch.prop_ix.post_value(*id, &n.labels, key, value);
559            }
560            RedoOp::AddLabels { id, labels } => {
561                let n = Self::scratch_node(&self.batch.nodes, *id);
562                self.batch.prop_ix.post_labels(*id, labels, &n.properties);
563            }
564            RedoOp::SetRelProp { id, key, value } => {
565                let r = Self::scratch_rel(&self.batch.rels, *id);
566                self.batch
567                    .rel_prop_ix
568                    .post_value(*id, &r.rel_type, key, value);
569            }
570            RedoOp::DeleteNode { .. }
571            | RedoOp::DeleteRel { .. }
572            | RedoOp::RemoveNodeProp { .. }
573            | RedoOp::RemoveRelProp { .. }
574            | RedoOp::RemoveLabels { .. }
575            | RedoOp::CreateIndex { .. }
576            | RedoOp::DropIndex { .. }
577            | RedoOp::CreateConstraint { .. }
578            | RedoOp::DropConstraint { .. }
579            | RedoOp::CatalogIndexDetail { .. }
580            | RedoOp::CatalogDerivedConstraint { .. }
581            | RedoOp::PutDatabase { .. }
582            | RedoOp::DropDatabase { .. }
583            | RedoOp::PutGraphType { .. }
584            | RedoOp::SetCurrentGraphType { .. }
585            | RedoOp::PullIdentityPut { .. }
586            | RedoOp::OntologySet { .. }
587            | RedoOp::OntologyDrop { .. } => {}
588        }
589    }
590
591    pub(super) fn alloc_node(&self) -> Result<NodeId> {
592        crate::graph::alloc_exhaustible_id(self.node_id_alloc.as_ref(), "node")
593    }
594
595    pub(super) fn alloc_rel(&self) -> Result<RelId> {
596        crate::graph::alloc_exhaustible_id(self.rel_id_alloc.as_ref(), "relationship")
597    }
598
599    /// Pre-batch state for `CALL { … } IN TRANSACTIONS`. The rollback image is
600    /// the whole scratch state as of here, in three parts: the per-batch maps
601    /// (the one embedded [`PerBatchState`] capture), the statement-spanning
602    /// [`StatementState`] (its ADR-0309 counters **and** its applied-change
603    /// count, so a rolled-back batch restores both), and the redo log
604    /// positionally — a cursor, not a second op vec — so per-batch capture is
605    /// O(1) in the accumulated ops (a by-value copy would be quadratic on the
606    /// no-sink path, where each batch re-captures over an ever-growing log).
607    /// Id allocators stay on the live scratch so a rolled-back batch does not
608    /// hand the same id out again; they are not part of the image.
609    ///
610    /// The pipelined write batch does not use this: its per-statement rollback
611    /// is [`Self::mark_statement`], which the batch's CREATE-only eligibility
612    /// rule makes exact at O(statement) instead of O(batch).
613    pub fn checkpoint(&self) -> ScratchCheckpoint {
614        ScratchCheckpoint {
615            batch: self.batch.clone(),
616            statement: self.statement.clone(),
617            redo: self.redo.cursor(),
618        }
619    }
620
621    /// Roll back to a captured [`Self::checkpoint`]: the per-batch state and
622    /// the statement-spanning state restores as one, and the redo log truncates
623    /// to its captured position (the live log's ops stay with the live log).
624    /// Because the applied-change count rides the restored [`StatementState`],
625    /// a batch that rolled back applied nothing — a statement whose every batch
626    /// failed is still a zero-effect write (ADR-0402 Decision 2) — and the
627    /// restore never has to derive that from how many ops the truncation
628    /// dropped.
629    pub fn restore(&mut self, checkpoint: ScratchCheckpoint) {
630        self.batch = checkpoint.batch;
631        self.statement = checkpoint.statement;
632        self.redo.restore_cursor(checkpoint.redo);
633        self.sync_workspace_best_effort();
634    }
635
636    /// Pre-statement mark for the pipelined write batch (ADR-0642): the redo
637    /// cursor and the statement-spanning state as of the statement's entry.
638    /// Cheap by construction — O(statement), never a copy of the batch image —
639    /// because the batch admits only CREATE-only statements, so the entries a
640    /// failed statement can have added are exactly the ids its own
641    /// [`StatementState::created_nodes`] / `created_rels` recorded at the redo
642    /// funnel.
643    pub fn mark_statement(&self) -> StatementMark {
644        StatementMark {
645            redo: self.redo.cursor(),
646            statement: self.statement.clone(),
647        }
648    }
649
650    /// Roll back to a [`Self::mark_statement`]: drop the entities the failed
651    /// statement created, truncate the redo to the mark's cursor and put the
652    /// statement-spanning state back. The batch's other entries — the earlier
653    /// statements' rows — are untouched, so a failing batched statement loses
654    /// only its own writes.
655    ///
656    /// The lazy equality indexes keep their postings for the dropped ids: they
657    /// are additions-only supersets every seek re-verifies on its view
658    /// (ADR-0172 §3), which is the same state a delete leaves behind.
659    ///
660    /// A redo this mark cannot invert is refused, not half-applied: the
661    /// statement's entries stay where they are and the caller fails the batch,
662    /// so a rollback that could not finish never leaves partial writes to be
663    /// committed with the batch — the durability lie the batch's whole
664    /// failure contract exists to avoid.
665    pub fn rollback_statement(&mut self, mark: StatementMark) -> Result<()> {
666        // The batch admits CREATE-only statements, so the only non-create ops
667        // a statement appends are the property defaults and label changes the
668        // engine makes for the entities it just created — and dropping those
669        // entities undoes those ops with them. Anything else is a redo this
670        // mark cannot invert.
671        let created: HashSet<EntityId> = self
672            .statement
673            .created_nodes
674            .iter()
675            .map(|id| EntityId::Node(*id))
676            .chain(
677                self.statement
678                    .created_rels
679                    .iter()
680                    .map(|id| EntityId::Rel(*id)),
681            )
682            .collect();
683        for op in self.redo.ops_after(&mark.redo) {
684            if !invertible_by_dropping_creates(&op, &created) {
685                return Err(relate_core::Error::storage(
686                    "a batched statement's redo holds an op its rollback cannot invert",
687                ));
688            }
689        }
690        let created_rels = std::mem::take(&mut self.statement.created_rels);
691        let created_nodes = std::mem::take(&mut self.statement.created_nodes);
692        // The bulk adjacency pass before the per-entity undo: one retain per
693        // map, never a scan per dropped id.
694        self.batch.drop_adjacency(&created_rels);
695        for id in created_rels {
696            self.batch.uncreate_rel(id);
697        }
698        for id in created_nodes {
699            self.batch.uncreate_node(id);
700        }
701        self.redo.restore_cursor(mark.redo);
702        self.statement = mark.statement;
703        self.sync_workspace_best_effort();
704        Ok(())
705    }
706}
707
708/// Whether dropping the statement's created entities undoes `op`: a create is
709/// the entity itself, and a property or label op is undone by the same drop
710/// when it names one of them — which is the only target a CREATE-only
711/// statement's defaults can reach.
712pub(super) fn invertible_by_dropping_creates(op: &RedoOp, created: &HashSet<EntityId>) -> bool {
713    match op {
714        RedoOp::CreateNode { .. } | RedoOp::CreateRel { .. } => true,
715        RedoOp::SetNodeProp { id, .. }
716        | RedoOp::RemoveNodeProp { id, .. }
717        | RedoOp::AddLabels { id, .. }
718        | RedoOp::RemoveLabels { id, .. } => created.contains(&EntityId::Node(*id)),
719        RedoOp::SetRelProp { id, .. } | RedoOp::RemoveRelProp { id, .. } => {
720            created.contains(&EntityId::Rel(*id))
721        }
722        _ => false,
723    }
724}
725
726/// The pipelined write batch's pre-statement rollback image
727/// ([`WriteScratch::mark_statement`]): the redo cursor and the
728/// statement-spanning state as of the statement's entry. Opaque to the facade,
729/// which marks once per batched statement and rolls back when it fails.
730pub struct StatementMark {
731    redo: super::redo_log::RedoCursor,
732    statement: StatementState,
733}
734
735/// Rollback image of a [`WriteScratch`]: its two state halves — the per-batch
736/// state (via the one embedded capture) and the statement-spanning state
737/// ([`StatementState`]: counters and applied count as of the capture) — plus
738/// the redo log's positional cursor. Cloning the maps is shallow once node and
739/// relationship payloads are `Arc`s; the redo ops stay with the live log, and
740/// the id allocators are not captured (they never roll back).
741///
742/// Opaque to the facade, which captures one per `CALL { … } IN TRANSACTIONS`
743/// batch and restores it when that batch fails. Its clone is O(batch), so it
744/// is a per-batch image — never a per-statement one ([`StatementMark`]).
745pub struct ScratchCheckpoint {
746    batch: PerBatchState,
747    statement: StatementState,
748    redo: super::redo_log::RedoCursor,
749}