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