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