Elffuss BraidHub

utopia-ia/elffuss-braid public

9598fdbd3dec · 55.3 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `verify`: run a project's tests on a branch's head, keep a green ref at
5//! the newest changeset that passed them, and when they fail, find the
6//! changeset that broke them and, if asked, revert it.
7//!
8//! One pass per invocation. The tests run in a fresh copy of the
9//! changeset's files outside the repository, with no shell, in a process
10//! group of their own that a watchdog process kills if braid goes away. The
11//! green ref, `braid/green/<branch>`, is in braid's own namespace, so it is
12//! never exported to git or sent to a hub: it is local to the repository.
13//! It moves with a compare-and-swap, in an operation of its own.
14//!
15//! What verify must not do again it reads from the branch itself, so that a
16//! fresh clone, as CI has, follows the same rules: a revert verify made
17//! carries a `reverts` field and the agent `braid-verify`, and verify never
18//! reverts such a changeset, nor lands more reverts an hour than it is
19//! allowed, counting them by their own committer time. A label anyone can
20//! write is safe to refuse on. `.braid/verify/` keeps a record of the reverts this
21//! repository landed, as a second source for both rules.
22
23use std::collections::{BTreeSet, HashSet};
24use std::ffi::OsString;
25use std::fs::{self, File};
26use std::io::{self, BufRead, Write};
27use std::path::{Path, PathBuf};
28use std::process::{Child, Command, ExitCode, ExitStatus, Stdio};
29use std::sync::atomic::{AtomicU32, Ordering};
30use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
31
32use anyhow::{Context, Result, bail};
33use braid_engine::{AGENT as AGENT_FIELD, REVERTS};
34use braid_format::{Changeset, ObjectId};
35use braid_repo::Repo;
36use braid_store::RefUpdate;
37use braid_wc::RevertRequest;
38use clap::Args;
39use serde::{Deserialize, Serialize};
40use serde_json::{Value, json};
41
42use crate::hub::{self, link::Link};
43use crate::revert::{branch_or_main, land_revert};
44use crate::work::{IdentityArgs, Report, count, hex, identity, print_conflicts, short};
45use crate::{Cli, open_repo, print_json, resolve_changeset};
46
47/// The agent label of everything verify records: the green ref's moves,
48/// and the reverts it makes and lands.
49pub(crate) const AGENT: &str = "braid-verify";
50
51/// The hidden subcommand that watches a test run for braid going away.
52pub(crate) const WATCHDOG: &str = "__verify-watchdog";
53
54/// Exit status of a pass that leaves the branch red: the tests fail on its
55/// head, whether or not the culprit was found or reverted.
56const RED: u8 = 4;
57
58/// The exit status of a revert that conflicts, as for every conflict.
59const CONFLICTS: u8 = crate::work::CONFLICTS;
60
61/// The prefix of the scratch directories the tests run in.
62const SCRATCH_PREFIX: &str = "braid-verify-";
63
64/// How many changesets down the branch verify looks for its own reverts of
65/// the last hour, at most.
66const HISTORY_DEPTH: usize = 200;
67
68/// The walk for those reverts stops at the first changeset committed more
69/// than this long, in seconds, before now: a day.
70const HISTORY_AGE: i64 = 86_400;
71
72/// What the watchdog says once it runs, before braid starts any test. The
73/// number changes with the protocol, so that another braid's watchdog is
74/// never taken for this one's.
75const READY: &[u8] = b"braid verify watchdog 2 ready\n";
76
77/// How long braid waits for the watchdog to say it runs.
78#[cfg(unix)]
79const READY_WAIT: Duration = Duration::from_secs(30);
80
81/// The green ref of `branch`: the newest changeset of it that passed.
82pub(crate) fn green_ref(branch: &str) -> String {
83 format!("braid/green/{branch}")
84}
85
86/// The long help of `verify`.
87pub(crate) const VERIFY_HELP: &str =
88 "Run the project's tests on the head of a branch, once, and keep the
89branch green: braid/green/<branch> points at the newest changeset of the
90branch that passed. When the tests fail, find the changeset that broke
91them, and with --revert, revert it.
92
93The command comes after `--` and runs as given, with no shell: write
94`-- sh -c '...'` for one. It runs in a fresh copy of the changeset's files,
95in a new directory under the system's temporary directory, outside the
96repository and with no .braid file and no .git, so each run starts from
97scratch; the directory is removed after the run. Its output goes to
98standard error. It gets BRAID_VERIFY_CHANGESET (the changeset's id),
99BRAID_VERIFY_BRANCH and PWD (its directory); BRAID_TOKEN, every variable
100whose name starts with BRAID_HUB, and OLDPWD are taken out.
101
102That is all the isolation there is: the command runs as you, with your
103access to every file, the network, the braid command, and any hub login
104saved in braid's configuration directory. Run verify in a sandbox, a
105container or as a separate user when the code it tests is not trusted.
106
107A run fails when the command exits with a status other than 0, is killed,
108or runs longer than --timeout (10m by default; s, m and h are the units).
109On Unix the command runs in a process group of its own: when it exits or
110times out, the group is killed, and so are processes it started that are
111still in it (one that left the group, as a daemon does, is not). A watchdog
112process, started before the command, kills the group and removes the
113directory if braid is killed or exits while the tests run; when the
114watchdog cannot start, or stops, the run fails. Elsewhere (Windows is not
115verified) only the command itself is killed, and nothing watches braid. In
116a container, run braid under an init such as tini (docker run --init), not
117as PID 1, which gets no default signal handling and must reap the
118processes others leave behind.
119
120 - The head is the green changeset already: pass, and nothing runs.
121 - The tests pass: the green ref moves to the head, in an operation of
122 its own by braid-verify. A run that failed and passed when run again
123 (--reruns, 1 by default) is flaky: the green ref stays, unless
124 --flaky-moves-green.
125 - They fail, again on every rerun: verify bisects the changesets after
126 the green one along first parents, the head's changes and its
127 parents', to find the first that fails. With no green ref yet it does
128 not bisect unless --from names a changeset to take as passing. A
129 changeset whose files cannot be written on this system is skipped, and
130 listed in skipped. When the first failing changeset was reverted later
131 in the range, verify tests the revert and, if it passes, goes on
132 bisecting after it. Otherwise midpoints run as they are.
133 - With --revert, the culprit is reverted and the revert landed, as
134 `braid revert` does. Verify does not revert a merge, nor a revert it
135 made (one with a reverts field and the agent braid-verify), nor more
136 than --max-reverts-per-hour (3 by default), which it counts by each
137 revert's committer time among the last 200 changesets of the branch
138 (down to one made more than a day before), and in .braid/verify/. The
139 green ref does not move: the next run tests the new head.
140
141The green ref is local: a fresh clone has none, so give --from there.
142--dry-run runs the tests but moves no ref, records nothing, lands nothing
143and does not fetch. In a repository linked to a hub, verify fetches first
144and lands a revert on the hub; --local, or BRAID_HUB=off, keeps it here.
145Run one verify per branch at a time.
146
147With --json it prints branch; tip, the head it tested; green_before and
148green, the green ref before and after; outcome, one of pass, flaky, red,
149reverted, revert_conflicts, refused, no_culprit or error; culprit, the
150first failing changeset, or null; revert, the revert made, or null;
151skipped, the changesets that could not be tested; tests_run, how many
152times the command ran; reason, why, in words, or null; dry_run; and land,
153the landing report of the revert as `braid land --help` describes it, or
154null.
155
156Exit status: 0 for pass and flaky; 4 for red, reverted, refused and
157no_culprit; 2 for revert_conflicts; 1 for an error. Once the tests have
158started, or a revert was made, an error prints the report too, with what
159was done until then.";
160
161#[derive(Debug, Args)]
162pub(crate) struct VerifyArgs {
163 /// The branch to verify (default: main, master, or the repository's
164 /// only branch).
165 #[arg(long, value_name = "BRANCH")]
166 branch: Option<String>,
167 /// Revert the changeset that broke the tests, and land the revert.
168 #[arg(long)]
169 revert: bool,
170 /// Run the tests, but move no ref, record nothing, land nothing and
171 /// fetch nothing.
172 #[arg(long)]
173 dry_run: bool,
174 /// The most reverts verify lands on the branch in an hour.
175 #[arg(long, value_name = "N", default_value_t = 3)]
176 max_reverts_per_hour: usize,
177 /// How many times to run a failing command again before it counts as
178 /// failing.
179 #[arg(long, value_name = "N", default_value_t = 1)]
180 reruns: u32,
181 /// Move the green ref when the tests passed only on a rerun.
182 #[arg(long)]
183 flaky_moves_green: bool,
184 /// How long one run may take: a number with s, m or h.
185 #[arg(long, value_name = "DURATION", default_value = "10m", value_parser = parse_duration)]
186 timeout: Duration,
187 /// A changeset of the branch to take as passing, to bisect from instead
188 /// of the green one.
189 #[arg(long, value_name = "REV")]
190 from: Option<String>,
191 #[command(flatten)]
192 identity: IdentityArgs,
193 /// Stay in this repository even if it is linked to a hub.
194 #[arg(long)]
195 local: bool,
196 /// The test command and its arguments, after `--`.
197 #[arg(last = true, required = true, value_name = "COMMAND")]
198 command: Vec<OsString>,
199}
200
201/// A duration: a whole number followed by `s`, `m` or `h`, or a number of
202/// seconds; never zero.
203fn parse_duration(text: &str) -> Result<Duration, String> {
204 let (digits, unit) = match text.char_indices().find(|(_, c)| !c.is_ascii_digit()) {
205 Some((at, _)) => text.split_at(at),
206 None => (text, "s"),
207 };
208 let scale = match unit {
209 "s" => 1,
210 "m" => 60,
211 "h" => 3600,
212 _ => return Err(format!("{text:?} is not a duration such as 30s, 10m or 1h")),
213 };
214 match digits.parse::<u64>() {
215 Ok(n) if n > 0 => n
216 .checked_mul(scale)
217 .map(Duration::from_secs)
218 .ok_or_else(|| format!("{text:?} is too long")),
219 _ => Err(format!("{text:?} is not a duration such as 30s, 10m or 1h")),
220 }
221}
222
223/// What one pass found, filled in as it goes, so that an error keeps what
224/// was done before it.
225#[derive(Default)]
226struct Verdict {
227 outcome: &'static str,
228 green: Option<ObjectId>,
229 culprit: Option<ObjectId>,
230 revert: Option<ObjectId>,
231 skipped: Vec<ObjectId>,
232 reason: Option<String>,
233 land: Option<Report>,
234}
235
236impl Verdict {
237 fn exit_code(&self) -> ExitCode {
238 match self.outcome {
239 "pass" | "flaky" => ExitCode::SUCCESS,
240 "revert_conflicts" => ExitCode::from(CONFLICTS),
241 "error" => ExitCode::FAILURE,
242 _ => ExitCode::from(RED),
243 }
244 }
245
246 fn red(&mut self, outcome: &'static str, reason: String) {
247 self.outcome = outcome;
248 self.reason = Some(reason);
249 }
250}
251
252/// The reverts verify landed on one branch from this repository, as
253/// `.braid/verify/<branch in hex>.json` keeps them.
254#[derive(Debug, Default, Serialize, Deserialize)]
255struct Record {
256 #[serde(default)]
257 reverts: Vec<Reverted>,
258}
259
260/// One revert verify landed.
261#[derive(Debug, Serialize, Deserialize)]
262struct Reverted {
263 /// The changeset it reverted, in hex.
264 culprit: String,
265 /// The revert as verify made it, in hex.
266 revert: String,
267 /// The changeset that holds it on the branch: itself, or the rebased
268 /// one; null when the landing's answer was lost.
269 landed: Option<String>,
270 /// When it landed, in seconds since the Unix epoch.
271 time: u64,
272}
273
274impl Record {
275 /// The file of `branch`: its name in hex, so that no two branches share
276 /// a file, even on a file system that ignores case.
277 fn path(repo: &Repo, branch: &str) -> PathBuf {
278 let name: String = branch.bytes().map(|byte| format!("{byte:02x}")).collect();
279 repo.root()
280 .join(braid_repo::DIR)
281 .join("verify")
282 .join(format!("{name}.json"))
283 }
284
285 fn load(path: &Path) -> Result<Record> {
286 match fs::read(path) {
287 Ok(bytes) => serde_json::from_slice(&bytes).with_context(|| {
288 format!(
289 "{} is not verify's record of its reverts; delete it to start a new one (verify also finds its reverts on the branch)",
290 path.display()
291 )
292 }),
293 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Record::default()),
294 Err(err) => Err(err).with_context(|| format!("cannot read {}", path.display())),
295 }
296 }
297
298 /// Writes the record whole, through a scratch file that reaches the
299 /// disk before it is renamed into place.
300 fn save(&self, path: &Path) -> Result<()> {
301 let dir = path.parent().context("the record has no directory")?;
302 fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
303 let scratch = path.with_extension("json.new");
304 let mut text = serde_json::to_vec_pretty(self)?;
305 text.push(b'\n');
306 File::create(&scratch)
307 .and_then(|mut file| {
308 file.write_all(&text)?;
309 file.sync_all()
310 })
311 .with_context(|| format!("cannot write {}", scratch.display()))?;
312 fs::rename(&scratch, path).with_context(|| format!("cannot write {}", path.display()))?;
313 #[cfg(unix)]
314 if let Ok(dir) = File::open(dir) {
315 let _ = dir.sync_all();
316 }
317 Ok(())
318 }
319
320 /// Whether this repository's verify made `id`: a revert, as made or
321 /// landed.
322 fn made(&self, id: ObjectId) -> bool {
323 let hex = id.to_hex();
324 self.reverts
325 .iter()
326 .any(|r| r.revert == hex || r.landed.as_deref() == Some(hex.as_str()))
327 }
328
329 /// The reverts landed in the hour before `now`, by the id that holds
330 /// each on the branch.
331 fn in_last_hour(&self, now: u64) -> HashSet<String> {
332 self.reverts
333 .iter()
334 .filter(|r| r.time + 3600 > now)
335 .map(|r| r.landed.clone().unwrap_or_else(|| r.revert.clone()))
336 .collect()
337 }
338}
339
340fn now_seconds() -> u64 {
341 SystemTime::now()
342 .duration_since(UNIX_EPOCH)
343 .map_or(0, |since| since.as_secs())
344}
345
346/// The value of an extra field of `changeset`.
347fn extra<'c>(changeset: &'c Changeset, key: &[u8]) -> Option<&'c [u8]> {
348 changeset
349 .extras
350 .iter()
351 .find(|(k, _)| k.as_slice() == key)
352 .map(|(_, value)| value.as_slice())
353}
354
355/// Whether `changeset` says it is a revert verify made: a `reverts` field,
356/// and `braid-verify` as its agent. Anyone can write both, which is why it
357/// is only ever a reason to refuse.
358fn is_verify_revert(changeset: &Changeset) -> bool {
359 extra(changeset, REVERTS).is_some() && extra(changeset, AGENT_FIELD) == Some(AGENT.as_bytes())
360}
361
362/// The reverts verify made on the branch below `tip` that were committed in
363/// the hour before `now`, each by its own committer time. Committer times
364/// do not only grow along a branch (a changeset that landed by a
365/// fast-forward keeps the time it was made), so the walk down first parents
366/// goes on past older changesets: it stops after [`HISTORY_DEPTH`]
367/// changesets, or at the first one committed more than [`HISTORY_AGE`]
368/// before now.
369fn reverts_in_last_hour(repo: &Repo, tip: ObjectId, now: u64) -> Result<HashSet<String>> {
370 let now = i64::try_from(now).unwrap_or(i64::MAX);
371 let mut found = HashSet::new();
372 let mut current = Some(tip);
373 for _ in 0..HISTORY_DEPTH {
374 let Some(id) = current else { break };
375 let changeset = braid_engine::read_changeset(repo.store(), id)?;
376 let committed = changeset.committer.seconds;
377 if committed < now.saturating_sub(HISTORY_AGE) {
378 break;
379 }
380 if committed > now.saturating_sub(3600) && is_verify_revert(&changeset) {
381 found.insert(id.to_hex());
382 }
383 current = changeset.parents.first().copied();
384 }
385 Ok(found)
386}
387
388/// How a changeset fared.
389enum Check {
390 /// The tests passed: `flaky` when a run failed first.
391 Passed { flaky: bool },
392 /// Every run failed.
393 Failed,
394 /// Its files cannot be written on this system, so it was not tested.
395 Skipped,
396}
397
398/// Runs the test command on changesets, counting the runs.
399struct Tester<'a> {
400 repo: &'a Repo,
401 branch: &'a str,
402 command: &'a [OsString],
403 timeout: Duration,
404 reruns: u32,
405 runs: usize,
406}
407
408/// How one run ended.
409enum RunEnd {
410 Exited(ExitStatus),
411 TimedOut,
412}
413
414impl Tester<'_> {
415 /// Whether the tests pass on `changeset`: the first run, or one of the
416 /// reruns after it fails.
417 fn check(&mut self, changeset: ObjectId) -> Result<Check> {
418 for attempt in 0..=self.reruns {
419 match self.run(changeset)? {
420 None => return Ok(Check::Skipped),
421 Some(true) => return Ok(Check::Passed { flaky: attempt > 0 }),
422 Some(false) => {}
423 }
424 }
425 Ok(Check::Failed)
426 }
427
428 /// Runs the command once on a fresh copy of `changeset`: whether it
429 /// passed, or `None` when the files cannot be written here.
430 fn run(&mut self, changeset: ObjectId) -> Result<Option<bool>> {
431 let dir = scratch_dir()?;
432 let result = self.run_in(changeset, &dir);
433 // Whatever the command left goes too.
434 let _ = fs::remove_dir_all(&dir);
435 let Some(end) = result? else {
436 return Ok(None);
437 };
438 // Only a command that ran counts.
439 self.runs += 1;
440 let passed = matches!(&end, RunEnd::Exited(status) if status.success());
441 let said = match &end {
442 RunEnd::Exited(status) if status.success() => "passed".to_owned(),
443 RunEnd::Exited(status) => format!("failed ({status})"),
444 RunEnd::TimedOut => format!("timed out after {:?} and was killed", self.timeout),
445 };
446 eprintln!("braid verify: {} {said}", changeset.short());
447 Ok(Some(passed))
448 }
449
450 /// Runs the command in `dir` under a watchdog, started first: from then
451 /// on, however braid ends, the directory goes and the tests stop.
452 fn run_in(&self, changeset: ObjectId, dir: &Path) -> Result<Option<RunEnd>> {
453 let mut watchdog = Watchdog::start(dir)?;
454 let end = self.watched(changeset, dir, &mut watchdog);
455 watchdog.done();
456 end
457 }
458
459 fn watched(
460 &self,
461 changeset: ObjectId,
462 dir: &Path,
463 watchdog: &mut Watchdog,
464 ) -> Result<Option<RunEnd>> {
465 match braid_wc::materialize(self.repo.store(), changeset, dir) {
466 Ok(_) => {}
467 Err(err @ (braid_wc::Error::Unsafe { .. } | braid_wc::Error::Collision { .. })) => {
468 eprintln!(
469 "braid verify: {} skipped: its files cannot be written here: {err}",
470 changeset.short()
471 );
472 return Ok(None);
473 }
474 Err(err) => {
475 return Err(err).with_context(|| {
476 format!("cannot write changeset {} to test it", changeset.short())
477 });
478 }
479 }
480 let (program, args) = self.command.split_first().context("no command to run")?;
481 let mut command = Command::new(program);
482 command
483 .args(args)
484 .current_dir(dir)
485 .stdin(Stdio::null())
486 .stdout(to_stderr()?)
487 .stderr(to_stderr()?)
488 .env("BRAID_VERIFY_CHANGESET", changeset.to_hex())
489 .env("BRAID_VERIFY_BRANCH", self.branch)
490 .env("PWD", dir)
491 .env_remove("OLDPWD");
492 for (name, _) in std::env::vars_os() {
493 if is_credential(&name) {
494 command.env_remove(&name);
495 }
496 }
497 #[cfg(unix)]
498 {
499 use std::os::unix::process::CommandExt;
500 // A group of its own, so that what it started goes with it.
501 command.process_group(0);
502 }
503 let mut child = command
504 .spawn()
505 .with_context(|| format!("cannot run {}", program.to_string_lossy()))?;
506 if let Err(err) = watchdog.watch(&child) {
507 kill_group(&mut child);
508 let _ = child.wait();
509 return Err(err);
510 }
511 self.wait(&mut child, watchdog).map(Some)
512 }
513
514 /// Waits for the command, at most until the timeout, then kills its
515 /// group: whatever it left running, or all of it on a timeout. Should
516 /// the watchdog stop meanwhile, or the wait fail, the group is killed
517 /// too, and the run fails.
518 fn wait(&self, child: &mut Child, watchdog: &mut Watchdog) -> Result<RunEnd> {
519 let deadline = Instant::now() + self.timeout;
520 loop {
521 let gone = match exited(child) {
522 Ok(gone) => gone,
523 Err(err) => {
524 kill_group(child);
525 let _ = child.wait();
526 return Err(err.context("cannot wait for the tests; they were stopped"));
527 }
528 };
529 if gone {
530 // The command is not reaped yet, so its group's id cannot
531 // be anyone else's.
532 kill_group(child);
533 return Ok(RunEnd::Exited(child.wait()?));
534 }
535 if watchdog.stopped() {
536 kill_group(child);
537 let _ = child.wait();
538 bail!("verify's watchdog stopped while the tests ran, so they were stopped too");
539 }
540 let now = Instant::now();
541 if now >= deadline {
542 kill_group(child);
543 let _ = child.wait();
544 return Ok(RunEnd::TimedOut);
545 }
546 std::thread::sleep((deadline - now).min(Duration::from_millis(20)));
547 }
548 }
549}
550
551/// Whether the command exited, without reaping it where the system can.
552fn exited(child: &mut Child) -> Result<bool> {
553 #[cfg(unix)]
554 {
555 use rustix::process::{Pid, WaitId, WaitIdOptions, waitid};
556 let options = WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT;
557 loop {
558 match waitid(WaitId::Pid(Pid::from_child(child)), options) {
559 Ok(found) => return Ok(found.is_some()),
560 Err(rustix::io::Errno::INTR) => continue,
561 Err(err) => return Err(io::Error::from(err).into()),
562 }
563 }
564 }
565 #[cfg(not(unix))]
566 {
567 Ok(child.try_wait()?.is_some())
568 }
569}
570
571/// A process that kills a test run's group, and removes its directory,
572/// if braid goes away while it runs. Braid starts it before the test, and
573/// starts no test until it says [`READY`]; then tells it the test's process
574/// group, a `group <id>` line on its standard input, and at the end `done`.
575/// Its standard input closes however braid ends: without `done` before,
576/// the watchdog kills the group and removes the directory. On systems other
577/// than Unix there is none.
578struct Watchdog {
579 child: Option<Child>,
580}
581
582impl Watchdog {
583 /// Starts the watchdog of a run in `dir`, from this very braid.
584 fn start(dir: &Path) -> Result<Watchdog> {
585 #[cfg(unix)]
586 {
587 let mut command = Command::new(own_exe()?);
588 command.arg(WATCHDOG).arg(dir);
589 Watchdog::spawn(command, READY_WAIT)
590 }
591 #[cfg(not(unix))]
592 {
593 let _ = dir;
594 Ok(Watchdog { child: None })
595 }
596 }
597
598 /// Starts `command` as the watchdog, out of braid's process group, and
599 /// waits up to `wait` for it to say [`READY`].
600 #[cfg(unix)]
601 fn spawn(mut command: Command, wait: Duration) -> Result<Watchdog> {
602 use std::io::BufReader;
603 use std::os::unix::process::CommandExt;
604 let mut child = command
605 .stdin(Stdio::piped())
606 .stdout(Stdio::piped())
607 .stderr(Stdio::null())
608 // Out of braid's group, so that a Ctrl-C meant for braid does
609 // not stop it too.
610 .process_group(0)
611 .spawn()
612 .context("cannot start verify's watchdog, so the tests did not run")?;
613 let said = match child.stdout.take() {
614 Some(stdout) => {
615 let (sender, receiver) = std::sync::mpsc::channel();
616 std::thread::spawn(move || {
617 let mut line = Vec::new();
618 let read = BufReader::new(stdout).read_until(b'\n', &mut line);
619 let _ = sender.send(read.map(|_| line));
620 });
621 receiver.recv_timeout(wait)
622 }
623 None => Err(std::sync::mpsc::RecvTimeoutError::Disconnected),
624 };
625 let why = match said {
626 Ok(Ok(line)) if line == READY => return Ok(Watchdog { child: Some(child) }),
627 Ok(Ok(line)) if line.is_empty() => "it ended without a word".to_owned(),
628 Ok(Ok(line)) => format!("it said {:?}", String::from_utf8_lossy(&line)),
629 Ok(Err(err)) => format!("it could not be read: {err}"),
630 Err(_) => format!("it said nothing for {wait:?}"),
631 };
632 let _ = child.kill();
633 let _ = child.wait();
634 bail!(
635 "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?"
636 )
637 }
638
639 /// Tells the watchdog the process group of `test`, which runs in one of
640 /// its own.
641 fn watch(&mut self, test: &Child) -> Result<()> {
642 let Some(child) = &mut self.child else {
643 return Ok(());
644 };
645 let stdin = child
646 .stdin
647 .as_mut()
648 .context("verify's watchdog cannot be told what to watch")?;
649 writeln!(stdin, "group {}", test.id())
650 .and_then(|()| stdin.flush())
651 .context("verify's watchdog went away, so the tests were stopped")
652 }
653
654 /// Whether the watchdog stopped, which it should not do before `done`.
655 fn stopped(&mut self) -> bool {
656 match &mut self.child {
657 Some(child) => !matches!(child.try_wait(), Ok(None)),
658 None => false,
659 }
660 }
661
662 /// Tells the watchdog the run is over, and waits for it.
663 fn done(mut self) {
664 if let Some(mut child) = self.child.take() {
665 if let Some(mut stdin) = child.stdin.take() {
666 let _ = stdin.write_all(b"done\n");
667 }
668 let _ = child.wait();
669 }
670 }
671}
672
673/// The braid command to start the watchdog with: on Linux this very binary,
674/// through `/proc/self/exe`, even if its file was replaced or removed since
675/// it started; elsewhere the file it was started from.
676#[cfg(unix)]
677fn own_exe() -> Result<PathBuf> {
678 #[cfg(target_os = "linux")]
679 {
680 let this = PathBuf::from("/proc/self/exe");
681 if this.exists() {
682 return Ok(this);
683 }
684 }
685 std::env::current_exe().context(
686 "cannot find the braid command to start verify's watchdog, so the tests did not run",
687 )
688}
689
690/// The watchdog of one test run in `dir`, as [`Watchdog`] starts it.
691pub(crate) fn watchdog(dir: &Path) -> Result<ExitCode> {
692 {
693 let mut out = io::stdout().lock();
694 let _ = out.write_all(READY).and_then(|()| out.flush());
695 }
696 let mut group = None;
697 for line in io::stdin().lock().split(b'\n') {
698 let Ok(line) = line else { break };
699 if line == b"done" {
700 return Ok(ExitCode::SUCCESS);
701 }
702 if let Some(id) = line.strip_prefix(b"group ") {
703 group = std::str::from_utf8(id)
704 .ok()
705 .and_then(|id| id.parse::<i32>().ok())
706 .filter(|id| *id > 1);
707 }
708 }
709 // Braid went away while the tests ran, or before they started.
710 #[cfg(unix)]
711 if let Some(pid) = group.and_then(rustix::process::Pid::from_raw) {
712 let _ = rustix::process::kill_process_group(pid, rustix::process::Signal::KILL);
713 }
714 #[cfg(not(unix))]
715 let _ = group;
716 // Only ever one of verify's scratch directories.
717 let ours = dir.parent() == Some(std::env::temp_dir().as_path())
718 && dir
719 .file_name()
720 .is_some_and(|name| name.to_string_lossy().starts_with(SCRATCH_PREFIX));
721 if ours {
722 for _ in 0..10 {
723 if fs::remove_dir_all(dir).is_ok() || !dir.exists() {
724 break;
725 }
726 std::thread::sleep(Duration::from_millis(50));
727 }
728 }
729 Ok(ExitCode::SUCCESS)
730}
731
732/// Whether an environment variable is one of the hub's credentials or
733/// settings, which the tests never see: `BRAID_TOKEN` and every variable
734/// whose name starts with `BRAID_HUB`.
735fn is_credential(name: &std::ffi::OsStr) -> bool {
736 let name = name.to_string_lossy();
737 name == "BRAID_TOKEN" || name.starts_with("BRAID_HUB")
738}
739
740/// Kills the command and every process left in its group. A group already
741/// gone is no error.
742fn kill_group(child: &mut Child) {
743 #[cfg(unix)]
744 {
745 let group = rustix::process::Pid::from_child(child);
746 let _ = rustix::process::kill_process_group(group, rustix::process::Signal::KILL);
747 }
748 let _ = child.kill();
749}
750
751/// Standard error, for the command's output, so that standard output keeps
752/// only the report.
753fn to_stderr() -> Result<Stdio> {
754 #[cfg(unix)]
755 {
756 use std::os::fd::AsFd;
757 Ok(Stdio::from(io::stderr().as_fd().try_clone_to_owned()?))
758 }
759 #[cfg(windows)]
760 {
761 use std::os::windows::io::AsHandle;
762 Ok(Stdio::from(io::stderr().as_handle().try_clone_to_owned()?))
763 }
764 #[cfg(not(any(unix, windows)))]
765 {
766 Ok(Stdio::inherit())
767 }
768}
769
770/// A new, empty directory under the system's temporary directory, readable
771/// only by this user where the system has modes.
772fn scratch_dir() -> Result<PathBuf> {
773 static COUNTER: AtomicU32 = AtomicU32::new(0);
774 let base = std::env::temp_dir();
775 let nanos = SystemTime::now()
776 .duration_since(UNIX_EPOCH)
777 .map_or(0, |since| since.subsec_nanos());
778 loop {
779 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
780 let dir = base.join(format!(
781 "{SCRATCH_PREFIX}{}-{nanos:08x}-{n}",
782 std::process::id()
783 ));
784 let mut builder = fs::DirBuilder::new();
785 #[cfg(unix)]
786 {
787 use std::os::unix::fs::DirBuilderExt;
788 builder.mode(0o700);
789 }
790 match builder.create(&dir) {
791 Ok(()) => return Ok(dir),
792 Err(err) if err.kind() == io::ErrorKind::AlreadyExists && n < 1000 => continue,
793 Err(err) => {
794 return Err(err).with_context(|| format!("cannot create {}", dir.display()));
795 }
796 }
797 }
798}
799
800/// The changesets after `good` up to `tip`, along first parents, oldest
801/// first, or `None` when `good` is not on the chain.
802fn range(repo: &Repo, tip: ObjectId, good: ObjectId) -> Result<Option<Vec<ObjectId>>> {
803 let mut chain = Vec::new();
804 let mut current = tip;
805 while current != good {
806 chain.push(current);
807 match braid_engine::read_changeset(repo.store(), current)?
808 .parents
809 .first()
810 {
811 Some(parent) => current = *parent,
812 None => return Ok(None),
813 }
814 }
815 chain.reverse();
816 Ok(Some(chain))
817}
818
819/// `a, b and c`, of short ids.
820fn listed(ids: &[ObjectId]) -> String {
821 let shorts: Vec<String> = ids.iter().map(ObjectId::short).collect();
822 match shorts.as_slice() {
823 [] => String::new(),
824 [one] => one.clone(),
825 [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
826 }
827}
828
829/// Everything one pass needs.
830struct Pass<'a> {
831 args: &'a VerifyArgs,
832 repo: &'a Repo,
833 link: Option<Link>,
834 branch: &'a str,
835 tip: ObjectId,
836 green_before: Option<ObjectId>,
837 /// `--from`, resolved.
838 from: Option<ObjectId>,
839}
840
841impl Pass<'_> {
842 fn run(&self, tester: &mut Tester<'_>, verdict: &mut Verdict) -> Result<()> {
843 if self.green_before == Some(self.tip) {
844 verdict.outcome = "pass";
845 verdict.reason = Some("the head is the green changeset already".to_owned());
846 return Ok(());
847 }
848 let flaky = match tester.check(self.tip)? {
849 Check::Passed { flaky } => flaky,
850 Check::Failed => return self.red(tester, verdict),
851 Check::Skipped => bail!(
852 "the files of the head, {}, cannot be written on this system, so it cannot be tested here",
853 self.tip.short()
854 ),
855 };
856 verdict.outcome = if flaky { "flaky" } else { "pass" };
857 let mut reasons = Vec::new();
858 if flaky {
859 reasons.push("a run failed, and a rerun passed".to_owned());
860 }
861 if flaky && !self.args.flaky_moves_green {
862 reasons.push("the green ref stays; --flaky-moves-green would move it".to_owned());
863 } else if self.args.dry_run {
864 reasons.push(format!(
865 "dry run: the green ref would move to {}",
866 self.tip.short()
867 ));
868 } else {
869 self.move_green()?;
870 verdict.green = Some(self.tip);
871 }
872 if !reasons.is_empty() {
873 verdict.reason = Some(reasons.join("; "));
874 }
875 Ok(())
876 }
877
878 /// The tests fail on the head: find the first changeset that fails.
879 fn red(&self, tester: &mut Tester<'_>, verdict: &mut Verdict) -> Result<()> {
880 verdict.outcome = "red";
881 let Some(good) = self.from.or(self.green_before) else {
882 verdict.reason = Some(
883 "the tests fail on the head, and with no green changeset there is nothing to bisect from: --from names one"
884 .to_owned(),
885 );
886 return Ok(());
887 };
888 let Some(range) = range(self.repo, self.tip, good)? else {
889 verdict.reason = Some(format!(
890 "{} is not on {}'s first-parent chain: there is nothing to bisect",
891 good.short(),
892 self.branch
893 ));
894 return Ok(());
895 };
896 if range.is_empty() {
897 verdict.red(
898 "no_culprit",
899 format!("the head is {}, which was to pass", good.short()),
900 );
901 return Ok(());
902 }
903 let last = range.len() as isize - 1;
904 // `range[lo]` passes (or is `good`, at -1), and the head fails.
905 let mut lo = -1;
906 loop {
907 let (passing, failing, untested) = bisect(tester, &range, lo, last, verdict)?;
908 if !untested.is_empty() {
909 let mut candidates: Vec<ObjectId> =
910 untested.iter().map(|i| range[*i as usize]).collect();
911 candidates.push(range[failing as usize]);
912 verdict.reason = Some(format!(
913 "the first changeset that fails is one of {}: the others could not be tested here",
914 listed(&candidates)
915 ));
916 return Ok(());
917 }
918 let culprit = range[failing as usize];
919 if let Some(at) = reverted_at(self.repo, &range, failing)? {
920 // Fixed once already: what fails now came after, hidden by
921 // the culprit until its revert.
922 let revert = range[at];
923 let hidden = format!(
924 "{} fails, and {revert_short} reverted it later, but the tests fail at {revert_short} too: what broke them since is hidden behind {}",
925 culprit.short(),
926 culprit.short(),
927 revert_short = revert.short()
928 );
929 if at as isize == last {
930 verdict.red("no_culprit", hidden);
931 return Ok(());
932 }
933 match tester.check(revert)? {
934 Check::Passed { .. } => {
935 lo = at as isize;
936 continue;
937 }
938 Check::Failed => {
939 verdict.red("no_culprit", hidden);
940 return Ok(());
941 }
942 Check::Skipped => {
943 verdict.skipped.push(revert);
944 verdict.reason = Some(format!(
945 "{} fails, and {} reverted it later, but the revert could not be tested here",
946 culprit.short(),
947 revert.short()
948 ));
949 return Ok(());
950 }
951 }
952 }
953 if passing < 0 {
954 match tester.check(good)? {
955 Check::Passed { .. } => {}
956 Check::Failed => {
957 // The changeset taken as passing fails now too:
958 // something outside the range broke the tests.
959 verdict.red(
960 "no_culprit",
961 format!(
962 "{} fails too, though it was to pass: the failure is not in the changesets after it",
963 good.short()
964 ),
965 );
966 return Ok(());
967 }
968 // It cannot be checked; it was to pass.
969 Check::Skipped => verdict.skipped.push(good),
970 }
971 }
972 verdict.culprit = Some(culprit);
973 return self.revert(culprit, verdict);
974 }
975 }
976
977 /// Moves the green ref from where it was to the tip, unless someone
978 /// moved it meanwhile.
979 fn move_green(&self) -> Result<()> {
980 let name = green_ref(self.branch);
981 let description = format!("verify: {name} at {}", self.tip.short());
982 self.repo
983 .store()
984 .transact(AGENT, &description, |refs| {
985 let current = refs.get(&name);
986 if current != self.green_before {
987 return Err(format!(
988 "{name} moved while verify ran, to {}: is another verify running?",
989 short(current)
990 ));
991 }
992 Ok(vec![RefUpdate::new(
993 name.clone(),
994 self.green_before,
995 Some(self.tip),
996 )])
997 })
998 .map_err(|err| anyhow::anyhow!("{err}"))?;
999 Ok(())
1000 }
1001
1002 /// Decides whether to revert `culprit`, and does.
1003 fn revert(&self, culprit: ObjectId, verdict: &mut Verdict) -> Result<()> {
1004 let first = format!(
1005 "the tests fail from {}, the first changeset that fails",
1006 culprit.short()
1007 );
1008 if !self.args.revert {
1009 verdict.reason = Some(format!("{first}; --revert would revert it"));
1010 return Ok(());
1011 }
1012 let changeset = braid_engine::read_changeset(self.repo.store(), culprit)?;
1013 let path = Record::path(self.repo, self.branch);
1014 let mut record = Record::load(&path)?;
1015 let now = now_seconds();
1016 let mut recent = reverts_in_last_hour(self.repo, self.tip, now)?;
1017 recent.extend(record.in_last_hour(now));
1018 let refusal = if changeset.parents.len() > 1 {
1019 Some(format!(
1020 "{first}, and it is a merge: verify does not revert merges"
1021 ))
1022 } else if is_verify_revert(&changeset) || record.made(culprit) {
1023 Some(format!(
1024 "{first}, and it is a revert verify made: verify does not revert its own reverts"
1025 ))
1026 } else if recent.len() >= self.args.max_reverts_per_hour {
1027 Some(format!(
1028 "{first}, but verify landed {} on {} in the last hour, the most --max-reverts-per-hour allows",
1029 count(recent.len(), "revert"),
1030 self.branch
1031 ))
1032 } else {
1033 None
1034 };
1035 if let Some(reason) = refusal {
1036 verdict.red("refused", reason);
1037 return Ok(());
1038 }
1039 if self.args.dry_run {
1040 verdict.reason = Some(format!("{first}; dry run: verify would revert it"));
1041 return Ok(());
1042 }
1043 let author = identity(&self.args.identity, self.repo)?;
1044 let change = braid_wc::create_revert(
1045 self.repo.store(),
1046 &RevertRequest {
1047 culprit,
1048 mainline: false,
1049 author: author.clone(),
1050 agent: AGENT.to_owned(),
1051 },
1052 )?;
1053 verdict.revert = Some(change);
1054 let landed = land_revert(
1055 self.repo,
1056 self.link.as_ref(),
1057 self.branch,
1058 change,
1059 AGENT,
1060 &author,
1061 );
1062 let mut report = match landed {
1063 Ok(report) => report,
1064 Err(err) => {
1065 // The hub may have landed it all the same: the record
1066 // keeps it, as the branch will once fetched.
1067 record.reverts.push(Reverted {
1068 culprit: culprit.to_hex(),
1069 revert: change.to_hex(),
1070 landed: None,
1071 time: now,
1072 });
1073 let _ = record.save(&path);
1074 return Err(err);
1075 }
1076 };
1077 let outcome = report.outcome.clone();
1078 match outcome.as_str() {
1079 "fast-forward" | "rebased" => {
1080 verdict.red(
1081 "reverted",
1082 format!("{first}; its revert landed on {}", self.branch),
1083 );
1084 record.reverts.push(Reverted {
1085 culprit: culprit.to_hex(),
1086 revert: change.to_hex(),
1087 landed: report.head.map(|id| id.to_hex()),
1088 time: now,
1089 });
1090 verdict.land = Some(report);
1091 record.save(&path)?;
1092 return Ok(());
1093 }
1094 "conflicts" => {
1095 verdict.red(
1096 "revert_conflicts",
1097 format!(
1098 "{first}; its revert conflicts with what landed since, so {} did not move: revert it by hand in a workspace",
1099 self.branch
1100 ),
1101 );
1102 report.next = None;
1103 }
1104 "already-applied" => verdict.red(
1105 "refused",
1106 format!(
1107 "{first}, but {} has what its revert would change already",
1108 self.branch
1109 ),
1110 ),
1111 other => {
1112 verdict.land = Some(report);
1113 bail!("the revert's landing ended with {other}");
1114 }
1115 }
1116 verdict.land = Some(report);
1117 Ok(())
1118 }
1119}
1120
1121/// Bisects `range` between `lo`, which passes (-1 for the changeset before
1122/// the range), and `hi`, which fails, skipping changesets that cannot be
1123/// tested. Returns the last passing and the first failing index found, and
1124/// the skipped indexes between them.
1125fn bisect(
1126 tester: &mut Tester<'_>,
1127 range: &[ObjectId],
1128 mut lo: isize,
1129 mut hi: isize,
1130 verdict: &mut Verdict,
1131) -> Result<(isize, isize, Vec<isize>)> {
1132 let mut skipped = BTreeSet::new();
1133 loop {
1134 let middle = lo + (hi - lo) / 2;
1135 let Some(pick) = (lo + 1..hi)
1136 .filter(|i| !skipped.contains(i))
1137 .min_by_key(|i| (i - middle).abs())
1138 else {
1139 break;
1140 };
1141 match tester.check(range[pick as usize])? {
1142 Check::Passed { .. } => lo = pick,
1143 Check::Failed => hi = pick,
1144 Check::Skipped => {
1145 skipped.insert(pick);
1146 verdict.skipped.push(range[pick as usize]);
1147 }
1148 }
1149 }
1150 let untested = skipped.into_iter().filter(|i| *i > lo && *i < hi).collect();
1151 Ok((lo, hi, untested))
1152}
1153
1154/// Where in `range`, after `index`, a changeset reverts `range[index]`, if
1155/// one does.
1156fn reverted_at(repo: &Repo, range: &[ObjectId], index: isize) -> Result<Option<usize>> {
1157 let culprit = range[index as usize].to_hex().into_bytes();
1158 for (at, id) in range.iter().enumerate().skip(index as usize + 1) {
1159 let changeset = braid_engine::read_changeset(repo.store(), *id)?;
1160 if extra(&changeset, REVERTS) == Some(culprit.as_slice()) {
1161 return Ok(Some(at));
1162 }
1163 }
1164 Ok(None)
1165}
1166
1167pub(crate) fn verify(cli: &Cli, args: &VerifyArgs) -> Result<ExitCode> {
1168 let repo = open_repo(cli)?;
1169 let branch = branch_or_main(&repo, args.branch.as_deref())?;
1170 let link = hub::linked(&repo, args.local)?;
1171 if let Some(link) = &link
1172 && !args.dry_run
1173 {
1174 let hub = hub::connect(link)?;
1175 let remote = hub.repo(link.repo.clone());
1176 hub::fetch::fetch(&repo, &remote, link, AGENT, None).context(
1177 "cannot fetch from the hub before verifying (--local verifies the local branch as it is)",
1178 )?;
1179 }
1180 let refs = repo.store().refs()?;
1181 let Some(tip) = refs.get(&branch) else {
1182 bail!("there is no branch {branch:?} to verify");
1183 };
1184 let from = match &args.from {
1185 Some(revision) => Some(resolve_changeset(&repo, revision)?),
1186 None => None,
1187 };
1188 let green_before = refs.get(&green_ref(&branch));
1189 let pass = Pass {
1190 args,
1191 repo: &repo,
1192 link,
1193 branch: &branch,
1194 tip,
1195 green_before,
1196 from,
1197 };
1198 let mut tester = Tester {
1199 repo: &repo,
1200 branch: &branch,
1201 command: &args.command,
1202 timeout: args.timeout,
1203 reruns: args.reruns,
1204 runs: 0,
1205 };
1206 let mut verdict = Verdict {
1207 green: green_before,
1208 ..Verdict::default()
1209 };
1210 if let Err(err) = pass.run(&mut tester, &mut verdict) {
1211 // Before anything ran or was made, an error is only an error.
1212 if tester.runs == 0 && verdict.revert.is_none() {
1213 return Err(err);
1214 }
1215 eprintln!("braid: error: {err:#}");
1216 verdict.outcome = "error";
1217 verdict.reason = Some(format!("{err:#}"));
1218 }
1219 if cli.json {
1220 print_json(&json!({
1221 "branch": branch,
1222 "tip": tip.to_hex(),
1223 "green_before": hex(green_before),
1224 "green": hex(verdict.green),
1225 "outcome": verdict.outcome,
1226 "culprit": hex(verdict.culprit),
1227 "revert": hex(verdict.revert),
1228 "skipped": verdict.skipped.iter().map(ObjectId::to_hex).collect::<Vec<_>>(),
1229 "tests_run": tester.runs,
1230 "reason": verdict.reason,
1231 "dry_run": args.dry_run,
1232 "land": verdict.land.as_ref().map_or(Value::Null, Report::json),
1233 }))?;
1234 } else {
1235 print_text(&branch, tip, &verdict, tester.runs);
1236 }
1237 Ok(verdict.exit_code())
1238}
1239
1240fn print_text(branch: &str, tip: ObjectId, verdict: &Verdict, runs: usize) {
1241 let ran = count(runs, "run");
1242 match verdict.outcome {
1243 "pass" | "flaky" => println!(
1244 "{branch} is green at {} ({}, {ran})",
1245 tip.short(),
1246 verdict.outcome
1247 ),
1248 outcome => println!("{branch} at {}: {outcome} ({ran})", tip.short()),
1249 }
1250 if let Some(reason) = &verdict.reason {
1251 println!("{reason}");
1252 }
1253 if let Some(revert) = verdict.revert {
1254 println!("Revert: {}", revert.short());
1255 }
1256 if !verdict.skipped.is_empty() {
1257 println!("Not tested here: {}", listed(&verdict.skipped));
1258 }
1259 if let Some(report) = &verdict.land
1260 && report.conflicted()
1261 {
1262 print_conflicts(&report.conflicts);
1263 }
1264}
1265
1266#[cfg(test)]
1267mod tests {
1268 use super::*;
1269
1270 #[test]
1271 fn durations() {
1272 assert_eq!(parse_duration("10m"), Ok(Duration::from_secs(600)));
1273 assert_eq!(parse_duration("30s"), Ok(Duration::from_secs(30)));
1274 assert_eq!(parse_duration("2h"), Ok(Duration::from_secs(7200)));
1275 assert_eq!(parse_duration("45"), Ok(Duration::from_secs(45)));
1276 for bad in ["", "0s", "m", "10x", "1.5m", "-1s", "10 m"] {
1277 assert!(parse_duration(bad).is_err(), "{bad}");
1278 }
1279 }
1280
1281 #[test]
1282 fn credentials_are_recognised() {
1283 for name in [
1284 "BRAID_TOKEN",
1285 "BRAID_HUB",
1286 "BRAID_HUB_URL",
1287 "BRAID_HUB_MAX_BODY",
1288 ] {
1289 assert!(is_credential(name.as_ref()), "{name}");
1290 }
1291 for name in ["BRAID_AGENT", "BRAID_AUTHOR", "PATH", "BRAID_TOKENS"] {
1292 assert!(!is_credential(name.as_ref()), "{name}");
1293 }
1294 }
1295
1296 #[test]
1297 fn record_files_are_named_in_hex_and_kept_whole() {
1298 let temp = tempfile::tempdir().unwrap();
1299 let repo = Repo::init(temp.path()).unwrap();
1300 let path = Record::path(&repo, "feature/x");
1301 assert_eq!(path.file_name().unwrap(), "666561747572652f78.json");
1302 // Two names that differ only in case get two files.
1303 assert_ne!(Record::path(&repo, "Main"), Record::path(&repo, "main"));
1304 let mut record = Record::default();
1305 record.reverts.push(Reverted {
1306 culprit: "c".repeat(64),
1307 revert: "a".repeat(64),
1308 landed: Some("b".repeat(64)),
1309 time: 10_000,
1310 });
1311 let landed: ObjectId = "b".repeat(64).parse().unwrap();
1312 assert!(record.made(landed));
1313 assert_eq!(record.in_last_hour(10_000 + 3599).len(), 1);
1314 assert_eq!(record.in_last_hour(10_000 + 3600).len(), 0);
1315 record.save(&path).unwrap();
1316 assert_eq!(Record::load(&path).unwrap().reverts.len(), 1);
1317 assert!(!path.with_extension("json.new").exists());
1318
1319 // A damaged record says how to recover.
1320 fs::write(&path, "{").unwrap();
1321 let err = format!("{:#}", Record::load(&path).unwrap_err());
1322 assert!(err.contains("delete it"), "{err}");
1323 }
1324
1325 #[test]
1326 fn the_hourly_cap_counts_by_each_reverts_own_time() {
1327 let temp = tempfile::tempdir().unwrap();
1328 let repo = Repo::init(temp.path()).unwrap();
1329 let now: i64 = 1_800_000_000;
1330 let signature = |seconds| braid_format::Signature {
1331 name: b"Ada".to_vec(),
1332 email: b"ada@example.org".to_vec(),
1333 seconds,
1334 offset_minutes: 0,
1335 };
1336 let revert_by = |agent: &str| {
1337 vec![
1338 (AGENT_FIELD.to_vec(), agent.as_bytes().to_vec()),
1339 (REVERTS.to_vec(), "c".repeat(64).into_bytes()),
1340 ]
1341 };
1342 let commit = |parent: Option<ObjectId>, ago: i64, extras| {
1343 braid_engine::commit(
1344 repo.store(),
1345 parent.into_iter().collect(),
1346 Vec::new(),
1347 signature(now - ago),
1348 signature(now - ago),
1349 b"change\n".to_vec(),
1350 extras,
1351 )
1352 .unwrap()
1353 };
1354 // Down from the tip: a revert by someone else, one of verify's, a
1355 // changeset that landed by a fast-forward hours after it was made,
1356 // another of verify's below it, one older than an hour, and a base
1357 // older than a day, where the walk stops.
1358 let base = commit(None, 2 * 86_400, Vec::new());
1359 let too_old = commit(Some(base), 2 * 3600, revert_by(AGENT));
1360 let below = commit(Some(too_old), 30 * 60, revert_by(AGENT));
1361 let made_earlier = commit(Some(below), 3 * 3600, Vec::new());
1362 let recent = commit(Some(made_earlier), 10 * 60, revert_by(AGENT));
1363 let others = commit(Some(recent), 5 * 60, revert_by("ada"));
1364 let tip = commit(Some(others), 60, Vec::new());
1365 let found = reverts_in_last_hour(&repo, tip, now as u64).unwrap();
1366 let expected: HashSet<String> = [below, recent].iter().map(ObjectId::to_hex).collect();
1367 assert_eq!(found, expected);
1368
1369 // A revert deeper than the walk goes is not counted.
1370 let mut top = commit(Some(tip), 60, revert_by(AGENT));
1371 let deep = top;
1372 for _ in 0..HISTORY_DEPTH {
1373 top = commit(Some(top), 30, Vec::new());
1374 }
1375 let found = reverts_in_last_hour(&repo, top, now as u64).unwrap();
1376 assert!(!found.contains(&deep.to_hex()));
1377 assert!(found.is_empty(), "{found:?}");
1378 }
1379
1380 /// A stand-in for the watchdog: `script`, run by `sh`.
1381 #[cfg(unix)]
1382 fn fake_watchdog(script: &str) -> Command {
1383 let mut command = Command::new("sh");
1384 command.args(["-c", script]);
1385 command
1386 }
1387
1388 #[cfg(unix)]
1389 #[test]
1390 fn no_test_runs_unless_the_watchdog_says_it_runs() {
1391 let quick = Duration::from_millis(300);
1392 // An older braid, which has no such command, or another program.
1393 let err = Watchdog::spawn(fake_watchdog("echo 'no such command' >&2; exit 2"), quick)
1394 .err()
1395 .unwrap();
1396 let err = format!("{err:#}");
1397 assert!(
1398 err.contains("did not start") && err.contains("without a word"),
1399 "{err}"
1400 );
1401 // One that answers with another protocol.
1402 let older = fake_watchdog("echo 'braid verify watchdog 1 ready'; exec cat");
1403 let err = format!("{:#}", Watchdog::spawn(older, quick).err().unwrap());
1404 assert!(err.contains("it said"), "{err}");
1405 // One that never answers: it echoes its input, and gets none.
1406 let silent = fake_watchdog("exec cat");
1407 let err = format!("{:#}", Watchdog::spawn(silent, quick).err().unwrap());
1408 assert!(err.contains("said nothing"), "{err}");
1409 }
1410
1411 #[cfg(unix)]
1412 #[test]
1413 fn the_watchdog_is_told_the_group_and_when_the_run_is_over() {
1414 let temp = tempfile::tempdir().unwrap();
1415 let heard = temp.path().join("heard");
1416 let script = format!(
1417 "echo '{}'; cat > '{}'",
1418 String::from_utf8_lossy(READY).trim_end(),
1419 heard.display()
1420 );
1421 let mut watchdog =
1422 Watchdog::spawn(fake_watchdog(&script), Duration::from_secs(10)).unwrap();
1423 let mut test = Command::new("sh").args(["-c", "exit 0"]).spawn().unwrap();
1424 watchdog.watch(&test).unwrap();
1425 assert!(!watchdog.stopped());
1426 watchdog.done();
1427 test.wait().unwrap();
1428 assert_eq!(
1429 fs::read_to_string(&heard).unwrap(),
1430 format!("group {}\ndone\n", test.id())
1431 );
1432 }
1433
1434 #[cfg(unix)]
1435 #[test]
1436 fn a_run_stops_when_its_watchdog_does() {
1437 use std::os::unix::process::CommandExt;
1438 let temp = tempfile::tempdir().unwrap();
1439 let repo = Repo::init(temp.path()).unwrap();
1440 let tester = Tester {
1441 repo: &repo,
1442 branch: "main",
1443 command: &[],
1444 timeout: Duration::from_secs(60),
1445 reruns: 0,
1446 runs: 0,
1447 };
1448 // It answers, hears the group, and stops.
1449 let mut watchdog = Watchdog::spawn(
1450 fake_watchdog(&format!(
1451 "echo '{}'; read line; exit 0",
1452 String::from_utf8_lossy(READY).trim_end()
1453 )),
1454 Duration::from_secs(10),
1455 )
1456 .unwrap();
1457 let mut test = Command::new("sleep")
1458 .arg("60")
1459 .process_group(0)
1460 .spawn()
1461 .unwrap();
1462 watchdog.watch(&test).unwrap();
1463 let err = match tester.wait(&mut test, &mut watchdog) {
1464 Ok(_) => panic!("the run went on without its watchdog"),
1465 Err(err) => format!("{err:#}"),
1466 };
1467 assert!(err.contains("watchdog stopped"), "{err}");
1468 // The test went with it, and was reaped.
1469 assert!(test.try_wait().unwrap().is_some());
1470 watchdog.done();
1471 }
1472
1473 #[test]
1474 fn ids_are_listed_in_words() {
1475 let ids: Vec<ObjectId> = ["a", "b", "c"]
1476 .iter()
1477 .map(|c| c.repeat(64).parse().unwrap())
1478 .collect();
1479 assert_eq!(listed(&ids[..1]), "a".repeat(12));
1480 assert_eq!(
1481 listed(&ids),
1482 format!(
1483 "{}, {} and {}",
1484 "a".repeat(12),
1485 "b".repeat(12),
1486 "c".repeat(12)
1487 )
1488 );
1489 }
1490}