Elffuss BraidHub

utopia-ia/elffuss-braid public

a71130e7a2a9 · 44.1 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 committer time. A label anyone can write
20//! 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, Read, 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 far down the branch verify looks for its own reverts of the last
65/// hour, at most.
66const HISTORY_LIMIT: usize = 10_000;
67
68/// The green ref of `branch`: the newest changeset of it that passed.
69pub(crate) fn green_ref(branch: &str) -> String {
70 format!("braid/green/{branch}")
71}
72
73/// The long help of `verify`.
74pub(crate) const VERIFY_HELP: &str =
75 "Run the project's tests on the head of a branch, once, and keep the
76branch green: braid/green/<branch> points at the newest changeset of the
77branch that passed. When the tests fail, find the changeset that broke
78them, and with --revert, revert it.
79
80The command comes after `--` and runs as given, with no shell: write
81`-- sh -c '...'` for one. It runs in a fresh copy of the changeset's files,
82in a new directory under the system's temporary directory, outside the
83repository and with no .braid file and no .git, so each run starts from
84scratch; the directory is removed after the run. Its output goes to
85standard error. It gets BRAID_VERIFY_CHANGESET (the changeset's id),
86BRAID_VERIFY_BRANCH and PWD (its directory); BRAID_TOKEN, every variable
87whose name starts with BRAID_HUB, and OLDPWD are taken out.
88
89That is all the isolation there is: the command runs as you, with your
90access to every file, the network, the braid command, and any hub login
91saved in braid's configuration directory. Run verify in a sandbox, a
92container or as a separate user when the code it tests is not trusted.
93
94A run fails when the command exits with a status other than 0, is killed,
95or runs longer than --timeout (10m by default; s, m and h are the units).
96The command runs in a process group of its own: when it exits or times
97out, the group is killed, and so are processes it started that are still
98in it (one that left the group, as a daemon does, is not). If braid itself
99is stopped, a watchdog process kills the group and removes the directory.
100
101 - The head is the green changeset already: pass, and nothing runs.
102 - The tests pass: the green ref moves to the head, in an operation of
103 its own by braid-verify. A run that failed and passed when run again
104 (--reruns, 1 by default) is flaky: the green ref stays, unless
105 --flaky-moves-green.
106 - They fail, again on every rerun: verify bisects the changesets after
107 the green one along first parents, the head's changes and its
108 parents', to find the first that fails. With no green ref yet it does
109 not bisect unless --from names a changeset to take as passing. A
110 changeset whose files cannot be written on this system is skipped, and
111 listed in skipped. When the first failing changeset was reverted later
112 in the range, verify tests the revert and, if it passes, goes on
113 bisecting after it. Otherwise midpoints run as they are.
114 - With --revert, the culprit is reverted and the revert landed, as
115 `braid revert` does. Verify does not revert a merge, nor a revert it
116 made (one with a reverts field and the agent braid-verify), nor more
117 than --max-reverts-per-hour (3 by default), which it counts on the
118 branch by committer time and in .braid/verify/. The green ref does not
119 move: the next run tests the new head.
120
121The green ref is local: a fresh clone has none, so give --from there.
122--dry-run runs the tests but moves no ref, records nothing, lands nothing
123and does not fetch. In a repository linked to a hub, verify fetches first
124and lands a revert on the hub; --local, or BRAID_HUB=off, keeps it here.
125Run one verify per branch at a time.
126
127With --json it prints branch; tip, the head it tested; green_before and
128green, the green ref before and after; outcome, one of pass, flaky, red,
129reverted, revert_conflicts, refused, no_culprit or error; culprit, the
130first failing changeset, or null; revert, the revert made, or null;
131skipped, the changesets that could not be tested; tests_run, how many
132times the command ran; reason, why, in words, or null; dry_run; and land,
133the landing report of the revert as `braid land --help` describes it, or
134null.
135
136Exit status: 0 for pass and flaky; 4 for red, reverted, refused and
137no_culprit; 2 for revert_conflicts; 1 for an error. Once the tests have
138started, or a revert was made, an error prints the report too, with what
139was done until then.";
140
141#[derive(Debug, Args)]
142pub(crate) struct VerifyArgs {
143 /// The branch to verify (default: main, master, or the repository's
144 /// only branch).
145 #[arg(long, value_name = "BRANCH")]
146 branch: Option<String>,
147 /// Revert the changeset that broke the tests, and land the revert.
148 #[arg(long)]
149 revert: bool,
150 /// Run the tests, but move no ref, record nothing, land nothing and
151 /// fetch nothing.
152 #[arg(long)]
153 dry_run: bool,
154 /// The most reverts verify lands on the branch in an hour.
155 #[arg(long, value_name = "N", default_value_t = 3)]
156 max_reverts_per_hour: usize,
157 /// How many times to run a failing command again before it counts as
158 /// failing.
159 #[arg(long, value_name = "N", default_value_t = 1)]
160 reruns: u32,
161 /// Move the green ref when the tests passed only on a rerun.
162 #[arg(long)]
163 flaky_moves_green: bool,
164 /// How long one run may take: a number with s, m or h.
165 #[arg(long, value_name = "DURATION", default_value = "10m", value_parser = parse_duration)]
166 timeout: Duration,
167 /// A changeset of the branch to take as passing, to bisect from instead
168 /// of the green one.
169 #[arg(long, value_name = "REV")]
170 from: Option<String>,
171 #[command(flatten)]
172 identity: IdentityArgs,
173 /// Stay in this repository even if it is linked to a hub.
174 #[arg(long)]
175 local: bool,
176 /// The test command and its arguments, after `--`.
177 #[arg(last = true, required = true, value_name = "COMMAND")]
178 command: Vec<OsString>,
179}
180
181/// A duration: a whole number followed by `s`, `m` or `h`, or a number of
182/// seconds; never zero.
183fn parse_duration(text: &str) -> Result<Duration, String> {
184 let (digits, unit) = match text.char_indices().find(|(_, c)| !c.is_ascii_digit()) {
185 Some((at, _)) => text.split_at(at),
186 None => (text, "s"),
187 };
188 let scale = match unit {
189 "s" => 1,
190 "m" => 60,
191 "h" => 3600,
192 _ => return Err(format!("{text:?} is not a duration such as 30s, 10m or 1h")),
193 };
194 match digits.parse::<u64>() {
195 Ok(n) if n > 0 => n
196 .checked_mul(scale)
197 .map(Duration::from_secs)
198 .ok_or_else(|| format!("{text:?} is too long")),
199 _ => Err(format!("{text:?} is not a duration such as 30s, 10m or 1h")),
200 }
201}
202
203/// What one pass found, filled in as it goes, so that an error keeps what
204/// was done before it.
205#[derive(Default)]
206struct Verdict {
207 outcome: &'static str,
208 green: Option<ObjectId>,
209 culprit: Option<ObjectId>,
210 revert: Option<ObjectId>,
211 skipped: Vec<ObjectId>,
212 reason: Option<String>,
213 land: Option<Report>,
214}
215
216impl Verdict {
217 fn exit_code(&self) -> ExitCode {
218 match self.outcome {
219 "pass" | "flaky" => ExitCode::SUCCESS,
220 "revert_conflicts" => ExitCode::from(CONFLICTS),
221 "error" => ExitCode::FAILURE,
222 _ => ExitCode::from(RED),
223 }
224 }
225
226 fn red(&mut self, outcome: &'static str, reason: String) {
227 self.outcome = outcome;
228 self.reason = Some(reason);
229 }
230}
231
232/// The reverts verify landed on one branch from this repository, as
233/// `.braid/verify/<branch in hex>.json` keeps them.
234#[derive(Debug, Default, Serialize, Deserialize)]
235struct Record {
236 #[serde(default)]
237 reverts: Vec<Reverted>,
238}
239
240/// One revert verify landed.
241#[derive(Debug, Serialize, Deserialize)]
242struct Reverted {
243 /// The changeset it reverted, in hex.
244 culprit: String,
245 /// The revert as verify made it, in hex.
246 revert: String,
247 /// The changeset that holds it on the branch: itself, or the rebased
248 /// one; null when the landing's answer was lost.
249 landed: Option<String>,
250 /// When it landed, in seconds since the Unix epoch.
251 time: u64,
252}
253
254impl Record {
255 /// The file of `branch`: its name in hex, so that no two branches share
256 /// a file, even on a file system that ignores case.
257 fn path(repo: &Repo, branch: &str) -> PathBuf {
258 let name: String = branch.bytes().map(|byte| format!("{byte:02x}")).collect();
259 repo.root()
260 .join(braid_repo::DIR)
261 .join("verify")
262 .join(format!("{name}.json"))
263 }
264
265 fn load(path: &Path) -> Result<Record> {
266 match fs::read(path) {
267 Ok(bytes) => serde_json::from_slice(&bytes).with_context(|| {
268 format!(
269 "{} is not verify's record of its reverts; delete it to start a new one (verify also finds its reverts on the branch)",
270 path.display()
271 )
272 }),
273 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Record::default()),
274 Err(err) => Err(err).with_context(|| format!("cannot read {}", path.display())),
275 }
276 }
277
278 /// Writes the record whole, through a scratch file that reaches the
279 /// disk before it is renamed into place.
280 fn save(&self, path: &Path) -> Result<()> {
281 let dir = path.parent().context("the record has no directory")?;
282 fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
283 let scratch = path.with_extension("json.new");
284 let mut text = serde_json::to_vec_pretty(self)?;
285 text.push(b'\n');
286 File::create(&scratch)
287 .and_then(|mut file| {
288 file.write_all(&text)?;
289 file.sync_all()
290 })
291 .with_context(|| format!("cannot write {}", scratch.display()))?;
292 fs::rename(&scratch, path).with_context(|| format!("cannot write {}", path.display()))?;
293 #[cfg(unix)]
294 if let Ok(dir) = File::open(dir) {
295 let _ = dir.sync_all();
296 }
297 Ok(())
298 }
299
300 /// Whether this repository's verify made `id`: a revert, as made or
301 /// landed.
302 fn made(&self, id: ObjectId) -> bool {
303 let hex = id.to_hex();
304 self.reverts
305 .iter()
306 .any(|r| r.revert == hex || r.landed.as_deref() == Some(hex.as_str()))
307 }
308
309 /// The reverts landed in the hour before `now`, by the id that holds
310 /// each on the branch.
311 fn in_last_hour(&self, now: u64) -> HashSet<String> {
312 self.reverts
313 .iter()
314 .filter(|r| r.time + 3600 > now)
315 .map(|r| r.landed.clone().unwrap_or_else(|| r.revert.clone()))
316 .collect()
317 }
318}
319
320fn now_seconds() -> u64 {
321 SystemTime::now()
322 .duration_since(UNIX_EPOCH)
323 .map_or(0, |since| since.as_secs())
324}
325
326/// The value of an extra field of `changeset`.
327fn extra<'c>(changeset: &'c Changeset, key: &[u8]) -> Option<&'c [u8]> {
328 changeset
329 .extras
330 .iter()
331 .find(|(k, _)| k.as_slice() == key)
332 .map(|(_, value)| value.as_slice())
333}
334
335/// Whether `changeset` says it is a revert verify made: a `reverts` field,
336/// and `braid-verify` as its agent. Anyone can write both, which is why it
337/// is only ever a reason to refuse.
338fn is_verify_revert(changeset: &Changeset) -> bool {
339 extra(changeset, REVERTS).is_some() && extra(changeset, AGENT_FIELD) == Some(AGENT.as_bytes())
340}
341
342/// The reverts verify made that landed on the branch below `tip` in the
343/// hour before `now`, by committer time. The walk down first parents stops
344/// at the first changeset committed earlier than that.
345fn reverts_in_last_hour(repo: &Repo, tip: ObjectId, now: u64) -> Result<HashSet<String>> {
346 let since = now as i64 - 3600;
347 let mut found = HashSet::new();
348 let mut current = Some(tip);
349 for _ in 0..HISTORY_LIMIT {
350 let Some(id) = current else { break };
351 let changeset = braid_engine::read_changeset(repo.store(), id)?;
352 if changeset.committer.seconds <= since {
353 break;
354 }
355 if is_verify_revert(&changeset) {
356 found.insert(id.to_hex());
357 }
358 current = changeset.parents.first().copied();
359 }
360 Ok(found)
361}
362
363/// How a changeset fared.
364enum Check {
365 /// The tests passed: `flaky` when a run failed first.
366 Passed { flaky: bool },
367 /// Every run failed.
368 Failed,
369 /// Its files cannot be written on this system, so it was not tested.
370 Skipped,
371}
372
373/// Runs the test command on changesets, counting the runs.
374struct Tester<'a> {
375 repo: &'a Repo,
376 branch: &'a str,
377 command: &'a [OsString],
378 timeout: Duration,
379 reruns: u32,
380 runs: usize,
381}
382
383/// How one run ended.
384enum RunEnd {
385 Exited(ExitStatus),
386 TimedOut,
387}
388
389impl Tester<'_> {
390 /// Whether the tests pass on `changeset`: the first run, or one of the
391 /// reruns after it fails.
392 fn check(&mut self, changeset: ObjectId) -> Result<Check> {
393 for attempt in 0..=self.reruns {
394 match self.run(changeset)? {
395 None => return Ok(Check::Skipped),
396 Some(true) => return Ok(Check::Passed { flaky: attempt > 0 }),
397 Some(false) => {}
398 }
399 }
400 Ok(Check::Failed)
401 }
402
403 /// Runs the command once on a fresh copy of `changeset`: whether it
404 /// passed, or `None` when the files cannot be written here.
405 fn run(&mut self, changeset: ObjectId) -> Result<Option<bool>> {
406 let dir = scratch_dir()?;
407 let result = self.run_in(changeset, &dir);
408 // Whatever the command left goes too.
409 let _ = fs::remove_dir_all(&dir);
410 let Some(end) = result? else {
411 return Ok(None);
412 };
413 // Only a command that ran counts.
414 self.runs += 1;
415 let passed = matches!(&end, RunEnd::Exited(status) if status.success());
416 let said = match &end {
417 RunEnd::Exited(status) if status.success() => "passed".to_owned(),
418 RunEnd::Exited(status) => format!("failed ({status})"),
419 RunEnd::TimedOut => format!("timed out after {:?} and was killed", self.timeout),
420 };
421 eprintln!("braid verify: {} {said}", changeset.short());
422 Ok(Some(passed))
423 }
424
425 fn run_in(&self, changeset: ObjectId, dir: &Path) -> Result<Option<RunEnd>> {
426 match braid_wc::materialize(self.repo.store(), changeset, dir) {
427 Ok(_) => {}
428 Err(err @ (braid_wc::Error::Unsafe { .. } | braid_wc::Error::Collision { .. })) => {
429 eprintln!(
430 "braid verify: {} skipped: its files cannot be written here: {err}",
431 changeset.short()
432 );
433 return Ok(None);
434 }
435 Err(err) => {
436 return Err(err).with_context(|| {
437 format!("cannot write changeset {} to test it", changeset.short())
438 });
439 }
440 }
441 let (program, args) = self.command.split_first().context("no command to run")?;
442 let mut command = Command::new(program);
443 command
444 .args(args)
445 .current_dir(dir)
446 .stdin(Stdio::null())
447 .stdout(to_stderr()?)
448 .stderr(to_stderr()?)
449 .env("BRAID_VERIFY_CHANGESET", changeset.to_hex())
450 .env("BRAID_VERIFY_BRANCH", self.branch)
451 .env("PWD", dir)
452 .env_remove("OLDPWD");
453 for (name, _) in std::env::vars_os() {
454 if is_credential(&name) {
455 command.env_remove(&name);
456 }
457 }
458 #[cfg(unix)]
459 {
460 use std::os::unix::process::CommandExt;
461 // A group of its own, so that what it started goes with it.
462 command.process_group(0);
463 }
464 let mut child = command
465 .spawn()
466 .with_context(|| format!("cannot run {}", program.to_string_lossy()))?;
467 let watchdog = match Watchdog::start(&child, dir) {
468 Ok(watchdog) => watchdog,
469 Err(err) => {
470 kill_group(&mut child);
471 let _ = child.wait();
472 return Err(err);
473 }
474 };
475 let end = self.wait(&mut child);
476 watchdog.done();
477 end.map(Some)
478 }
479
480 /// Waits for the command, at most until the timeout, then kills its
481 /// group: whatever it left running, or all of it on a timeout.
482 fn wait(&self, child: &mut Child) -> Result<RunEnd> {
483 let deadline = Instant::now() + self.timeout;
484 loop {
485 if exited(child)? {
486 // The command is not reaped yet, so its group's id cannot
487 // be anyone else's.
488 kill_group(child);
489 return Ok(RunEnd::Exited(child.wait()?));
490 }
491 let now = Instant::now();
492 if now >= deadline {
493 kill_group(child);
494 let _ = child.wait();
495 return Ok(RunEnd::TimedOut);
496 }
497 std::thread::sleep((deadline - now).min(Duration::from_millis(20)));
498 }
499 }
500}
501
502/// Whether the command exited, without reaping it where the system can.
503fn exited(child: &mut Child) -> Result<bool> {
504 #[cfg(unix)]
505 {
506 use rustix::process::{Pid, WaitId, WaitIdOptions, waitid};
507 let options = WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT;
508 loop {
509 match waitid(WaitId::Pid(Pid::from_child(child)), options) {
510 Ok(found) => return Ok(found.is_some()),
511 Err(rustix::io::Errno::INTR) => continue,
512 Err(err) => return Err(io::Error::from(err).into()),
513 }
514 }
515 }
516 #[cfg(not(unix))]
517 {
518 Ok(child.try_wait()?.is_some())
519 }
520}
521
522/// A process that kills a test run's group, and removes its directory,
523/// if braid goes away while it runs: it waits for its standard input to
524/// close, which happens however braid ends, and does nothing when braid
525/// said `done` first.
526struct Watchdog(Option<Child>);
527
528impl Watchdog {
529 #[cfg(unix)]
530 fn start(child: &Child, dir: &Path) -> Result<Watchdog> {
531 use std::os::unix::process::CommandExt;
532 let exe = std::env::current_exe().context("cannot find the braid command")?;
533 let watchdog = Command::new(exe)
534 .arg(WATCHDOG)
535 .arg(child.id().to_string())
536 .arg(dir)
537 .stdin(Stdio::piped())
538 .stdout(Stdio::null())
539 .stderr(Stdio::null())
540 // Out of braid's group, so that a Ctrl-C meant for braid does
541 // not stop it too.
542 .process_group(0)
543 .spawn()
544 .context("cannot start verify's watchdog")?;
545 Ok(Watchdog(Some(watchdog)))
546 }
547
548 #[cfg(not(unix))]
549 fn start(_child: &Child, _dir: &Path) -> Result<Watchdog> {
550 Ok(Watchdog(None))
551 }
552
553 /// Tells the watchdog the run is over, and waits for it.
554 fn done(mut self) {
555 if let Some(mut watchdog) = self.0.take() {
556 if let Some(mut stdin) = watchdog.stdin.take() {
557 let _ = stdin.write_all(b"done\n");
558 }
559 let _ = watchdog.wait();
560 }
561 }
562}
563
564/// The watchdog of one test run, as [`Watchdog`] starts it: `group` is the
565/// test's process group, `dir` its scratch directory.
566pub(crate) fn watchdog(group: &str, dir: &Path) -> Result<ExitCode> {
567 let mut said = Vec::new();
568 let _ = io::stdin().lock().read_to_end(&mut said);
569 if said.starts_with(b"done") {
570 return Ok(ExitCode::SUCCESS);
571 }
572 // Braid went away while the tests ran.
573 #[cfg(unix)]
574 if let Some(pid) = group
575 .parse::<i32>()
576 .ok()
577 .filter(|group| *group > 1)
578 .and_then(rustix::process::Pid::from_raw)
579 {
580 let _ = rustix::process::kill_process_group(pid, rustix::process::Signal::KILL);
581 }
582 #[cfg(not(unix))]
583 let _ = group;
584 // Only ever one of verify's scratch directories.
585 let ours = dir.parent() == Some(std::env::temp_dir().as_path())
586 && dir
587 .file_name()
588 .is_some_and(|name| name.to_string_lossy().starts_with(SCRATCH_PREFIX));
589 if ours {
590 for _ in 0..10 {
591 if fs::remove_dir_all(dir).is_ok() || !dir.exists() {
592 break;
593 }
594 std::thread::sleep(Duration::from_millis(50));
595 }
596 }
597 Ok(ExitCode::SUCCESS)
598}
599
600/// Whether an environment variable is one of the hub's credentials or
601/// settings, which the tests never see: `BRAID_TOKEN` and every variable
602/// whose name starts with `BRAID_HUB`.
603fn is_credential(name: &std::ffi::OsStr) -> bool {
604 let name = name.to_string_lossy();
605 name == "BRAID_TOKEN" || name.starts_with("BRAID_HUB")
606}
607
608/// Kills the command and every process left in its group. A group already
609/// gone is no error.
610fn kill_group(child: &mut Child) {
611 #[cfg(unix)]
612 {
613 let group = rustix::process::Pid::from_child(child);
614 let _ = rustix::process::kill_process_group(group, rustix::process::Signal::KILL);
615 }
616 let _ = child.kill();
617}
618
619/// Standard error, for the command's output, so that standard output keeps
620/// only the report.
621fn to_stderr() -> Result<Stdio> {
622 #[cfg(unix)]
623 {
624 use std::os::fd::AsFd;
625 Ok(Stdio::from(io::stderr().as_fd().try_clone_to_owned()?))
626 }
627 #[cfg(windows)]
628 {
629 use std::os::windows::io::AsHandle;
630 Ok(Stdio::from(io::stderr().as_handle().try_clone_to_owned()?))
631 }
632 #[cfg(not(any(unix, windows)))]
633 {
634 Ok(Stdio::inherit())
635 }
636}
637
638/// A new, empty directory under the system's temporary directory, readable
639/// only by this user where the system has modes.
640fn scratch_dir() -> Result<PathBuf> {
641 static COUNTER: AtomicU32 = AtomicU32::new(0);
642 let base = std::env::temp_dir();
643 let nanos = SystemTime::now()
644 .duration_since(UNIX_EPOCH)
645 .map_or(0, |since| since.subsec_nanos());
646 loop {
647 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
648 let dir = base.join(format!(
649 "{SCRATCH_PREFIX}{}-{nanos:08x}-{n}",
650 std::process::id()
651 ));
652 let mut builder = fs::DirBuilder::new();
653 #[cfg(unix)]
654 {
655 use std::os::unix::fs::DirBuilderExt;
656 builder.mode(0o700);
657 }
658 match builder.create(&dir) {
659 Ok(()) => return Ok(dir),
660 Err(err) if err.kind() == io::ErrorKind::AlreadyExists && n < 1000 => continue,
661 Err(err) => {
662 return Err(err).with_context(|| format!("cannot create {}", dir.display()));
663 }
664 }
665 }
666}
667
668/// The changesets after `good` up to `tip`, along first parents, oldest
669/// first, or `None` when `good` is not on the chain.
670fn range(repo: &Repo, tip: ObjectId, good: ObjectId) -> Result<Option<Vec<ObjectId>>> {
671 let mut chain = Vec::new();
672 let mut current = tip;
673 while current != good {
674 chain.push(current);
675 match braid_engine::read_changeset(repo.store(), current)?
676 .parents
677 .first()
678 {
679 Some(parent) => current = *parent,
680 None => return Ok(None),
681 }
682 }
683 chain.reverse();
684 Ok(Some(chain))
685}
686
687/// `a, b and c`, of short ids.
688fn listed(ids: &[ObjectId]) -> String {
689 let shorts: Vec<String> = ids.iter().map(ObjectId::short).collect();
690 match shorts.as_slice() {
691 [] => String::new(),
692 [one] => one.clone(),
693 [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
694 }
695}
696
697/// Everything one pass needs.
698struct Pass<'a> {
699 args: &'a VerifyArgs,
700 repo: &'a Repo,
701 link: Option<Link>,
702 branch: &'a str,
703 tip: ObjectId,
704 green_before: Option<ObjectId>,
705 /// `--from`, resolved.
706 from: Option<ObjectId>,
707}
708
709impl Pass<'_> {
710 fn run(&self, tester: &mut Tester<'_>, verdict: &mut Verdict) -> Result<()> {
711 if self.green_before == Some(self.tip) {
712 verdict.outcome = "pass";
713 verdict.reason = Some("the head is the green changeset already".to_owned());
714 return Ok(());
715 }
716 let flaky = match tester.check(self.tip)? {
717 Check::Passed { flaky } => flaky,
718 Check::Failed => return self.red(tester, verdict),
719 Check::Skipped => bail!(
720 "the files of the head, {}, cannot be written on this system, so it cannot be tested here",
721 self.tip.short()
722 ),
723 };
724 verdict.outcome = if flaky { "flaky" } else { "pass" };
725 let mut reasons = Vec::new();
726 if flaky {
727 reasons.push("a run failed, and a rerun passed".to_owned());
728 }
729 if flaky && !self.args.flaky_moves_green {
730 reasons.push("the green ref stays; --flaky-moves-green would move it".to_owned());
731 } else if self.args.dry_run {
732 reasons.push(format!(
733 "dry run: the green ref would move to {}",
734 self.tip.short()
735 ));
736 } else {
737 self.move_green()?;
738 verdict.green = Some(self.tip);
739 }
740 if !reasons.is_empty() {
741 verdict.reason = Some(reasons.join("; "));
742 }
743 Ok(())
744 }
745
746 /// The tests fail on the head: find the first changeset that fails.
747 fn red(&self, tester: &mut Tester<'_>, verdict: &mut Verdict) -> Result<()> {
748 verdict.outcome = "red";
749 let Some(good) = self.from.or(self.green_before) else {
750 verdict.reason = Some(
751 "the tests fail on the head, and with no green changeset there is nothing to bisect from: --from names one"
752 .to_owned(),
753 );
754 return Ok(());
755 };
756 let Some(range) = range(self.repo, self.tip, good)? else {
757 verdict.reason = Some(format!(
758 "{} is not on {}'s first-parent chain: there is nothing to bisect",
759 good.short(),
760 self.branch
761 ));
762 return Ok(());
763 };
764 if range.is_empty() {
765 verdict.red(
766 "no_culprit",
767 format!("the head is {}, which was to pass", good.short()),
768 );
769 return Ok(());
770 }
771 let last = range.len() as isize - 1;
772 // `range[lo]` passes (or is `good`, at -1), and the head fails.
773 let mut lo = -1;
774 loop {
775 let (passing, failing, untested) = bisect(tester, &range, lo, last, verdict)?;
776 if !untested.is_empty() {
777 let mut candidates: Vec<ObjectId> =
778 untested.iter().map(|i| range[*i as usize]).collect();
779 candidates.push(range[failing as usize]);
780 verdict.reason = Some(format!(
781 "the first changeset that fails is one of {}: the others could not be tested here",
782 listed(&candidates)
783 ));
784 return Ok(());
785 }
786 let culprit = range[failing as usize];
787 if let Some(at) = reverted_at(self.repo, &range, failing)? {
788 // Fixed once already: what fails now came after, hidden by
789 // the culprit until its revert.
790 let revert = range[at];
791 let hidden = format!(
792 "{} fails, and {revert_short} reverted it later, but the tests fail at {revert_short} too: what broke them since is hidden behind {}",
793 culprit.short(),
794 culprit.short(),
795 revert_short = revert.short()
796 );
797 if at as isize == last {
798 verdict.red("no_culprit", hidden);
799 return Ok(());
800 }
801 match tester.check(revert)? {
802 Check::Passed { .. } => {
803 lo = at as isize;
804 continue;
805 }
806 Check::Failed => {
807 verdict.red("no_culprit", hidden);
808 return Ok(());
809 }
810 Check::Skipped => {
811 verdict.skipped.push(revert);
812 verdict.reason = Some(format!(
813 "{} fails, and {} reverted it later, but the revert could not be tested here",
814 culprit.short(),
815 revert.short()
816 ));
817 return Ok(());
818 }
819 }
820 }
821 if passing < 0 {
822 match tester.check(good)? {
823 Check::Passed { .. } => {}
824 Check::Failed => {
825 // The changeset taken as passing fails now too:
826 // something outside the range broke the tests.
827 verdict.red(
828 "no_culprit",
829 format!(
830 "{} fails too, though it was to pass: the failure is not in the changesets after it",
831 good.short()
832 ),
833 );
834 return Ok(());
835 }
836 // It cannot be checked; it was to pass.
837 Check::Skipped => verdict.skipped.push(good),
838 }
839 }
840 verdict.culprit = Some(culprit);
841 return self.revert(culprit, verdict);
842 }
843 }
844
845 /// Moves the green ref from where it was to the tip, unless someone
846 /// moved it meanwhile.
847 fn move_green(&self) -> Result<()> {
848 let name = green_ref(self.branch);
849 let description = format!("verify: {name} at {}", self.tip.short());
850 self.repo
851 .store()
852 .transact(AGENT, &description, |refs| {
853 let current = refs.get(&name);
854 if current != self.green_before {
855 return Err(format!(
856 "{name} moved while verify ran, to {}: is another verify running?",
857 short(current)
858 ));
859 }
860 Ok(vec![RefUpdate::new(
861 name.clone(),
862 self.green_before,
863 Some(self.tip),
864 )])
865 })
866 .map_err(|err| anyhow::anyhow!("{err}"))?;
867 Ok(())
868 }
869
870 /// Decides whether to revert `culprit`, and does.
871 fn revert(&self, culprit: ObjectId, verdict: &mut Verdict) -> Result<()> {
872 let first = format!(
873 "the tests fail from {}, the first changeset that fails",
874 culprit.short()
875 );
876 if !self.args.revert {
877 verdict.reason = Some(format!("{first}; --revert would revert it"));
878 return Ok(());
879 }
880 let changeset = braid_engine::read_changeset(self.repo.store(), culprit)?;
881 let path = Record::path(self.repo, self.branch);
882 let mut record = Record::load(&path)?;
883 let now = now_seconds();
884 let mut recent = reverts_in_last_hour(self.repo, self.tip, now)?;
885 recent.extend(record.in_last_hour(now));
886 let refusal = if changeset.parents.len() > 1 {
887 Some(format!(
888 "{first}, and it is a merge: verify does not revert merges"
889 ))
890 } else if is_verify_revert(&changeset) || record.made(culprit) {
891 Some(format!(
892 "{first}, and it is a revert verify made: verify does not revert its own reverts"
893 ))
894 } else if recent.len() >= self.args.max_reverts_per_hour {
895 Some(format!(
896 "{first}, but verify landed {} on {} in the last hour, the most --max-reverts-per-hour allows",
897 count(recent.len(), "revert"),
898 self.branch
899 ))
900 } else {
901 None
902 };
903 if let Some(reason) = refusal {
904 verdict.red("refused", reason);
905 return Ok(());
906 }
907 if self.args.dry_run {
908 verdict.reason = Some(format!("{first}; dry run: verify would revert it"));
909 return Ok(());
910 }
911 let author = identity(&self.args.identity, self.repo)?;
912 let change = braid_wc::create_revert(
913 self.repo.store(),
914 &RevertRequest {
915 culprit,
916 mainline: false,
917 author: author.clone(),
918 agent: AGENT.to_owned(),
919 },
920 )?;
921 verdict.revert = Some(change);
922 let landed = land_revert(
923 self.repo,
924 self.link.as_ref(),
925 self.branch,
926 change,
927 AGENT,
928 &author,
929 );
930 let mut report = match landed {
931 Ok(report) => report,
932 Err(err) => {
933 // The hub may have landed it all the same: the record
934 // keeps it, as the branch will once fetched.
935 record.reverts.push(Reverted {
936 culprit: culprit.to_hex(),
937 revert: change.to_hex(),
938 landed: None,
939 time: now,
940 });
941 let _ = record.save(&path);
942 return Err(err);
943 }
944 };
945 let outcome = report.outcome.clone();
946 match outcome.as_str() {
947 "fast-forward" | "rebased" => {
948 verdict.red(
949 "reverted",
950 format!("{first}; its revert landed on {}", self.branch),
951 );
952 record.reverts.push(Reverted {
953 culprit: culprit.to_hex(),
954 revert: change.to_hex(),
955 landed: report.head.map(|id| id.to_hex()),
956 time: now,
957 });
958 verdict.land = Some(report);
959 record.save(&path)?;
960 return Ok(());
961 }
962 "conflicts" => {
963 verdict.red(
964 "revert_conflicts",
965 format!(
966 "{first}; its revert conflicts with what landed since, so {} did not move: revert it by hand in a workspace",
967 self.branch
968 ),
969 );
970 report.next = None;
971 }
972 "already-applied" => verdict.red(
973 "refused",
974 format!(
975 "{first}, but {} has what its revert would change already",
976 self.branch
977 ),
978 ),
979 other => {
980 verdict.land = Some(report);
981 bail!("the revert's landing ended with {other}");
982 }
983 }
984 verdict.land = Some(report);
985 Ok(())
986 }
987}
988
989/// Bisects `range` between `lo`, which passes (-1 for the changeset before
990/// the range), and `hi`, which fails, skipping changesets that cannot be
991/// tested. Returns the last passing and the first failing index found, and
992/// the skipped indexes between them.
993fn bisect(
994 tester: &mut Tester<'_>,
995 range: &[ObjectId],
996 mut lo: isize,
997 mut hi: isize,
998 verdict: &mut Verdict,
999) -> Result<(isize, isize, Vec<isize>)> {
1000 let mut skipped = BTreeSet::new();
1001 loop {
1002 let middle = lo + (hi - lo) / 2;
1003 let Some(pick) = (lo + 1..hi)
1004 .filter(|i| !skipped.contains(i))
1005 .min_by_key(|i| (i - middle).abs())
1006 else {
1007 break;
1008 };
1009 match tester.check(range[pick as usize])? {
1010 Check::Passed { .. } => lo = pick,
1011 Check::Failed => hi = pick,
1012 Check::Skipped => {
1013 skipped.insert(pick);
1014 verdict.skipped.push(range[pick as usize]);
1015 }
1016 }
1017 }
1018 let untested = skipped.into_iter().filter(|i| *i > lo && *i < hi).collect();
1019 Ok((lo, hi, untested))
1020}
1021
1022/// Where in `range`, after `index`, a changeset reverts `range[index]`, if
1023/// one does.
1024fn reverted_at(repo: &Repo, range: &[ObjectId], index: isize) -> Result<Option<usize>> {
1025 let culprit = range[index as usize].to_hex().into_bytes();
1026 for (at, id) in range.iter().enumerate().skip(index as usize + 1) {
1027 let changeset = braid_engine::read_changeset(repo.store(), *id)?;
1028 if extra(&changeset, REVERTS) == Some(culprit.as_slice()) {
1029 return Ok(Some(at));
1030 }
1031 }
1032 Ok(None)
1033}
1034
1035pub(crate) fn verify(cli: &Cli, args: &VerifyArgs) -> Result<ExitCode> {
1036 let repo = open_repo(cli)?;
1037 let branch = branch_or_main(&repo, args.branch.as_deref())?;
1038 let link = hub::linked(&repo, args.local)?;
1039 if let Some(link) = &link
1040 && !args.dry_run
1041 {
1042 let hub = hub::connect(link)?;
1043 let remote = hub.repo(link.repo.clone());
1044 hub::fetch::fetch(&repo, &remote, link, AGENT, None).context(
1045 "cannot fetch from the hub before verifying (--local verifies the local branch as it is)",
1046 )?;
1047 }
1048 let refs = repo.store().refs()?;
1049 let Some(tip) = refs.get(&branch) else {
1050 bail!("there is no branch {branch:?} to verify");
1051 };
1052 let from = match &args.from {
1053 Some(revision) => Some(resolve_changeset(&repo, revision)?),
1054 None => None,
1055 };
1056 let green_before = refs.get(&green_ref(&branch));
1057 let pass = Pass {
1058 args,
1059 repo: &repo,
1060 link,
1061 branch: &branch,
1062 tip,
1063 green_before,
1064 from,
1065 };
1066 let mut tester = Tester {
1067 repo: &repo,
1068 branch: &branch,
1069 command: &args.command,
1070 timeout: args.timeout,
1071 reruns: args.reruns,
1072 runs: 0,
1073 };
1074 let mut verdict = Verdict {
1075 green: green_before,
1076 ..Verdict::default()
1077 };
1078 if let Err(err) = pass.run(&mut tester, &mut verdict) {
1079 // Before anything ran or was made, an error is only an error.
1080 if tester.runs == 0 && verdict.revert.is_none() {
1081 return Err(err);
1082 }
1083 eprintln!("braid: error: {err:#}");
1084 verdict.outcome = "error";
1085 verdict.reason = Some(format!("{err:#}"));
1086 }
1087 if cli.json {
1088 print_json(&json!({
1089 "branch": branch,
1090 "tip": tip.to_hex(),
1091 "green_before": hex(green_before),
1092 "green": hex(verdict.green),
1093 "outcome": verdict.outcome,
1094 "culprit": hex(verdict.culprit),
1095 "revert": hex(verdict.revert),
1096 "skipped": verdict.skipped.iter().map(ObjectId::to_hex).collect::<Vec<_>>(),
1097 "tests_run": tester.runs,
1098 "reason": verdict.reason,
1099 "dry_run": args.dry_run,
1100 "land": verdict.land.as_ref().map_or(Value::Null, Report::json),
1101 }))?;
1102 } else {
1103 print_text(&branch, tip, &verdict, tester.runs);
1104 }
1105 Ok(verdict.exit_code())
1106}
1107
1108fn print_text(branch: &str, tip: ObjectId, verdict: &Verdict, runs: usize) {
1109 let ran = count(runs, "run");
1110 match verdict.outcome {
1111 "pass" | "flaky" => println!(
1112 "{branch} is green at {} ({}, {ran})",
1113 tip.short(),
1114 verdict.outcome
1115 ),
1116 outcome => println!("{branch} at {}: {outcome} ({ran})", tip.short()),
1117 }
1118 if let Some(reason) = &verdict.reason {
1119 println!("{reason}");
1120 }
1121 if let Some(revert) = verdict.revert {
1122 println!("Revert: {}", revert.short());
1123 }
1124 if !verdict.skipped.is_empty() {
1125 println!("Not tested here: {}", listed(&verdict.skipped));
1126 }
1127 if let Some(report) = &verdict.land
1128 && report.conflicted()
1129 {
1130 print_conflicts(&report.conflicts);
1131 }
1132}
1133
1134#[cfg(test)]
1135mod tests {
1136 use super::*;
1137
1138 #[test]
1139 fn durations() {
1140 assert_eq!(parse_duration("10m"), Ok(Duration::from_secs(600)));
1141 assert_eq!(parse_duration("30s"), Ok(Duration::from_secs(30)));
1142 assert_eq!(parse_duration("2h"), Ok(Duration::from_secs(7200)));
1143 assert_eq!(parse_duration("45"), Ok(Duration::from_secs(45)));
1144 for bad in ["", "0s", "m", "10x", "1.5m", "-1s", "10 m"] {
1145 assert!(parse_duration(bad).is_err(), "{bad}");
1146 }
1147 }
1148
1149 #[test]
1150 fn credentials_are_recognised() {
1151 for name in [
1152 "BRAID_TOKEN",
1153 "BRAID_HUB",
1154 "BRAID_HUB_URL",
1155 "BRAID_HUB_MAX_BODY",
1156 ] {
1157 assert!(is_credential(name.as_ref()), "{name}");
1158 }
1159 for name in ["BRAID_AGENT", "BRAID_AUTHOR", "PATH", "BRAID_TOKENS"] {
1160 assert!(!is_credential(name.as_ref()), "{name}");
1161 }
1162 }
1163
1164 #[test]
1165 fn record_files_are_named_in_hex_and_kept_whole() {
1166 let temp = tempfile::tempdir().unwrap();
1167 let repo = Repo::init(temp.path()).unwrap();
1168 let path = Record::path(&repo, "feature/x");
1169 assert_eq!(path.file_name().unwrap(), "666561747572652f78.json");
1170 // Two names that differ only in case get two files.
1171 assert_ne!(Record::path(&repo, "Main"), Record::path(&repo, "main"));
1172 let mut record = Record::default();
1173 record.reverts.push(Reverted {
1174 culprit: "c".repeat(64),
1175 revert: "a".repeat(64),
1176 landed: Some("b".repeat(64)),
1177 time: 10_000,
1178 });
1179 let landed: ObjectId = "b".repeat(64).parse().unwrap();
1180 assert!(record.made(landed));
1181 assert_eq!(record.in_last_hour(10_000 + 3599).len(), 1);
1182 assert_eq!(record.in_last_hour(10_000 + 3600).len(), 0);
1183 record.save(&path).unwrap();
1184 assert_eq!(Record::load(&path).unwrap().reverts.len(), 1);
1185 assert!(!path.with_extension("json.new").exists());
1186
1187 // A damaged record says how to recover.
1188 fs::write(&path, "{").unwrap();
1189 let err = format!("{:#}", Record::load(&path).unwrap_err());
1190 assert!(err.contains("delete it"), "{err}");
1191 }
1192
1193 #[test]
1194 fn ids_are_listed_in_words() {
1195 let ids: Vec<ObjectId> = ["a", "b", "c"]
1196 .iter()
1197 .map(|c| c.repeat(64).parse().unwrap())
1198 .collect();
1199 assert_eq!(listed(&ids[..1]), "a".repeat(12));
1200 assert_eq!(
1201 listed(&ids),
1202 format!(
1203 "{}, {} and {}",
1204 "a".repeat(12),
1205 "b".repeat(12),
1206 "c".repeat(12)
1207 )
1208 );
1209 }
1210}