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