interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-coord / tests / durability.rs

1982 lines · 75787 bytes Raw Blame History
1//! Durability boundaries of the board and the coordination store (review findings B6, B7,
2//! B8 of aien-dev/aien-sovereign-core-mv#928):
3//!
4//! - B6: a refused recovery leaves `journal.log` and `journal.idx` byte for byte as they
5//! were, so a retry refuses again instead of cutting acknowledged events as a torn tail
6//! (same boot, after a reboot, and with a partly written final table entry).
7//! - B7: a failed directory sync never yields a durable-success result (post receipt,
8//! compaction report, cursor ack, coordination record), and the next writer flushes a
9//! created-but-unsynced root entry again before it acknowledges; `EINVAL` (a file system
10//! that cannot sync directories) is the one tolerated answer.
11//! - B8: a cursor directory that cannot be listed refuses compaction; nothing is dropped.
12//!
13//! Round 11 review findings of the same pull request:
14//!
15//! - R4: a reboot rebuild refuses (twice, bytes unchanged) when `journal.idx` proves a
16//! frame committed that the journal no longer verifies: a partly written final entry
17//! over a corrupt frame, and a journal that ends on a frame boundary before a committed
18//! frame (also the same-boot partial-entry case).
19//! - R5: an "already applied" retry (an ack at or below the cursor, a repeated
20//! subscription, a compaction whose cursors were already expired) syncs its directory
21//! again and fails while that sync still fails; compaction never publishes over cursor
22//! state it could not flush.
23//! - R6: `dirsync.pending` is reconciled by every durable mutator, not only journal
24//! writers: a registration or a first read retried while the root sync still fails is an
25//! error; after the repair it succeeds and the marker is gone.
26//!
27//! Round 12 review findings of the same pull request:
28//!
29//! - N3: an empty or missing `journal.log` under a `journal.idx` that names committed
30//! events is refused (twice, both files unchanged, no id reused), same boot and after a
31//! reboot; a generation-mismatch rebuild must reach the table's last committed id. A
32//! compaction cut between its renames still recovers (controls).
33//! - N4: a first delivery retried while its cursor's directory sync still fails is an
34//! error; after the repair it succeeds, and a delivery with nothing pending needs no
35//! directory sync.
36//! - N5: a root sync that succeeded earlier never clears the `dirsync.pending` of a later
37//! publication whose own sync failed (a deterministic two-process interleaving through
38//! the `pause-after-root-sync` barrier), plus a serial retry control.
39//!
40//! Round 14 review findings of the same pull request (a lookup or listing whose error was
41//! read as absence), driven by the `stat-eio:<name>`, `readdir-eio:<name>` and
42//! `readdirent-eio:<name>` fault points of `SYNAPSE_COORD_FAULT`:
43//!
44//! - B1: `init` on an existing board of an old boot whose `journal.log` lookup fails is an
45//! error with `boot` unchanged, so the next read of the new boot still rebuilds a lost
46//! inbox entry (fresh-board and existing-board controls).
47//! - B2: a coordination-store discriminator (`dirs`, `STORE_ID`) that cannot be looked up
48//! is an error, never a board: no `BOARD_ID` is created.
49//! - The audit: a lost journal whose lookups fail creates no journal; the reboot rebuild,
50//! the torn-tail index cleanup, the compaction trim and `check` refuse (or report) an
51//! index directory they cannot list; an unlistable `agents/` is no second tag; an
52//! unlistable coordination `dirs/` keeps an agent's presence and locks; an unanswerable
53//! target lookup refuses the key instead of keying the file differently.
54//!
55//! Round 17 review finding B1: a generation-mismatch rebuild (a compaction cut between its
56//! renames) keeps the old table's terminal slot evidence. A partly written or undecodable
57//! final slot after its last decodable entry still proves one more committed id, so a
58//! journal ending at the last decodable id is refused (twice, files unchanged, no post, no
59//! id reused), same boot and after a reboot; the reviewer's six controls are kept.
60//!
61//! Permission-based cases make a directory unreadable (mode 0300: entries can still be
62//! created, renamed and opened by name, but the directory cannot be opened or listed). The
63//! superuser bypasses that, so those cases print `NOT_RUN` and return when run as uid 0.
64
65use std::fs;
66use std::os::unix::fs::{MetadataExt, PermissionsExt};
67use std::path::{Path, PathBuf};
68use std::process::{Command, Output, Stdio};
69use std::sync::atomic::{AtomicU32, Ordering};
70use synapse_coord::board::{Board, BoardError, Kind, Post, Resume, Sub};
71use synapse_coord::json::{self, J};
72use synapse_coord::{ClaimOutcome, CoordError, CoordStore, Holder, Workspace};
73
74const BIN: &str = env!("CARGO_BIN_EXE_synapse-coord");
75static N: AtomicU32 = AtomicU32::new(0);
76
77struct Fx {
78 root: PathBuf,
79}
80impl Drop for Fx {
81 fn drop(&mut self) {
82 // Restore every mode a test changed so the tree can be removed.
83 for d in [
84 self.root.clone(),
85 self.root.join("cursors"),
86 self.root.join("subs"),
87 self.root.join("store/crumb/v1/dirs"),
88 ] {
89 let _ = fs::set_permissions(&d, fs::Permissions::from_mode(0o755));
90 }
91 let _ = fs::remove_dir_all(&self.root);
92 }
93}
94
95fn scratch(name: &str) -> Fx {
96 let root = std::env::temp_dir().join(format!(
97 "sb-dur-{name}-{}-{}",
98 std::process::id(),
99 N.fetch_add(1, Ordering::SeqCst)
100 ));
101 let _ = fs::remove_dir_all(&root);
102 Fx { root }
103}
104
105fn fx(name: &str) -> (Fx, Board) {
106 let f = scratch(name);
107 let b = Board::init(&f.root).unwrap();
108 (f, b)
109}
110
111/// True (after printing NOT_RUN) when permission bits do not bind this process.
112fn is_superuser(name: &str, probe: &Path) -> bool {
113 if fs::metadata(probe).unwrap().uid() == 0 {
114 println!("NOT_RUN {name}: running as uid 0, directory permissions are not enforced");
115 return true;
116 }
117 false
118}
119
120fn chmod(p: &Path, mode: u32) {
121 fs::set_permissions(p, fs::Permissions::from_mode(mode)).unwrap();
122}
123
124fn post(b: &Board, session: &str, to: &[&str], text: &str) -> Result<u64, BoardError> {
125 let mut p = Post::new(&b.whoami(session)?, "t", "lane/test", Kind::Finding, text);
126 p.to = to.iter().map(|s| s.to_string()).collect();
127 b.post(&p).map(|r| r.id)
128}
129
130fn bytes(root: &Path) -> (Vec<u8>, Vec<u8>) {
131 (
132 fs::read(root.join("journal.log")).unwrap(),
133 fs::read(root.join("journal.idx")).unwrap(),
134 )
135}
136
137/// Offsets of the frames in `journal.log` (4-byte length, 4-byte CRC-32C, body).
138fn frame_offsets(j: &[u8]) -> Vec<usize> {
139 let mut v = Vec::new();
140 let mut pos = 0;
141 while pos + 8 <= j.len() {
142 v.push(pos);
143 let len = u32::from_le_bytes(j[pos..pos + 4].try_into().unwrap()) as usize;
144 pos += 8 + len;
145 }
146 v
147}
148
149/// Flip one body byte of the frame at `off` (its CRC no longer verifies).
150fn corrupt_frame_at(root: &Path, off: usize) {
151 let p = root.join("journal.log");
152 let mut j = fs::read(&p).unwrap();
153 j[off + 8 + 3] ^= 0x5a;
154 fs::write(&p, &j).unwrap();
155}
156
157fn is_corrupt<T: std::fmt::Debug>(r: &Result<T, BoardError>) -> bool {
158 matches!(r, Err(BoardError::Corrupt { .. }))
159}
160
161fn is_io<T: std::fmt::Debug>(r: &Result<T, BoardError>) -> bool {
162 matches!(r, Err(BoardError::Io { .. }))
163}
164
165// ---------------------------------------------------------------------------------------
166// B6: a failed recovery keeps its evidence.
167
168#[test]
169fn b6_corrupt_first_frame_refused_twice_with_bytes_unchanged() {
170 let (f, b) = fx("b6-first");
171 b.register("sa", "alpha", None).unwrap();
172 for i in 1..=3 {
173 assert_eq!(post(&b, "sa", &[], &format!("event {i}")).unwrap(), i);
174 }
175 corrupt_frame_at(&f.root, 0);
176 let before = bytes(&f.root);
177 // Small enough that the old code took the remainder for one torn frame.
178 assert!(before.0.len() < 1 << 16);
179 for attempt in 1..=2 {
180 let r = b.recover();
181 assert!(
182 is_corrupt(&r),
183 "attempt {attempt}: expected Corrupt, got {r:?}"
184 );
185 assert_eq!(
186 bytes(&f.root),
187 before,
188 "attempt {attempt}: journal.log and journal.idx must be unchanged"
189 );
190 }
191 // A post goes through the same recovery: refused, nothing written, no id reused.
192 let r = post(&b, "sa", &[], "after the damage");
193 assert!(is_corrupt(&r), "post: expected Corrupt, got {r:?}");
194 assert_eq!(bytes(&f.root), before, "post must not touch the files");
195 let r = b.recover();
196 assert!(
197 is_corrupt(&r),
198 "third recovery: expected Corrupt, got {r:?}"
199 );
200 assert_eq!(bytes(&f.root), before);
201}
202
203#[test]
204fn b6_partly_written_final_entry_never_licenses_cutting_its_frame() {
205 let (f, b) = fx("b6-partial");
206 b.register("sa", "alpha", None).unwrap();
207 post(&b, "sa", &[], "one").unwrap();
208 post(&b, "sa", &[], "two").unwrap();
209 // journal.idx loses its last whole entry and ends in a partial one (the commit of
210 // event 2), and event 2's frame (synced before that entry was written) is damaged.
211 let ip = f.root.join("journal.idx");
212 let mut t = fs::read(&ip).unwrap();
213 t.truncate(64);
214 t.extend_from_slice(&[0xab; 20]);
215 fs::write(&ip, &t).unwrap();
216 let j = fs::read(f.root.join("journal.log")).unwrap();
217 corrupt_frame_at(&f.root, frame_offsets(&j)[1]);
218 let before = bytes(&f.root);
219 for attempt in 1..=2 {
220 let r = b.recover();
221 assert!(
222 is_corrupt(&r),
223 "attempt {attempt}: expected Corrupt, got {r:?}"
224 );
225 assert_eq!(bytes(&f.root), before, "attempt {attempt}: unchanged");
226 }
227}
228
229#[test]
230fn b6_partly_written_final_entry_is_still_dropped_when_its_frame_verifies() {
231 let (f, b) = fx("b6-partial-ok");
232 b.register("sa", "alpha", None).unwrap();
233 post(&b, "sa", &[], "one").unwrap();
234 post(&b, "sa", &[], "two").unwrap();
235 let ip = f.root.join("journal.idx");
236 let mut t = fs::read(&ip).unwrap();
237 t.truncate(64);
238 t.extend_from_slice(&[0xab; 20]);
239 fs::write(&ip, &t).unwrap();
240 let r = b.recover().unwrap();
241 assert!(r.dropped_table_entry, "{r:?}");
242 assert_eq!(r.adopted, vec![2], "{r:?}");
243 assert_eq!(b.bounds().unwrap(), (1, 2));
244 assert_eq!(fs::metadata(&ip).unwrap().len(), 128);
245 assert!(b.check().unwrap().ok());
246}
247
248/// The board CLI with an overridden boot id (a "reboot" for the test).
249fn board_cli(root: &Path, session: Option<&str>, args: &[&str], boot: &str) -> Output {
250 let mut c = Command::new(BIN);
251 c.arg("board").arg("--board-root").arg(root);
252 if let Some(s) = session {
253 c.arg("--session").arg(s);
254 }
255 c.args(args)
256 .env_remove("SYNAPSE_COORD_FAULT")
257 .env_remove("SYNAPSE_BOARD_ID")
258 .env_remove("SYNAPSE_BOARD_SESSION")
259 .env_remove("CRUMB_SESSION")
260 .env("SYNAPSE_BOARD_BOOT_ID", boot)
261 .stdin(Stdio::null())
262 .stdout(Stdio::piped())
263 .stderr(Stdio::piped());
264 c.output().unwrap()
265}
266
267fn summary(o: &Output) -> J {
268 let out = String::from_utf8_lossy(&o.stdout);
269 let last = out.lines().last().unwrap_or_else(|| {
270 panic!(
271 "no summary line; stderr: {}",
272 String::from_utf8_lossy(&o.stderr)
273 )
274 });
275 json::parse(last.as_bytes()).unwrap_or_else(|| panic!("not JSON: {last}"))
276}
277
278fn ok_cli(o: &Output) -> J {
279 assert!(
280 o.status.success(),
281 "exit {:?}: {} {}",
282 o.status.code(),
283 String::from_utf8_lossy(&o.stdout),
284 String::from_utf8_lossy(&o.stderr)
285 );
286 summary(o)
287}
288
289fn reboot_fixture(name: &str) -> Fx {
290 let f = scratch(name);
291 ok_cli(&board_cli(&f.root, None, &["init"], "test-boot-one"));
292 ok_cli(&board_cli(
293 &f.root,
294 Some("sa"),
295 &["register", "alpha"],
296 "test-boot-one",
297 ));
298 for i in 1..=3 {
299 let text = format!("event {i}");
300 ok_cli(&board_cli(
301 &f.root,
302 Some("sa"),
303 &[
304 "post", "--thread", "t", "--topic", "lane/x", "--text", &text,
305 ],
306 "test-boot-one",
307 ));
308 }
309 f
310}
311
312fn assert_boot_rebuild_refuses_twice(f: &Fx) {
313 let before = bytes(&f.root);
314 for attempt in 1..=2 {
315 let o = board_cli(&f.root, None, &["recover"], "test-boot-two");
316 assert_eq!(
317 o.status.code(),
318 Some(2),
319 "attempt {attempt}: {} {}",
320 String::from_utf8_lossy(&o.stdout),
321 String::from_utf8_lossy(&o.stderr)
322 );
323 assert_eq!(
324 summary(&o).str_of("error").as_deref(),
325 Some("Corrupt"),
326 "attempt {attempt}"
327 );
328 assert_eq!(bytes(&f.root), before, "attempt {attempt}: unchanged");
329 }
330}
331
332#[test]
333fn b6_boot_rebuild_never_cuts_a_corrupt_first_committed_frame() {
334 let f = reboot_fixture("b6-boot-first");
335 corrupt_frame_at(&f.root, 0);
336 assert_boot_rebuild_refuses_twice(&f);
337}
338
339#[test]
340fn b6_boot_rebuild_never_cuts_a_corrupt_last_committed_frame() {
341 let f = reboot_fixture("b6-boot-last");
342 let j = fs::read(f.root.join("journal.log")).unwrap();
343 corrupt_frame_at(&f.root, *frame_offsets(&j).last().unwrap());
344 assert_boot_rebuild_refuses_twice(&f);
345}
346
347// ---------------------------------------------------------------------------------------
348// B7: a failed directory sync is a failure.
349
350#[test]
351fn b7_root_sync_failure_gives_no_receipt_and_is_retried() {
352 let (f, b) = fx("b7-root");
353 if is_superuser(
354 "b7_root_sync_failure_gives_no_receipt_and_is_retried",
355 &f.root,
356 ) {
357 return;
358 }
359 b.register("sa", "alpha", None).unwrap();
360 let pending = f.root.join("dirsync.pending");
361 chmod(&f.root, 0o300);
362 // Each writer open creates what is missing (the subdirectories, then journal.log and
363 // journal.idx) and fails on the root sync that would make it durable.
364 let mut opens = 0;
365 while fs::symlink_metadata(f.root.join("journal.log")).is_err() {
366 let r = b.recover();
367 assert!(is_io(&r), "writer open {opens}: expected Io, got {r:?}");
368 opens += 1;
369 assert!(opens < 10, "journal.log never created");
370 }
371 let r = b.recover();
372 assert!(
373 is_io(&r),
374 "created-but-unsynced journal: expected Io, got {r:?}"
375 );
376 // The files exist now; a post must still not be acknowledged over their unsynced
377 // entries.
378 let r = post(&b, "sa", &[], "never acknowledged");
379 assert!(is_io(&r), "post: expected Io (no receipt), got {r:?}");
380 assert!(fs::symlink_metadata(&pending).is_ok(), "retry marker kept");
381 chmod(&f.root, 0o755);
382 assert_eq!(post(&b, "sa", &[], "durable").unwrap(), 1, "no id was used");
383 assert!(
384 fs::symlink_metadata(&pending).is_err(),
385 "the successful root sync clears the marker"
386 );
387 assert_eq!(b.bounds().unwrap(), (1, 1));
388 assert!(b.check().unwrap().ok());
389}
390
391#[test]
392fn b7_compaction_root_sync_failure_is_refused_and_flushed_before_the_next_ack() {
393 let (f, b) = fx("b7-compact");
394 if is_superuser("b7_compaction_root_sync_failure", &f.root) {
395 return;
396 }
397 b.register("sa", "alpha", None).unwrap();
398 for i in 1..=4 {
399 post(&b, "sa", &[], &format!("e{i}")).unwrap();
400 }
401 chmod(&f.root, 0o300);
402 let r = b.compact(3, false);
403 assert!(is_io(&r), "compact: expected Io, got {r:?}");
404 assert!(fs::symlink_metadata(f.root.join("dirsync.pending")).is_ok());
405 // The renamed generation is not durable yet: no post into it is acknowledged.
406 let r = post(&b, "sa", &[], "into the unsynced generation");
407 assert!(is_io(&r), "post: expected Io (no receipt), got {r:?}");
408 chmod(&f.root, 0o755);
409 assert_eq!(post(&b, "sa", &[], "e5").unwrap(), 5);
410 assert!(fs::symlink_metadata(f.root.join("dirsync.pending")).is_err());
411 assert_eq!(b.bounds().unwrap(), (3, 5));
412}
413
414#[test]
415fn b7_cursor_dir_sync_failure_is_not_an_ack() {
416 let (f, b) = fx("b7-cursor");
417 if is_superuser("b7_cursor_dir_sync_failure_is_not_an_ack", &f.root) {
418 return;
419 }
420 b.register("sa", "alpha", None).unwrap();
421 b.register("sb", "beta", None).unwrap();
422 let id = post(&b, "sa", &["beta"], "for beta").unwrap();
423 assert_eq!(b.deliver("sb", 10, Resume::Acked).unwrap().events.len(), 1);
424 chmod(&f.root.join("cursors"), 0o300);
425 let r = b.ack("sb", id);
426 assert!(is_io(&r), "ack: expected Io, got {r:?}");
427 chmod(&f.root.join("cursors"), 0o755);
428 b.ack("sb", id).unwrap();
429 assert_eq!(b.acked("sb").unwrap(), id);
430}
431
432#[test]
433fn b7_coord_record_dir_sync_failure_is_an_error() {
434 let f = scratch("b7-coord");
435 let top = f.root.join("wa");
436 fs::create_dir_all(top.join("src")).unwrap();
437 fs::write(top.join("src/a.c"), "a").unwrap();
438 fs::write(top.join("src/b.c"), "b").unwrap();
439 let store = f.root.join("store/crumb/v1");
440 let cs = CoordStore::open(&store);
441 let mut h = Holder::git("A", "0123456789ab", "ba9876543210");
442 h.session = Some("A-session".into());
443 let ws = Workspace::worktree(top.to_str().unwrap(), h);
444 match cs
445 .claim(&ws, "agent-a", "src", "a.c", "first", None)
446 .unwrap()
447 {
448 ClaimOutcome::Claimed { .. } => {}
449 o => panic!("expected a claim, got {o:?}"),
450 }
451 if is_superuser("b7_coord_record_dir_sync_failure_is_an_error", &store) {
452 return;
453 }
454 let dirs = store.join("dirs");
455 chmod(&dirs, 0o300);
456 let r = cs.claim(&ws, "agent-a", "src", "b.c", "second", None);
457 chmod(&dirs, 0o755);
458 assert!(
459 matches!(r, Err(CoordError::Io { .. })),
460 "claim over a failed directory sync: expected Io, got {r:?}"
461 );
462}
463
464fn post_cli(root: &Path, text: &str, fault: Option<&str>) -> Output {
465 let mut c = Command::new(BIN);
466 c.arg("board")
467 .arg("--board-root")
468 .arg(root)
469 .arg("--session")
470 .arg("sa")
471 .args(["post", "--thread", "t", "--topic", "lane/x", "--text", text])
472 .env_remove("SYNAPSE_COORD_FAULT")
473 .env_remove("SYNAPSE_BOARD_ID")
474 .env_remove("SYNAPSE_BOARD_SESSION")
475 .env_remove("CRUMB_SESSION")
476 .env_remove("SYNAPSE_BOARD_BOOT_ID")
477 .stdin(Stdio::null())
478 .stdout(Stdio::piped())
479 .stderr(Stdio::piped());
480 if let Some(p) = fault {
481 c.env("SYNAPSE_COORD_FAULT", p);
482 }
483 c.output().unwrap()
484}
485
486#[test]
487fn b7_injected_eio_refuses_the_receipt_and_einval_is_tolerated() {
488 let (f, b) = fx("b7-inject");
489 b.register("sa", "alpha", None).unwrap();
490 // EIO on the directory sync of the first post (it creates the journal): exit 1, a
491 // failure summary, no id.
492 let o = post_cli(&f.root, "lost", Some("dir-sync-eio"));
493 assert_eq!(
494 o.status.code(),
495 Some(1),
496 "{}",
497 String::from_utf8_lossy(&o.stdout)
498 );
499 let s = summary(&o);
500 assert_eq!(s.get("ok"), Some(&J::False), "{s:?}");
501 assert_eq!(s.str_of("error").as_deref(), Some("Io"), "{s:?}");
502 assert!(s.get("id").is_none(), "no receipt: {s:?}");
503 // The created-but-unsynced journal is flushed again by the next post: still EIO.
504 let o = post_cli(&f.root, "lost again", Some("dir-sync-eio"));
505 assert_eq!(o.status.code(), Some(1), "retry must sync the root again");
506 // EINVAL (a file system that cannot sync directories) is the documented exception.
507 let o = post_cli(&f.root, "kept", Some("dir-sync-einval"));
508 let s = ok_cli(&o);
509 let id = match s.get("id") {
510 Some(J::Num(t)) => String::from_utf8_lossy(t).into_owned(),
511 other => panic!("no id in {s:?}: {other:?}"),
512 };
513 assert_eq!(id, "1", "{s:?}");
514 assert_eq!(b.bounds().unwrap(), (1, 1), "exactly one event, id 1");
515}
516
517// ---------------------------------------------------------------------------------------
518// B8: compaction refuses unless the cursor enumeration is complete.
519
520#[test]
521fn b8_unlistable_cursor_dir_refuses_compaction() {
522 let (f, b) = fx("b8");
523 if is_superuser("b8_unlistable_cursor_dir_refuses_compaction", &f.root) {
524 return;
525 }
526 b.register("sa", "alpha", None).unwrap();
527 b.register("sb", "beta", None).unwrap();
528 let first = post(&b, "sa", &["beta"], "e1").unwrap();
529 assert_eq!(b.deliver("sb", 1, Resume::Acked).unwrap().events.len(), 1);
530 b.ack("sb", first).unwrap();
531 for i in 2..=4 {
532 post(&b, "sa", &["beta"], &format!("e{i}")).unwrap();
533 }
534 // beta's cursor (acked 1) lags behind keep_since 3.
535 let cursors = f.root.join("cursors");
536 assert!(fs::symlink_metadata(cursors.join("beta.json")).is_ok());
537 let before = bytes(&f.root);
538 chmod(&cursors, 0o300);
539 for expire in [false, true] {
540 let r = b.compact(3, expire);
541 assert!(
542 is_io(&r),
543 "compact(expire={expire}) over an unlistable cursors/: expected Io, got {r:?}"
544 );
545 assert_eq!(bytes(&f.root), before, "expire={expire}: nothing dropped");
546 }
547 chmod(&cursors, 0o755);
548 assert_eq!(b.acked("sb").unwrap(), first, "the cursor was not expired");
549 // Control: with the directory listable, the lagging cursor is found and named.
550 match b.compact(3, false) {
551 Err(BoardError::CompactRefused { tags, .. }) => {
552 assert!(tags.iter().any(|t| t == "beta"), "{tags:?}")
553 }
554 other => panic!("expected CompactRefused, got {other:?}"),
555 }
556 assert_eq!(bytes(&f.root), before);
557}
558
559// ---------------------------------------------------------------------------------------
560// R4: a reboot rebuild keeps every committed boundary journal.idx proves.
561
562/// `journal.idx` keeps its first two entries and ends in a partly written third one.
563fn partial_third_entry(root: &Path) {
564 let ip = root.join("journal.idx");
565 let mut t = fs::read(&ip).unwrap();
566 assert_eq!(t.len(), 192, "three whole entries");
567 t.truncate(128);
568 t.extend_from_slice(&[0xab; 20]);
569 fs::write(&ip, &t).unwrap();
570}
571
572fn truncate_journal_before_frame(root: &Path, n: usize) {
573 let jp = root.join("journal.log");
574 let mut j = fs::read(&jp).unwrap();
575 let off = frame_offsets(&j)[n];
576 j.truncate(off);
577 fs::write(&jp, &j).unwrap();
578}
579
580#[test]
581fn r4_boot_rebuild_refuses_a_partly_written_final_entry_over_a_corrupt_frame() {
582 // The reviewer's variant A: the old rebuild cut 236 bytes at offset 472 (event 3,
583 // whose partly written entry proves it was durable) and reported success.
584 let f = reboot_fixture("r4-partial");
585 partial_third_entry(&f.root);
586 let j = fs::read(f.root.join("journal.log")).unwrap();
587 corrupt_frame_at(&f.root, frame_offsets(&j)[2]);
588 assert_boot_rebuild_refuses_twice(&f);
589}
590
591#[test]
592fn r4_boot_rebuild_refuses_a_journal_that_ends_before_a_committed_frame() {
593 // The reviewer's variant B: an intact three-entry table, the journal cut exactly
594 // before the third frame. The old rebuild reached EOF on a frame boundary, never
595 // compared it with the table's floor, and replaced the table with two entries.
596 let f = reboot_fixture("r4-eof");
597 truncate_journal_before_frame(&f.root, 2);
598 assert_boot_rebuild_refuses_twice(&f);
599}
600
601#[test]
602fn r4_boot_rebuild_refuses_a_partly_written_entry_whose_frame_is_gone() {
603 // Both at once: the partly written third entry is the only evidence of event 3, and
604 // the journal ends on the boundary before it.
605 let f = reboot_fixture("r4-partial-eof");
606 partial_third_entry(&f.root);
607 truncate_journal_before_frame(&f.root, 2);
608 assert_boot_rebuild_refuses_twice(&f);
609}
610
611#[test]
612fn r4_same_boot_partly_written_entry_refuses_a_journal_that_ends_at_its_frame() {
613 let (f, b) = fx("r4-same-boot-eof");
614 b.register("sa", "alpha", None).unwrap();
615 for i in 1..=3 {
616 post(&b, "sa", &[], &format!("event {i}")).unwrap();
617 }
618 partial_third_entry(&f.root);
619 truncate_journal_before_frame(&f.root, 2);
620 let before = bytes(&f.root);
621 for attempt in 1..=2 {
622 let r = b.recover();
623 assert!(
624 is_corrupt(&r),
625 "attempt {attempt}: expected Corrupt, got {r:?}"
626 );
627 assert_eq!(bytes(&f.root), before, "attempt {attempt}: unchanged");
628 }
629}
630
631#[test]
632fn r4_boot_rebuild_adopts_a_partly_written_final_entry_whose_frame_verifies() {
633 // Control: the evidence only refuses what does not verify. The frame the partial
634 // entry names is intact, so the rebuild succeeds with all three events.
635 let f = reboot_fixture("r4-partial-ok");
636 partial_third_entry(&f.root);
637 let s = ok_cli(&board_cli(&f.root, None, &["recover"], "test-boot-two"));
638 assert_eq!(s.get("rebuilt_after_boot"), Some(&J::True), "{s:?}");
639 assert_eq!(s.get("torn_tail_at"), Some(&J::Null), "nothing cut: {s:?}");
640 assert_eq!(
641 fs::metadata(f.root.join("journal.idx")).unwrap().len(),
642 192,
643 "all three events committed again"
644 );
645 // `check` exits 0 only when journal.idx and every index agree with the journal.
646 ok_cli(&board_cli(&f.root, None, &["check"], "test-boot-two"));
647}
648
649// ---------------------------------------------------------------------------------------
650// R5: an already-applied retry is not durable until its directory is synced.
651
652#[test]
653fn r5_ack_retry_with_the_cursor_dir_sync_still_failing_is_not_an_ack() {
654 let (f, b) = fx("r5-ack");
655 if is_superuser("r5_ack_retry", &f.root) {
656 return;
657 }
658 b.register("sa", "alpha", None).unwrap();
659 b.register("sb", "beta", None).unwrap();
660 let id = post(&b, "sa", &["beta"], "message").unwrap();
661 assert_eq!(b.deliver("sb", 10, Resume::Acked).unwrap().events.len(), 1);
662 chmod(&f.root.join("cursors"), 0o300);
663 // The first ack renames the cursor into place, then fails its directory sync. The
664 // retry finds the cursor already at `id`: it must sync again, and that still fails.
665 let first = b.ack("sb", id);
666 let retry = b.ack("sb", id);
667 chmod(&f.root.join("cursors"), 0o755);
668 assert!(is_io(&first), "first: expected Io, got {first:?}");
669 assert!(
670 is_io(&retry),
671 "retry with the sync still failing: expected Io, got {retry:?}"
672 );
673 // Repaired: the same retry is now a durable success.
674 let c = b.ack("sb", id).unwrap();
675 assert_eq!((c.acked, c.delivered, c.exists), (id, id, true));
676}
677
678#[test]
679fn r5_subscribe_retry_with_the_subs_dir_sync_still_failing_is_an_error() {
680 let (f, b) = fx("r5-subs");
681 if is_superuser("r5_subscribe_retry", &f.root) {
682 return;
683 }
684 b.register("sa", "alpha", None).unwrap();
685 b.subscribe("sa", &Sub::Topic("lane/a".into())).unwrap();
686 chmod(&f.root.join("subs"), 0o300);
687 let sub = Sub::Topic("lane/b".into());
688 let first = b.subscribe("sa", &sub);
689 let retry = b.subscribe("sa", &sub);
690 chmod(&f.root.join("subs"), 0o755);
691 assert!(is_io(&first), "first: expected Io, got {first:?}");
692 assert!(is_io(&retry), "retry: expected Io, got {retry:?}");
693 let s = b.subscribe("sa", &sub).unwrap();
694 assert_eq!(s.topics, vec!["lane/a".to_string(), "lane/b".to_string()]);
695}
696
697/// `board compact --keep-since <keep> --expire-cursors`, optionally with an injected fault.
698fn compact_cli(root: &Path, keep: u64, fault: Option<&str>) -> Output {
699 let mut c = Command::new(BIN);
700 c.arg("board")
701 .arg("--board-root")
702 .arg(root)
703 .args([
704 "compact",
705 "--keep-since",
706 &keep.to_string(),
707 "--expire-cursors",
708 ])
709 .env_remove("SYNAPSE_COORD_FAULT")
710 .env_remove("SYNAPSE_BOARD_ID")
711 .env_remove("SYNAPSE_BOARD_SESSION")
712 .env_remove("CRUMB_SESSION")
713 .env_remove("SYNAPSE_BOARD_BOOT_ID")
714 .stdin(Stdio::null())
715 .stdout(Stdio::piped())
716 .stderr(Stdio::piped());
717 if let Some(p) = fault {
718 c.env("SYNAPSE_COORD_FAULT", p);
719 }
720 c.output().unwrap()
721}
722
723#[test]
724fn r5_compaction_retry_after_a_failed_expiration_sync_refuses_with_the_journal_unchanged() {
725 let (f, b) = fx("r5-compact");
726 b.register("sa", "alpha", None).unwrap();
727 b.register("sb", "beta", None).unwrap();
728 let first = post(&b, "sa", &["beta"], "e1").unwrap();
729 assert_eq!(b.deliver("sb", 1, Resume::Acked).unwrap().events.len(), 1);
730 b.ack("sb", first).unwrap();
731 for i in 2..=4 {
732 post(&b, "sa", &["beta"], &format!("e{i}")).unwrap();
733 }
734 // beta (acked 1) lags behind keep_since 3. Every directory sync fails (EIO): the first
735 // attempt writes `expired: true` and fails its sync; the retry finds beta already
736 // expired, so it writes no cursor, and must still not publish over that unsynced
737 // expiration.
738 let before = bytes(&f.root);
739 for attempt in 1..=2 {
740 let o = compact_cli(&f.root, 3, Some("dir-sync-eio"));
741 assert_eq!(
742 o.status.code(),
743 Some(1),
744 "attempt {attempt}: {} {}",
745 String::from_utf8_lossy(&o.stdout),
746 String::from_utf8_lossy(&o.stderr)
747 );
748 assert_eq!(
749 summary(&o).str_of("error").as_deref(),
750 Some("Io"),
751 "attempt {attempt}"
752 );
753 assert_eq!(
754 bytes(&f.root),
755 before,
756 "attempt {attempt}: journal.log and journal.idx must be unchanged"
757 );
758 }
759 // Control: with the fault gone, the compaction runs. beta's expiration was written by
760 // the first attempt (so this run expires nobody new) and is flushed before publishing.
761 let s = ok_cli(&compact_cli(&f.root, 3, None));
762 assert_eq!(s.get("expired"), Some(&J::Arr(vec![])), "{s:?}");
763 assert_eq!(b.bounds().unwrap(), (3, 4));
764 assert!(b.cursor("beta").unwrap().expired);
765}
766
767// ---------------------------------------------------------------------------------------
768// R6: every durable mutator reconciles a pending root sync.
769
770#[test]
771fn r6_register_retry_with_the_root_sync_still_failing_is_an_error() {
772 let (f, b) = fx("r6-register");
773 if is_superuser("r6_register_retry", &f.root) {
774 return;
775 }
776 let pending = f.root.join("dirsync.pending");
777 chmod(&f.root, 0o300);
778 // The first call creates agents/ and fails the root sync; the retry finds agents/
779 // there and must flush the root again (still failing) before writing a binding.
780 let first = b.register("sa", "alpha", None);
781 let retry = b.register("sa", "alpha", None);
782 let marked = fs::symlink_metadata(&pending).is_ok();
783 chmod(&f.root, 0o755);
784 assert!(is_io(&first), "first: expected Io, got {first:?}");
785 assert!(
786 is_io(&retry),
787 "retry with the root sync still failing: expected Io, got {retry:?}"
788 );
789 assert!(marked, "the retry marker is kept while the sync fails");
790 let r = b.register("sa", "alpha", None).unwrap();
791 assert_eq!(r.me.tag, "alpha");
792 assert!(
793 fs::symlink_metadata(&pending).is_err(),
794 "the successful root sync clears the marker"
795 );
796 assert_eq!(b.whoami("sa").unwrap().tag, "alpha");
797}
798
799#[test]
800fn r6_first_read_with_a_pending_root_sync_still_failing_is_an_error() {
801 let (f, b) = fx("r6-cursor");
802 if is_superuser("r6_first_read", &f.root) {
803 return;
804 }
805 b.register("sa", "alpha", None).unwrap();
806 b.register("sb", "beta", None).unwrap();
807 post(&b, "sa", &["beta"], "for beta").unwrap();
808 // An earlier root change whose sync failed (the marker is what that failure leaves).
809 let pending = f.root.join("dirsync.pending");
810 fs::write(&pending, b"").unwrap();
811 chmod(&f.root, 0o300);
812 // beta's first read creates its durable cursor under cursors/, which exists: the root
813 // must be flushed first, and that still fails.
814 let first = b.deliver("sb", 10, Resume::Acked);
815 let retry = b.deliver("sb", 10, Resume::Acked);
816 chmod(&f.root, 0o755);
817 assert!(is_io(&first), "first: expected Io, got {first:?}");
818 assert!(is_io(&retry), "retry: expected Io, got {retry:?}");
819 assert!(!b.cursor("beta").unwrap().exists, "no cursor was created");
820 assert_eq!(b.deliver("sb", 10, Resume::Acked).unwrap().events.len(), 1);
821 assert!(fs::symlink_metadata(&pending).is_err());
822 assert!(b.cursor("beta").unwrap().exists);
823}
824
825// ---------------------------------------------------------------------------------------
826// Round 12 helpers.
827
828/// The board CLI with the inherited test variables removed and `env` applied (no boot id
829/// override unless `env` sets one).
830fn cli_cmd(root: &Path, session: Option<&str>, args: &[&str], env: &[(&str, &str)]) -> Command {
831 let mut c = Command::new(BIN);
832 c.arg("board").arg("--board-root").arg(root);
833 if let Some(s) = session {
834 c.arg("--session").arg(s);
835 }
836 c.args(args)
837 .env_remove("SYNAPSE_COORD_FAULT")
838 .env_remove("SYNAPSE_COORD_PAUSE_DIR")
839 .env_remove("SYNAPSE_BOARD_ID")
840 .env_remove("SYNAPSE_BOARD_SESSION")
841 .env_remove("CRUMB_SESSION")
842 .env_remove("SYNAPSE_BOARD_BOOT_ID")
843 .stdin(Stdio::null())
844 .stdout(Stdio::piped())
845 .stderr(Stdio::piped());
846 for (k, v) in env {
847 c.env(k, v);
848 }
849 c
850}
851
852fn cli(root: &Path, session: Option<&str>, args: &[&str], env: &[(&str, &str)]) -> Output {
853 cli_cmd(root, session, args, env).output().unwrap()
854}
855
856fn show(o: &Output) -> String {
857 format!(
858 "exit {:?}: {} {}",
859 o.status.code(),
860 String::from_utf8_lossy(&o.stdout),
861 String::from_utf8_lossy(&o.stderr)
862 )
863}
864
865/// Exit status 1 with an `Io` failure summary (no receipt).
866fn assert_io_cli(o: &Output, what: &str) {
867 assert_eq!(o.status.code(), Some(1), "{what}: {}", show(o));
868 assert_eq!(
869 summary(o).str_of("error").as_deref(),
870 Some("Io"),
871 "{what}: {}",
872 show(o)
873 );
874}
875
876// ---------------------------------------------------------------------------------------
877// N3: an empty or missing journal never erases what journal.idx proves committed.
878
879/// `journal.log` cut to zero bytes (`empty`) or removed; `journal.idx` left intact.
880fn lose_journal(root: &Path, empty: bool) {
881 let jp = root.join("journal.log");
882 if empty {
883 fs::write(&jp, b"").unwrap();
884 } else {
885 fs::remove_file(&jp).unwrap();
886 }
887}
888
889/// The journal (None when missing), the table and the boot record, byte for byte.
890type BoardFiles = (Option<Vec<u8>>, Vec<u8>, Option<Vec<u8>>);
891
892fn files(root: &Path) -> BoardFiles {
893 (
894 fs::read(root.join("journal.log")).ok(),
895 fs::read(root.join("journal.idx")).unwrap(),
896 fs::read(root.join("boot")).ok(),
897 )
898}
899
900#[test]
901fn n3_same_boot_empty_or_missing_journal_is_refused_with_the_table_kept() {
902 for empty in [true, false] {
903 let (f, b) = fx(if empty { "n3-empty" } else { "n3-missing" });
904 b.register("sa", "alpha", None).unwrap();
905 for i in 1..=3 {
906 assert_eq!(post(&b, "sa", &[], &format!("event {i}")).unwrap(), i);
907 }
908 lose_journal(&f.root, empty);
909 let before = files(&f.root);
910 assert_eq!(before.1.len(), 192, "the intact three-entry table");
911 for attempt in 1..=2 {
912 let r = b.recover();
913 assert!(
914 is_corrupt(&r),
915 "empty={empty} attempt {attempt}: expected Corrupt, got {r:?}"
916 );
917 assert_eq!(
918 files(&f.root),
919 before,
920 "empty={empty} attempt {attempt}: both files unchanged"
921 );
922 }
923 // A post runs the same recovery: refused, so id 1 is never handed out again.
924 let r = post(&b, "sa", &[], "would reuse id 1");
925 assert!(
926 is_corrupt(&r),
927 "empty={empty} post: expected Corrupt, got {r:?}"
928 );
929 assert_eq!(
930 files(&f.root),
931 before,
932 "empty={empty}: the post wrote nothing"
933 );
934 }
935}
936
937#[test]
938fn n3_boot_rebuild_refuses_an_empty_or_missing_journal_with_the_table_kept() {
939 for empty in [true, false] {
940 let f = reboot_fixture(if empty {
941 "n3-boot-empty"
942 } else {
943 "n3-boot-missing"
944 });
945 lose_journal(&f.root, empty);
946 let before = files(&f.root);
947 assert_eq!(before.1.len(), 192, "the intact three-entry table");
948 for attempt in 1..=2 {
949 let o = board_cli(&f.root, None, &["recover"], "test-boot-two");
950 assert_eq!(
951 o.status.code(),
952 Some(2),
953 "empty={empty} attempt {attempt}: {}",
954 show(&o)
955 );
956 assert_eq!(
957 summary(&o).str_of("error").as_deref(),
958 Some("Corrupt"),
959 "empty={empty} attempt {attempt}"
960 );
961 assert_eq!(
962 files(&f.root),
963 before,
964 "empty={empty} attempt {attempt}: journal, table and boot record unchanged"
965 );
966 }
967 let o = board_cli(
968 &f.root,
969 Some("sa"),
970 &[
971 "post",
972 "--thread",
973 "t",
974 "--topic",
975 "lane/x",
976 "--text",
977 "would reuse id 1",
978 ],
979 "test-boot-two",
980 );
981 assert_eq!(o.status.code(), Some(2), "empty={empty} post: {}", show(&o));
982 assert_eq!(
983 files(&f.root),
984 before,
985 "empty={empty}: the post wrote nothing"
986 );
987 }
988}
989
990/// `board compact --keep-since <keep>` killed between its two renames: the new journal
991/// generation is in place, `journal.idx` is still the old one.
992fn compact_cut_between_renames(root: &Path, keep: u64, boot: Option<&str>) {
993 let keep = keep.to_string();
994 let mut env = vec![("SYNAPSE_COORD_FAULT", "compact-between-renames")];
995 if let Some(b) = boot {
996 env.push(("SYNAPSE_BOARD_BOOT_ID", b));
997 }
998 let o = cli(root, None, &["compact", "--keep-since", &keep], &env);
999 assert_eq!(o.status.code(), Some(86), "{}", show(&o));
1000}
1001
1002#[test]
1003fn n3_control_a_compaction_cut_between_its_renames_still_recovers() {
1004 // Same boot: the table of the old generation is rebuilt from the new journal.
1005 let (f, b) = fx("n3-cut");
1006 b.register("sa", "alpha", None).unwrap();
1007 for i in 1..=3 {
1008 post(&b, "sa", &[], &format!("event {i}")).unwrap();
1009 }
1010 compact_cut_between_renames(&f.root, 2, None);
1011 let r = b.recover().unwrap();
1012 assert!(r.table_rebuilt, "{r:?}");
1013 assert_eq!(r.torn_tail_at, None, "nothing cut: {r:?}");
1014 assert_eq!(b.bounds().unwrap(), (2, 3));
1015 assert!(b.check().unwrap().ok());
1016 assert_eq!(post(&b, "sa", &[], "event 4").unwrap(), 4, "no id reused");
1017 // After a reboot: the rebuild from offset 0 accepts the new generation too.
1018 let g = reboot_fixture("n3-cut-boot");
1019 compact_cut_between_renames(&g.root, 2, Some("test-boot-one"));
1020 let s = ok_cli(&board_cli(&g.root, None, &["recover"], "test-boot-two"));
1021 assert_eq!(s.get("rebuilt_after_boot"), Some(&J::True), "{s:?}");
1022 assert_eq!(s.get("torn_tail_at"), Some(&J::Null), "nothing cut: {s:?}");
1023 assert_eq!(
1024 fs::metadata(g.root.join("journal.idx")).unwrap().len(),
1025 128,
1026 "events 2 and 3 committed"
1027 );
1028 ok_cli(&board_cli(&g.root, None, &["check"], "test-boot-two"));
1029}
1030
1031#[test]
1032fn n3_a_generation_mismatch_rebuild_must_reach_the_tables_last_committed_id() {
1033 // A cut compaction leaves the new journal (events 2 and 3) under the old table, which
1034 // names event 3 committed. A journal that then ends on the boundary before event 3 has
1035 // lost it: the rebuild must not accept that boundary (and hand id 3 out again).
1036 let (f, b) = fx("n3-cut-short");
1037 b.register("sa", "alpha", None).unwrap();
1038 for i in 1..=3 {
1039 post(&b, "sa", &[], &format!("event {i}")).unwrap();
1040 }
1041 compact_cut_between_renames(&f.root, 2, None);
1042 truncate_journal_before_frame(&f.root, 1);
1043 let before = files(&f.root);
1044 for attempt in 1..=2 {
1045 let r = b.recover();
1046 assert!(
1047 is_corrupt(&r),
1048 "attempt {attempt}: expected Corrupt, got {r:?}"
1049 );
1050 assert_eq!(files(&f.root), before, "attempt {attempt}: unchanged");
1051 }
1052 let r = post(&b, "sa", &[], "would reuse id 3");
1053 assert!(is_corrupt(&r), "post: expected Corrupt, got {r:?}");
1054 assert_eq!(files(&f.root), before);
1055}
1056
1057// ---------------------------------------------------------------------------------------
1058// N4: a first delivery is not a success over an unsynced durable cursor.
1059
1060#[test]
1061fn n4_first_delivery_retry_with_the_cursor_dir_sync_still_failing_is_an_error() {
1062 let (f, b) = fx("n4-first");
1063 if is_superuser("n4_first_delivery_retry", &f.root) {
1064 return;
1065 }
1066 b.register("sa", "alpha", None).unwrap();
1067 b.register("sb", "beta", None).unwrap();
1068 post(&b, "sa", &["beta"], "one").unwrap();
1069 // The writer created cursors/; beta never read, so it has no durable cursor yet.
1070 assert!(fs::symlink_metadata(f.root.join("cursors/beta.json")).is_err());
1071 chmod(&f.root.join("cursors"), 0o300);
1072 // The first delivery renames beta's cursor into place, then fails its directory sync.
1073 // The retry finds the cursor there: it must flush it again, and that still fails.
1074 let first = b.deliver("sb", 10, Resume::Acked);
1075 let retry = b.deliver("sb", 10, Resume::Acked);
1076 chmod(&f.root.join("cursors"), 0o755);
1077 assert!(is_io(&first), "first: expected Io, got {first:?}");
1078 assert!(
1079 is_io(&retry),
1080 "retry with the sync still failing: expected Io, got {retry:?}"
1081 );
1082 // Repaired: the same retry flushes the cursor and delivers.
1083 let r = b.deliver("sb", 10, Resume::Acked).unwrap();
1084 assert_eq!(r.events.len(), 1, "{r:?}");
1085 let c = b.cursor("beta").unwrap();
1086 assert!(c.exists && c.acked == 0, "{c:?}");
1087}
1088
1089#[test]
1090fn n4_control_a_delivery_with_nothing_pending_needs_no_cursor_dir_sync() {
1091 let (f, b) = fx("n4-clean");
1092 if is_superuser("n4_control_clean_delivery", &f.root) {
1093 return;
1094 }
1095 b.register("sa", "alpha", None).unwrap();
1096 b.register("sb", "beta", None).unwrap();
1097 post(&b, "sa", &["beta"], "one").unwrap();
1098 assert_eq!(b.deliver("sb", 10, Resume::Acked).unwrap().events.len(), 1);
1099 let two = post(&b, "sa", &["beta"], "two").unwrap();
1100 // beta's cursor was flushed by its first delivery: a later delivery owes no directory
1101 // sync, so an unreadable cursors/ does not fail it.
1102 chmod(&f.root.join("cursors"), 0o300);
1103 let r = b.deliver("sb", 10, Resume::Delivered);
1104 chmod(&f.root.join("cursors"), 0o755);
1105 let ids: Vec<u64> = r.unwrap().events.iter().map(|d| d.event.id).collect();
1106 assert_eq!(ids, vec![two]);
1107}
1108
1109// ---------------------------------------------------------------------------------------
1110// N5: an earlier root sync never clears a later publication's dirsync.pending.
1111
1112/// alpha posts three events to beta, beta reads and acknowledges them all.
1113fn n5_board(name: &str) -> (Fx, Board) {
1114 let (f, b) = fx(name);
1115 b.register("sa", "alpha", None).unwrap();
1116 b.register("sb", "beta", None).unwrap();
1117 for i in 1..=3 {
1118 post(&b, "sa", &["beta"], &format!("e{i}")).unwrap();
1119 }
1120 assert_eq!(b.deliver("sb", 10, Resume::Acked).unwrap().events.len(), 3);
1121 b.ack("sb", 3).unwrap();
1122 (f, b)
1123}
1124
1125fn wait_for(p: &Path, child: &mut std::process::Child, what: &str) {
1126 let t0 = std::time::Instant::now();
1127 while fs::symlink_metadata(p).is_err() {
1128 if let Some(st) = child.try_wait().unwrap() {
1129 panic!("{what}: exited ({st}) before reaching the barrier");
1130 }
1131 assert!(
1132 t0.elapsed() < std::time::Duration::from_secs(30),
1133 "{what}: never reached the barrier"
1134 );
1135 std::thread::sleep(std::time::Duration::from_millis(5));
1136 }
1137}
1138
1139#[test]
1140fn n5_a_paused_root_sync_never_clears_a_later_failed_publication() {
1141 // The reviewer's interleaving, deterministic through the test barrier:
1142 // A (beta's read) reconciles a pending marker: its root fsync succeeds and it pauses
1143 // before clearing the marker;
1144 // B (a compaction) publishes a new generation and its root sync fails (EIO), so its
1145 // marker must stay;
1146 // A resumes;
1147 // C (a post with every directory sync failing) must then sync the root and fail.
1148 let (f, b) = n5_board("n5-race");
1149 let sig = scratch("n5-race-sig");
1150 fs::create_dir_all(&sig.root).unwrap();
1151 let pending = f.root.join("dirsync.pending");
1152 // An earlier root change whose sync failed.
1153 fs::write(&pending, b"").unwrap();
1154 let sigdir = sig.root.to_str().unwrap().to_string();
1155 let mut a = cli_cmd(
1156 &f.root,
1157 Some("sb"),
1158 &["read"],
1159 &[
1160 ("SYNAPSE_COORD_FAULT", "pause-after-root-sync"),
1161 ("SYNAPSE_COORD_PAUSE_DIR", &sigdir),
1162 ],
1163 )
1164 .spawn()
1165 .unwrap();
1166 wait_for(&sig.root.join("ready"), &mut a, "reader A");
1167 let mut bp = cli_cmd(
1168 &f.root,
1169 None,
1170 &["compact", "--keep-since", "2"],
1171 &[("SYNAPSE_COORD_FAULT", "compact-root-sync-eio")],
1172 )
1173 .spawn()
1174 .unwrap();
1175 // B must not get through its publication while A is between its sync and its clear.
1176 let t0 = std::time::Instant::now();
1177 let mut b_done_while_a_paused = false;
1178 while t0.elapsed() < std::time::Duration::from_secs(3) {
1179 if bp.try_wait().unwrap().is_some() {
1180 b_done_while_a_paused = true;
1181 break;
1182 }
1183 std::thread::sleep(std::time::Duration::from_millis(20));
1184 }
1185 fs::write(sig.root.join("go"), b"").unwrap();
1186 let ao = a.wait_with_output().unwrap();
1187 let bo = bp.wait_with_output().unwrap();
1188 assert!(ao.status.success(), "reader A: {}", show(&ao));
1189 assert_io_cli(&bo, "compaction B");
1190 let marked = fs::symlink_metadata(&pending).is_ok();
1191 let co = cli(
1192 &f.root,
1193 Some("sa"),
1194 &["post", "--thread", "t", "--topic", "lane/x", "--text", "C"],
1195 &[("SYNAPSE_COORD_FAULT", "dir-sync-eio")],
1196 );
1197 println!(
1198 "B finished while A paused: {b_done_while_a_paused}; marker after A and B: {marked}; C: {}",
1199 show(&co)
1200 );
1201 assert_io_cli(&co, "post C over B's unsynced publication");
1202 assert!(marked, "B's failed publication keeps dirsync.pending");
1203 assert!(
1204 !b_done_while_a_paused,
1205 "B published while A was between its root sync and its marker removal"
1206 );
1207 // Control: with the root sync working, the next post flushes and is acknowledged.
1208 assert_eq!(b.bounds().unwrap(), (2, 3), "B's generation is in place");
1209 let s = ok_cli(&post_cli(&f.root, "after the repair", None));
1210 assert_eq!(s.get("id"), Some(&J::Num(b"4".to_vec())), "{s:?}");
1211 assert!(fs::symlink_metadata(&pending).is_err());
1212}
1213
1214#[test]
1215fn n5_control_a_failed_publication_is_cleared_only_by_a_successful_root_sync() {
1216 let (f, b) = n5_board("n5-serial");
1217 let pending = f.root.join("dirsync.pending");
1218 let o = cli(
1219 &f.root,
1220 None,
1221 &["compact", "--keep-since", "2"],
1222 &[("SYNAPSE_COORD_FAULT", "compact-root-sync-eio")],
1223 );
1224 assert_io_cli(&o, "compaction");
1225 assert!(fs::symlink_metadata(&pending).is_ok());
1226 // A reader and a post whose root sync fails: each is an error and the marker stays.
1227 for attempt in 1..=2 {
1228 let o = cli(
1229 &f.root,
1230 Some("sb"),
1231 &["read"],
1232 &[("SYNAPSE_COORD_FAULT", "dir-sync-eio")],
1233 );
1234 assert_io_cli(&o, &format!("read attempt {attempt}"));
1235 assert!(fs::symlink_metadata(&pending).is_ok(), "attempt {attempt}");
1236 let o = post_cli(&f.root, "not acknowledged", Some("dir-sync-eio"));
1237 assert_io_cli(&o, &format!("post attempt {attempt}"));
1238 assert!(fs::symlink_metadata(&pending).is_ok(), "attempt {attempt}");
1239 }
1240 // A reader whose root sync succeeds discharges the marker; the next post needs none.
1241 let o = cli(&f.root, Some("sb"), &["read"], &[]);
1242 assert!(o.status.success(), "{}", show(&o));
1243 assert!(fs::symlink_metadata(&pending).is_err());
1244 let s = ok_cli(&post_cli(&f.root, "e4", None));
1245 assert_eq!(s.get("id"), Some(&J::Num(b"4".to_vec())), "{s:?}");
1246 assert_eq!(b.bounds().unwrap(), (2, 4));
1247}
1248
1249// Round 13 (#928 review P1): a durability marker whose lookup fails (anything but
1250// NotFound) still owes its flush; a failed lookup must never read as "nothing pending".
1251
1252fn cli_with_fault(root: &Path, session: &str, args: &[&str], fault: Option<&str>) -> Output {
1253 let mut c = Command::new(BIN);
1254 c.arg("board")
1255 .arg("--board-root")
1256 .arg(root)
1257 .arg("--session")
1258 .arg(session)
1259 .args(args)
1260 .env_remove("SYNAPSE_COORD_FAULT")
1261 .env_remove("SYNAPSE_BOARD_ID")
1262 .env_remove("SYNAPSE_BOARD_SESSION")
1263 .env_remove("CRUMB_SESSION")
1264 .env_remove("SYNAPSE_BOARD_BOOT_ID")
1265 .stdin(Stdio::null())
1266 .stdout(Stdio::piped())
1267 .stderr(Stdio::piped());
1268 if let Some(p) = fault {
1269 c.env("SYNAPSE_COORD_FAULT", p);
1270 }
1271 c.output().unwrap()
1272}
1273
1274#[test]
1275fn r13_unobservable_cursor_marker_is_not_a_flushed_cursor() {
1276 let (f, b) = fx("r13-cursor");
1277 if is_superuser("r13_unobservable_cursor_marker", &f.root) {
1278 return;
1279 }
1280 b.register("sa", "alpha", None).unwrap();
1281 b.register("sb", "beta", None).unwrap();
1282 post(&b, "sa", &["beta"], "one").unwrap();
1283 let marker = f.root.join("cursors/beta.unsynced");
1284 chmod(&f.root.join("cursors"), 0o300);
1285 // First delivery: beta's cursor is renamed into place, its directory sync fails, the
1286 // marker stays (positive control for the obligation).
1287 let first = cli_with_fault(&f.root, "sb", &["read", "--limit", "10"], None);
1288 // The marker cannot be looked up (EIO on that one stat) while the sync still fails.
1289 let blind = cli_with_fault(
1290 &f.root,
1291 "sb",
1292 &["read", "--limit", "10"],
1293 Some("marker-stat-eio:beta.unsynced"),
1294 );
1295 chmod(&f.root.join("cursors"), 0o755);
1296 assert!(
1297 !first.status.success(),
1298 "first delivery must fail: {first:?}"
1299 );
1300 assert!(
1301 !blind.status.success(),
1302 "a delivery that cannot see its cursor marker returned success: {} {}",
1303 String::from_utf8_lossy(&blind.stdout),
1304 String::from_utf8_lossy(&blind.stderr)
1305 );
1306 assert!(fs::symlink_metadata(&marker).is_ok(), "marker must be kept");
1307 // Repaired directory, no injection: the retry flushes and clears the marker.
1308 let ok = cli_with_fault(&f.root, "sb", &["read", "--limit", "10"], None);
1309 assert!(ok.status.success(), "repaired retry: {ok:?}");
1310 assert!(
1311 fs::symlink_metadata(&marker).is_err(),
1312 "marker cleared after the flush"
1313 );
1314}
1315
1316#[test]
1317fn r13_unobservable_root_marker_gives_no_receipt() {
1318 let (f, b) = fx("r13-root");
1319 b.register("sa", "alpha", None).unwrap();
1320 for i in 1..=4 {
1321 post(&b, "sa", &[], &format!("e{i}")).unwrap();
1322 }
1323 // A compaction whose final root sync fails leaves dirsync.pending.
1324 let o = compact_cli(&f.root, 3, Some("compact-root-sync-eio"));
1325 assert!(
1326 !o.status.success(),
1327 "compaction with a failed root sync: {o:?}"
1328 );
1329 let pending = f.root.join("dirsync.pending");
1330 assert!(fs::symlink_metadata(&pending).is_ok());
1331 // A post that cannot look the marker up must not acknowledge anything.
1332 let blind = cli_with_fault(
1333 &f.root,
1334 "sa",
1335 &[
1336 "post", "--thread", "t", "--topic", "lane/x", "--text", "blind",
1337 ],
1338 Some("marker-stat-eio:dirsync.pending"),
1339 );
1340 assert!(
1341 !blind.status.success(),
1342 "a post that cannot see dirsync.pending returned a receipt: {}",
1343 String::from_utf8_lossy(&blind.stdout)
1344 );
1345 assert!(
1346 fs::symlink_metadata(&pending).is_ok(),
1347 "marker must be kept"
1348 );
1349 // Control: without the injection the post flushes the root and clears the marker.
1350 let ok = cli_with_fault(
1351 &f.root,
1352 "sa",
1353 &[
1354 "post", "--thread", "t", "--topic", "lane/x", "--text", "seen",
1355 ],
1356 None,
1357 );
1358 assert!(ok.status.success(), "control post: {ok:?}");
1359 assert!(fs::symlink_metadata(&pending).is_err(), "marker cleared");
1360}
1361
1362// ---------------------------------------------------------------------------------------
1363// Round 14 (#928 review): a lookup or listing that fails is never "absent" or "empty".
1364
1365const BOOT_ONE: (&str, &str) = ("SYNAPSE_BOARD_BOOT_ID", "boot-one");
1366const BOOT_TWO: (&str, &str) = ("SYNAPSE_BOARD_BOOT_ID", "boot-two");
1367
1368fn fault(spec: &str) -> (&str, &str) {
1369 ("SYNAPSE_COORD_FAULT", spec)
1370}
1371
1372/// Board of boot `boot-one`: alpha (session sa) posted events 1, 2, 3 to beta (sb).
1373fn r14_beta_board(name: &str) -> Fx {
1374 let f = scratch(name);
1375 ok_cli(&cli(&f.root, None, &["init"], &[BOOT_ONE]));
1376 ok_cli(&cli(
1377 &f.root,
1378 Some("sa"),
1379 &["register", "alpha"],
1380 &[BOOT_ONE],
1381 ));
1382 ok_cli(&cli(
1383 &f.root,
1384 Some("sb"),
1385 &["register", "beta"],
1386 &[BOOT_ONE],
1387 ));
1388 for i in 1..=3 {
1389 let text = format!("e{i}");
1390 ok_cli(&cli(
1391 &f.root,
1392 Some("sa"),
1393 &[
1394 "post", "--thread", "t", "--topic", "lane/x", "--to", "beta", "--text", &text,
1395 ],
1396 &[BOOT_ONE],
1397 ));
1398 }
1399 f
1400}
1401
1402/// Derived-index loss as after a power loss: beta's inbox index loses its last id (the
1403/// journal and `journal.idx` are intact), the model of tests/board_cli.rs.
1404fn lose_last_inbox_id(root: &Path) {
1405 let ip = root.join("inbox/beta.idx");
1406 let b = fs::read(&ip).unwrap();
1407 assert_eq!(b.len(), 24, "three ids");
1408 fs::write(&ip, &b[..16]).unwrap();
1409}
1410
1411/// The event ids `read --mine --peek` returns to beta.
1412fn beta_reads(root: &Path, env: &[(&str, &str)]) -> Vec<i64> {
1413 let o = cli(
1414 root,
1415 Some("sb"),
1416 &["read", "--mine", "--peek", "--limit", "100"],
1417 env,
1418 );
1419 ok_cli(&o);
1420 String::from_utf8_lossy(&o.stdout)
1421 .lines()
1422 .filter_map(|l| json::parse(l.as_bytes()))
1423 .filter(|j| j.get("v").is_some())
1424 .map(|j| j.long_of("id", -1))
1425 .collect()
1426}
1427
1428fn boot_record(root: &Path) -> Option<Vec<u8>> {
1429 fs::read(root.join("boot")).ok()
1430}
1431
1432fn assert_cli_error(o: &Output, code: i32, error: &str, what: &str) {
1433 assert_eq!(o.status.code(), Some(code), "{what}: {}", show(o));
1434 assert_eq!(
1435 summary(o).str_of("error").as_deref(),
1436 Some(error),
1437 "{what}: {}",
1438 show(o)
1439 );
1440}
1441
1442#[test]
1443fn r14_b1_journal_lookup_error_on_init_keeps_the_old_boot_and_the_rebuild() {
1444 let f = r14_beta_board("r14-b1");
1445 lose_last_inbox_id(&f.root);
1446 assert_eq!(boot_record(&f.root).as_deref(), Some(&b"boot-one\n"[..]));
1447 // A new boot; init cannot look the journal up. That is not a fresh board.
1448 let o = cli(
1449 &f.root,
1450 None,
1451 &["init"],
1452 &[BOOT_TWO, fault("stat-eio:journal.log")],
1453 );
1454 assert_io_cli(&o, "init with an unobservable journal");
1455 assert_eq!(
1456 boot_record(&f.root).as_deref(),
1457 Some(&b"boot-one\n"[..]),
1458 "boot must not be marked verified"
1459 );
1460 // The next uninjected read of the new boot rebuilds: the acknowledged event 3 is back.
1461 assert_eq!(beta_reads(&f.root, &[BOOT_TWO]), vec![1, 2, 3]);
1462 assert_eq!(boot_record(&f.root).as_deref(), Some(&b"boot-two\n"[..]));
1463}
1464
1465#[test]
1466fn r14_b1_controls_fresh_and_existing_board_init() {
1467 // Fresh board: no journal (NotFound), so init records its boot.
1468 let fresh = scratch("r14-b1-fresh");
1469 ok_cli(&cli(&fresh.root, None, &["init"], &[BOOT_ONE]));
1470 assert_eq!(
1471 boot_record(&fresh.root).as_deref(),
1472 Some(&b"boot-one\n"[..])
1473 );
1474 // Existing board, new boot, ordinary init: the old boot is kept, the next read
1475 // rebuilds the lost inbox id and records the new boot.
1476 let f = r14_beta_board("r14-b1-existing");
1477 lose_last_inbox_id(&f.root);
1478 ok_cli(&cli(&f.root, None, &["init"], &[BOOT_TWO]));
1479 assert_eq!(boot_record(&f.root).as_deref(), Some(&b"boot-one\n"[..]));
1480 assert_eq!(beta_reads(&f.root, &[BOOT_TWO]), vec![1, 2, 3]);
1481 assert_eq!(boot_record(&f.root).as_deref(), Some(&b"boot-two\n"[..]));
1482}
1483
1484#[test]
1485fn r14_b2_unobservable_store_discriminator_never_becomes_a_board() {
1486 let f = scratch("r14-b2");
1487 let board_id = |r: &Path| fs::symlink_metadata(r.join("BOARD_ID")).is_ok();
1488 // Clean root: a board.
1489 let clean = f.root.join("clean");
1490 ok_cli(&cli(&clean, None, &["init"], &[]));
1491 assert!(board_id(&clean));
1492 // Legacy coordination root (dirs/, no STORE_ID): refused, then refused while dirs
1493 // cannot be looked up.
1494 let legacy = f.root.join("legacy");
1495 fs::create_dir_all(legacy.join("dirs")).unwrap();
1496 let o = cli(&legacy, None, &["init"], &[]);
1497 assert_cli_error(&o, 2, "NotABoard", "legacy root");
1498 let o = cli(&legacy, None, &["init"], &[fault("stat-eio:dirs")]);
1499 assert_io_cli(&o, "legacy root, dirs unobservable");
1500 assert!(!board_id(&legacy), "no BOARD_ID in a coordination root");
1501 // Marked store (STORE_ID): the same for its marker, and for both at once.
1502 let marked = f.root.join("marked");
1503 fs::create_dir_all(marked.join("dirs")).unwrap();
1504 fs::write(marked.join("STORE_ID"), b"crumb-coord-store-id/1 x\n").unwrap();
1505 let o = cli(&marked, None, &["init"], &[]);
1506 assert_cli_error(&o, 2, "NotABoard", "marked store");
1507 let o = cli(&marked, None, &["init"], &[fault("stat-eio:STORE_ID")]);
1508 assert_cli_error(&o, 2, "NotABoard", "marked store, STORE_ID unobservable");
1509 let o = cli(
1510 &marked,
1511 None,
1512 &["init"],
1513 &[fault("stat-eio:STORE_ID,stat-eio:dirs")],
1514 );
1515 assert_io_cli(&o, "marked store, both discriminators unobservable");
1516 assert!(!board_id(&marked), "no BOARD_ID in a coordination root");
1517 let only_id = f.root.join("only-id");
1518 fs::create_dir_all(&only_id).unwrap();
1519 fs::write(only_id.join("STORE_ID"), b"crumb-coord-store-id/1 x\n").unwrap();
1520 let o = cli(&only_id, None, &["init"], &[fault("stat-eio:STORE_ID")]);
1521 assert_io_cli(&o, "store marker only, unobservable");
1522 assert!(!board_id(&only_id), "no BOARD_ID in a coordination root");
1523 // An uninspectable root is not adopted either, and opening a board refuses the same.
1524 let blind = f.root.join("blind");
1525 let o = cli(&blind, None, &["init"], &[fault("stat-eio:dirs")]);
1526 assert_io_cli(&o, "clean root, dirs unobservable");
1527 assert!(!board_id(&blind));
1528 let o = cli(&clean, None, &["agents"], &[fault("stat-eio:STORE_ID")]);
1529 assert_io_cli(&o, "open with STORE_ID unobservable");
1530}
1531
1532#[test]
1533fn r14_lost_journal_whose_lookups_fail_creates_no_journal() {
1534 let (f, b) = fx("r14-lost");
1535 b.register("sa", "alpha", None).unwrap();
1536 for i in 1..=3 {
1537 post(&b, "sa", &[], &format!("e{i}")).unwrap();
1538 }
1539 lose_journal(&f.root, false);
1540 let before = files(&f.root);
1541 for spec in ["stat-eio:journal.log", "stat-eio:journal.idx"] {
1542 let o = cli(
1543 &f.root,
1544 Some("sa"),
1545 &[
1546 "post", "--thread", "t", "--topic", "lane/x", "--text", "late",
1547 ],
1548 &[fault(spec)],
1549 );
1550 assert_io_cli(&o, spec);
1551 assert_eq!(files(&f.root), before, "{spec}: no journal created");
1552 }
1553 // Control: observable, the lost journal is refused as in N3, still with nothing created.
1554 let o = cli(
1555 &f.root,
1556 Some("sa"),
1557 &[
1558 "post", "--thread", "t", "--topic", "lane/x", "--text", "late",
1559 ],
1560 &[],
1561 );
1562 assert_cli_error(&o, 2, "Corrupt", "lost journal");
1563 assert_eq!(files(&f.root), before);
1564}
1565
1566#[test]
1567fn r14_reboot_rebuild_that_cannot_list_an_index_dir_keeps_the_old_boot() {
1568 let f = r14_beta_board("r14-rebuild");
1569 // A derived index no event names (gamma never received anything): the rebuild must
1570 // reach it, so it must list inbox/.
1571 let stale = f.root.join("inbox/gamma.idx");
1572 fs::write(&stale, 2u64.to_le_bytes()).unwrap();
1573 for spec in [
1574 "readdir-eio:inbox",
1575 "readdirent-eio:inbox",
1576 "readdir-eio:topics",
1577 "readdirent-eio:topics",
1578 ] {
1579 let o = cli(&f.root, None, &["recover"], &[BOOT_TWO, fault(spec)]);
1580 assert_io_cli(&o, spec);
1581 assert_eq!(
1582 boot_record(&f.root).as_deref(),
1583 Some(&b"boot-one\n"[..]),
1584 "{spec}: boot must not be marked verified"
1585 );
1586 }
1587 let r = ok_cli(&cli(&f.root, None, &["recover"], &[BOOT_TWO]));
1588 assert_eq!(r.get("rebuilt_after_boot"), Some(&J::True), "{r:?}");
1589 assert_eq!(fs::read(&stale).unwrap(), b"", "stale index rewritten");
1590 ok_cli(&cli(&f.root, None, &["check"], &[BOOT_TWO]));
1591 assert_eq!(beta_reads(&f.root, &[BOOT_TWO]), vec![1, 2, 3]);
1592}
1593
1594#[test]
1595fn r14_torn_tail_cleanup_that_cannot_list_keeps_the_tail_and_reuses_no_stale_id() {
1596 let (f, b) = fx("r14-torn");
1597 b.register("sa", "alpha", None).unwrap();
1598 b.register("sb", "beta", None).unwrap();
1599 for i in 1..=3 {
1600 post(&b, "sa", &["beta"], &format!("e{i}")).unwrap();
1601 }
1602 // A writer died after listing id 4 in beta's inbox and before committing it; its frame
1603 // is a torn tail (a 32-byte frame header with 4 body bytes).
1604 let ip = f.root.join("inbox/beta.idx");
1605 let mut ids = fs::read(&ip).unwrap();
1606 ids.extend_from_slice(&4u64.to_le_bytes());
1607 fs::write(&ip, &ids).unwrap();
1608 let jp = f.root.join("journal.log");
1609 let mut j = fs::read(&jp).unwrap();
1610 j.extend_from_slice(&[32, 0, 0, 0, 1, 2, 3, 4, b'{', b'"', b'v', b'"']);
1611 fs::write(&jp, &j).unwrap();
1612 let args = [
1613 "post", "--thread", "t", "--topic", "lane/y", "--text", "next",
1614 ];
1615 for spec in ["readdir-eio:inbox", "readdirent-eio:inbox"] {
1616 let o = cli(&f.root, Some("sa"), &args, &[fault(spec)]);
1617 assert_io_cli(&o, spec);
1618 assert_eq!(
1619 fs::read(&jp).unwrap(),
1620 j,
1621 "{spec}: torn tail kept for the retry"
1622 );
1623 }
1624 // The retry cleans the stale id, cuts the tail and hands id 4 to a post beta is not
1625 // addressed by: beta must not receive it.
1626 let s = ok_cli(&cli(&f.root, Some("sa"), &args, &[]));
1627 assert_eq!(s.long_of("id", -1), 4, "{s:?}");
1628 assert_eq!(beta_reads(&f.root, &[]), vec![1, 2, 3]);
1629 assert!(b.check().unwrap().ok(), "{:?}", b.check().unwrap().problems);
1630}
1631
1632#[test]
1633fn r14_trim_that_cannot_list_is_not_a_successful_compaction() {
1634 let (f, b) = fx("r14-trim");
1635 b.register("sa", "alpha", None).unwrap();
1636 for i in 1..=4 {
1637 post(&b, "sa", &[], &format!("e{i}")).unwrap();
1638 }
1639 let o = compact_cli(&f.root, 3, Some("readdir-eio:topics"));
1640 assert_io_cli(&o, "compaction whose trim cannot list topics/");
1641 // The new generation was published (durable) before the trim; readers skip the ids
1642 // below the base that the topic index still holds.
1643 assert_eq!(b.bounds().unwrap(), (3, 4));
1644 assert!(b.check().unwrap().ok(), "{:?}", b.check().unwrap().problems);
1645 let topic_ids = |root: &Path| -> Vec<u64> {
1646 let mut v = Vec::new();
1647 for e in fs::read_dir(root.join("topics")).unwrap() {
1648 let p = e.unwrap().path();
1649 if p.extension().and_then(|x| x.to_str()) == Some("idx") {
1650 for c in fs::read(&p).unwrap().chunks(8) {
1651 v.push(u64::from_le_bytes(c.try_into().unwrap()));
1652 }
1653 }
1654 }
1655 v
1656 };
1657 assert_eq!(topic_ids(&f.root), vec![1, 2, 3, 4], "untrimmed");
1658 // A later compaction trims everything below its base.
1659 for i in 5..=6 {
1660 post(&b, "sa", &[], &format!("e{i}")).unwrap();
1661 }
1662 let o = compact_cli(&f.root, 5, None);
1663 assert!(o.status.success(), "{}", show(&o));
1664 assert_eq!(topic_ids(&f.root), vec![5, 6]);
1665}
1666
1667#[test]
1668fn r14_check_that_cannot_list_does_not_pass() {
1669 let (f, b) = fx("r14-check");
1670 b.register("sa", "alpha", None).unwrap();
1671 b.register("sb", "beta", None).unwrap();
1672 post(&b, "sa", &["beta"], "one").unwrap();
1673 ok_cli(&cli(&f.root, None, &["check"], &[]));
1674 for spec in [
1675 "readdirent-eio:inbox",
1676 "readdir-eio:inbox",
1677 "readdirent-eio:topics",
1678 "readdir-eio:topics",
1679 ] {
1680 let o = cli(&f.root, None, &["check"], &[fault(spec)]);
1681 assert_cli_error(&o, 2, "CheckFailed", spec);
1682 assert!(
1683 String::from_utf8_lossy(&o.stdout).contains("cannot list"),
1684 "{spec}: {}",
1685 show(&o)
1686 );
1687 }
1688}
1689
1690#[test]
1691fn r14_unlistable_agents_dir_is_no_second_tag() {
1692 let (f, b) = fx("r14-agents");
1693 b.register("sa", "alpha", None).unwrap();
1694 let gamma = f.root.join("agents/gamma.json");
1695 for spec in ["readdir-eio:agents", "readdirent-eio:agents"] {
1696 let o = cli(&f.root, Some("sa"), &["register", "gamma"], &[fault(spec)]);
1697 assert_io_cli(&o, spec);
1698 assert!(fs::symlink_metadata(&gamma).is_err(), "{spec}: no binding");
1699 let o = cli(&f.root, Some("sa"), &["whoami"], &[fault(spec)]);
1700 assert_io_cli(&o, spec);
1701 }
1702 // Control: the session already holds alpha.
1703 let o = cli(&f.root, Some("sa"), &["register", "gamma"], &[]);
1704 assert_cli_error(&o, 2, "SessionTagged", "second tag");
1705 assert!(fs::symlink_metadata(&gamma).is_err());
1706 assert_eq!(b.whoami("sa").unwrap().tag, "alpha");
1707}
1708
1709fn store_cli(store: &Path, top: &Path, args: &[&str], spec: Option<&str>) -> Output {
1710 let mut c = Command::new(BIN);
1711 c.arg("--store")
1712 .arg(store)
1713 .arg("--top")
1714 .arg(top)
1715 .args(args)
1716 .env_remove("SYNAPSE_COORD_FAULT")
1717 .env_remove("CRUMB_SESSION")
1718 .stdin(Stdio::null())
1719 .stdout(Stdio::piped())
1720 .stderr(Stdio::piped());
1721 if let Some(s) = spec {
1722 c.env("SYNAPSE_COORD_FAULT", s);
1723 }
1724 c.output().unwrap()
1725}
1726
1727#[test]
1728fn r14_unlistable_store_dirs_keeps_presence_and_locks() {
1729 let f = scratch("r14-store");
1730 let top = f.root.join("wa");
1731 fs::create_dir_all(top.join("src")).unwrap();
1732 fs::create_dir_all(top.join("lib")).unwrap();
1733 fs::write(top.join("src/a.c"), "a").unwrap();
1734 fs::write(top.join("lib/b.c"), "b").unwrap();
1735 let store = f.root.join("store/crumb/v1");
1736 let cs = CoordStore::open(&store);
1737 let ws = Workspace::worktree(top.to_str().unwrap(), Holder::default());
1738 for (dir, t) in [("src", "a.c"), ("lib", "b.c")] {
1739 match cs.claim(&ws, "agent-a", dir, t, "work", None).unwrap() {
1740 ClaimOutcome::Claimed { .. } => {}
1741 o => panic!("expected a claim, got {o:?}"),
1742 }
1743 }
1744 let presence = store.join("agents/agent-a.json");
1745 assert!(fs::symlink_metadata(&presence).is_ok());
1746 let close = ["close", "agent-a", "src", "a.c", "modify"];
1747 for spec in ["readdir-eio:dirs", "readdirent-eio:dirs"] {
1748 // Closing a.c must see that agent-a still holds lib/b.c in another record.
1749 let o = store_cli(&store, &top, &close, Some(spec));
1750 assert!(!o.status.success(), "{spec}: {}", show(&o));
1751 assert!(
1752 fs::symlink_metadata(&presence).is_ok(),
1753 "{spec}: presence kept"
1754 );
1755 let o = store_cli(&store, &top, &["sniff", "agent-a", "."], Some(spec));
1756 assert!(!o.status.success(), "{spec}: sniff {}", show(&o));
1757 }
1758 let o = store_cli(
1759 &store,
1760 &top,
1761 &["sniff", "agent-a", "."],
1762 Some("readdir-eio:agents"),
1763 );
1764 assert!(!o.status.success(), "sniff without agents/: {}", show(&o));
1765 let s = cs.sniff(&ws, "agent-a", ".").unwrap();
1766 assert_eq!(s.locks.len(), 2, "both locks still held");
1767 // Control: the uninjected close releases a.c and keeps the presence (b.c is held).
1768 let o = store_cli(&store, &top, &close, None);
1769 assert!(o.status.success(), "{}", show(&o));
1770 assert!(
1771 fs::symlink_metadata(&presence).is_ok(),
1772 "agent-a still holds lib/b.c"
1773 );
1774 assert_eq!(cs.sniff(&ws, "agent-a", ".").unwrap().locks.len(), 1);
1775}
1776
1777#[test]
1778fn r14_unanswerable_target_lookup_refuses_the_key() {
1779 let f = scratch("r14-key");
1780 let top = f.root.join("wa");
1781 fs::create_dir_all(top.join("src/x")).unwrap();
1782 fs::write(top.join("src/x/a.c"), "a").unwrap();
1783 let ws = Workspace::worktree(top.to_str().unwrap(), Holder::default());
1784 // Controls: an existing file keys from its directory; a path through a regular file
1785 // (ENOTDIR) is absent for every process and keys as written.
1786 assert_eq!(ws.target_key("x/a.c", "src").unwrap(), "src/x/a.c");
1787 assert_eq!(ws.target_key("a.c/z", "src/x").unwrap(), "a.c/z");
1788 // EIO on the lookup: keying it as "x/a.c" would let a second agent, which sees the
1789 // file, hold "src/x/a.c" at the same time.
1790 let store = f.root.join("store/crumb/v1");
1791 let o = store_cli(
1792 &store,
1793 &top,
1794 &["claim", "agent-a", "src", "x/a.c", "work"],
1795 Some("stat-eio:a.c"),
1796 );
1797 assert!(!o.status.success(), "{}", show(&o));
1798 assert!(
1799 !String::from_utf8_lossy(&o.stdout).contains("CLAIMED"),
1800 "{}",
1801 show(&o)
1802 );
1803 let o = store_cli(
1804 &store,
1805 &top,
1806 &["claim", "agent-a", "src", "x/a.c", "work"],
1807 None,
1808 );
1809 assert!(
1810 String::from_utf8_lossy(&o.stdout).contains("CLAIMED src/x/a.c"),
1811 "{}",
1812 show(&o)
1813 );
1814}
1815
1816// ---------------------------------------------------------------------------------------
1817// Round 17 B1: a generation-mismatch rebuild keeps the terminal slots of the old table.
1818
1819/// The reviewer's damaged fixtures (round 17 controls.py), all built from three posted
1820/// events: ids 1, 2 and 3 acknowledged.
1821#[derive(Clone, Copy, Debug)]
1822enum R17 {
1823 /// Cut compaction (new journal 2, 3), old table = two entries and one byte of the
1824 /// third; the journal is intact. Control: recovers, the next post is id 4.
1825 ValidPartial,
1826 /// Cut compaction, intact old table, the journal loses its final frame (event 3).
1827 /// Control: refused.
1828 IntactTableLostFrame,
1829 /// No compaction: same-generation table of two entries and one byte, the journal loses
1830 /// frame 3. Control: refused.
1831 SameGenerationPartialLost,
1832 /// B1: cut compaction, old table = two entries and one byte of the third slot, the
1833 /// journal loses its final frame. The partial slot is the only evidence of event 3.
1834 PartialLost,
1835 /// B1: cut compaction, three whole slots with the third one's checksum broken, the
1836 /// journal loses its final frame.
1837 UndecodableLost,
1838}
1839
1840const R17_ONE: &str = "r17-boot-one";
1841const R17_TWO: &str = "r17-boot-two";
1842
1843fn r17_post(root: &Path, text: &str, boot: &str) -> Output {
1844 cli(
1845 root,
1846 Some("sa"),
1847 &["post", "--thread", "t", "--topic", "lane/x", "--text", text],
1848 &[("SYNAPSE_BOARD_BOOT_ID", boot)],
1849 )
1850}
1851
1852fn r17_fixture(v: R17, reboot: bool) -> Fx {
1853 let f = scratch(&format!("r17-{v:?}-{reboot}"));
1854 let boot = [("SYNAPSE_BOARD_BOOT_ID", R17_ONE)];
1855 ok_cli(&cli(&f.root, None, &["init"], &boot));
1856 ok_cli(&cli(&f.root, Some("sa"), &["register", "alpha"], &boot));
1857 for i in 1..=3 {
1858 let s = ok_cli(&r17_post(&f.root, &format!("event {i}"), R17_ONE));
1859 assert_eq!(s.long_of("id", -1), i, "{v:?}: acknowledged id");
1860 }
1861 let ip = f.root.join("journal.idx");
1862 let table = fs::read(&ip).unwrap();
1863 assert_eq!(table.len(), 192, "{v:?}: three whole entries");
1864 if !matches!(v, R17::SameGenerationPartialLost) {
1865 compact_cut_between_renames(&f.root, 2, Some(R17_ONE));
1866 }
1867 if !matches!(v, R17::ValidPartial) {
1868 // The journal ends exactly on the boundary before its final frame (event 3).
1869 let j = fs::read(f.root.join("journal.log")).unwrap();
1870 let last = frame_offsets(&j).len() - 1;
1871 truncate_journal_before_frame(&f.root, last);
1872 }
1873 match v {
1874 R17::ValidPartial | R17::SameGenerationPartialLost | R17::PartialLost => {
1875 fs::write(&ip, &table[..129]).unwrap();
1876 }
1877 R17::UndecodableLost => {
1878 let mut t = table.clone();
1879 t[191] ^= 0x80;
1880 fs::write(&ip, &t).unwrap();
1881 }
1882 R17::IntactTableLostFrame => {}
1883 }
1884 f
1885}
1886
1887/// Two recoveries and a post, all refused as `Corrupt` (exit 2) with the journal, the
1888/// table and the boot record byte for byte unchanged: no id is handed out again.
1889fn r17_assert_refused(v: R17, reboot: bool) {
1890 let f = r17_fixture(v, reboot);
1891 let boot = if reboot { R17_TWO } else { R17_ONE };
1892 let env = [("SYNAPSE_BOARD_BOOT_ID", boot)];
1893 let before = files(&f.root);
1894 for attempt in 1..=2 {
1895 let o = cli(&f.root, None, &["recover"], &env);
1896 assert_eq!(
1897 o.status.code(),
1898 Some(2),
1899 "{v:?} reboot={reboot} attempt {attempt}: {}",
1900 show(&o)
1901 );
1902 assert_eq!(
1903 summary(&o).str_of("error").as_deref(),
1904 Some("Corrupt"),
1905 "{v:?} reboot={reboot} attempt {attempt}: {}",
1906 show(&o)
1907 );
1908 assert_eq!(
1909 files(&f.root),
1910 before,
1911 "{v:?} reboot={reboot} attempt {attempt}: journal, table and boot record unchanged"
1912 );
1913 }
1914 let o = r17_post(&f.root, "would reuse id 3", boot);
1915 assert_eq!(
1916 o.status.code(),
1917 Some(2),
1918 "{v:?} reboot={reboot} post: {}",
1919 show(&o)
1920 );
1921 assert_eq!(
1922 summary(&o).str_of("error").as_deref(),
1923 Some("Corrupt"),
1924 "{v:?} reboot={reboot} post: {}",
1925 show(&o)
1926 );
1927 assert_eq!(
1928 files(&f.root),
1929 before,
1930 "{v:?} reboot={reboot}: the post wrote nothing"
1931 );
1932}
1933
1934#[test]
1935fn r17_b1_same_boot_cut_compaction_partial_third_slot_with_its_frame_lost_is_refused() {
1936 r17_assert_refused(R17::PartialLost, false);
1937}
1938
1939#[test]
1940fn r17_b1_boot_rebuild_cut_compaction_partial_third_slot_with_its_frame_lost_is_refused() {
1941 r17_assert_refused(R17::PartialLost, true);
1942}
1943
1944#[test]
1945fn r17_b1_same_boot_cut_compaction_undecodable_third_slot_with_its_frame_lost_is_refused() {
1946 r17_assert_refused(R17::UndecodableLost, false);
1947}
1948
1949#[test]
1950fn r17_b1_boot_rebuild_cut_compaction_undecodable_third_slot_with_its_frame_lost_is_refused() {
1951 r17_assert_refused(R17::UndecodableLost, true);
1952}
1953
1954#[test]
1955fn r17_control_intact_table_or_same_generation_with_a_lost_frame_is_refused() {
1956 for reboot in [false, true] {
1957 r17_assert_refused(R17::IntactTableLostFrame, reboot);
1958 r17_assert_refused(R17::SameGenerationPartialLost, reboot);
1959 }
1960}
1961
1962#[test]
1963fn r17_control_cut_compaction_with_a_partial_slot_and_an_intact_journal_recovers() {
1964 // Valid compaction removed a prefix: the new journal holds two frames under a table of
1965 // three slots, and still reaches the last committed id 3.
1966 for reboot in [false, true] {
1967 let v = R17::ValidPartial;
1968 let f = r17_fixture(v, reboot);
1969 let boot = if reboot { R17_TWO } else { R17_ONE };
1970 let env = [("SYNAPSE_BOARD_BOOT_ID", boot)];
1971 let s = ok_cli(&cli(&f.root, None, &["recover"], &env));
1972 assert_eq!(s.get("torn_tail_at"), Some(&J::Null), "nothing cut: {s:?}");
1973 assert_eq!(
1974 fs::metadata(f.root.join("journal.idx")).unwrap().len(),
1975 128,
1976 "reboot={reboot}: events 2 and 3 committed"
1977 );
1978 ok_cli(&cli(&f.root, None, &["check"], &env));
1979 let p = ok_cli(&r17_post(&f.root, "event 4", boot));
1980 assert_eq!(p.long_of("id", -1), 4, "reboot={reboot}: no id reused");
1981 }
1982}