Elffuss BraidHub

utopia-ia/elffuss-braid public

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