memstead_base/engine/mutation/update/batch.rs
1//! `Engine::batch_update`: the same phases as a single update, driven
2//! over every item before anything is written — short ids resolved
3//! up front, every touched mem reloaded once, the per-item prepare
4//! (resolve, validate, compose) with report-all refusal, then stage
5//! everything and commit once per mem. A refused or rehearsed batch
6//! rolls the store snapshot back and discards every pending buffer.
7
8use crate::entity::EntityId;
9use crate::ops::WarningHint;
10use crate::provenance::{Provenance, ProvenanceKind};
11
12use super::super::{batch_empty, batch_receipt, batch_refusal};
13use super::{
14 Actor, ClientId, Engine, EngineError, PrepareOutcome, PreparedUpdate, UpdateEntityArgs,
15};
16
17/// What each batch item is, in submission order, so the result
18/// entries echo the input order. `Prepared` is a real write (its
19/// `PreparedUpdate` lives in the batch's prepared list); `Noop` is an
20/// applied no-op (content unchanged, no write); `Error` is a refusal
21/// (its envelope lives in the batch's errors by index).
22pub(super) enum BatchItem {
23 Prepared,
24 Noop,
25 Error,
26}
27
28impl Engine {
29 /// Apply a batch of [`UpdateEntityArgs`] **atomically** — all or
30 /// nothing. Surfaces `BatchResult` for `memstead batch-update`
31 /// consumers.
32 ///
33 /// The batch validates and prepares every item first (each with
34 /// its own optimistic-lock check), then commits the whole set as
35 /// **one** commit per mem. If any item fails — validation error,
36 /// `HASH_MISMATCH`, entity-not-found, any per-item refusal —
37 /// **nothing is committed**: the on-disk mem and the in-memory
38 /// store are restored to exactly their pre-call state, and the
39 /// result is marked `applied: false` with EVERY failing item
40 /// carrying a typed `{code, message, details}` error envelope
41 /// (the family's report-all contract — bounded at
42 /// [`Self::BATCH_ERROR_REPORT_CAP`] detailed envelopes, with
43 /// `errors_suppressed` counting the rest) and every valid item
44 /// marked `"not_applied"`, so one repair cycle fixes the file.
45 ///
46 /// On success the returned `write_id` is the single batch commit
47 /// — an honest `memstead_changes_since` cursor / revert handle. Each
48 /// item's per-entry note rides into its own provenance record.
49 ///
50 /// Empty batches return `applied: true` with zero counts and no
51 /// commit. A batch where every item is a no-op (content unchanged)
52 /// likewise applies with an empty `write_id`.
53 ///
54 /// **Rehearsal** (`dry_run: true`): the FULL per-item validation
55 /// pass runs — identical refusals, identical report-all envelope —
56 /// then the batch stops before any write or commit. A legal batch
57 /// returns the would-be receipt (`applied: true`, per-entry
58 /// actions) with the marker form's empty `write_id`; an illegal
59 /// one returns the same refusal a real call would. Nothing is
60 /// staged, committed, or stamped.
61 ///
62 /// Atomicity is per-mem: for the common single-mem batch a
63 /// commit-time backend failure rolls the whole batch back. A batch
64 /// spanning multiple mems commits each mem in turn; if a later
65 /// mem's commit fails, already-committed mems stay committed
66 /// (true cross-mem two-phase commit is out of scope) — but the
67 /// dominant failure mode, a per-item validation/hash refusal, is
68 /// always fully atomic because no commit happens until every item
69 /// has passed.
70 pub fn batch_update(
71 &mut self,
72 updates: Vec<(UpdateEntityArgs, Option<String>)>,
73 actor: Actor,
74 client: Option<&ClientId>,
75 dry_run: bool,
76 ) -> Result<crate::ops::BatchResult, EngineError> {
77 if updates.is_empty() {
78 return Ok(batch_empty());
79 }
80
81 // Reload-before-operation: refresh every mem this batch
82 // touches *before* preparing items, so each item's
83 // `expected_hash` check runs against current truth (the batch
84 // is the one multi-op-per-process path, so a sibling commit
85 // between boot and this call is plausible). Notices stash on
86 // the engine for the caller to drain.
87 // Short ids resolve once, before the touched-mem probe reads
88 // each item's mem; an item that does not resolve fails as its
89 // own error below, never the whole batch.
90 let mut short_hints: Vec<WarningHint> = Vec::new();
91 let mut short_errors: Vec<(usize, EngineError)> = Vec::new();
92 let updates: Vec<(UpdateEntityArgs, Option<String>)> = updates
93 .into_iter()
94 .enumerate()
95 .map(|(i, (mut a, n))| {
96 match self.resolve_entity_id(&a.id) {
97 Ok((rid, hint)) => {
98 a.id = rid;
99 short_hints.extend(hint);
100 }
101 Err(e) => short_errors.push((i, e)),
102 }
103 for r in &mut a.declare_relations {
104 match self.resolve_entity_id(&r.target) {
105 Ok((t, hint)) => {
106 r.target = t;
107 short_hints.extend(hint);
108 }
109 Err(e) => short_errors.push((i, e)),
110 }
111 }
112 (a, n)
113 })
114 .collect();
115 let mut touched_mems: Vec<String> = updates
116 .iter()
117 .map(|(a, _)| a.id.mem().to_string())
118 .collect();
119 touched_mems.sort();
120 touched_mems.dedup();
121 for v in &touched_mems {
122 self.reload_if_stale(Some(v));
123 }
124 // Same acyclic-guard rule as the single-item path: declared
125 // relations on an ACYCLIC rel-type (or one in an
126 // `acyclic_sets` set) walk the whole subgraph, so the walk
127 // must see every mem — deferred ones included (see the
128 // batch_relate comment). Declared signals on any involved
129 // schema need the full load too (see the single-item path).
130 if updates.iter().any(|(a, _)| {
131 a.declare_relations.iter().any(|r| {
132 self.schemas.get(a.id.mem()).is_some_and(|s| {
133 s.relationship_acyclic(&r.rel_type)
134 || s.acyclic_set_containing(&r.rel_type).is_some()
135 }) || self
136 .schemas
137 .get(r.target.mem())
138 .is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
139 }) || self
140 .schemas
141 .get(a.id.mem())
142 .is_some_and(|s| s.types.values().any(|td| !td.signals.is_empty()))
143 }) {
144 self.ensure_mems_loaded(None);
145 }
146
147 // Snapshot the in-memory store so a refused batch (or a
148 // commit-time backend failure) can roll back any auto-stubs
149 // and store pushes that earlier items already applied during
150 // preparation. The on-disk side rolls back by discarding each
151 // backend's staged-but-uncommitted pending buffer.
152 let store_snapshot = self.store.clone();
153
154 let mut items: Vec<(EntityId, BatchItem)> = Vec::with_capacity(updates.len());
155 let mut prepared: Vec<PreparedUpdate> = Vec::new();
156 let mut notes: Vec<Option<String>> = Vec::new();
157 let mut errors: Vec<(usize, EngineError)> = Vec::new();
158
159 // --- Phase 1: validate + prepare every item (no commits).
160 // Report-all: a failing item never stops preparation — every
161 // remaining item still validates so the refusal can name every
162 // failing entry at once (the family's upgraded contract).
163 for (i, (args, note)) in updates.into_iter().enumerate() {
164 let id = args.id.clone();
165 if let Some(pos) = short_errors.iter().position(|(j, _)| *j == i) {
166 let (_, e) = short_errors.remove(pos);
167 items.push((id, BatchItem::Error));
168 errors.push((i, e));
169 continue;
170 }
171 // Rehearsal is batch-level (the `dry_run` parameter) —
172 // force the per-entry flag off so `Done` below always
173 // means a genuine content no-op, never a per-entry
174 // dry-run short-circuit misread as one.
175 let mut args = args;
176 args.dry_run = false;
177 match self.prepare_update(args) {
178 Ok(PrepareOutcome::Done(_)) => {
179 // No-op: applied, no write.
180 items.push((id, BatchItem::Noop));
181 }
182 Ok(PrepareOutcome::Prepared(p)) => {
183 prepared.push(p);
184 notes.push(note);
185 items.push((id, BatchItem::Prepared));
186 }
187 Err(e) => {
188 items.push((id, BatchItem::Error));
189 errors.push((i, e));
190 }
191 }
192 }
193
194 if !errors.is_empty() {
195 // Refuse the whole batch. Roll back store + disk, then
196 // report every failing entry — bounded at
197 // `BATCH_ERROR_REPORT_CAP` detailed envelopes with
198 // `errors_suppressed` counting the rest.
199 self.store = store_snapshot;
200 self.discard_all_pending();
201 return Ok(batch_refusal(
202 items.into_iter().map(|(id, _)| id).collect(),
203 errors,
204 ));
205 }
206
207 // Rehearsal: every item validated (the pass above is the same
208 // one a real batch runs), nothing failed — stop before any
209 // write. Roll back the prepare pass's store effects, discard
210 // any pending buffers, and return the would-be receipt with
211 // the marker form's empty `write_id`.
212 if dry_run {
213 self.store = store_snapshot;
214 self.discard_all_pending();
215 return Ok(batch_receipt(
216 update_actions(items),
217 Vec::new(),
218 Vec::new(),
219 String::new(),
220 ));
221 }
222
223 // --- Phase 2: stage every prepared write, then commit once
224 // per mem. --- Each item's anchors are staged into the same
225 // per-mem pending buffer so they ride the batch commit
226 // atomically.
227 for p in &prepared {
228 // The self-check records each item passed its gate on follow
229 // the entity to its post-write hash, before anything is staged
230 // (the single path's order, see `commit_prepared_update`).
231 if let Err(e) = self.carry_prepared_self_checks(p) {
232 self.store = store_snapshot;
233 self.discard_all_pending();
234 return Err(e);
235 }
236 }
237 for p in &prepared {
238 if let Err(e) = self.stage_prepared_update(p) {
239 self.store = store_snapshot;
240 self.discard_all_pending();
241 return Err(e);
242 }
243 }
244
245 // Distinct mount indices in first-seen order — one commit each.
246 let mut distinct_mounts: Vec<usize> = Vec::new();
247 for p in &prepared {
248 if !distinct_mounts.contains(&p.mount_idx) {
249 distinct_mounts.push(p.mount_idx);
250 }
251 }
252 let mut mount_commits: Vec<(usize, String)> = Vec::with_capacity(distinct_mounts.len());
253 for &m in &distinct_mounts {
254 let entity_ids: Vec<String> = prepared
255 .iter()
256 .filter(|p| p.mount_idx == m)
257 .map(|p| p.id.to_string())
258 .collect();
259 let count = entity_ids.len();
260 let subject = format!("memstead: batch-update ({count} entities)");
261 // Per-entry notes ride the batch commit's note record as
262 // `<id>: <note>` lines (decision 3) — `append_provenance` is a
263 // no-op on the git-branch backend, so this record is where
264 // they survive. No notes → no note record.
265 let note_lines: Vec<String> = prepared
266 .iter()
267 .zip(notes.iter())
268 .filter(|(p, _)| p.mount_idx == m)
269 .filter_map(|(p, n)| n.as_ref().map(|n| format!("{}: {n}", p.id)))
270 .collect();
271 let mut ctx = self.commit_context(
272 Some("batch_update"),
273 actor,
274 client.cloned(),
275 if note_lines.is_empty() {
276 None
277 } else {
278 Some(note_lines.join("\n"))
279 },
280 );
281 ctx.entity_ids = Some(entity_ids);
282 match self.mounts[m].backend.commit(&subject, &ctx) {
283 Ok(sha) => mount_commits.push((m, sha)),
284 Err(e) => {
285 // A commit failed. Roll back the store and any
286 // still-pending backends. Mems already committed
287 // in this loop stay committed (per-mem atomicity).
288 self.store = store_snapshot;
289 self.discard_all_pending();
290 return Err(e.into());
291 }
292 }
293 }
294
295 // Provenance + store application per item, now that the commits
296 // landed. `record_self_write` marks the commit as engine-self
297 // so drift detection ignores it.
298 let mut batch_warnings: Vec<WarningHint> = short_hints;
299 for (p, note) in prepared.iter().zip(notes.iter()) {
300 let write_id = mount_commits
301 .iter()
302 .find(|(m, _)| *m == p.mount_idx)
303 .map(|(_, s)| s.clone())
304 .unwrap_or_default();
305 self.mounts[p.mount_idx].backend.append_provenance(
306 &Provenance::new(
307 std::time::SystemTime::now(),
308 ProvenanceKind::Update,
309 Some(p.id.to_string()),
310 actor,
311 client.cloned(),
312 note.clone(),
313 )
314 .with_role(self.current_role)
315 .with_identity(self.current_identity.clone()),
316 )?;
317 self.record_self_write(p.mount_idx, &write_id);
318 batch_warnings.extend(self.stamp_mutation_versions(p.mount_idx));
319 self.apply_prepared_to_store(p)?;
320 }
321
322 self.invalidate_communities();
323 self.invalidate_search_indexes();
324
325 // Single-mem batches name their one commit; multi-mem names
326 // the last mem committed (see the method docstring).
327 let write_id = mount_commits
328 .last()
329 .map(|(_, s)| s.clone())
330 .unwrap_or_default();
331 Ok(batch_receipt(
332 update_actions(items),
333 batch_warnings,
334 Vec::new(),
335 write_id,
336 ))
337 }
338
339 /// Best-effort discard of every backend's staged-but-uncommitted
340 /// pending buffer — the disk-side half of an atomic-batch rollback.
341 /// Discard errors (a poisoned pending mutex) are swallowed: we are
342 /// already unwinding a refused batch and have nothing better to do.
343 pub(in crate::engine::mutation) fn discard_all_pending(&self) {
344 for mount in &self.mounts {
345 let _ = mount.backend.discard_pending();
346 }
347 }
348}
349
350/// The update verb's action words: `updated` for a prepared item,
351/// `noop` for an applied no-op.
352fn update_actions(items: Vec<(EntityId, BatchItem)>) -> Vec<(EntityId, String)> {
353 items
354 .into_iter()
355 .map(|(id, item)| {
356 let action = match item {
357 BatchItem::Prepared => "updated",
358 BatchItem::Noop => "noop",
359 BatchItem::Error => unreachable!("refusal path returned above"),
360 };
361 (id, action.to_string())
362 })
363 .collect()
364}