memstead-base 0.27.0

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
Documentation
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! `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.
        // The lock first, then the ids. The batch locks the mems its
        // items name; it takes the whole workspace when an item names
        // an entity by a bare slug (resolved under the lock, against
        // the reloaded view) or declares a relation on an acyclic
        // relationship (the cycle guard walks edges in every mem). What
        // the roster reconcile and the reloads report (a mem attached
        // since, a sibling's commit, a commit this load completed)
        // rides the receipt like on a single verb.
        let mut touched_mems: Vec<String> = updates
            .iter()
            .map(|(a, _)| a.id.mem().to_string())
            .collect();
        touched_mems.sort();
        touched_mems.dedup();
        let (_write_lock, drift_warnings) = {
            let items = &updates;
            // Each item's own mem, and the mems its result refers to.
            self.lock_for_verb_referring(
                !dry_run,
                &touched_mems,
                |engine| {
                    let mut referred = Vec::new();
                    for (a, _) in items {
                        let texts = super::update_result_texts(engine, a);
                        referred.extend(crate::engine::write_lock::referred_mems(
                            a.id.mem(),
                            a.declare_relations.iter().map(|r| &r.target),
                            texts.iter().map(String::as_str).chain(
                                a.declare_relations
                                    .iter()
                                    .filter_map(|r| r.description.as_deref()),
                            ),
                        ));
                    }
                    referred.sort();
                    referred.dedup();
                    referred
                },
                |engine| {
                    items.iter().any(|(a, _)| {
                        a.id.mem().is_empty()
                            || a.declare_relations
                                .iter()
                                .any(|r| r.target.mem().is_empty())
                            || engine.write_needs_full_load(
                                a.id.mem(),
                                a.declare_relations.iter().map(|r| {
                                    crate::engine::mutation::EdgeWrite {
                                        rel_type: &r.rel_type,
                                        target_mem: r.target.mem(),
                                        remove: false,
                                    }
                                }),
                                super::update_result_texts(engine, a)
                                    .iter()
                                    .map(String::as_str),
                            )
                    })
                },
            )?
        };
        // An item whose short id 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();
        // 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, _)| {
            let texts = super::update_result_texts(self, a);
            self.write_needs_full_load(
                a.id.mem(),
                a.declare_relations
                    .iter()
                    .map(|r| crate::engine::mutation::EdgeWrite {
                        rel_type: &r.rel_type,
                        target_mem: r.target.mem(),
                        remove: false,
                    }),
                texts.iter().map(String::as_str),
            )
        }) {
            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).
        // Items naming one entity compose in order: each later item is
        // prepared against the store as the earlier one leaves it, so its
        // hash compare and its write start from that result. The rollback
        // below restores the snapshot on any refusal and on a rehearsal.
        let named: Vec<EntityId> = updates.iter().map(|(a, _)| a.id.clone()).collect();
        for (i, (args, note)) in updates.into_iter().enumerate() {
            let id = args.id.clone();
            let named_again = named[i + 1..].contains(&id);
            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)) => {
                    if named_again && let Err(e) = self.apply_prepared_to_store(&p) {
                        items.push((id, BatchItem::Error));
                        errors.push((i, e));
                        continue;
                    }
                    prepared.push(p);
                    notes.push(note);
                    items.push((id, BatchItem::Prepared));
                }
                Err(e) => {
                    items.push((id, BatchItem::Error));
                    errors.push((i, e));
                }
            }
        }

        // The checks form over the store as the whole batch leaves it: an
        // entry that edits a checked criterion beside an entry that closes
        // its plan is the same pair of writes refused one after the other.
        if errors.is_empty() {
            let mut post = store_snapshot.clone();
            let mut writes = Vec::new();
            for p in &prepared {
                match crate::entity::parser::parse_markdown(
                    &p.markdown,
                    &p.file_path,
                    p.type_def.as_ref(),
                    &p.mem,
                ) {
                    Ok(parsed) => {
                        post.upsert(parsed.entity.id.clone(), parsed.entity.clone());
                        writes.push((parsed.entity, p.type_def.clone()));
                    }
                    Err(e) => {
                        self.store = store_snapshot;
                        self.discard_all_pending();
                        return Err(EngineError::ParseAfterWrite(e.to_string()));
                    }
                }
            }
            for (entity, blocked) in self.checks_form_after(&post, &store_snapshot, &writes) {
                let i = items
                    .iter()
                    .position(|(id, _)| *id == entity.id)
                    .unwrap_or(0);
                errors.push((
                    i,
                    EngineError::ConstraintUnsatisfied {
                        entity_type: entity.entity_type.clone(),
                        entity_id: entity.id.to_string(),
                        violations: blocked,
                    },
                ));
            }
        }

        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());
        let mut batch_warnings: Vec<WarningHint> = drift_warnings;
        batch_warnings.extend(short_hints);
        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 — `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| crate::vcs::batch_note_line(p.id.as_ref(), n))
                })
                .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);
            // One provenance record per item, landing with the mem's
            // commit.
            let records: Vec<Provenance> = prepared
                .iter()
                .zip(notes.iter())
                .filter(|(p, _)| p.mount_idx == m)
                .map(|(p, note)| {
                    self.provenance_record(
                        ProvenanceKind::Update,
                        &p.id,
                        actor,
                        client,
                        note.as_deref(),
                    )
                })
                .collect();
            match self.commit_or_complete(m, self.commit_staged(m, &subject, &ctx, &records)) {
                Ok(landed) => {
                    batch_warnings.extend(landed.warnings);
                    mount_commits.push((m, landed.write_id));
                }
                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),
                    // so the view of each is reloaded from storage.
                    self.store = store_snapshot;
                    self.discard_all_pending();
                    let items: Vec<(usize, EntityId)> = prepared
                        .iter()
                        .map(|p| (p.mount_idx, p.id.clone()))
                        .collect();
                    return Err(self.batch_commit_failed(
                        &distinct_mounts,
                        &items,
                        mount_commits,
                        m,
                        e,
                    ));
                }
            }
        }

        // Store application per item, now that the commits landed.
        // `record_self_write` marks the commit as engine-self so drift
        // detection ignores it.
        for (m, write_id) in &mount_commits {
            self.record_self_write(*m, write_id);
            batch_warnings.extend(self.stamp_mutation_versions(*m));
        }
        let committed_mounts: Vec<usize> = mount_commits.iter().map(|(m, _)| *m).collect();
        self.after_commits(
            &committed_mounts,
            "store_update",
            &mut batch_warnings,
            |engine| {
                for p in &prepared {
                    engine.apply_prepared_to_store(p)?;
                }
                Ok(())
            },
        );

        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()
}