Elffuss BraidHub

utopia-ia/elffuss-braid public

verify: no test runs until its watchdog answers

The watchdog now starts before the test, from the very binary that runs on
Linux (/proc/self/exe), and must say it runs, with the number of its
protocol, before any test starts: a watchdog that ends at once (an older
braid, or the file replaced by another program), answers otherwise, or
says nothing fails the run. Braid then sends it the test's process group,
and checks while the test runs that it is still there; if it stops, the
test is stopped and the run fails. When waiting for the test fails, its
group is killed before the error.

The help says the process group and the watchdog exist on Unix only, that
they act when braid is killed or exits, and to run braid under an init in
a container.
Changeset1e0ec6999675d6c85aa82c43a88a0b162fe96d6c5ba4b233fe07cdfbcabfc350
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-21 15:54 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-21 15:54 +02:00
Parents2e9b2e7907ff

Browse the files at this changeset

3 files changed

modified crates/cli/src/main.rs +1 −3
@@ -327,8 +327,6 @@
327327 /// Kill a test run's process group when verify goes away (internal).
328328 #[command(name = verify::WATCHDOG, hide = true)]
329329 VerifyWatchdog {
330- /// The process group of the test run.
331- group: String,
332330 /// The run's scratch directory.
333331 dir: PathBuf,
334332 },
@@ -536,7 +534,7 @@
536534 Command::Change { action } => work::change(cli, action),
537535 Command::Revert(args) => revert::revert(cli, args),
538536 Command::Verify(args) => verify::verify(cli, args),
539- Command::VerifyWatchdog { group, dir } => verify::watchdog(group, dir),
537+ Command::VerifyWatchdog { dir } => verify::watchdog(dir),
540538 }
541539 }
542540
modified crates/cli/src/verify.rs +267 −52
@@ -23,7 +23,7 @@
2323 use std::collections::{BTreeSet, HashSet};
2424 use std::ffi::OsString;
2525 use std::fs::{self, File};
26-use std::io::{self, Read, Write};
26+use std::io::{self, BufRead, Write};
2727 use std::path::{Path, PathBuf};
2828 use std::process::{Child, Command, ExitCode, ExitStatus, Stdio};
2929 use std::sync::atomic::{AtomicU32, Ordering};
@@ -65,6 +65,15 @@
6565 /// hour, at most.
6666 const HISTORY_LIMIT: usize = 10_000;
6767
68+/// What the watchdog says once it runs, before braid starts any test. The
69+/// number changes with the protocol, so that another braid's watchdog is
70+/// never taken for this one's.
71+const READY: &[u8] = b"braid verify watchdog 2 ready\n";
72+
73+/// How long braid waits for the watchdog to say it runs.
74+#[cfg(unix)]
75+const READY_WAIT: Duration = Duration::from_secs(30);
76+
6877 /// The green ref of `branch`: the newest changeset of it that passed.
6978 pub(crate) fn green_ref(branch: &str) -> String {
7079 format!("braid/green/{branch}")
@@ -93,10 +102,16 @@
93102
94103 A run fails when the command exits with a status other than 0, is killed,
95104 or runs longer than --timeout (10m by default; s, m and h are the units).
96-The command runs in a process group of its own: when it exits or times
97-out, the group is killed, and so are processes it started that are still
98-in it (one that left the group, as a daemon does, is not). If braid itself
99-is stopped, a watchdog process kills the group and removes the directory.
105+On Unix the command runs in a process group of its own: when it exits or
106+times out, the group is killed, and so are processes it started that are
107+still in it (one that left the group, as a daemon does, is not). A watchdog
108+process, started before the command, kills the group and removes the
109+directory if braid is killed or exits while the tests run; when the
110+watchdog cannot start, or stops, the run fails. Elsewhere (Windows is not
111+verified) only the command itself is killed, and nothing watches braid. In
112+a container, run braid under an init such as tini (docker run --init), not
113+as PID 1, which gets no default signal handling and must reap the
114+processes others leave behind.
100115
101116 - The head is the green changeset already: pass, and nothing runs.
102117 - The tests pass: the green ref moves to the head, in an operation of
@@ -422,7 +437,21 @@
422437 Ok(Some(passed))
423438 }
424439
440+ /// Runs the command in `dir` under a watchdog, started first: from then
441+ /// on, however braid ends, the directory goes and the tests stop.
425442 fn run_in(&self, changeset: ObjectId, dir: &Path) -> Result<Option<RunEnd>> {
443+ let mut watchdog = Watchdog::start(dir)?;
444+ let end = self.watched(changeset, dir, &mut watchdog);
445+ watchdog.done();
446+ end
447+ }
448+
449+ fn watched(
450+ &self,
451+ changeset: ObjectId,
452+ dir: &Path,
453+ watchdog: &mut Watchdog,
454+ ) -> Result<Option<RunEnd>> {
426455 match braid_wc::materialize(self.repo.store(), changeset, dir) {
427456 Ok(_) => {}
428457 Err(err @ (braid_wc::Error::Unsafe { .. } | braid_wc::Error::Collision { .. })) => {
@@ -464,30 +493,40 @@
464493 let mut child = command
465494 .spawn()
466495 .with_context(|| format!("cannot run {}", program.to_string_lossy()))?;
467- let watchdog = match Watchdog::start(&child, dir) {
468- Ok(watchdog) => watchdog,
469- Err(err) => {
470- kill_group(&mut child);
471- let _ = child.wait();
472- return Err(err);
473- }
474- };
475- let end = self.wait(&mut child);
476- watchdog.done();
477- end.map(Some)
496+ if let Err(err) = watchdog.watch(&child) {
497+ kill_group(&mut child);
498+ let _ = child.wait();
499+ return Err(err);
500+ }
501+ self.wait(&mut child, watchdog).map(Some)
478502 }
479503
480504 /// Waits for the command, at most until the timeout, then kills its
481- /// group: whatever it left running, or all of it on a timeout.
482- fn wait(&self, child: &mut Child) -> Result<RunEnd> {
505+ /// group: whatever it left running, or all of it on a timeout. Should
506+ /// the watchdog stop meanwhile, or the wait fail, the group is killed
507+ /// too, and the run fails.
508+ fn wait(&self, child: &mut Child, watchdog: &mut Watchdog) -> Result<RunEnd> {
483509 let deadline = Instant::now() + self.timeout;
484510 loop {
485- if exited(child)? {
511+ let gone = match exited(child) {
512+ Ok(gone) => gone,
513+ Err(err) => {
514+ kill_group(child);
515+ let _ = child.wait();
516+ return Err(err.context("cannot wait for the tests; they were stopped"));
517+ }
518+ };
519+ if gone {
486520 // The command is not reaped yet, so its group's id cannot
487521 // be anyone else's.
488522 kill_group(child);
489523 return Ok(RunEnd::Exited(child.wait()?));
490524 }
525+ if watchdog.stopped() {
526+ kill_group(child);
527+ let _ = child.wait();
528+ bail!("verify's watchdog stopped while the tests ran, so they were stopped too");
529+ }
491530 let now = Instant::now();
492531 if now >= deadline {
493532 kill_group(child);
@@ -520,63 +559,146 @@
520559 }
521560
522561 /// A process that kills a test run's group, and removes its directory,
523-/// if braid goes away while it runs: it waits for its standard input to
524-/// close, which happens however braid ends, and does nothing when braid
525-/// said `done` first.
526-struct Watchdog(Option<Child>);
562+/// if braid goes away while it runs. Braid starts it before the test, and
563+/// starts no test until it says [`READY`]; then tells it the test's process
564+/// group, a `group <id>` line on its standard input, and at the end `done`.
565+/// Its standard input closes however braid ends: without `done` before,
566+/// the watchdog kills the group and removes the directory. On systems other
567+/// than Unix there is none.
568+struct Watchdog {
569+ child: Option<Child>,
570+}
527571
528572 impl Watchdog {
573+ /// Starts the watchdog of a run in `dir`, from this very braid.
574+ fn start(dir: &Path) -> Result<Watchdog> {
575+ #[cfg(unix)]
576+ {
577+ let mut command = Command::new(own_exe()?);
578+ command.arg(WATCHDOG).arg(dir);
579+ Watchdog::spawn(command, READY_WAIT)
580+ }
581+ #[cfg(not(unix))]
582+ {
583+ let _ = dir;
584+ Ok(Watchdog { child: None })
585+ }
586+ }
587+
588+ /// Starts `command` as the watchdog, out of braid's process group, and
589+ /// waits up to `wait` for it to say [`READY`].
529590 #[cfg(unix)]
530- fn start(child: &Child, dir: &Path) -> Result<Watchdog> {
591+ fn spawn(mut command: Command, wait: Duration) -> Result<Watchdog> {
592+ use std::io::BufReader;
531593 use std::os::unix::process::CommandExt;
532- let exe = std::env::current_exe().context("cannot find the braid command")?;
533- let watchdog = Command::new(exe)
534- .arg(WATCHDOG)
535- .arg(child.id().to_string())
536- .arg(dir)
594+ let mut child = command
537595 .stdin(Stdio::piped())
538- .stdout(Stdio::null())
596+ .stdout(Stdio::piped())
539597 .stderr(Stdio::null())
540598 // Out of braid's group, so that a Ctrl-C meant for braid does
541599 // not stop it too.
542600 .process_group(0)
543601 .spawn()
544- .context("cannot start verify's watchdog")?;
545- Ok(Watchdog(Some(watchdog)))
602+ .context("cannot start verify's watchdog, so the tests did not run")?;
603+ let said = match child.stdout.take() {
604+ Some(stdout) => {
605+ let (sender, receiver) = std::sync::mpsc::channel();
606+ std::thread::spawn(move || {
607+ let mut line = Vec::new();
608+ let read = BufReader::new(stdout).read_until(b'\n', &mut line);
609+ let _ = sender.send(read.map(|_| line));
610+ });
611+ receiver.recv_timeout(wait)
612+ }
613+ None => Err(std::sync::mpsc::RecvTimeoutError::Disconnected),
614+ };
615+ let why = match said {
616+ Ok(Ok(line)) if line == READY => return Ok(Watchdog { child: Some(child) }),
617+ Ok(Ok(line)) if line.is_empty() => "it ended without a word".to_owned(),
618+ Ok(Ok(line)) => format!("it said {:?}", String::from_utf8_lossy(&line)),
619+ Ok(Err(err)) => format!("it could not be read: {err}"),
620+ Err(_) => format!("it said nothing for {wait:?}"),
621+ };
622+ let _ = child.kill();
623+ let _ = child.wait();
624+ bail!(
625+ "verify's watchdog did not start ({why}), so the tests did not run; is the braid command being replaced, or another braid in its place?"
626+ )
627+ }
628+
629+ /// Tells the watchdog the process group of `test`, which runs in one of
630+ /// its own.
631+ fn watch(&mut self, test: &Child) -> Result<()> {
632+ let Some(child) = &mut self.child else {
633+ return Ok(());
634+ };
635+ let stdin = child
636+ .stdin
637+ .as_mut()
638+ .context("verify's watchdog cannot be told what to watch")?;
639+ writeln!(stdin, "group {}", test.id())
640+ .and_then(|()| stdin.flush())
641+ .context("verify's watchdog went away, so the tests were stopped")
546642 }
547643
548- #[cfg(not(unix))]
549- fn start(_child: &Child, _dir: &Path) -> Result<Watchdog> {
550- Ok(Watchdog(None))
644+ /// Whether the watchdog stopped, which it should not do before `done`.
645+ fn stopped(&mut self) -> bool {
646+ match &mut self.child {
647+ Some(child) => !matches!(child.try_wait(), Ok(None)),
648+ None => false,
649+ }
551650 }
552651
553652 /// Tells the watchdog the run is over, and waits for it.
554653 fn done(mut self) {
555- if let Some(mut watchdog) = self.0.take() {
556- if let Some(mut stdin) = watchdog.stdin.take() {
654+ if let Some(mut child) = self.child.take() {
655+ if let Some(mut stdin) = child.stdin.take() {
557656 let _ = stdin.write_all(b"done\n");
558657 }
559- let _ = watchdog.wait();
658+ let _ = child.wait();
560659 }
561660 }
562661 }
563662
564-/// The watchdog of one test run, as [`Watchdog`] starts it: `group` is the
565-/// test's process group, `dir` its scratch directory.
566-pub(crate) fn watchdog(group: &str, dir: &Path) -> Result<ExitCode> {
567- let mut said = Vec::new();
568- let _ = io::stdin().lock().read_to_end(&mut said);
569- if said.starts_with(b"done") {
570- return Ok(ExitCode::SUCCESS);
663+/// The braid command to start the watchdog with: on Linux this very binary,
664+/// through `/proc/self/exe`, even if its file was replaced or removed since
665+/// it started; elsewhere the file it was started from.
666+#[cfg(unix)]
667+fn own_exe() -> Result<PathBuf> {
668+ #[cfg(target_os = "linux")]
669+ {
670+ let this = PathBuf::from("/proc/self/exe");
671+ if this.exists() {
672+ return Ok(this);
673+ }
571674 }
572- // Braid went away while the tests ran.
573- #[cfg(unix)]
574- if let Some(pid) = group
575- .parse::<i32>()
576- .ok()
577- .filter(|group| *group > 1)
578- .and_then(rustix::process::Pid::from_raw)
675+ std::env::current_exe().context(
676+ "cannot find the braid command to start verify's watchdog, so the tests did not run",
677+ )
678+}
679+
680+/// The watchdog of one test run in `dir`, as [`Watchdog`] starts it.
681+pub(crate) fn watchdog(dir: &Path) -> Result<ExitCode> {
579682 {
683+ let mut out = io::stdout().lock();
684+ let _ = out.write_all(READY).and_then(|()| out.flush());
685+ }
686+ let mut group = None;
687+ for line in io::stdin().lock().split(b'\n') {
688+ let Ok(line) = line else { break };
689+ if line == b"done" {
690+ return Ok(ExitCode::SUCCESS);
691+ }
692+ if let Some(id) = line.strip_prefix(b"group ") {
693+ group = std::str::from_utf8(id)
694+ .ok()
695+ .and_then(|id| id.parse::<i32>().ok())
696+ .filter(|id| *id > 1);
697+ }
698+ }
699+ // Braid went away while the tests ran, or before they started.
700+ #[cfg(unix)]
701+ if let Some(pid) = group.and_then(rustix::process::Pid::from_raw) {
580702 let _ = rustix::process::kill_process_group(pid, rustix::process::Signal::KILL);
581703 }
582704 #[cfg(not(unix))]
@@ -1190,6 +1312,99 @@
11901312 assert!(err.contains("delete it"), "{err}");
11911313 }
11921314
1315+ /// A stand-in for the watchdog: `script`, run by `sh`.
1316+ #[cfg(unix)]
1317+ fn fake_watchdog(script: &str) -> Command {
1318+ let mut command = Command::new("sh");
1319+ command.args(["-c", script]);
1320+ command
1321+ }
1322+
1323+ #[cfg(unix)]
1324+ #[test]
1325+ fn no_test_runs_unless_the_watchdog_says_it_runs() {
1326+ let quick = Duration::from_millis(300);
1327+ // An older braid, which has no such command, or another program.
1328+ let err = Watchdog::spawn(fake_watchdog("echo 'no such command' >&2; exit 2"), quick)
1329+ .err()
1330+ .unwrap();
1331+ let err = format!("{err:#}");
1332+ assert!(
1333+ err.contains("did not start") && err.contains("without a word"),
1334+ "{err}"
1335+ );
1336+ // One that answers with another protocol.
1337+ let older = fake_watchdog("echo 'braid verify watchdog 1 ready'; exec cat");
1338+ let err = format!("{:#}", Watchdog::spawn(older, quick).err().unwrap());
1339+ assert!(err.contains("it said"), "{err}");
1340+ // One that never answers: it echoes its input, and gets none.
1341+ let silent = fake_watchdog("exec cat");
1342+ let err = format!("{:#}", Watchdog::spawn(silent, quick).err().unwrap());
1343+ assert!(err.contains("said nothing"), "{err}");
1344+ }
1345+
1346+ #[cfg(unix)]
1347+ #[test]
1348+ fn the_watchdog_is_told_the_group_and_when_the_run_is_over() {
1349+ let temp = tempfile::tempdir().unwrap();
1350+ let heard = temp.path().join("heard");
1351+ let script = format!(
1352+ "echo '{}'; cat > '{}'",
1353+ String::from_utf8_lossy(READY).trim_end(),
1354+ heard.display()
1355+ );
1356+ let mut watchdog =
1357+ Watchdog::spawn(fake_watchdog(&script), Duration::from_secs(10)).unwrap();
1358+ let mut test = Command::new("sh").args(["-c", "exit 0"]).spawn().unwrap();
1359+ watchdog.watch(&test).unwrap();
1360+ assert!(!watchdog.stopped());
1361+ watchdog.done();
1362+ test.wait().unwrap();
1363+ assert_eq!(
1364+ fs::read_to_string(&heard).unwrap(),
1365+ format!("group {}\ndone\n", test.id())
1366+ );
1367+ }
1368+
1369+ #[cfg(unix)]
1370+ #[test]
1371+ fn a_run_stops_when_its_watchdog_does() {
1372+ use std::os::unix::process::CommandExt;
1373+ let temp = tempfile::tempdir().unwrap();
1374+ let repo = Repo::init(temp.path()).unwrap();
1375+ let tester = Tester {
1376+ repo: &repo,
1377+ branch: "main",
1378+ command: &[],
1379+ timeout: Duration::from_secs(60),
1380+ reruns: 0,
1381+ runs: 0,
1382+ };
1383+ // It answers, hears the group, and stops.
1384+ let mut watchdog = Watchdog::spawn(
1385+ fake_watchdog(&format!(
1386+ "echo '{}'; read line; exit 0",
1387+ String::from_utf8_lossy(READY).trim_end()
1388+ )),
1389+ Duration::from_secs(10),
1390+ )
1391+ .unwrap();
1392+ let mut test = Command::new("sleep")
1393+ .arg("60")
1394+ .process_group(0)
1395+ .spawn()
1396+ .unwrap();
1397+ watchdog.watch(&test).unwrap();
1398+ let err = match tester.wait(&mut test, &mut watchdog) {
1399+ Ok(_) => panic!("the run went on without its watchdog"),
1400+ Err(err) => format!("{err:#}"),
1401+ };
1402+ assert!(err.contains("watchdog stopped"), "{err}");
1403+ // The test went with it, and was reaped.
1404+ assert!(test.try_wait().unwrap().is_some());
1405+ watchdog.done();
1406+ }
1407+
11931408 #[test]
11941409 fn ids_are_listed_in_words() {
11951410 let ids: Vec<ObjectId> = ["a", "b", "c"]
modified crates/cli/tests/verify.rs +71 −0
@@ -673,3 +673,74 @@
673673 let shown = run(&r.dir, &["show", "main"], 0);
674674 assert_eq!(shown["agent"], "braid-verify");
675675 }
676+
677+/// Starts braid's own watchdog for `dir`, as verify does, and reads its
678+/// handshake.
679+#[cfg(unix)]
680+fn start_watchdog(dir: &Path) -> std::process::Child {
681+ use std::io::{BufRead, BufReader};
682+ let mut watchdog = Command::new(env!("CARGO_BIN_EXE_braid"))
683+ .arg("__verify-watchdog")
684+ .arg(dir)
685+ .stdin(std::process::Stdio::piped())
686+ .stdout(std::process::Stdio::piped())
687+ .stderr(std::process::Stdio::null())
688+ .spawn()
689+ .unwrap();
690+ let mut line = String::new();
691+ BufReader::new(watchdog.stdout.take().unwrap())
692+ .read_line(&mut line)
693+ .unwrap();
694+ assert_eq!(line, "braid verify watchdog 2 ready\n");
695+ watchdog
696+}
697+
698+#[cfg(unix)]
699+#[test]
700+fn the_watchdog_stops_the_group_and_removes_the_copy_unless_told_done() {
701+ use std::io::Write;
702+ use std::os::unix::process::{CommandExt, ExitStatusExt};
703+ // Directories named as verify names its copies, where the watchdog
704+ // looks for them.
705+ let base = std::env::temp_dir();
706+ let dir = |n: u32| {
707+ let dir = base.join(format!("braid-verify-test-{}-{n}", std::process::id()));
708+ std::fs::create_dir(&dir).unwrap();
709+ std::fs::write(dir.join("file"), "x").unwrap();
710+ dir
711+ };
712+ // A process of this test's own, in a group of its own, as a test run is.
713+ let sleeper = || {
714+ Command::new("sleep")
715+ .arg("60")
716+ .process_group(0)
717+ .spawn()
718+ .unwrap()
719+ };
720+
721+ // Braid goes away: its end of the watchdog's input closes.
722+ let gone = dir(1);
723+ let mut test = sleeper();
724+ let mut watchdog = start_watchdog(&gone);
725+ let mut input = watchdog.stdin.take().unwrap();
726+ writeln!(input, "group {}", test.id()).unwrap();
727+ drop(input);
728+ watchdog.wait().unwrap();
729+ assert_eq!(test.wait().unwrap().signal(), Some(9));
730+ assert!(!gone.exists());
731+
732+ // The run ended and braid said so: nothing is touched.
733+ let kept = dir(2);
734+ let mut test = sleeper();
735+ let mut watchdog = start_watchdog(&kept);
736+ let mut input = watchdog.stdin.take().unwrap();
737+ writeln!(input, "group {}\ndone", test.id()).unwrap();
738+ drop(input);
739+ watchdog.wait().unwrap();
740+ assert!(test.try_wait().unwrap().is_none());
741+ assert!(kept.join("file").is_file());
742+ // This test's own process, by its id.
743+ test.kill().unwrap();
744+ test.wait().unwrap();
745+ std::fs::remove_dir_all(&kept).unwrap();
746+}