Elffuss BraidHub

utopia-ia/elffuss-braid public

verify: bisect past its own reverts, guards a clone keeps, no leftovers

- A culprit reverted later in the range no longer stalls the bisect: verify
  tests the revert and, when it passes, bisects again after it.
- Its own reverts are told by their reverts field and the agent
  braid-verify, and the hourly cap is counted on the branch by committer
  time, so a fresh clone keeps both rules; .braid/verify/ is a second
  source. Its files are named by the branch in hex, written with an fsync,
  and a damaged one says to delete it.
- The test's process group is killed whenever the command exits, not only
  on a timeout, while the command is not yet reaped. A watchdog process,
  braid's hidden __verify-watchdog, kills the group and removes the copy
  when braid goes away, by a signal or otherwise.
- PWD names the copy and OLDPWD is taken out.
- A flaky pass leaves the green ref unless --flaky-moves-green; --from is
  resolved before any test; a changeset whose files cannot be written here
  is skipped and listed; an error after a revert landed keeps the culprit,
  the revert and the landing in the report.
Changeset20a66f74c39ef486402fffd26bd21bbfd3b0c098a1f2da350e6a6e346b396361
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-21 12:16 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-21 12:16 +02:00
Parentsa93ee013835a

Browse the files at this changeset

3 files changed

modified crates/cli/src/main.rs +9 −0
@@ -324,6 +324,14 @@
324324 /// the branch is red).
325325 #[command(long_about = verify::VERIFY_HELP)]
326326 Verify(verify::VerifyArgs),
327+ /// Kill a test run's process group when verify goes away (internal).
328+ #[command(name = verify::WATCHDOG, hide = true)]
329+ VerifyWatchdog {
330+ /// The process group of the test run.
331+ group: String,
332+ /// The run's scratch directory.
333+ dir: PathBuf,
334+ },
327335 }
328336
329337 #[derive(Debug, Subcommand)]
@@ -528,6 +536,7 @@
528536 Command::Change { action } => work::change(cli, action),
529537 Command::Revert(args) => revert::revert(cli, args),
530538 Command::Verify(args) => verify::verify(cli, args),
539+ Command::VerifyWatchdog { group, dir } => verify::watchdog(group, dir),
531540 }
532541 }
533542
modified crates/cli/src/verify.rs +605 −193
@@ -6,24 +6,32 @@
66 //! changeset that broke them and, if asked, revert it.
77 //!
88 //! One pass per invocation. The tests run in a fresh copy of the
9-//! changeset's files outside the repository, with no shell, and with the
10-//! hub's credentials taken out of their environment. The green ref,
11-//! `braid/green/<branch>`, is in braid's own namespace, so it is never
12-//! exported to git or sent to a hub; it moves with a compare-and-swap, in
13-//! an operation of its own. The reverts verify landed are recorded in
14-//! `.braid/verify/<branch>.json`, which is what it trusts to tell its own
15-//! reverts, never the `reverts` field a changeset carries.
16-
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+
23+use std::collections::{BTreeSet, HashSet};
1724 use std::ffi::OsString;
18-use std::fs;
19-use std::io;
25+use std::fs::{self, File};
26+use std::io::{self, Read, Write};
2027 use std::path::{Path, PathBuf};
2128 use std::process::{Child, Command, ExitCode, ExitStatus, Stdio};
2229 use std::sync::atomic::{AtomicU32, Ordering};
2330 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
2431
2532 use anyhow::{Context, Result, bail};
26-use braid_format::ObjectId;
33+use braid_engine::{AGENT as AGENT_FIELD, REVERTS};
34+use braid_format::{Changeset, ObjectId};
2735 use braid_repo::Repo;
2836 use braid_store::RefUpdate;
2937 use braid_wc::RevertRequest;
@@ -33,13 +41,16 @@
3341
3442 use crate::hub::{self, link::Link};
3543 use crate::revert::{branch_or_main, land_revert};
36-use crate::work::{IdentityArgs, Report, hex, identity, print_conflicts, short};
44+use crate::work::{IdentityArgs, Report, count, hex, identity, print_conflicts, short};
3745 use crate::{Cli, open_repo, print_json, resolve_changeset};
3846
3947 /// The agent label of everything verify records: the green ref's moves,
4048 /// and the reverts it makes and lands.
4149 pub(crate) const AGENT: &str = "braid-verify";
4250
51+/// The hidden subcommand that watches a test run for braid going away.
52+pub(crate) const WATCHDOG: &str = "__verify-watchdog";
53+
4354 /// Exit status of a pass that leaves the branch red: the tests fail on its
4455 /// head, whether or not the culprit was found or reverted.
4556 const RED: u8 = 4;
@@ -47,6 +58,13 @@
4758 /// The exit status of a revert that conflicts, as for every conflict.
4859 const CONFLICTS: u8 = crate::work::CONFLICTS;
4960
61+/// The prefix of the scratch directories the tests run in.
62+const 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.
66+const HISTORY_LIMIT: usize = 10_000;
67+
5068 /// The green ref of `branch`: the newest changeset of it that passed.
5169 pub(crate) fn green_ref(branch: &str) -> String {
5270 format!("braid/green/{branch}")
@@ -61,47 +79,64 @@
6179
6280 The command comes after `--` and runs as given, with no shell: write
6381 `-- sh -c '...'` for one. It runs in a fresh copy of the changeset's files,
64-in a new directory under the system's temporary directory: outside the
65-repository, with no .braid file and no .git, so each run starts from
66-scratch and nothing it writes stays. Its output goes to standard error. It
67-gets BRAID_VERIFY_CHANGESET (the changeset's id) and BRAID_VERIFY_BRANCH,
68-and neither BRAID_TOKEN nor any BRAID_HUB variable. A run fails when the
69-command exits with a status other than 0, is killed, or runs longer than
70---timeout (10m by default; s, m and h are the units), which kills it and
71-every process it started.
82+in a new directory under the system's temporary directory, outside the
83+repository and with no .braid file and no .git, so each run starts from
84+scratch; the directory is removed after the run. Its output goes to
85+standard error. It gets BRAID_VERIFY_CHANGESET (the changeset's id),
86+BRAID_VERIFY_BRANCH and PWD (its directory); BRAID_TOKEN, every variable
87+whose name starts with BRAID_HUB, and OLDPWD are taken out.
88+
89+That is all the isolation there is: the command runs as you, with your
90+access to every file, the network, the braid command, and any hub login
91+saved in braid's configuration directory. Run verify in a sandbox, a
92+container or as a separate user when the code it tests is not trusted.
93+
94+A run fails when the command exits with a status other than 0, is killed,
95+or runs longer than --timeout (10m by default; s, m and h are the units).
96+The command runs in a process group of its own: when it exits or times
97+out, the group is killed, and so are processes it started that are still
98+in it (one that left the group, as a daemon does, is not). If braid itself
99+is stopped, a watchdog process kills the group and removes the directory.
72100
73101 - The head is the green changeset already: pass, and nothing runs.
74102 - The tests pass: the green ref moves to the head, in an operation of
75103 its own by braid-verify. A run that failed and passed when run again
76- (--reruns, 1 by default) is flaky, and moves it too.
104+ (--reruns, 1 by default) is flaky: the green ref stays, unless
105+ --flaky-moves-green.
77106 - They fail, again on every rerun: verify bisects the changesets after
78107 the green one along first parents, the head's changes and its
79108 parents', to find the first that fails. With no green ref yet it does
80- not bisect unless --from names a changeset to take as passing.
81- Midpoints run as they are: an earlier revert in the range is not
82- undone first.
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.
83114 - With --revert, the culprit is reverted and the revert landed, as
84115 `braid revert` does. Verify does not revert a merge, nor a revert it
85- made itself (it keeps those in .braid/verify/<branch>.json), nor more
86- than --max-reverts-per-hour (3 by default). The green ref does not move:
87- the next run tests the new head.
88-
89---dry-run runs the tests but moves no ref, records nothing and lands
90-nothing. In a repository linked to a hub, verify fetches first and lands a
91-revert on the hub; --local, or BRAID_HUB=off, keeps it here. Run one verify
92-per branch at a time.
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+
121+The 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
123+and does not fetch. In a repository linked to a hub, verify fetches first
124+and lands a revert on the hub; --local, or BRAID_HUB=off, keeps it here.
125+Run one verify per branch at a time.
93126
94127 With --json it prints branch; tip, the head it tested; green_before and
95128 green, the green ref before and after; outcome, one of pass, flaky, red,
96129 reverted, revert_conflicts, refused, no_culprit or error; culprit, the
97130 first failing changeset, or null; revert, the revert made, or null;
98-tests_run, how many times the command ran; reason, why, in words, or null;
99-dry_run; and land, the landing report of the revert as `braid land --help`
100-describes it, or null.
131+skipped, the changesets that could not be tested; tests_run, how many
132+times the command ran; reason, why, in words, or null; dry_run; and land,
133+the landing report of the revert as `braid land --help` describes it, or
134+null.
101135
102136 Exit status: 0 for pass and flaky; 4 for red, reverted, refused and
103-no_culprit; 2 for revert_conflicts; 1 for an error, with the report
104-printed when the tests had started.";
137+no_culprit; 2 for revert_conflicts; 1 for an error. Once the tests have
138+started, or a revert was made, an error prints the report too, with what
139+was done until then.";
105140
106141 #[derive(Debug, Args)]
107142 pub(crate) struct VerifyArgs {
@@ -112,7 +147,8 @@
112147 /// Revert the changeset that broke the tests, and land the revert.
113148 #[arg(long)]
114149 revert: bool,
115- /// Run the tests, but move no ref, record nothing and land nothing.
150+ /// Run the tests, but move no ref, record nothing, land nothing and
151+ /// fetch nothing.
116152 #[arg(long)]
117153 dry_run: bool,
118154 /// The most reverts verify lands on the branch in an hour.
@@ -122,6 +158,9 @@
122158 /// failing.
123159 #[arg(long, value_name = "N", default_value_t = 1)]
124160 reruns: u32,
161+ /// Move the green ref when the tests passed only on a rerun.
162+ #[arg(long)]
163+ flaky_moves_green: bool,
125164 /// How long one run may take: a number with s, m or h.
126165 #[arg(long, value_name = "DURATION", default_value = "10m", value_parser = parse_duration)]
127166 timeout: Duration,
@@ -161,13 +200,15 @@
161200 }
162201 }
163202
164-/// What one pass found.
203+/// What one pass found, filled in as it goes, so that an error keeps what
204+/// was done before it.
165205 #[derive(Default)]
166206 struct Verdict {
167207 outcome: &'static str,
168208 green: Option<ObjectId>,
169209 culprit: Option<ObjectId>,
170210 revert: Option<ObjectId>,
211+ skipped: Vec<ObjectId>,
171212 reason: Option<String>,
172213 land: Option<Report>,
173214 }
@@ -181,10 +222,15 @@
181222 _ => ExitCode::from(RED),
182223 }
183224 }
225+
226+ fn red(&mut self, outcome: &'static str, reason: String) {
227+ self.outcome = outcome;
228+ self.reason = Some(reason);
229+ }
184230 }
185231
186-/// The reverts verify landed on one branch, as `.braid/verify/<branch>.json`
187-/// keeps them.
232+/// The reverts verify landed on one branch from this repository, as
233+/// `.braid/verify/<branch in hex>.json` keeps them.
188234 #[derive(Debug, Default, Serialize, Deserialize)]
189235 struct Record {
190236 #[serde(default)]
@@ -199,25 +245,17 @@
199245 /// The revert as verify made it, in hex.
200246 revert: String,
201247 /// The changeset that holds it on the branch: itself, or the rebased
202- /// one.
248+ /// one; null when the landing's answer was lost.
203249 landed: Option<String>,
204250 /// When it landed, in seconds since the Unix epoch.
205251 time: u64,
206252 }
207253
208254 impl Record {
209- /// The file of `branch`. A branch name may hold `/` and other bytes a
210- /// file name should not, so all but letters, digits, `.`, `_` and `-`
211- /// are written as `%XX`.
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.
212257 fn path(repo: &Repo, branch: &str) -> PathBuf {
213- let mut name = String::new();
214- for byte in branch.bytes() {
215- if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-') {
216- name.push(byte as char);
217- } else {
218- name.push_str(&format!("%{byte:02X}"));
219- }
220- }
258+ let name: String = branch.bytes().map(|byte| format!("{byte:02x}")).collect();
221259 repo.root()
222260 .join(braid_repo::DIR)
223261 .join("verify")
@@ -226,26 +264,41 @@
226264
227265 fn load(path: &Path) -> Result<Record> {
228266 match fs::read(path) {
229- Ok(bytes) => serde_json::from_slice(&bytes)
230- .with_context(|| format!("{} is not verify's record", path.display())),
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+ }),
231273 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Record::default()),
232274 Err(err) => Err(err).with_context(|| format!("cannot read {}", path.display())),
233275 }
234276 }
235277
236- /// Writes the record whole, through a scratch file and a rename.
278+ /// Writes the record whole, through a scratch file that reaches the
279+ /// disk before it is renamed into place.
237280 fn save(&self, path: &Path) -> Result<()> {
238281 let dir = path.parent().context("the record has no directory")?;
239282 fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
240283 let scratch = path.with_extension("json.new");
241284 let mut text = serde_json::to_vec_pretty(self)?;
242285 text.push(b'\n');
243- fs::write(&scratch, text).with_context(|| format!("cannot write {}", scratch.display()))?;
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()))?;
244292 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+ }
245297 Ok(())
246298 }
247299
248- /// Whether verify made `id`: a revert of its own, as made or landed.
300+ /// Whether this repository's verify made `id`: a revert, as made or
301+ /// landed.
249302 fn made(&self, id: ObjectId) -> bool {
250303 let hex = id.to_hex();
251304 self.reverts
@@ -253,9 +306,14 @@
253306 .any(|r| r.revert == hex || r.landed.as_deref() == Some(hex.as_str()))
254307 }
255308
256- /// How many reverts landed in the hour before `now`.
257- fn in_last_hour(&self, now: u64) -> usize {
258- self.reverts.iter().filter(|r| r.time + 3600 > now).count()
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()
259317 }
260318 }
261319
@@ -265,6 +323,53 @@
265323 .map_or(0, |since| since.as_secs())
266324 }
267325
326+/// The value of an extra field of `changeset`.
327+fn 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.
338+fn 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.
345+fn 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.
364+enum 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+
268373 /// Runs the test command on changesets, counting the runs.
269374 struct Tester<'a> {
270375 repo: &'a Repo,
@@ -283,25 +388,29 @@
283388
284389 impl Tester<'_> {
285390 /// Whether the tests pass on `changeset`: the first run, or one of the
286- /// reruns after it fails. Returns whether they passed, and whether a
287- /// run failed before one passed.
288- fn passes(&mut self, changeset: ObjectId) -> Result<(bool, bool)> {
391+ /// reruns after it fails.
392+ fn check(&mut self, changeset: ObjectId) -> Result<Check> {
289393 for attempt in 0..=self.reruns {
290- if self.run(changeset)? {
291- return Ok((true, attempt > 0));
394+ match self.run(changeset)? {
395+ None => return Ok(Check::Skipped),
396+ Some(true) => return Ok(Check::Passed { flaky: attempt > 0 }),
397+ Some(false) => {}
292398 }
293399 }
294- Ok((false, false))
400+ Ok(Check::Failed)
295401 }
296402
297- /// Runs the command once on a fresh copy of `changeset`.
298- fn run(&mut self, changeset: ObjectId) -> Result<bool> {
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>> {
299406 let dir = scratch_dir()?;
300407 let result = self.run_in(changeset, &dir);
301408 // Whatever the command left goes too.
302409 let _ = fs::remove_dir_all(&dir);
410+ let Some(end) = result? else {
411+ return Ok(None);
412+ };
303413 // Only a command that ran counts.
304- let end = result?;
305414 self.runs += 1;
306415 let passed = matches!(&end, RunEnd::Exited(status) if status.success());
307416 let said = match &end {
@@ -310,12 +419,25 @@
310419 RunEnd::TimedOut => format!("timed out after {:?} and was killed", self.timeout),
311420 };
312421 eprintln!("braid verify: {} {said}", changeset.short());
313- Ok(passed)
422+ Ok(Some(passed))
314423 }
315424
316- fn run_in(&self, changeset: ObjectId, dir: &Path) -> Result<RunEnd> {
317- braid_wc::materialize(self.repo.store(), changeset, dir)
318- .with_context(|| format!("cannot write changeset {} to test it", changeset.short()))?;
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+ }
319441 let (program, args) = self.command.split_first().context("no command to run")?;
320442 let mut command = Command::new(program);
321443 command
@@ -325,7 +447,9 @@
325447 .stdout(to_stderr()?)
326448 .stderr(to_stderr()?)
327449 .env("BRAID_VERIFY_CHANGESET", changeset.to_hex())
328- .env("BRAID_VERIFY_BRANCH", self.branch);
450+ .env("BRAID_VERIFY_BRANCH", self.branch)
451+ .env("PWD", dir)
452+ .env_remove("OLDPWD");
329453 for (name, _) in std::env::vars_os() {
330454 if is_credential(&name) {
331455 command.env_remove(&name);
@@ -334,21 +458,39 @@
334458 #[cfg(unix)]
335459 {
336460 use std::os::unix::process::CommandExt;
337- // A group of its own, so that a timeout kills everything it
338- // started.
461+ // A group of its own, so that what it started goes with it.
339462 command.process_group(0);
340463 }
341464 let mut child = command
342465 .spawn()
343466 .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> {
344483 let deadline = Instant::now() + self.timeout;
345484 loop {
346- if let Some(status) = child.try_wait()? {
347- return Ok(RunEnd::Exited(status));
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()?));
348490 }
349491 let now = Instant::now();
350492 if now >= deadline {
351- kill(&mut child);
493+ kill_group(child);
352494 let _ = child.wait();
353495 return Ok(RunEnd::TimedOut);
354496 }
@@ -357,16 +499,115 @@
357499 }
358500 }
359501
502+/// Whether the command exited, without reaping it where the system can.
503+fn 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.
526+struct Watchdog(Option<Child>);
527+
528+impl 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.
566+pub(crate) fn watchdog(group: &str, dir: &Path) -> Result<ExitCode> {
567+ let mut said = Vec::new();
568+ let _ = io::stdin().lock().read_to_end(&mut said);
569+ if said.starts_with(b"done") {
570+ return Ok(ExitCode::SUCCESS);
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+
360600 /// Whether an environment variable is one of the hub's credentials or
361-/// settings, which the tests never see: `BRAID_TOKEN` and every
362-/// `BRAID_HUB…`.
601+/// settings, which the tests never see: `BRAID_TOKEN` and every variable
602+/// whose name starts with `BRAID_HUB`.
363603 fn is_credential(name: &std::ffi::OsStr) -> bool {
364604 let name = name.to_string_lossy();
365605 name == "BRAID_TOKEN" || name.starts_with("BRAID_HUB")
366606 }
367607
368-/// Kills the command and every process in its group.
369-fn kill(child: &mut Child) {
608+/// Kills the command and every process left in its group. A group already
609+/// gone is no error.
610+fn kill_group(child: &mut Child) {
370611 #[cfg(unix)]
371612 {
372613 let group = rustix::process::Pid::from_child(child);
@@ -405,7 +646,7 @@
405646 loop {
406647 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
407648 let dir = base.join(format!(
408- "braid-verify-{}-{nanos:08x}-{n}",
649+ "{SCRATCH_PREFIX}{}-{nanos:08x}-{n}",
409650 std::process::id()
410651 ));
411652 let mut builder = fs::DirBuilder::new();
@@ -443,6 +684,16 @@
443684 Ok(Some(chain))
444685 }
445686
687+/// `a, b and c`, of short ids.
688+fn 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+
446697 /// Everything one pass needs.
447698 struct Pass<'a> {
448699 args: &'a VerifyArgs,
@@ -451,49 +702,56 @@
451702 branch: &'a str,
452703 tip: ObjectId,
453704 green_before: Option<ObjectId>,
705+ /// `--from`, resolved.
706+ from: Option<ObjectId>,
454707 }
455708
456709 impl Pass<'_> {
457- fn run(&self, tester: &mut Tester<'_>) -> Result<Verdict> {
458- let mut verdict = Verdict {
459- green: self.green_before,
460- ..Verdict::default()
461- };
710+ fn run(&self, tester: &mut Tester<'_>, verdict: &mut Verdict) -> Result<()> {
462711 if self.green_before == Some(self.tip) {
463712 verdict.outcome = "pass";
464713 verdict.reason = Some("the head is the green changeset already".to_owned());
465- return Ok(verdict);
466- }
467- let (passed, flaky) = tester.passes(self.tip)?;
468- if passed {
469- verdict.outcome = if flaky { "flaky" } else { "pass" };
470- if flaky {
471- verdict.reason = Some("a run failed, and a rerun passed".to_owned());
472- }
473- if self.args.dry_run {
474- let moved = format!("dry run: the green ref would move to {}", self.tip.short());
475- verdict.reason = Some(match verdict.reason.take() {
476- Some(reason) => format!("{reason}; {moved}"),
477- None => moved,
478- });
479- } else {
480- self.move_green()?;
481- verdict.green = Some(self.tip);
482- }
483- return Ok(verdict);
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);
484739 }
740+ if !reasons.is_empty() {
741+ verdict.reason = Some(reasons.join("; "));
742+ }
743+ Ok(())
744+ }
485745
746+ /// The tests fail on the head: find the first changeset that fails.
747+ fn red(&self, tester: &mut Tester<'_>, verdict: &mut Verdict) -> Result<()> {
486748 verdict.outcome = "red";
487- let good = match &self.args.from {
488- Some(revision) => Some(resolve_changeset(self.repo, revision)?),
489- None => self.green_before,
490- };
491- let Some(good) = good else {
749+ let Some(good) = self.from.or(self.green_before) else {
492750 verdict.reason = Some(
493751 "the tests fail on the head, and with no green changeset there is nothing to bisect from: --from names one"
494752 .to_owned(),
495753 );
496- return Ok(verdict);
754+ return Ok(());
497755 };
498756 let Some(range) = range(self.repo, self.tip, good)? else {
499757 verdict.reason = Some(format!(
@@ -501,36 +759,87 @@
501759 good.short(),
502760 self.branch
503761 ));
504- return Ok(verdict);
762+ return Ok(());
505763 };
506764 if range.is_empty() {
507- verdict.outcome = "no_culprit";
508- verdict.reason = Some(format!("the head is {}, which was to pass", good.short()));
509- return Ok(verdict);
510- }
511- // `range[lo]` passes (or is `good`, at -1), `range[hi]` fails.
512- let (mut lo, mut hi) = (-1_isize, range.len() as isize - 1);
513- while hi - lo > 1 {
514- let mid = lo + (hi - lo) / 2;
515- if tester.passes(range[mid as usize])?.0 {
516- lo = mid;
517- } else {
518- hi = mid;
519- }
765+ verdict.red(
766+ "no_culprit",
767+ format!("the head is {}, which was to pass", good.short()),
768+ );
769+ return Ok(());
520770 }
521- let culprit = range[hi as usize];
522- if lo < 0 && !tester.passes(good)?.0 {
523- // The changeset taken as passing fails now too: something
524- // outside the range broke the tests.
525- verdict.outcome = "no_culprit";
526- verdict.reason = Some(format!(
527- "{} fails too, though it was to pass: the failure is not in the changesets after it",
528- good.short()
529- ));
530- return Ok(verdict);
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);
531842 }
532- verdict.culprit = Some(culprit);
533- self.revert(culprit, verdict)
534843 }
535844
536845 /// Moves the green ref from where it was to the tip, unless someone
@@ -559,46 +868,45 @@
559868 }
560869
561870 /// Decides whether to revert `culprit`, and does.
562- fn revert(&self, culprit: ObjectId, mut verdict: Verdict) -> Result<Verdict> {
871+ fn revert(&self, culprit: ObjectId, verdict: &mut Verdict) -> Result<()> {
563872 let first = format!(
564873 "the tests fail from {}, the first changeset that fails",
565874 culprit.short()
566875 );
567876 if !self.args.revert {
568877 verdict.reason = Some(format!("{first}; --revert would revert it"));
569- return Ok(verdict);
878+ return Ok(());
570879 }
571- let parents = braid_engine::read_changeset(self.repo.store(), culprit)?
572- .parents
573- .len();
880+ let changeset = braid_engine::read_changeset(self.repo.store(), culprit)?;
574881 let path = Record::path(self.repo, self.branch);
575882 let mut record = Record::load(&path)?;
576883 let now = now_seconds();
577- let refusal = if parents > 1 {
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 {
578887 Some(format!(
579888 "{first}, and it is a merge: verify does not revert merges"
580889 ))
581- } else if record.made(culprit) {
890+ } else if is_verify_revert(&changeset) || record.made(culprit) {
582891 Some(format!(
583892 "{first}, and it is a revert verify made: verify does not revert its own reverts"
584893 ))
585- } else if record.in_last_hour(now) >= self.args.max_reverts_per_hour {
894+ } else if recent.len() >= self.args.max_reverts_per_hour {
586895 Some(format!(
587896 "{first}, but verify landed {} on {} in the last hour, the most --max-reverts-per-hour allows",
588- crate::work::count(record.in_last_hour(now), "revert"),
897+ count(recent.len(), "revert"),
589898 self.branch
590899 ))
591900 } else {
592901 None
593902 };
594903 if let Some(reason) = refusal {
595- verdict.outcome = "refused";
596- verdict.reason = Some(reason);
597- return Ok(verdict);
904+ verdict.red("refused", reason);
905+ return Ok(());
598906 }
599907 if self.args.dry_run {
600908 verdict.reason = Some(format!("{first}; dry run: verify would revert it"));
601- return Ok(verdict);
909+ return Ok(());
602910 }
603911 let author = identity(&self.args.identity, self.repo)?;
604912 let change = braid_wc::create_revert(
@@ -611,46 +919,117 @@
611919 },
612920 )?;
613921 verdict.revert = Some(change);
614- let mut report = land_revert(
922+ let landed = land_revert(
615923 self.repo,
616924 self.link.as_ref(),
617925 self.branch,
618926 change,
619927 AGENT,
620928 &author,
621- )?;
622- match report.outcome.as_str() {
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() {
623947 "fast-forward" | "rebased" => {
948+ verdict.red(
949+ "reverted",
950+ format!("{first}; its revert landed on {}", self.branch),
951+ );
624952 record.reverts.push(Reverted {
625953 culprit: culprit.to_hex(),
626954 revert: change.to_hex(),
627955 landed: report.head.map(|id| id.to_hex()),
628956 time: now,
629957 });
958+ verdict.land = Some(report);
630959 record.save(&path)?;
631- verdict.outcome = "reverted";
632- verdict.reason = Some(format!("{first}; its revert landed on {}", self.branch));
960+ return Ok(());
633961 }
634962 "conflicts" => {
635- verdict.outcome = "revert_conflicts";
636- verdict.reason = Some(format!(
637- "{first}; its revert conflicts with what landed since, so {} did not move: revert it by hand in a workspace",
638- self.branch
639- ));
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+ );
640970 report.next = None;
641971 }
642- "already-applied" => {
643- verdict.outcome = "refused";
644- verdict.reason = Some(format!(
972+ "already-applied" => verdict.red(
973+ "refused",
974+ format!(
645975 "{first}, but {} has what its revert would change already",
646976 self.branch
647- ));
977+ ),
978+ ),
979+ other => {
980+ verdict.land = Some(report);
981+ bail!("the revert's landing ended with {other}");
648982 }
649- other => bail!("the revert's landing ended with {other}"),
650983 }
651984 verdict.land = Some(report);
652- Ok(verdict)
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.
993+fn 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.
1024+fn 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+ }
6531031 }
1032+ Ok(None)
6541033 }
6551034
6561035 pub(crate) fn verify(cli: &Cli, args: &VerifyArgs) -> Result<ExitCode> {
@@ -670,6 +1049,10 @@
6701049 let Some(tip) = refs.get(&branch) else {
6711050 bail!("there is no branch {branch:?} to verify");
6721051 };
1052+ let from = match &args.from {
1053+ Some(revision) => Some(resolve_changeset(&repo, revision)?),
1054+ None => None,
1055+ };
6731056 let green_before = refs.get(&green_ref(&branch));
6741057 let pass = Pass {
6751058 args,
@@ -678,6 +1061,7 @@
6781061 branch: &branch,
6791062 tip,
6801063 green_before,
1064+ from,
6811065 };
6821066 let mut tester = Tester {
6831067 repo: &repo,
@@ -687,20 +1071,19 @@
6871071 reruns: args.reruns,
6881072 runs: 0,
6891073 };
690- let verdict = match pass.run(&mut tester) {
691- Ok(verdict) => verdict,
692- // Before anything ran, an error is only an error.
693- Err(err) if tester.runs == 0 => return Err(err),
694- Err(err) => {
695- eprintln!("braid: error: {err:#}");
696- Verdict {
697- outcome: "error",
698- green: green_before,
699- reason: Some(format!("{err:#}")),
700- ..Verdict::default()
701- }
702- }
1074+ let mut verdict = Verdict {
1075+ green: green_before,
1076+ ..Verdict::default()
7031077 };
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+ }
7041087 if cli.json {
7051088 print_json(&json!({
7061089 "branch": branch,
@@ -710,6 +1093,7 @@
7101093 "outcome": verdict.outcome,
7111094 "culprit": hex(verdict.culprit),
7121095 "revert": hex(verdict.revert),
1096+ "skipped": verdict.skipped.iter().map(ObjectId::to_hex).collect::<Vec<_>>(),
7131097 "tests_run": tester.runs,
7141098 "reason": verdict.reason,
7151099 "dry_run": args.dry_run,
@@ -722,7 +1106,7 @@
7221106 }
7231107
7241108 fn print_text(branch: &str, tip: ObjectId, verdict: &Verdict, runs: usize) {
725- let ran = crate::work::count(runs, "run");
1109+ let ran = count(runs, "run");
7261110 match verdict.outcome {
7271111 "pass" | "flaky" => println!(
7281112 "{branch} is green at {} ({}, {ran})",
@@ -734,6 +1118,12 @@
7341118 if let Some(reason) = &verdict.reason {
7351119 println!("{reason}");
7361120 }
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+ }
7371127 if let Some(report) = &verdict.land
7381128 && report.conflicted()
7391129 {
@@ -772,15 +1162,13 @@
7721162 }
7731163
7741164 #[test]
775- fn record_paths_escape_branch_names() {
1165+ fn record_files_are_named_in_hex_and_kept_whole() {
7761166 let temp = tempfile::tempdir().unwrap();
7771167 let repo = Repo::init(temp.path()).unwrap();
778- let path = Record::path(&repo, "feature/x y");
779- assert_eq!(path.file_name().unwrap(), "feature%2Fx%20y.json");
780- assert_eq!(
781- Record::path(&repo, "main").file_name().unwrap(),
782- "main.json"
783- );
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"));
7841172 let mut record = Record::default();
7851173 record.reverts.push(Reverted {
7861174 culprit: "c".repeat(64),
@@ -790,9 +1178,33 @@
7901178 });
7911179 let landed: ObjectId = "b".repeat(64).parse().unwrap();
7921180 assert!(record.made(landed));
793- assert_eq!(record.in_last_hour(10_000 + 3599), 1);
794- assert_eq!(record.in_last_hour(10_000 + 3600), 0);
1181+ assert_eq!(record.in_last_hour(10_000 + 3599).len(), 1);
1182+ assert_eq!(record.in_last_hour(10_000 + 3600).len(), 0);
7951183 record.save(&path).unwrap();
7961184 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+ );
7971209 }
7981210 }
modified crates/cli/tests/verify.rs +207 −3
@@ -153,7 +153,14 @@
153153 }
154154
155155 fn has_record(&self) -> bool {
156- self.dir.join(".braid/verify/main.json").is_file()
156+ // The branch's name in hex.
157+ self.dir.join(".braid/verify/6d61696e.json").is_file()
158+ }
159+
160+ /// Forgets the local record of verify's reverts, as a fresh clone
161+ /// never had it.
162+ fn forget_record(&self) {
163+ std::fs::remove_dir_all(self.dir.join(".braid/verify")).unwrap();
157164 }
158165 }
159166
@@ -321,9 +328,12 @@
321328 4,
322329 );
323330 assert_eq!(first["outcome"], "reverted");
324- // Green again, then broken again: the cap of one an hour is spent.
331+ // Green again, then broken again: the cap of one an hour is spent. It
332+ // is counted on the branch, so a clone without verify's record, as CI
333+ // has, counts it too.
325334 assert_eq!(r.verify(&[], 0)["outcome"], "pass");
326335 let again = r.land(&[("broken", "again\n")], &[], "Break again");
336+ r.forget_record();
327337 let second = r.verify(
328338 &["--revert", "--reruns", "0", "--max-reverts-per-hour", "1"],
329339 4,
@@ -350,8 +360,10 @@
350360 let revert = r.head().unwrap();
351361
352362 // Now the revert fails and the change it undid passes: the culprit is
353- // the revert, which verify leaves alone.
363+ // the revert, which verify leaves alone, by what the revert says of
364+ // itself, without its record.
354365 std::fs::write(&list, format!("{revert}\n")).unwrap();
366+ r.forget_record();
355367 let out = r.verify_env(&["--revert", "--reruns", "0"], &command, &[], 4);
356368 assert_eq!(out["outcome"], "refused");
357369 assert_eq!(out["culprit"], revert.as_str());
@@ -400,6 +412,13 @@
400412 let out = r.verify_env(&[], &["sh", "-c", &script], &[], 0);
401413 assert_eq!(out["outcome"], "flaky");
402414 assert_eq!(out["tests_run"], 2);
415+ // A flaky pass leaves the green ref where it was, unless asked.
416+ assert_eq!(out["green"], Value::Null);
417+ assert!(id(&out["reason"]).contains("--flaky-moves-green"));
418+ assert_eq!(r.green(), None);
419+ std::fs::remove_file(&marker).unwrap();
420+ let out = r.verify_env(&["--flaky-moves-green"], &["sh", "-c", &script], &[], 0);
421+ assert_eq!(out["outcome"], "flaky");
403422 assert_eq!(out["green"], r.head().unwrap().as_str());
404423 }
405424
@@ -422,6 +441,29 @@
422441 let leak = "test -n \"$BRAID_AGENT\"";
423442 let out = r.verify_env(&["--dry-run"], &["sh", "-c", leak], &envs, 0);
424443 assert_eq!(out["outcome"], "pass");
444+ // The environment as `env` prints it, with no shell to change it: PWD
445+ // names the copy, and OLDPWD, which named the repository, is gone.
446+ let envs = [
447+ ("BRAID_TOKEN", "brd_secret"),
448+ ("BRAID_HUB_URL", "https://hub.example.org"),
449+ ("OLDPWD", r.dir.to_str().unwrap()),
450+ ("PWD", r.dir.to_str().unwrap()),
451+ ];
452+ let out = braid_with(&r.dir, &["verify", "--dry-run", "--", "env"], &envs);
453+ assert!(out.status.success());
454+ let printed = String::from_utf8_lossy(&out.stderr);
455+ let var = |name: &str| {
456+ printed
457+ .lines()
458+ .find_map(|line| line.strip_prefix(&format!("{name}=")))
459+ .map(str::to_owned)
460+ };
461+ assert_eq!(var("BRAID_TOKEN"), None);
462+ assert_eq!(var("BRAID_HUB_URL"), None);
463+ assert_eq!(var("OLDPWD"), None);
464+ let pwd = var("PWD").unwrap();
465+ assert!(pwd.contains("braid-verify-"), "{pwd}");
466+ assert_eq!(var("BRAID_VERIFY_BRANCH").as_deref(), Some("main"));
425467 // A command that cannot run is an error, not a red branch.
426468 let out = braid_with(&r.dir, &["verify", "--", "no-such-command-for-braid"], &[]);
427469 assert_eq!(out.status.code(), Some(1));
@@ -464,3 +506,165 @@
464506 }
465507 assert!(!alive, "the background process {pid} outlived the timeout");
466508 }
509+
510+/// Whether the process `pid` is gone, or a zombie waiting to be reaped,
511+/// within a few seconds.
512+#[cfg(unix)]
513+fn gone(pid: &str) -> bool {
514+ for _ in 0..100 {
515+ let ps = Command::new("ps")
516+ .args(["-o", "stat=", "-p", pid])
517+ .output()
518+ .unwrap();
519+ let state = String::from_utf8_lossy(&ps.stdout).trim().to_owned();
520+ if state.is_empty() || state.starts_with('Z') {
521+ return true;
522+ }
523+ std::thread::sleep(std::time::Duration::from_millis(50));
524+ }
525+ false
526+}
527+
528+/// The contents of `path` once a command wrote them, within a few seconds.
529+#[cfg(unix)]
530+fn written(path: &Path) -> String {
531+ for _ in 0..200 {
532+ if let Ok(text) = std::fs::read_to_string(path)
533+ && text.ends_with('\n')
534+ {
535+ return text.trim().to_owned();
536+ }
537+ std::thread::sleep(std::time::Duration::from_millis(50));
538+ }
539+ panic!("{} was never written", path.display());
540+}
541+
542+#[cfg(unix)]
543+#[test]
544+fn what_a_passing_command_leaves_running_is_killed() {
545+ let r = Repo::new();
546+ let pid_file = r.outside.join("pid");
547+ let script = format!(
548+ "sleep 120 > /dev/null 2>&1 & echo $! > '{}'",
549+ pid_file.display()
550+ );
551+ let out = r.verify_env(&["--dry-run"], &["sh", "-c", &script], &[], 0);
552+ assert_eq!(out["outcome"], "pass");
553+ let pid = written(&pid_file);
554+ assert!(gone(&pid), "the background process {pid} outlived its test");
555+}
556+
557+#[cfg(unix)]
558+#[test]
559+fn stopping_braid_stops_the_tests_and_removes_their_copy() {
560+ let r = Repo::new();
561+ let shell_file = r.outside.join("shell");
562+ let sleep_file = r.outside.join("sleep");
563+ let dir_file = r.outside.join("dir");
564+ let script = format!(
565+ "pwd > '{dir}'; echo $$ > '{shell}'; sleep 120 > /dev/null 2>&1 & echo $! > '{sleep}'; wait",
566+ dir = dir_file.display(),
567+ shell = shell_file.display(),
568+ sleep = sleep_file.display(),
569+ );
570+ let mut braid = Command::new(env!("CARGO_BIN_EXE_braid"))
571+ .current_dir(&r.dir)
572+ .args(["verify", "--", "sh", "-c", &script])
573+ .env("BRAID_HUB", "off")
574+ .stdout(std::process::Stdio::null())
575+ .stderr(std::process::Stdio::null())
576+ .spawn()
577+ .unwrap();
578+ let sleep = written(&sleep_file);
579+ let shell = written(&shell_file);
580+ let dir = PathBuf::from(written(&dir_file));
581+ assert!(dir.is_dir());
582+ // Only the braid this test started.
583+ let term = Command::new("kill")
584+ .args(["-TERM", &braid.id().to_string()])
585+ .status()
586+ .unwrap();
587+ assert!(term.success());
588+ braid.wait().unwrap();
589+ assert!(gone(&shell), "the test's shell {shell} outlived braid");
590+ assert!(gone(&sleep), "the test's sleep {sleep} outlived braid");
591+ let mut removed = false;
592+ for _ in 0..100 {
593+ if !dir.exists() {
594+ removed = true;
595+ break;
596+ }
597+ std::thread::sleep(std::time::Duration::from_millis(50));
598+ }
599+ assert!(removed, "{} is still there", dir.display());
600+}
601+
602+#[test]
603+fn a_revert_verify_made_earlier_does_not_stall_the_bisect() {
604+ // Green at the seed; C broke the tests and verify reverted it; then D
605+ // broke them again. Bisecting from the seed meets C first: verify sees
606+ // its revert, tests it, and goes on after it to find D.
607+ let r = Repo::new();
608+ assert_eq!(r.verify(&[], 0)["outcome"], "pass");
609+ let c = r.land(&[("broken", "c\n")], &[], "C breaks the tests");
610+ let first = r.verify(&["--revert", "--reruns", "0"], 4);
611+ assert_eq!(first["outcome"], "reverted");
612+ assert_eq!(first["culprit"], c.as_str());
613+ let d = r.land(
614+ &[("broken", "d\n"), ("d", "d\n")],
615+ &[],
616+ "D breaks them again",
617+ );
618+ let second = r.verify(&["--revert", "--reruns", "0"], 4);
619+ assert_eq!(second["outcome"], "reverted", "{second}");
620+ assert_eq!(second["culprit"], d.as_str());
621+ // The head, C, C's revert, then the green one is not needed.
622+ assert_eq!(second["tests_run"], 3);
623+ assert_eq!(r.verify(&[], 0)["outcome"], "pass");
624+}
625+
626+#[test]
627+fn a_changeset_that_cannot_be_written_here_is_skipped() {
628+ // Two names that differ only in case are one file where the file
629+ // system ignores case: such a changeset cannot be tested there.
630+ let probe = tempfile::tempdir().unwrap();
631+ std::fs::write(probe.path().join("Aa"), "").unwrap();
632+ if !probe.path().join("aA").exists() {
633+ return;
634+ }
635+ let r = Repo::new();
636+ assert_eq!(r.verify(&[], 0)["outcome"], "pass");
637+ r.land(&[("a", "a\n")], &[], "Add a");
638+ let twins = r.land(&[("Case", "1\n"), ("case", "2\n")], &[], "Add twins");
639+ r.land(&[], &["case"], "Remove a twin");
640+ let culprit = r.land(&[("broken", "x\n")], &[], "Break");
641+ r.land(&[("z", "z\n")], &[], "Add z");
642+ let out = r.verify(&["--reruns", "0"], 4);
643+ assert_eq!(out["outcome"], "red");
644+ assert_eq!(out["culprit"], culprit.as_str());
645+ assert_eq!(out["skipped"], serde_json::json!([twins]));
646+}
647+
648+#[cfg(unix)]
649+#[test]
650+fn an_error_after_the_revert_landed_keeps_it_in_the_report() {
651+ use std::os::unix::fs::PermissionsExt;
652+ let (r, _, ids) = broken_after_green();
653+ // Verify's record cannot be written.
654+ let record = r.dir.join(".braid/verify");
655+ std::fs::create_dir(&record).unwrap();
656+ std::fs::set_permissions(&record, std::fs::Permissions::from_mode(0o555)).unwrap();
657+ let out = r.verify(&["--revert", "--reruns", "0"], 1);
658+ std::fs::set_permissions(&record, std::fs::Permissions::from_mode(0o755)).unwrap();
659+ assert_eq!(out["outcome"], "error");
660+ assert_eq!(out["culprit"], ids[1].as_str());
661+ let revert = id(&out["revert"]);
662+ assert_eq!(out["land"]["outcome"], "rebased");
663+ let head = r.head().unwrap();
664+ assert_eq!(out["land"]["head"], head.as_str());
665+ assert_ne!(head, ids[3]);
666+ assert!(!revert.is_empty());
667+ // The branch says verify made it, so the next pass will not undo it.
668+ let shown = run(&r.dir, &["show", "main"], 0);
669+ assert_eq!(shown["agent"], "braid-verify");
670+}