memstead-base 0.26.1

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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! A folder commit that is decided (its record is in storage) and
//! whose apply step fails, as the second mem of an operation over two
//! mems after the first mem's commit landed. The faults strike the
//! first apply step after the commit point and then the first step of
//! each completion the engine attempts.

use std::collections::BTreeMap;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use indexmap::IndexMap;
use tempfile::TempDir;

use crate::backend::MemBackend;
use crate::engine::test_helpers::{cli_actor, empty_create_args, folder_mount};
use crate::engine::{Engine, EngineError, RenameEntityArgs, UpdateEntityArgs};
use crate::entity::EntityId;
use crate::storage::FilesystemBackend;
use crate::storage::filesystem::fault_io::FaultIo;
use crate::storage::filesystem::io::{DirEntry, FolderIo};

const ONE: &str = "one";
const TWO: &str = "two";

/// Real IO, recorded by the inner `FaultIo`; the calls whose index is
/// in `fail` return an error instead of running. Exactly those.
#[derive(Clone)]
struct TwoFaults {
    inner: FaultIo,
    count: Arc<AtomicUsize>,
    fail: Arc<std::sync::Mutex<Vec<usize>>>,
    struck: Arc<AtomicUsize>,
}

impl TwoFaults {
    fn new() -> Self {
        Self {
            inner: FaultIo::new(),
            count: Arc::new(AtomicUsize::new(0)),
            fail: Arc::new(std::sync::Mutex::new(Vec::new())),
            struck: Arc::new(AtomicUsize::new(0)),
        }
    }
    fn reset(&self) {
        self.inner.reset();
        self.count.store(0, Ordering::SeqCst);
        self.fail.lock().unwrap().clear();
        self.struck.store(0, Ordering::SeqCst);
    }
    fn arm(&self, at: &[usize]) {
        *self.fail.lock().unwrap() = at.to_vec();
    }
    fn disarm(&self) {
        self.fail.lock().unwrap().clear();
    }
    fn gate(&self) -> io::Result<()> {
        let index = self.count.fetch_add(1, Ordering::SeqCst);
        if self.fail.lock().unwrap().contains(&index) {
            self.struck.fetch_add(1, Ordering::SeqCst);
            return Err(io::Error::other(format!("injected error at step {index}")));
        }
        Ok(())
    }
}

impl FolderIo for TwoFaults {
    fn exists(&self, path: &Path) -> io::Result<bool> {
        self.gate()?;
        self.inner.exists(path)
    }
    fn read(&self, path: &Path) -> io::Result<Option<Vec<u8>>> {
        self.gate()?;
        self.inner.read(path)
    }
    fn read_tail(&self, path: &Path, max: u64) -> io::Result<Option<Vec<u8>>> {
        self.gate()?;
        self.inner.read_tail(path, max)
    }
    fn list_dir(&self, path: &Path) -> io::Result<Vec<DirEntry>> {
        self.gate()?;
        self.inner.list_dir(path)
    }
    fn create_dir(&self, path: &Path) -> io::Result<()> {
        self.gate()?;
        self.inner.create_dir(path)
    }
    fn write(&self, path: &Path, bytes: &[u8]) -> io::Result<()> {
        self.gate()?;
        self.inner.write(path, bytes)
    }
    fn append(&self, path: &Path, bytes: &[u8]) -> io::Result<()> {
        self.gate()?;
        self.inner.append(path, bytes)
    }
    fn sync_file(&self, path: &Path) -> io::Result<()> {
        self.gate()?;
        self.inner.sync_file(path)
    }
    fn sync_dir(&self, path: &Path) -> io::Result<()> {
        self.gate()?;
        self.inner.sync_dir(path)
    }
    fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
        self.gate()?;
        self.inner.rename(from, to)
    }
    fn remove_file(&self, path: &Path) -> io::Result<()> {
        self.gate()?;
        self.inner.remove_file(path)
    }
    fn remove_dir(&self, path: &Path) -> io::Result<()> {
        self.gate()?;
        self.inner.remove_dir(path)
    }
}

fn id(mem: &str, slug: &str) -> EntityId {
    EntityId::new(mem, slug)
}

fn settings(engine: &mut Engine) {
    let mut settings = crate::WorkspaceSettings::default();
    for mem in [ONE, TWO] {
        settings.cross_mem_links.insert(
            mem.to_string(),
            memstead_schema::workspace_config::CrossLinkValue::Wildcard,
        );
    }
    engine.set_settings(settings);
}

fn dirs(root: &Path) -> (PathBuf, PathBuf) {
    (root.join(ONE), root.join(TWO))
}

/// A fresh engine over both mems, plain backends.
fn fresh(root: &Path) -> Engine {
    let (one, two) = dirs(root);
    let mut engine = Engine::from_mounts(vec![
        (
            folder_mount(ONE, one.clone()),
            Box::new(FilesystemBackend::new(one)) as Box<dyn MemBackend>,
        ),
        (
            folder_mount(TWO, two.clone()),
            Box::new(FilesystemBackend::new(two)) as Box<dyn MemBackend>,
        ),
    ])
    .expect("engine boots");
    settings(&mut engine);
    engine
}

/// The same, with `faulted`'s IO under `io`.
fn faulted(root: &Path, faulted_mem: &str, io: &TwoFaults) -> Engine {
    let (one, two) = dirs(root);
    let backend = |mem: &str, dir: PathBuf| -> Box<dyn MemBackend> {
        if mem == faulted_mem {
            Box::new(FilesystemBackend::with_io(dir, io.clone()))
        } else {
            Box::new(FilesystemBackend::new(dir))
        }
    };
    let mut engine = Engine::from_mounts(vec![
        (folder_mount(ONE, one.clone()), backend(ONE, one)),
        (folder_mount(TWO, two.clone()), backend(TWO, two)),
    ])
    .expect("engine boots");
    settings(&mut engine);
    engine
}

fn update_args(
    engine: &Engine,
    target: &EntityId,
    hash: Option<String>,
    text: &str,
) -> UpdateEntityArgs {
    let mut sections = IndexMap::new();
    sections.insert("purpose".to_string(), text.to_string());
    UpdateEntityArgs {
        id: target.clone(),
        expected_hash: crate::ExpectedHash::from_token(
            hash.or_else(|| engine.get_entity(target).map(|e| e.content_hash.clone())),
        ),
        sections,
        append_sections: Default::default(),
        patch_sections: Default::default(),
        sections_unset: Vec::new(),
        metadata: Default::default(),
        metadata_unset: Vec::new(),
        dry_run: false,
        declare_relations: Vec::new(),
        anchors: Vec::new(),
        anchors_unset: Vec::new(),
        relations_unset: Vec::new(),
    }
}

/// one: Alpha, Beta (Beta links [[one--alpha]]); two: Gamma (links
/// [[one--alpha]]).
fn seeded() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let (one, two) = dirs(tmp.path());
    std::fs::create_dir_all(&one).unwrap();
    std::fs::create_dir_all(&two).unwrap();
    let mut engine = fresh(tmp.path());
    let (actor, client) = cli_actor();
    for (mem, title) in [(ONE, "Alpha"), (ONE, "Beta"), (TWO, "Gamma")] {
        engine
            .create_entity(empty_create_args(mem, title), actor, Some(&client), None)
            .unwrap();
    }
    for (mem, slug) in [(ONE, "beta"), (TWO, "gamma")] {
        let args = update_args(&engine, &id(mem, slug), None, "see [[one--alpha]]");
        engine
            .update_entity(args, actor, Some(&client), None)
            .unwrap();
    }
    tmp
}

fn copy_dir(from: &Path, to: &Path) {
    std::fs::create_dir_all(to).unwrap();
    for entry in std::fs::read_dir(from).unwrap() {
        let path = entry.unwrap().path();
        let target = to.join(path.file_name().unwrap());
        if path.is_dir() {
            copy_dir(&path, &target);
        } else {
            std::fs::copy(&path, &target).unwrap();
        }
    }
}

fn view(engine: &Engine) -> BTreeMap<String, String> {
    let store = engine.store();
    let mut out = BTreeMap::new();
    for entity in store.all_entities() {
        let mut outgoing: Vec<String> = store
            .outgoing(&entity.id)
            .iter()
            .map(|e| format!("{}>{}", e.rel_type, e.target))
            .collect();
        outgoing.sort();
        out.insert(
            entity.id.to_string(),
            format!(
                "stub={} hash={} out={:?}",
                entity.stub, entity.content_hash, outgoing
            ),
        );
    }
    out
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum Op {
    BatchCreate,
    BatchUpdate,
    Rename,
    Sweep,
}

/// The mem whose commit comes second (and is faulted).
fn second_mem(op: Op) -> &'static str {
    match op {
        Op::BatchCreate | Op::BatchUpdate => TWO,
        // Peers first, the renamed entity's / mem's own mem last.
        Op::Rename | Op::Sweep => ONE,
    }
}

fn run(op: Op, engine: &mut Engine) -> Result<String, EngineError> {
    let (actor, client) = cli_actor();
    match op {
        Op::BatchCreate => engine
            .batch_create(
                vec![
                    (empty_create_args(ONE, "Delta"), None),
                    (empty_create_args(TWO, "Epsilon"), None),
                ],
                actor,
                Some(&client),
                false,
            )
            .map(|r| format!("applied={}", r.applied)),
        Op::BatchUpdate => {
            let updates = vec![
                (
                    update_args(engine, &id(ONE, "alpha"), None, "batch text"),
                    None,
                ),
                (
                    update_args(
                        engine,
                        &id(TWO, "gamma"),
                        None,
                        "batch text, see [[one--alpha]]",
                    ),
                    None,
                ),
            ];
            engine
                .batch_update(updates, actor, Some(&client), false)
                .map(|r| format!("applied={}", r.applied))
        }
        Op::Rename => {
            let args = RenameEntityArgs {
                id: id(ONE, "alpha"),
                expected_hash: crate::ExpectedHash::from_token(
                    engine
                        .get_entity(&id(ONE, "alpha"))
                        .map(|e| e.content_hash.clone()),
                ),
                new_title: "Alpha Renamed".to_string(),
            };
            engine
                .rename_entity(args, actor, Some(&client), None)
                .map(|o| o.new_id.to_string())
        }
        Op::Sweep => engine
            .rewrite_mem_references(ONE, "uno", None)
            .map(|o| format!("{:?}", o.rewritten_mems)),
    }
}

/// Run `op` with `faults` failures in a row from the first apply step
/// after the second mem's commit point. Returns what the call came to,
/// the engine, its storage, and the ids an undisturbed run ends with.
fn scenario(op: Op, faults: usize) -> (Result<String, EngineError>, Engine, TempDir, Vec<String>) {
    let template = seeded();
    let mem2 = second_mem(op);

    // Probe: where the commit point of the second mem's commit falls.
    let probe_dir = TempDir::new().unwrap();
    copy_dir(template.path(), probe_dir.path());
    let io = TwoFaults::new();
    let mut probe = faulted(probe_dir.path(), mem2, &io);
    io.reset();
    run(op, &mut probe).expect("the undisturbed call lands");
    let cp = io.inner.commit_point().expect("the second mem commits");
    assert!(
        io.inner.op_count() > cp + 1,
        "{op:?}: steps after the commit point"
    );
    let undisturbed: Vec<String> = view(&fresh(probe_dir.path())).into_keys().collect();
    drop(probe);

    let dir = TempDir::new().unwrap();
    copy_dir(template.path(), dir.path());
    let io = TwoFaults::new();
    let mut engine = faulted(dir.path(), mem2, &io);
    io.reset();
    let at: Vec<usize> = (1..=faults).map(|n| cp + n).collect();
    io.arm(&at);
    let outcome = run(op, &mut engine);
    assert_eq!(
        io.struck.load(Ordering::SeqCst),
        faults,
        "{op:?}: every injected fault struck"
    );
    io.disarm();
    (outcome, engine, dir, undisturbed)
}

const OPS: [Op; 4] = [Op::BatchCreate, Op::BatchUpdate, Op::Rename, Op::Sweep];

/// The apply step fails and so does the completion the commit call
/// runs at once. The commit is in storage all the same, so an
/// operation over several mems tries the completion once more before
/// it stops: the operation lands whole, and the engine serves what a
/// fresh load serves.
#[test]
fn a_decided_commit_whose_first_completion_fails_still_lands_the_operation() {
    for op in OPS {
        let (outcome, engine, dir, undisturbed) = scenario(op, 2);
        outcome.unwrap_or_else(|e| panic!("{op:?}: {e:?}"));
        let fresh_view = view(&fresh(dir.path()));
        assert_eq!(view(&engine), fresh_view, "{op:?}");
        assert_eq!(
            fresh_view.into_keys().collect::<Vec<_>>(),
            undisturbed,
            "{op:?}: the operation is complete in storage"
        );
    }
}

/// The completion fails a second time as well. The operation stops and
/// reports through the partial-failure envelope, and the report does
/// not call the decided commit not landed: its mem is named as landed,
/// with the failure as its error, and the reload that builds the
/// report completes the commit, so the hashes are the entities' hashes
/// now and nothing is left to send again.
#[test]
fn a_decided_commit_that_cannot_be_completed_at_once_is_reported_as_landed() {
    for op in OPS {
        let (outcome, engine, dir, undisturbed) = scenario(op, 3);
        let err = outcome.expect_err("three faults stop the operation");
        let EngineError::RenamePartialFailure {
            committed_mems,
            failed_mem,
            mems,
            ..
        } = &err
        else {
            panic!("{op:?}: expected the partial-failure envelope, got {err:?}");
        };
        assert_eq!(failed_mem, second_mem(op), "{op:?}");
        assert_eq!(
            committed_mems.len(),
            2,
            "{op:?}: both commits are in storage"
        );
        let fresh_engine = fresh(dir.path());
        for reported in mems {
            assert!(reported.landed, "{op:?}: {reported:?}");
            assert_eq!(
                reported.error.is_some(),
                &reported.mem == failed_mem,
                "{op:?}: {reported:?}"
            );
            for item in &reported.items {
                assert!(item.landed, "{op:?}: {item:?}");
                let (mem, slug) = item.id.split_once("--").unwrap();
                let now = fresh_engine
                    .get_entity(&id(mem, slug))
                    .filter(|e| !e.stub)
                    .map(|e| e.content_hash.clone());
                assert!(
                    now.is_some(),
                    "{op:?}: {item:?} names an entity that exists"
                );
                assert_eq!(item.current_hash, now, "{op:?}: {item:?}");
            }
        }
        let fresh_view = view(&fresh_engine);
        assert_eq!(view(&engine), fresh_view, "{op:?}");
        assert_eq!(
            fresh_view.into_keys().collect::<Vec<_>>(),
            undisturbed,
            "{op:?}: the operation is complete in storage"
        );
    }
}

// ---------------------------------------------------------------------
// A write into one mem and a peer's lock it never took
// ---------------------------------------------------------------------

mod a_peer_with_a_cut_off_commit {
    use super::*;
    use std::time::Duration;

    fn single_update(engine: &mut Engine) -> Result<(), String> {
        let (actor, client) = cli_actor();
        let args = update_args(engine, &id(ONE, "alpha"), None, "sibling text");
        engine
            .update_entity(args, actor, Some(&client), None)
            .map(|_| ())
            .map_err(|e| format!("{e:?}"))
    }

    fn lock_path(root: &Path, mem: &str) -> PathBuf {
        std::fs::canonicalize(root.join(mem))
            .unwrap()
            .join(".memstead")
            .join("locks")
            .join("write.lock")
    }

    fn hold(path: &Path) -> std::fs::File {
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        let f = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(path)
            .unwrap();
        f.lock().unwrap();
        f
    }

    fn is_free(path: &Path) -> bool {
        let Ok(f) = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(path)
        else {
            return true;
        };
        match f.try_lock() {
            Ok(()) => {
                let _ = f.unlock();
                true
            }
            Err(_) => false,
        }
    }

    /// Where the commit point of a single update of one--alpha falls.
    fn commit_point(template: &Path) -> usize {
        let probe_dir = TempDir::new().unwrap();
        copy_dir(template, probe_dir.path());
        let io = TwoFaults::new();
        let mut probe = faulted(probe_dir.path(), ONE, &io);
        io.reset();
        single_update(&mut probe).expect("undisturbed update lands");
        io.inner.commit_point().expect("commit point")
    }

    /// A second engine, on its own thread, updates one--alpha and its
    /// commit is cut off after the commit point by `faults` IO errors.
    fn cut_off_commit(root: &Path, cp: usize, faults: usize) -> String {
        let io = TwoFaults::new();
        let root = root.to_path_buf();
        std::thread::spawn(move || {
            let mut e = faulted(&root, ONE, &io);
            io.reset();
            let at: Vec<usize> = (1..=faults).map(|n| cp + n).collect();
            io.arm(&at);
            let r = single_update(&mut e);
            format!("{r:?} struck={}", io.struck.load(Ordering::SeqCst))
        })
        .join()
        .unwrap()
    }

    fn create_in_two(mut engine: Engine, title: &'static str) -> std::sync::mpsc::Receiver<String> {
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let (actor, client) = cli_actor();
            let r = engine
                .create_entity(empty_create_args(TWO, title), actor, Some(&client), None)
                .map(|_| ())
                .map_err(|e| format!("{e:?}"));
            let _ = tx.send(format!("{r:?}"));
        });
        rx
    }

    /// (finished while one's lock was held, two's lock free meanwhile, outcome after release)
    fn waits(with_record: bool) -> (bool, bool, String, String) {
        let template = seeded();
        let cp = commit_point(template.path());
        let dir = TempDir::new().unwrap();
        copy_dir(template.path(), dir.path());
        // The writer under test boots before the sibling's commit.
        let p1 = fresh(dir.path());
        let sibling = if with_record {
            cut_off_commit(dir.path(), cp, 2)
        } else {
            "none".to_string()
        };
        let record = dir.path().join(ONE).join(".memstead/commit.json");
        assert_eq!(
            record.exists(),
            with_record,
            "commit record on disk; sibling: {sibling}"
        );
        // A second process holds one's write lock.
        let held = hold(&lock_path(dir.path(), ONE));
        let rx = create_in_two(p1, "Zeta");
        let early = rx.recv_timeout(Duration::from_secs(4));
        let two_free = is_free(&lock_path(dir.path(), TWO));
        drop(held);
        let late = match &early {
            Ok(s) => s.clone(),
            Err(_) => rx
                .recv_timeout(Duration::from_secs(20))
                .unwrap_or_else(|_| "never returned".to_string()),
        };
        (early.is_ok(), two_free, late, sibling)
    }

    #[test]
    fn control_a_create_in_two_does_not_wait_on_ones_lock() {
        let (early, two_free, late, _) = waits(false);
        eprintln!("control: early={early} two_free={two_free} late={late}");
        assert!(early, "{late}");
    }

    #[test]
    fn a_create_in_two_holds_twos_lock_and_waits_on_ones() {
        let (early, two_free, late, sibling) = waits(true);
        eprintln!(
            "sibling: {sibling}\nearly={early} two_free_while_waiting={two_free} late={late}"
        );
        assert!(
            early,
            "a create into `two` did not return while another process held `one`'s lock; \
             `two`'s lock free meanwhile: {two_free}; after release: {late}; sibling: {sibling}"
        );
    }

    /// The whole cycle with two engines on two threads: one creates in
    /// `two`, the other batch-creates over `one` and `two`.
    #[test]
    fn a_single_mem_write_and_a_two_mem_batch_both_complete() {
        let template = seeded();
        let cp = commit_point(template.path());
        for round in 0..3 {
            let dir = TempDir::new().unwrap();
            copy_dir(template.path(), dir.path());
            let p1 = fresh(dir.path());
            let mut p2 = fresh(dir.path());
            let sibling = cut_off_commit(dir.path(), cp, 2);
            assert!(
                dir.path().join(ONE).join(".memstead/commit.json").exists(),
                "{sibling}"
            );
            // Sequence the two through two's lock.
            let gate = hold(&lock_path(dir.path(), TWO));
            let (tx2, rx2) = std::sync::mpsc::channel();
            let start_batch = move || {
                std::thread::spawn(move || {
                    let (actor, client) = cli_actor();
                    let r = p2
                        .batch_create(
                            vec![
                                (empty_create_args(ONE, "Delta"), None),
                                (empty_create_args(TWO, "Epsilon"), None),
                            ],
                            actor,
                            Some(&client),
                            false,
                        )
                        .map(|r| r.applied)
                        .map_err(|e| format!("{e:?}"));
                    let _ = tx2.send(format!("{r:?}"));
                });
            };
            let rx1;
            if round % 2 == 0 {
                rx1 = create_in_two(p1, "Zeta");
                std::thread::sleep(Duration::from_millis(300));
                start_batch();
            } else {
                start_batch();
                std::thread::sleep(Duration::from_millis(300));
                rx1 = create_in_two(p1, "Zeta");
            }
            std::thread::sleep(Duration::from_millis(500));
            let one_held_by_batch = !is_free(&lock_path(dir.path(), ONE));
            drop(gate);
            let a = rx1.recv_timeout(Duration::from_secs(8));
            let b = rx2.recv_timeout(Duration::from_secs(8));
            eprintln!(
                "round {round}: one_held_by_batch={one_held_by_batch} create={a:?} batch={b:?}"
            );
            assert!(
                a.is_ok() && b.is_ok(),
                "round {round}: deadlock: create in two = {a:?}, batch over one+two = {b:?} \
                 (one's lock held by the batch before the gate opened: {one_held_by_batch})"
            );
        }
    }

    fn delete_on_thread(
        mut engine: Engine,
        mem: &'static str,
        slug: &'static str,
    ) -> std::sync::mpsc::Receiver<String> {
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let (actor, client) = cli_actor();
            let r = engine
                .delete_entity(
                    crate::engine::DeleteEntityArgs {
                        id: id(mem, slug),
                        expected_hash: crate::ExpectedHash::Missing,
                    },
                    actor,
                    Some(&client),
                    None,
                )
                .map(|_| ())
                .map_err(|e| format!("{e:?}"));
            let _ = tx.send(format!("{r:?}"));
        });
        rx
    }

    /// Two deletes, each a verb over every mem, over the same two
    /// mems; the first engine mounts `one` read-only.
    #[test]
    fn two_workspace_wide_deletes_over_the_same_mems_both_complete() {
        let template = seeded();
        let cp = commit_point(template.path());
        let dir = TempDir::new().unwrap();
        copy_dir(template.path(), dir.path());
        let (one, two) = dirs(dir.path());
        let mut ro = folder_mount(ONE, one.clone());
        ro.capability = crate::workspace::MountCapability::ReadOnly;
        let mut p1 = Engine::from_mounts(vec![
            (
                ro,
                Box::new(FilesystemBackend::new(one)) as Box<dyn MemBackend>,
            ),
            (
                folder_mount(TWO, two.clone()),
                Box::new(FilesystemBackend::new(two)) as Box<dyn MemBackend>,
            ),
        ])
        .expect("engine boots");
        settings(&mut p1);
        let p2 = fresh(dir.path());
        let sibling = cut_off_commit(dir.path(), cp, 2);
        assert!(
            dir.path().join(ONE).join(".memstead/commit.json").exists(),
            "{sibling}"
        );
        let gate = hold(&lock_path(dir.path(), TWO));
        // p2 takes one's lock and waits at two's.
        let rx1 = delete_on_thread(p1, TWO, "gamma");
        std::thread::sleep(Duration::from_millis(300));
        let rx2 = delete_on_thread(p2, ONE, "beta");
        std::thread::sleep(Duration::from_millis(500));
        let one_held = !is_free(&lock_path(dir.path(), ONE));
        drop(gate);
        let a = rx1.recv_timeout(Duration::from_secs(8));
        let b = rx2.recv_timeout(Duration::from_secs(8));
        eprintln!("one_held_by_p2={one_held} p1 delete two--gamma={a:?} p2 delete one--beta={b:?}");
        assert!(
            a.is_ok() && b.is_ok(),
            "p1={a:?} p2={b:?} one_held_by_p2={one_held}"
        );
    }
}