Elffuss BraidHub

utopia-ia/elffuss-braid public

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