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 // The lock first, then the ids. The batch locks the mems its
88 // items name; it takes the whole workspace when an item names
89 // an entity by a bare slug (resolved under the lock, against
90 // the reloaded view) or declares a relation on an acyclic
91 // relationship (the cycle guard walks edges in every mem). What
92 // the roster reconcile and the reloads report (a mem attached
93 // since, a sibling's commit, a commit this load completed)
94 // rides the receipt like on a single verb.
95 let mut touched_mems: Vec<String> = updates
96 .iter()
97 .map(|(a, _)| a.id.mem().to_string())
98 .collect();
99 touched_mems.sort();
100 touched_mems.dedup();
101 let (_write_lock, drift_warnings) = {
102 let items = &updates;
103 // Each item's own mem, and the mems its result refers to.
104 self.lock_for_verb_referring(
105 !dry_run,
106 &touched_mems,
107 |engine| {
108 let mut referred = Vec::new();
109 for (a, _) in items {
110 let texts = super::update_result_texts(engine, a);
111 referred.extend(crate::engine::write_lock::referred_mems(
112 a.id.mem(),
113 a.declare_relations.iter().map(|r| &r.target),
114 texts.iter().map(String::as_str).chain(
115 a.declare_relations
116 .iter()
117 .filter_map(|r| r.description.as_deref()),
118 ),
119 ));
120 }
121 referred.sort();
122 referred.dedup();
123 referred
124 },
125 |engine| {
126 items.iter().any(|(a, _)| {
127 a.id.mem().is_empty()
128 || a.declare_relations
129 .iter()
130 .any(|r| r.target.mem().is_empty())
131 || engine.write_needs_full_load(
132 a.id.mem(),
133 a.declare_relations.iter().map(|r| {
134 crate::engine::mutation::EdgeWrite {
135 rel_type: &r.rel_type,
136 target_mem: r.target.mem(),
137 remove: false,
138 }
139 }),
140 super::update_result_texts(engine, a)
141 .iter()
142 .map(String::as_str),
143 )
144 })
145 },
146 )?
147 };
148 // An item whose short id does not resolve fails as its own
149 // error below, never the whole batch.
150 let mut short_hints: Vec<WarningHint> = Vec::new();
151 let mut short_errors: Vec<(usize, EngineError)> = Vec::new();
152 let updates: Vec<(UpdateEntityArgs, Option<String>)> = updates
153 .into_iter()
154 .enumerate()
155 .map(|(i, (mut a, n))| {
156 match self.resolve_entity_id(&a.id) {
157 Ok((rid, hint)) => {
158 a.id = rid;
159 short_hints.extend(hint);
160 }
161 Err(e) => short_errors.push((i, e)),
162 }
163 for r in &mut a.declare_relations {
164 match self.resolve_entity_id(&r.target) {
165 Ok((t, hint)) => {
166 r.target = t;
167 short_hints.extend(hint);
168 }
169 Err(e) => short_errors.push((i, e)),
170 }
171 }
172 (a, n)
173 })
174 .collect();
175 // Same acyclic-guard rule as the single-item path: declared
176 // relations on an ACYCLIC rel-type (or one in an
177 // `acyclic_sets` set) walk the whole subgraph, so the walk
178 // must see every mem — deferred ones included (see the
179 // batch_relate comment). Declared signals on any involved
180 // schema need the full load too (see the single-item path).
181 if updates.iter().any(|(a, _)| {
182 let texts = super::update_result_texts(self, a);
183 self.write_needs_full_load(
184 a.id.mem(),
185 a.declare_relations
186 .iter()
187 .map(|r| crate::engine::mutation::EdgeWrite {
188 rel_type: &r.rel_type,
189 target_mem: r.target.mem(),
190 remove: false,
191 }),
192 texts.iter().map(String::as_str),
193 )
194 }) {
195 self.ensure_mems_loaded(None);
196 }
197
198 // Snapshot the in-memory store so a refused batch (or a
199 // commit-time backend failure) can roll back any auto-stubs
200 // and store pushes that earlier items already applied during
201 // preparation. The on-disk side rolls back by discarding each
202 // backend's staged-but-uncommitted pending buffer.
203 let store_snapshot = self.store.clone();
204
205 let mut items: Vec<(EntityId, BatchItem)> = Vec::with_capacity(updates.len());
206 let mut prepared: Vec<PreparedUpdate> = Vec::new();
207 let mut notes: Vec<Option<String>> = Vec::new();
208 let mut errors: Vec<(usize, EngineError)> = Vec::new();
209
210 // --- Phase 1: validate + prepare every item (no commits).
211 // Report-all: a failing item never stops preparation — every
212 // remaining item still validates so the refusal can name every
213 // failing entry at once (the family's upgraded contract).
214 // Items naming one entity compose in order: each later item is
215 // prepared against the store as the earlier one leaves it, so its
216 // hash compare and its write start from that result. The rollback
217 // below restores the snapshot on any refusal and on a rehearsal.
218 let named: Vec<EntityId> = updates.iter().map(|(a, _)| a.id.clone()).collect();
219 for (i, (args, note)) in updates.into_iter().enumerate() {
220 let id = args.id.clone();
221 let named_again = named[i + 1..].contains(&id);
222 if let Some(pos) = short_errors.iter().position(|(j, _)| *j == i) {
223 let (_, e) = short_errors.remove(pos);
224 items.push((id, BatchItem::Error));
225 errors.push((i, e));
226 continue;
227 }
228 // Rehearsal is batch-level (the `dry_run` parameter) —
229 // force the per-entry flag off so `Done` below always
230 // means a genuine content no-op, never a per-entry
231 // dry-run short-circuit misread as one.
232 let mut args = args;
233 args.dry_run = false;
234 match self.prepare_update(args) {
235 Ok(PrepareOutcome::Done(_)) => {
236 // No-op: applied, no write.
237 items.push((id, BatchItem::Noop));
238 }
239 Ok(PrepareOutcome::Prepared(p)) => {
240 if named_again && let Err(e) = self.apply_prepared_to_store(&p) {
241 items.push((id, BatchItem::Error));
242 errors.push((i, e));
243 continue;
244 }
245 prepared.push(p);
246 notes.push(note);
247 items.push((id, BatchItem::Prepared));
248 }
249 Err(e) => {
250 items.push((id, BatchItem::Error));
251 errors.push((i, e));
252 }
253 }
254 }
255
256 // The checks form over the store as the whole batch leaves it: an
257 // entry that edits a checked criterion beside an entry that closes
258 // its plan is the same pair of writes refused one after the other.
259 if errors.is_empty() {
260 let mut post = store_snapshot.clone();
261 let mut writes = Vec::new();
262 for p in &prepared {
263 match crate::entity::parser::parse_markdown(
264 &p.markdown,
265 &p.file_path,
266 p.type_def.as_ref(),
267 &p.mem,
268 ) {
269 Ok(parsed) => {
270 post.upsert(parsed.entity.id.clone(), parsed.entity.clone());
271 writes.push((parsed.entity, p.type_def.clone()));
272 }
273 Err(e) => {
274 self.store = store_snapshot;
275 self.discard_all_pending();
276 return Err(EngineError::ParseAfterWrite(e.to_string()));
277 }
278 }
279 }
280 for (entity, blocked) in self.checks_form_after(&post, &store_snapshot, &writes) {
281 let i = items
282 .iter()
283 .position(|(id, _)| *id == entity.id)
284 .unwrap_or(0);
285 errors.push((
286 i,
287 EngineError::ConstraintUnsatisfied {
288 entity_type: entity.entity_type.clone(),
289 entity_id: entity.id.to_string(),
290 violations: blocked,
291 },
292 ));
293 }
294 }
295
296 if !errors.is_empty() {
297 // Refuse the whole batch. Roll back store + disk, then
298 // report every failing entry — bounded at
299 // `BATCH_ERROR_REPORT_CAP` detailed envelopes with
300 // `errors_suppressed` counting the rest.
301 self.store = store_snapshot;
302 self.discard_all_pending();
303 return Ok(batch_refusal(
304 items.into_iter().map(|(id, _)| id).collect(),
305 errors,
306 ));
307 }
308
309 // Rehearsal: every item validated (the pass above is the same
310 // one a real batch runs), nothing failed — stop before any
311 // write. Roll back the prepare pass's store effects, discard
312 // any pending buffers, and return the would-be receipt with
313 // the marker form's empty `write_id`.
314 if dry_run {
315 self.store = store_snapshot;
316 self.discard_all_pending();
317 return Ok(batch_receipt(
318 update_actions(items),
319 Vec::new(),
320 Vec::new(),
321 String::new(),
322 ));
323 }
324
325 // --- Phase 2: stage every prepared write, then commit once
326 // per mem. --- Each item's anchors are staged into the same
327 // per-mem pending buffer so they ride the batch commit
328 // atomically.
329 for p in &prepared {
330 // The self-check records each item passed its gate on follow
331 // the entity to its post-write hash, before anything is staged
332 // (the single path's order, see `commit_prepared_update`).
333 if let Err(e) = self.carry_prepared_self_checks(p) {
334 self.store = store_snapshot;
335 self.discard_all_pending();
336 return Err(e);
337 }
338 }
339 for p in &prepared {
340 if let Err(e) = self.stage_prepared_update(p) {
341 self.store = store_snapshot;
342 self.discard_all_pending();
343 return Err(e);
344 }
345 }
346
347 // Distinct mount indices in first-seen order — one commit each.
348 let mut distinct_mounts: Vec<usize> = Vec::new();
349 for p in &prepared {
350 if !distinct_mounts.contains(&p.mount_idx) {
351 distinct_mounts.push(p.mount_idx);
352 }
353 }
354 let mut mount_commits: Vec<(usize, String)> = Vec::with_capacity(distinct_mounts.len());
355 let mut batch_warnings: Vec<WarningHint> = drift_warnings;
356 batch_warnings.extend(short_hints);
357 for &m in &distinct_mounts {
358 let entity_ids: Vec<String> = prepared
359 .iter()
360 .filter(|p| p.mount_idx == m)
361 .map(|p| p.id.to_string())
362 .collect();
363 let count = entity_ids.len();
364 let subject = format!("memstead: batch-update ({count} entities)");
365 // Per-entry notes ride the batch commit's note record as
366 // `<id>: <note>` lines — `append_provenance` is a
367 // no-op on the git-branch backend, so this record is where
368 // they survive. No notes → no note record.
369 let note_lines: Vec<String> = prepared
370 .iter()
371 .zip(notes.iter())
372 .filter(|(p, _)| p.mount_idx == m)
373 .filter_map(|(p, n)| {
374 n.as_ref()
375 .map(|n| crate::vcs::batch_note_line(p.id.as_ref(), n))
376 })
377 .collect();
378 let mut ctx = self.commit_context(
379 Some("batch_update"),
380 actor,
381 client.cloned(),
382 if note_lines.is_empty() {
383 None
384 } else {
385 Some(note_lines.join("\n"))
386 },
387 );
388 ctx.entity_ids = Some(entity_ids);
389 // One provenance record per item, landing with the mem's
390 // commit.
391 let records: Vec<Provenance> = prepared
392 .iter()
393 .zip(notes.iter())
394 .filter(|(p, _)| p.mount_idx == m)
395 .map(|(p, note)| {
396 self.provenance_record(
397 ProvenanceKind::Update,
398 &p.id,
399 actor,
400 client,
401 note.as_deref(),
402 )
403 })
404 .collect();
405 match self.commit_or_complete(m, self.commit_staged(m, &subject, &ctx, &records)) {
406 Ok(landed) => {
407 batch_warnings.extend(landed.warnings);
408 mount_commits.push((m, landed.write_id));
409 }
410 Err(e) => {
411 // A commit failed. Roll back the store and any
412 // still-pending backends. Mems already committed
413 // in this loop stay committed (per-mem atomicity),
414 // so the view of each is reloaded from storage.
415 self.store = store_snapshot;
416 self.discard_all_pending();
417 let items: Vec<(usize, EntityId)> = prepared
418 .iter()
419 .map(|p| (p.mount_idx, p.id.clone()))
420 .collect();
421 return Err(self.batch_commit_failed(
422 &distinct_mounts,
423 &items,
424 mount_commits,
425 m,
426 e,
427 ));
428 }
429 }
430 }
431
432 // Store application per item, now that the commits landed.
433 // `record_self_write` marks the commit as engine-self so drift
434 // detection ignores it.
435 for (m, write_id) in &mount_commits {
436 self.record_self_write(*m, write_id);
437 batch_warnings.extend(self.stamp_mutation_versions(*m));
438 }
439 let committed_mounts: Vec<usize> = mount_commits.iter().map(|(m, _)| *m).collect();
440 self.after_commits(
441 &committed_mounts,
442 "store_update",
443 &mut batch_warnings,
444 |engine| {
445 for p in &prepared {
446 engine.apply_prepared_to_store(p)?;
447 }
448 Ok(())
449 },
450 );
451
452 self.invalidate_communities();
453 self.invalidate_search_indexes();
454
455 // Single-mem batches name their one commit; multi-mem names
456 // the last mem committed (see the method docstring).
457 let write_id = mount_commits
458 .last()
459 .map(|(_, s)| s.clone())
460 .unwrap_or_default();
461 Ok(batch_receipt(
462 update_actions(items),
463 batch_warnings,
464 Vec::new(),
465 write_id,
466 ))
467 }
468
469 /// Best-effort discard of every backend's staged-but-uncommitted
470 /// pending buffer — the disk-side half of an atomic-batch rollback.
471 /// Discard errors (a poisoned pending mutex) are swallowed: we are
472 /// already unwinding a refused batch and have nothing better to do.
473 pub(in crate::engine::mutation) fn discard_all_pending(&self) {
474 for mount in &self.mounts {
475 let _ = mount.backend.discard_pending();
476 }
477 }
478}
479
480/// The update verb's action words: `updated` for a prepared item,
481/// `noop` for an applied no-op.
482fn update_actions(items: Vec<(EntityId, BatchItem)>) -> Vec<(EntityId, String)> {
483 items
484 .into_iter()
485 .map(|(id, item)| {
486 let action = match item {
487 BatchItem::Prepared => "updated",
488 BatchItem::Noop => "noop",
489 BatchItem::Error => unreachable!("refusal path returned above"),
490 };
491 (id, action.to_string())
492 })
493 .collect()
494}