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 / board_cli.rs

753 lines · 23415 bytes Raw Blame History
1//! Board through the real binary (issue #83): concurrent writer processes, crashes at every
2//! fault point, subscriber kill and cursor resume, a lost wake datagram, and hostile files.
3//! Every child runs under a 5 s watchdog (killed and failed past it), like tests/hostile.rs.
4
5use std::collections::BTreeSet;
6use std::fs;
7use std::io::Write;
8use std::os::unix::fs::symlink;
9use std::path::{Path, PathBuf};
10use std::process::{Child, Command, Output, Stdio};
11use std::sync::atomic::{AtomicU32, Ordering};
12use std::time::{Duration, Instant};
13use synapse_coord::json::{self, J};
14
15const BIN: &str = env!("CARGO_BIN_EXE_synapse-coord");
16static N: AtomicU32 = AtomicU32::new(0);
17
18struct Fx {
19 root: PathBuf,
20}
21impl Drop for Fx {
22 fn drop(&mut self) {
23 let _ = fs::remove_dir_all(&self.root);
24 }
25}
26
27fn fx(name: &str) -> Fx {
28 let root = std::env::temp_dir().join(format!(
29 "sb-cli-{name}-{}-{}",
30 std::process::id(),
31 N.fetch_add(1, Ordering::SeqCst)
32 ));
33 let _ = fs::remove_dir_all(&root);
34 let f = Fx { root };
35 let o = run(&f.root, None, &["init"], &[]);
36 assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
37 f
38}
39
40fn cmd(root: &Path, session: Option<&str>, args: &[&str], env: &[(&str, &str)]) -> Command {
41 let mut c = Command::new(BIN);
42 c.arg("board").arg("--board-root").arg(root);
43 if let Some(s) = session {
44 c.arg("--session").arg(s);
45 }
46 c.args(args)
47 .env_remove("SYNAPSE_COORD_FAULT")
48 .env_remove("SYNAPSE_BOARD_ID")
49 .env_remove("SYNAPSE_BOARD_SESSION")
50 .env_remove("CRUMB_SESSION");
51 for (k, v) in env {
52 c.env(k, v);
53 }
54 c.stdin(Stdio::null())
55 .stdout(Stdio::piped())
56 .stderr(Stdio::piped());
57 c
58}
59
60/// Wait for a child under the 5 s watchdog.
61fn finish(mut ch: Child, what: &str) -> Output {
62 let t = Instant::now();
63 loop {
64 if ch.try_wait().unwrap().is_some() {
65 return ch.wait_with_output().unwrap();
66 }
67 if t.elapsed() > Duration::from_secs(5) {
68 let _ = ch.kill();
69 let _ = ch.wait();
70 panic!("{what} hung past the 5 s watchdog");
71 }
72 std::thread::sleep(Duration::from_millis(2));
73 }
74}
75
76fn run(root: &Path, session: Option<&str>, args: &[&str], env: &[(&str, &str)]) -> Output {
77 finish(
78 cmd(root, session, args, env).spawn().unwrap(),
79 &args.join(" "),
80 )
81}
82
83fn lines(o: &Output) -> Vec<J> {
84 String::from_utf8_lossy(&o.stdout)
85 .lines()
86 .map(|l| json::parse(l.as_bytes()).unwrap_or_else(|| panic!("not JSON: {l}")))
87 .collect()
88}
89
90fn num(j: &J, k: &str) -> Option<u64> {
91 match j.get(k) {
92 Some(J::Num(t)) => std::str::from_utf8(t).ok()?.parse().ok(),
93 _ => None,
94 }
95}
96
97fn s(j: &J, k: &str) -> Option<String> {
98 j.str_of(k)
99}
100
101fn summary(o: &Output) -> J {
102 lines(o).pop().expect("a summary line")
103}
104
105fn ok(o: &Output) -> J {
106 assert!(
107 o.status.success(),
108 "exit {:?}: {} {}",
109 o.status.code(),
110 String::from_utf8_lossy(&o.stdout),
111 String::from_utf8_lossy(&o.stderr)
112 );
113 summary(o)
114}
115
116/// A refusal: exit 2 and the named error.
117fn refused(o: &Output, name: &str) {
118 assert_eq!(
119 o.status.code(),
120 Some(2),
121 "{} {}",
122 String::from_utf8_lossy(&o.stdout),
123 String::from_utf8_lossy(&o.stderr)
124 );
125 assert_eq!(s(&summary(o), "error").as_deref(), Some(name));
126}
127
128fn register(f: &Fx, session: &str, tag: &str) {
129 ok(&run(&f.root, Some(session), &["register", tag], &[]));
130}
131
132fn post(f: &Fx, session: &str, text: &str, extra: &[&str]) -> u64 {
133 let mut a = vec!["post", "--thread", "t", "--topic", "lane/x", "--text", text];
134 a.extend_from_slice(extra);
135 num(&ok(&run(&f.root, Some(session), &a, &[])), "id").unwrap()
136}
137
138/// Every event on the board, by id, through the operator view.
139fn all(f: &Fx) -> Vec<(u64, String)> {
140 let o = run(&f.root, None, &["read", "--all", "--limit", "1024"], &[]);
141 let mut v = lines(&o);
142 let sum = v.pop().unwrap();
143 assert_eq!(sum.get("ok"), Some(&J::True), "{:?}", sum);
144 v.iter()
145 .map(|j| (num(j, "id").unwrap(), s(j, "text").unwrap()))
146 .collect()
147}
148
149fn check_ok(f: &Fx) {
150 let o = run(&f.root, None, &["check"], &[]);
151 assert!(
152 o.status.success(),
153 "check: {}",
154 String::from_utf8_lossy(&o.stdout)
155 );
156}
157
158fn concurrent_writers(writers: usize, per: usize) {
159 let f = fx(&format!("conc{writers}"));
160 for w in 0..writers {
161 register(&f, &format!("s{w}"), &format!("w{w}"));
162 }
163 let root = f.root.clone();
164 let handles: Vec<_> = (0..writers)
165 .map(|w| {
166 let root = root.clone();
167 std::thread::spawn(move || {
168 let mut ids = Vec::new();
169 for i in 0..per {
170 let text = format!("w{w}-{i}");
171 let o = finish(
172 cmd(
173 &root,
174 Some(&format!("s{w}")),
175 &[
176 "post", "--thread", "t", "--topic", "lane/x", "--text", &text,
177 ],
178 &[],
179 )
180 .spawn()
181 .unwrap(),
182 "post",
183 );
184 assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
185 ids.push(num(&summary(&o), "id").unwrap());
186 }
187 ids
188 })
189 })
190 .collect();
191 let mut acked = BTreeSet::new();
192 for h in handles {
193 for id in h.join().unwrap() {
194 assert!(acked.insert(id), "id {id} acknowledged twice");
195 }
196 }
197 let total = (writers * per) as u64;
198 assert_eq!(
199 acked,
200 (1..=total).collect::<BTreeSet<_>>(),
201 "no lost, no duplicate id"
202 );
203 let ev = all(&f);
204 assert_eq!(ev.len() as u64, total);
205 let texts: BTreeSet<_> = ev.iter().map(|e| e.1.clone()).collect();
206 assert_eq!(texts.len() as u64, total, "every body exactly once");
207 for (k, (id, _)) in ev.iter().enumerate() {
208 assert_eq!(*id, k as u64 + 1);
209 }
210 check_ok(&f);
211}
212
213#[test]
214fn concurrent_writers_1() {
215 concurrent_writers(1, 24);
216}
217
218#[test]
219fn concurrent_writers_4() {
220 concurrent_writers(4, 12);
221}
222
223#[test]
224fn concurrent_writers_8() {
225 concurrent_writers(8, 8);
226}
227
228#[test]
229fn concurrent_writers_32() {
230 concurrent_writers(32, 4);
231}
232
233/// Crash a post at `point`, then show: every acknowledged event survives, the board checks
234/// clean after the next post, and ids stay contiguous with no duplicate.
235fn crash_at(point: &str) -> (Fx, J) {
236 let f = fx(&format!("crash-{point}"));
237 register(&f, "sa", "alpha");
238 register(&f, "sb", "beta");
239 ok(&run(
240 &f.root,
241 Some("sb"),
242 &["subscribe", "--topic", "lane/x"],
243 &[],
244 ));
245 for i in 1..=3 {
246 assert_eq!(post(&f, "sa", &format!("acked {i}"), &["--to", "beta"]), i);
247 }
248 let o = run(
249 &f.root,
250 Some("sa"),
251 &[
252 "post", "--thread", "t", "--topic", "lane/x", "--to", "beta", "--text", "crashing",
253 ],
254 &[("SYNAPSE_COORD_FAULT", point)],
255 );
256 assert_eq!(
257 o.status.code(),
258 Some(86),
259 "{point}: the post must die at the fault"
260 );
261 assert!(lines(&o).is_empty(), "{point}: no ACK was printed");
262 let after = ok(&run(
263 &f.root,
264 Some("sa"),
265 &[
266 "post", "--thread", "t", "--topic", "lane/x", "--to", "beta", "--text", "after",
267 ],
268 &[],
269 ));
270 let ev = all(&f);
271 for i in 1..=3u64 {
272 assert_eq!(ev[i as usize - 1], (i, format!("acked {i}")), "{point}");
273 }
274 for (k, (id, _)) in ev.iter().enumerate() {
275 assert_eq!(*id, k as u64 + 1, "{point}: contiguous ids");
276 }
277 assert_eq!(ev.last().unwrap().1, "after");
278 check_ok(&f);
279 // the addressed reader sees every surviving event through its inbox index
280 let o = run(
281 &f.root,
282 Some("sb"),
283 &["read", "--mine", "--limit", "100"],
284 &[],
285 );
286 let n = lines(&o).len() - 1;
287 assert_eq!(n, ev.len(), "{point}: inbox index agrees after recovery");
288 (f, after)
289}
290
291#[test]
292fn crash_torn_journal_write_is_cut_and_named() {
293 let (_f, after) = crash_at("torn-journal-write");
294 assert_eq!(num(&after, "id"), Some(4));
295 assert!(
296 num(&after, "torn_tail_at").is_some(),
297 "torn tail named: {after:?}"
298 );
299}
300
301#[test]
302fn crash_before_journal_fsync_adopts_complete_frame() {
303 let (_f, after) = crash_at("before-journal-fsync");
304 // The process died, the kernel kept the page: a complete verifying frame is adopted.
305 assert_eq!(num(&after, "id"), Some(5));
306}
307
308#[test]
309fn crash_after_journal_before_index_repairs_indexes() {
310 let (_f, after) = crash_at("after-journal-before-index");
311 assert_eq!(num(&after, "id"), Some(5));
312}
313
314#[test]
315fn crash_before_table_entry_adopts() {
316 let (_f, after) = crash_at("before-table-entry");
317 assert_eq!(num(&after, "id"), Some(5));
318}
319
320#[test]
321fn crash_before_ack_keeps_committed_event() {
322 let (f, after) = crash_at("before-ack");
323 assert_eq!(num(&after, "id"), Some(5));
324 assert_eq!(all(&f)[3].1, "crashing", "committed before the ACK, kept");
325}
326
327#[test]
328fn crash_between_compaction_renames_rebuilds_table() {
329 let f = fx("crash-compact");
330 register(&f, "sa", "alpha");
331 for i in 1..=6 {
332 post(&f, "sa", &format!("e{i}"), &[]);
333 }
334 let o = run(
335 &f.root,
336 None,
337 &["compact", "--keep-since", "4"],
338 &[("SYNAPSE_COORD_FAULT", "compact-between-renames")],
339 );
340 assert_eq!(o.status.code(), Some(86));
341 // A reader alone heals the cut: writer recovery rebuilds journal.idx, cuts nothing.
342 let g = fx("crash-compact-reader");
343 register(&g, "sa", "alpha");
344 for i in 1..=6 {
345 post(&g, "sa", &format!("e{i}"), &[]);
346 }
347 let og = run(
348 &g.root,
349 None,
350 &["compact", "--keep-since", "4"],
351 &[("SYNAPSE_COORD_FAULT", "compact-between-renames")],
352 );
353 assert_eq!(og.status.code(), Some(86));
354 let ids: Vec<u64> = all(&g).iter().map(|e| e.0).collect();
355 assert_eq!(ids, vec![4, 5, 6]);
356 check_ok(&g);
357 let r = ok(&run(&f.root, None, &["recover"], &[]));
358 assert_eq!(r.get("table_rebuilt"), Some(&J::True), "{r:?}");
359 post(&f, "sa", "e7", &[]);
360 let ev = all(&f);
361 let ids: Vec<u64> = ev.iter().map(|e| e.0).collect();
362 assert_eq!(
363 ids,
364 vec![4, 5, 6, 7],
365 "kept events survive the cut compaction"
366 );
367 check_ok(&f);
368}
369
370#[test]
371fn subscriber_kill_and_cursor_resume_has_no_gap() {
372 let f = fx("resume");
373 register(&f, "sa", "alpha");
374 register(&f, "sb", "beta");
375 ok(&run(
376 &f.root,
377 Some("sb"),
378 &["subscribe", "--thread", "t"],
379 &[],
380 ));
381 for i in 1..=10 {
382 post(&f, "sa", &format!("e{i}"), &[]);
383 }
384 let r = run(&f.root, Some("sb"), &["read", "--limit", "4"], &[]);
385 assert_eq!(lines(&r).len(), 5);
386 ok(&run(&f.root, Some("sb"), &["ack", "4"], &[]));
387 // a watcher takes deliveries, then is killed before it acks
388 let w = cmd(
389 &f.root,
390 Some("sb"),
391 &["watch", "--follow", "1000", "--timeout-ms", "4000"],
392 &[],
393 )
394 .spawn()
395 .unwrap();
396 for i in 11..=13 {
397 post(&f, "sa", &format!("e{i}"), &[]);
398 }
399 std::thread::sleep(Duration::from_millis(150));
400 let mut w = w;
401 w.kill().unwrap();
402 let _ = w.wait();
403 // restart: resume from acked, every unprocessed event comes back, in order, no gap
404 let r = run(&f.root, Some("sb"), &["read", "--limit", "100"], &[]);
405 let mut v = lines(&r);
406 v.pop();
407 let ids: Vec<u64> = v.iter().map(|j| num(j, "id").unwrap()).collect();
408 assert_eq!(ids, (5..=13).collect::<Vec<_>>());
409 ok(&run(&f.root, Some("sb"), &["ack", "13"], &[]));
410 ok(&run(&f.root, Some("sb"), &["ack", "7"], &[])); // idempotent below the cursor
411 let r = run(&f.root, Some("sb"), &["read"], &[]);
412 assert_eq!(lines(&r).len(), 1, "nothing left after the ack");
413}
414
415#[test]
416fn lost_datagram_watch_times_out_and_still_reads() {
417 let f = fx("lostwake");
418 register(&f, "sa", "alpha");
419 register(&f, "sb", "beta");
420 let w = cmd(&f.root, Some("sb"), &["watch", "--timeout-ms", "400"], &[])
421 .spawn()
422 .unwrap();
423 std::thread::sleep(Duration::from_millis(100));
424 let t = Instant::now();
425 let p = ok(&run(
426 &f.root,
427 Some("sa"),
428 &[
429 "post", "--thread", "t", "--topic", "lane/x", "--to", "beta", "--text", "quiet",
430 ],
431 &[("SYNAPSE_COORD_FAULT", "drop-wake")],
432 ));
433 assert_eq!(num(&p, "woke"), Some(0), "the wake was dropped");
434 let o = finish(w, "watch");
435 let sum = ok(&o);
436 assert_eq!(
437 num(&sum, "count"),
438 Some(1),
439 "read after the timeout: {sum:?}"
440 );
441 assert_eq!(num(&sum, "wakes"), Some(0));
442 assert!(t.elapsed() >= Duration::from_millis(200));
443}
444
445#[test]
446fn hostile_inputs_refused_by_name() {
447 let f = fx("hostile");
448 register(&f, "sa", "alpha");
449 register(&f, "sb", "beta");
450 register(&f, "sc", "gamma");
451 post(&f, "sa", "first", &["--to", "beta"]);
452 // oversize text
453 let big = "x".repeat(4097);
454 refused(
455 &run(
456 &f.root,
457 Some("sa"),
458 &["post", "--thread", "t", "--topic", "lane/x", "--text", &big],
459 &[],
460 ),
461 "TooLarge",
462 );
463 // unregistered session
464 refused(
465 &run(&f.root, Some("nobody"), &["read"], &[]),
466 "NotRegistered",
467 );
468 // unauthorised audience: gamma neither addressed nor subscribed sees nothing
469 let r = run(&f.root, Some("sc"), &["read"], &[]);
470 assert_eq!(lines(&r).len(), 1);
471 // wrong mission
472 refused(
473 &run(
474 &f.root,
475 None,
476 &[
477 "--expect-board-id",
478 "00000000000000000000000000000001",
479 "check",
480 ],
481 &[],
482 ),
483 "BoardIdMismatch",
484 );
485 // bogus cursor ids
486 refused(
487 &run(&f.root, Some("sb"), &["read", "--after", "999"], &[]),
488 "CursorAhead",
489 );
490 fs::create_dir_all(f.root.join("cursors")).unwrap();
491 fs::write(
492 f.root.join("cursors/beta.json"),
493 "{\"v\":\"aien-board/1\",\"tag\":\"beta\",\"delivered\":999,\"acked\":0,\"expired\":false}\n",
494 )
495 .unwrap();
496 refused(&run(&f.root, Some("sb"), &["read"], &[]), "BadCursor");
497 fs::remove_file(f.root.join("cursors/beta.json")).unwrap();
498 // truncated frame appended: the next post cuts and names it
499 {
500 let mut j = fs::OpenOptions::new()
501 .append(true)
502 .open(f.root.join("journal.log"))
503 .unwrap();
504 j.write_all(&[40, 0, 0, 0, 1, 2]).unwrap();
505 }
506 assert_eq!(all(&f).len(), 1, "readers ignore the unacknowledged tail");
507 let p = ok(&run(
508 &f.root,
509 Some("sa"),
510 &[
511 "post", "--thread", "t", "--topic", "lane/x", "--text", "second",
512 ],
513 &[],
514 ));
515 assert_eq!(num(&p, "id"), Some(2));
516 assert!(num(&p, "torn_tail_at").is_some());
517 check_ok(&f);
518}
519
520#[test]
521fn foreign_mission_frame_refused() {
522 let a = fx("mission-a");
523 let b = fx("mission-b");
524 for f in [&a, &b] {
525 register(f, "sa", "alpha");
526 post(f, "sa", "same", &[]);
527 }
528 post(&b, "sa", "from b", &[]);
529 let ja = fs::read(a.root.join("journal.log")).unwrap();
530 let jb = fs::read(b.root.join("journal.log")).unwrap();
531 // board b's frame #2 (mission b) planted after board a's frame #1
532 fs::OpenOptions::new()
533 .append(true)
534 .open(a.root.join("journal.log"))
535 .unwrap()
536 .write_all(&jb[ja.len()..])
537 .unwrap();
538 refused(
539 &run(
540 &a.root,
541 Some("sa"),
542 &["post", "--thread", "t", "--topic", "lane/x", "--text", "x"],
543 &[],
544 ),
545 "ForeignMission",
546 );
547}
548
549#[test]
550fn planted_symlink_and_fifo_refused_promptly() {
551 for name in [
552 "journal.log",
553 "journal.idx",
554 "cursors/beta.json",
555 "cursors/beta.delivered",
556 ] {
557 for kind in ["symlink", "fifo"] {
558 let f = fx("plant");
559 register(&f, "sa", "alpha");
560 register(&f, "sb", "beta");
561 post(&f, "sa", "e1", &["--to", "beta"]);
562 ok(&run(&f.root, Some("sb"), &["read"], &[]));
563 let p = f.root.join(name);
564 fs::remove_file(&p).unwrap();
565 if kind == "symlink" {
566 symlink("/dev/zero", &p).unwrap();
567 } else {
568 let st = Command::new("mkfifo").arg(&p).status().unwrap();
569 assert!(st.success());
570 }
571 let post_args = ["post", "--thread", "t", "--topic", "lane/x", "--text", "x"];
572 let cases: Vec<&[&str]> = if name.starts_with("cursors") {
573 vec![&["read"]]
574 } else {
575 vec![&["read"], &post_args]
576 };
577 for args in cases {
578 let o = run(&f.root, Some("sb"), args, &[]);
579 refused(&o, "Refused");
580 }
581 }
582 }
583}
584
585#[test]
586fn corrupt_delivered_hint_is_ignored() {
587 let f = fx("hint");
588 register(&f, "sa", "alpha");
589 register(&f, "sb", "beta");
590 post(&f, "sa", "e1", &["--to", "beta"]);
591 post(&f, "sa", "e2", &["--to", "beta"]);
592 assert_eq!(lines(&ok_run(&f, "sb", &["read"])).len(), 3);
593 // The hint is advisory: garbage or an id past the last event is ignored, never trusted.
594 for junk in ["not a number\n", "999999\n", ""] {
595 fs::write(f.root.join("cursors/beta.delivered"), junk).unwrap();
596 let o = ok_run(&f, "sb", &["read", "--from", "delivered"]);
597 let ids: Vec<u64> = lines(&o).iter().filter_map(|j| num(j, "id")).collect();
598 assert!(ids.iter().all(|i| *i <= 2), "{junk:?}: {ids:?}");
599 }
600 // A valid hint moves `--from delivered` past what was handed out.
601 fs::write(f.root.join("cursors/beta.delivered"), "2\n").unwrap();
602 let o = ok_run(&f, "sb", &["read", "--from", "delivered"]);
603 assert_eq!(lines(&o).len(), 1, "nothing after the hint");
604 // Acked is the durable resume point: the default read still returns both.
605 assert_eq!(lines(&ok_run(&f, "sb", &["read"])).len(), 3);
606}
607
608fn ok_run(f: &Fx, session: &str, args: &[&str]) -> Output {
609 let o = run(&f.root, Some(session), args, &[]);
610 ok(&o);
611 o
612}
613
614#[test]
615fn idempotent_retry_finds_a_pending_frame() {
616 let f = fx("idem-pending");
617 register(&f, "sa", "alpha");
618 let args = [
619 "post", "--thread", "t", "--topic", "lane/x", "--idem", "k1", "--text", "hello",
620 ];
621 // The first try dies after its frame is durable but before it is committed.
622 let o = run(
623 &f.root,
624 Some("sa"),
625 &args,
626 &[("SYNAPSE_COORD_FAULT", "after-journal-before-index")],
627 );
628 assert_eq!(o.status.code(), Some(86));
629 let r = ok(&run(&f.root, Some("sa"), &args, &[]));
630 assert_eq!(num(&r, "id"), Some(1));
631 assert_eq!(r.get("dedup"), Some(&J::True), "{r:?}");
632 assert_eq!(all(&f), vec![(1, "hello".to_string())]);
633 check_ok(&f);
634}
635
636#[test]
637fn compaction_commits_pending_frames_first() {
638 let f = fx("compact-pending");
639 register(&f, "sa", "alpha");
640 post(&f, "sa", "e1", &[]);
641 post(&f, "sa", "e2", &[]);
642 let o = run(
643 &f.root,
644 Some("sa"),
645 &["post", "--thread", "t", "--topic", "lane/x", "--text", "e3"],
646 &[("SYNAPSE_COORD_FAULT", "before-journal-fsync")],
647 );
648 assert_eq!(o.status.code(), Some(86));
649 ok(&run(&f.root, None, &["compact", "--keep-since", "2"], &[]));
650 assert_eq!(
651 all(&f),
652 vec![(2, "e2".to_string()), (3, "e3".to_string())],
653 "the pending frame survived the rewrite"
654 );
655 check_ok(&f);
656}
657
658/// A power loss keeps every synced journal frame but may lose unsynced writes to the
659/// derived files in any order. Simulate that, then start a "new boot" (the boot id is
660/// overridden for the test) and show the first reader rebuilds them all from the journal.
661#[test]
662fn new_boot_rebuilds_derived_files_from_the_journal() {
663 let f = fx("reboot");
664 let b1: &[(&str, &str)] = &[("SYNAPSE_BOARD_BOOT_ID", "test-boot-one")];
665 let b2: &[(&str, &str)] = &[("SYNAPSE_BOARD_BOOT_ID", "test-boot-two")];
666 register(&f, "sa", "alpha");
667 register(&f, "sb", "beta");
668 for i in 1..=3 {
669 let r = ok(&run(
670 &f.root,
671 Some("sa"),
672 &[
673 "post",
674 "--thread",
675 "t",
676 "--topic",
677 "lane/x",
678 "--to",
679 "beta",
680 "--text",
681 &format!("e{i}"),
682 ],
683 b1,
684 ));
685 assert_eq!(num(&r, "id"), Some(i));
686 }
687 let one = |d: &str| {
688 let mut v: Vec<_> = fs::read_dir(f.root.join(d))
689 .unwrap()
690 .map(|e| e.unwrap().path())
691 .filter(|p| p.extension().is_some_and(|x| x == "idx"))
692 .collect();
693 assert_eq!(v.len(), 1, "{d}: {v:?}");
694 v.pop().unwrap()
695 };
696 let (inbox, topic) = (one("inbox"), one("topics"));
697 let table = f.root.join("journal.idx");
698 let cut = |p: &Path, by: u64| {
699 let fh = fs::OpenOptions::new().write(true).open(p).unwrap();
700 let len = fh.metadata().unwrap().len();
701 fh.set_len(len - by).unwrap();
702 };
703 cut(&table, 64); // the table lost its last entry
704 cut(&inbox, 8); // beta's inbox lost id 3
705 fs::OpenOptions::new()
706 .append(true)
707 .open(&topic)
708 .unwrap()
709 .write_all(&9u64.to_le_bytes())
710 .unwrap(); // the topic index kept a stray id
711 // Negative control: within the same boot the derived files are trusted as they are.
712 let o = run(
713 &f.root,
714 Some("sb"),
715 &["read", "--mine", "--peek", "--limit", "100"],
716 b1,
717 );
718 let ids: Vec<u64> = lines(&o).iter().filter_map(|j| num(j, "id")).collect();
719 assert_eq!(ids, vec![1, 2], "same boot: no rebuild");
720 let o = run(
721 &f.root,
722 Some("sb"),
723 &["read", "--mine", "--limit", "100"],
724 b2,
725 );
726 let mut v = lines(&o);
727 assert_eq!(v.pop().unwrap().get("ok"), Some(&J::True));
728 let ids: Vec<u64> = v.iter().filter_map(|j| num(j, "id")).collect();
729 assert_eq!(
730 ids,
731 vec![1, 2, 3],
732 "every event back through the rebuilt inbox"
733 );
734 check_ok(&f);
735 let r = ok(&run(
736 &f.root,
737 Some("sa"),
738 &["post", "--thread", "t", "--topic", "lane/x", "--text", "e4"],
739 b2,
740 ));
741 assert_eq!(num(&r, "id"), Some(4));
742 assert_eq!(r.get("rebuilt_after_boot"), None, "rebuilt once per boot");
743 // The writer path rebuilds too, and says so.
744 let r = ok(&run(
745 &f.root,
746 Some("sa"),
747 &["post", "--thread", "t", "--topic", "lane/x", "--text", "e5"],
748 &[("SYNAPSE_BOARD_BOOT_ID", "test-boot-three")],
749 ));
750 assert_eq!(num(&r, "id"), Some(5));
751 assert_eq!(r.get("rebuilt_after_boot"), Some(&J::True), "{r:?}");
752 check_ok(&f);
753}