utopia-ia/elffuss-braid public
Changesets · Branches · Tags · Compare
| Changeset | 20a66f74c39ef486402fffd26bd21bbfd3b0c098a1f2da350e6a6e346b396361 |
|---|---|
| Author | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-21 12:16 +02:00 |
| Committer | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-21 12:16 +02:00 |
| Parents | a93ee013835a |
3 files changed
modified crates/cli/src/main.rs +9 −0
| @@ -324,6 +324,14 @@ | ||
| 324 | 324 | /// the branch is red). |
| 325 | 325 | #[command(long_about = verify::VERIFY_HELP)] |
| 326 | 326 | 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 | + }, | |
| 327 | 335 | } |
| 328 | 336 | |
| 329 | 337 | #[derive(Debug, Subcommand)] |
| @@ -528,6 +536,7 @@ | ||
| 528 | 536 | Command::Change { action } => work::change(cli, action), |
| 529 | 537 | Command::Revert(args) => revert::revert(cli, args), |
| 530 | 538 | Command::Verify(args) => verify::verify(cli, args), |
| 539 | + Command::VerifyWatchdog { group, dir } => verify::watchdog(group, dir), | |
| 531 | 540 | } |
| 532 | 541 | } |
| 533 | 542 |
modified crates/cli/src/verify.rs +605 −193
| @@ -6,24 +6,32 @@ | ||
| 6 | 6 | //! changeset that broke them and, if asked, revert it. |
| 7 | 7 | //! |
| 8 | 8 | //! 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}; | |
| 17 | 24 | 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}; | |
| 20 | 27 | use std::path::{Path, PathBuf}; |
| 21 | 28 | use std::process::{Child, Command, ExitCode, ExitStatus, Stdio}; |
| 22 | 29 | use std::sync::atomic::{AtomicU32, Ordering}; |
| 23 | 30 | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; |
| 24 | 31 | |
| 25 | 32 | 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}; | |
| 27 | 35 | use braid_repo::Repo; |
| 28 | 36 | use braid_store::RefUpdate; |
| 29 | 37 | use braid_wc::RevertRequest; |
| @@ -33,13 +41,16 @@ | ||
| 33 | 41 | |
| 34 | 42 | use crate::hub::{self, link::Link}; |
| 35 | 43 | 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}; | |
| 37 | 45 | use crate::{Cli, open_repo, print_json, resolve_changeset}; |
| 38 | 46 | |
| 39 | 47 | /// The agent label of everything verify records: the green ref's moves, |
| 40 | 48 | /// and the reverts it makes and lands. |
| 41 | 49 | pub(crate) const AGENT: &str = "braid-verify"; |
| 42 | 50 | |
| 51 | +/// The hidden subcommand that watches a test run for braid going away. | |
| 52 | +pub(crate) const WATCHDOG: &str = "__verify-watchdog"; | |
| 53 | + | |
| 43 | 54 | /// Exit status of a pass that leaves the branch red: the tests fail on its |
| 44 | 55 | /// head, whether or not the culprit was found or reverted. |
| 45 | 56 | const RED: u8 = 4; |
| @@ -47,6 +58,13 @@ | ||
| 47 | 58 | /// The exit status of a revert that conflicts, as for every conflict. |
| 48 | 59 | const CONFLICTS: u8 = crate::work::CONFLICTS; |
| 49 | 60 | |
| 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 | + | |
| 50 | 68 | /// The green ref of `branch`: the newest changeset of it that passed. |
| 51 | 69 | pub(crate) fn green_ref(branch: &str) -> String { |
| 52 | 70 | format!("braid/green/{branch}") |
| @@ -61,47 +79,64 @@ | ||
| 61 | 79 | |
| 62 | 80 | The command comes after `--` and runs as given, with no shell: write |
| 63 | 81 | `-- 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. | |
| 72 | 100 | |
| 73 | 101 | - The head is the green changeset already: pass, and nothing runs. |
| 74 | 102 | - The tests pass: the green ref moves to the head, in an operation of |
| 75 | 103 | 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. | |
| 77 | 106 | - They fail, again on every rerun: verify bisects the changesets after |
| 78 | 107 | the green one along first parents, the head's changes and its |
| 79 | 108 | 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. | |
| 83 | 114 | - With --revert, the culprit is reverted and the revert landed, as |
| 84 | 115 | `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. | |
| 93 | 126 | |
| 94 | 127 | With --json it prints branch; tip, the head it tested; green_before and |
| 95 | 128 | green, the green ref before and after; outcome, one of pass, flaky, red, |
| 96 | 129 | reverted, revert_conflicts, refused, no_culprit or error; culprit, the |
| 97 | 130 | 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. | |
| 101 | 135 | |
| 102 | 136 | 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."; | |
| 105 | 140 | |
| 106 | 141 | #[derive(Debug, Args)] |
| 107 | 142 | pub(crate) struct VerifyArgs { |
| @@ -112,7 +147,8 @@ | ||
| 112 | 147 | /// Revert the changeset that broke the tests, and land the revert. |
| 113 | 148 | #[arg(long)] |
| 114 | 149 | 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. | |
| 116 | 152 | #[arg(long)] |
| 117 | 153 | dry_run: bool, |
| 118 | 154 | /// The most reverts verify lands on the branch in an hour. |
| @@ -122,6 +158,9 @@ | ||
| 122 | 158 | /// failing. |
| 123 | 159 | #[arg(long, value_name = "N", default_value_t = 1)] |
| 124 | 160 | reruns: u32, |
| 161 | + /// Move the green ref when the tests passed only on a rerun. | |
| 162 | + #[arg(long)] | |
| 163 | + flaky_moves_green: bool, | |
| 125 | 164 | /// How long one run may take: a number with s, m or h. |
| 126 | 165 | #[arg(long, value_name = "DURATION", default_value = "10m", value_parser = parse_duration)] |
| 127 | 166 | timeout: Duration, |
| @@ -161,13 +200,15 @@ | ||
| 161 | 200 | } |
| 162 | 201 | } |
| 163 | 202 | |
| 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. | |
| 165 | 205 | #[derive(Default)] |
| 166 | 206 | struct Verdict { |
| 167 | 207 | outcome: &'static str, |
| 168 | 208 | green: Option<ObjectId>, |
| 169 | 209 | culprit: Option<ObjectId>, |
| 170 | 210 | revert: Option<ObjectId>, |
| 211 | + skipped: Vec<ObjectId>, | |
| 171 | 212 | reason: Option<String>, |
| 172 | 213 | land: Option<Report>, |
| 173 | 214 | } |
| @@ -181,10 +222,15 @@ | ||
| 181 | 222 | _ => ExitCode::from(RED), |
| 182 | 223 | } |
| 183 | 224 | } |
| 225 | + | |
| 226 | + fn red(&mut self, outcome: &'static str, reason: String) { | |
| 227 | + self.outcome = outcome; | |
| 228 | + self.reason = Some(reason); | |
| 229 | + } | |
| 184 | 230 | } |
| 185 | 231 | |
| 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. | |
| 188 | 234 | #[derive(Debug, Default, Serialize, Deserialize)] |
| 189 | 235 | struct Record { |
| 190 | 236 | #[serde(default)] |
| @@ -199,25 +245,17 @@ | ||
| 199 | 245 | /// The revert as verify made it, in hex. |
| 200 | 246 | revert: String, |
| 201 | 247 | /// The changeset that holds it on the branch: itself, or the rebased |
| 202 | - /// one. | |
| 248 | + /// one; null when the landing's answer was lost. | |
| 203 | 249 | landed: Option<String>, |
| 204 | 250 | /// When it landed, in seconds since the Unix epoch. |
| 205 | 251 | time: u64, |
| 206 | 252 | } |
| 207 | 253 | |
| 208 | 254 | 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. | |
| 212 | 257 | 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(); | |
| 221 | 259 | repo.root() |
| 222 | 260 | .join(braid_repo::DIR) |
| 223 | 261 | .join("verify") |
| @@ -226,26 +264,41 @@ | ||
| 226 | 264 | |
| 227 | 265 | fn load(path: &Path) -> Result<Record> { |
| 228 | 266 | 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 | + }), | |
| 231 | 273 | Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Record::default()), |
| 232 | 274 | Err(err) => Err(err).with_context(|| format!("cannot read {}", path.display())), |
| 233 | 275 | } |
| 234 | 276 | } |
| 235 | 277 | |
| 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. | |
| 237 | 280 | fn save(&self, path: &Path) -> Result<()> { |
| 238 | 281 | let dir = path.parent().context("the record has no directory")?; |
| 239 | 282 | fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?; |
| 240 | 283 | let scratch = path.with_extension("json.new"); |
| 241 | 284 | let mut text = serde_json::to_vec_pretty(self)?; |
| 242 | 285 | 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()))?; | |
| 244 | 292 | fs::rename(&scratch, path).with_context(|| format!("cannot write {}", path.display()))?; |
| 293 | + #[cfg(unix)] | |
| 294 | + if let Ok(dir) = File::open(dir) { | |
| 295 | + let _ = dir.sync_all(); | |
| 296 | + } | |
| 245 | 297 | Ok(()) |
| 246 | 298 | } |
| 247 | 299 | |
| 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. | |
| 249 | 302 | fn made(&self, id: ObjectId) -> bool { |
| 250 | 303 | let hex = id.to_hex(); |
| 251 | 304 | self.reverts |
| @@ -253,9 +306,14 @@ | ||
| 253 | 306 | .any(|r| r.revert == hex || r.landed.as_deref() == Some(hex.as_str())) |
| 254 | 307 | } |
| 255 | 308 | |
| 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() | |
| 259 | 317 | } |
| 260 | 318 | } |
| 261 | 319 | |
| @@ -265,6 +323,53 @@ | ||
| 265 | 323 | .map_or(0, |since| since.as_secs()) |
| 266 | 324 | } |
| 267 | 325 | |
| 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 | + | |
| 268 | 373 | /// Runs the test command on changesets, counting the runs. |
| 269 | 374 | struct Tester<'a> { |
| 270 | 375 | repo: &'a Repo, |
| @@ -283,25 +388,29 @@ | ||
| 283 | 388 | |
| 284 | 389 | impl Tester<'_> { |
| 285 | 390 | /// 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> { | |
| 289 | 393 | 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) => {} | |
| 292 | 398 | } |
| 293 | 399 | } |
| 294 | - Ok((false, false)) | |
| 400 | + Ok(Check::Failed) | |
| 295 | 401 | } |
| 296 | 402 | |
| 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>> { | |
| 299 | 406 | let dir = scratch_dir()?; |
| 300 | 407 | let result = self.run_in(changeset, &dir); |
| 301 | 408 | // Whatever the command left goes too. |
| 302 | 409 | let _ = fs::remove_dir_all(&dir); |
| 410 | + let Some(end) = result? else { | |
| 411 | + return Ok(None); | |
| 412 | + }; | |
| 303 | 413 | // Only a command that ran counts. |
| 304 | - let end = result?; | |
| 305 | 414 | self.runs += 1; |
| 306 | 415 | let passed = matches!(&end, RunEnd::Exited(status) if status.success()); |
| 307 | 416 | let said = match &end { |
| @@ -310,12 +419,25 @@ | ||
| 310 | 419 | RunEnd::TimedOut => format!("timed out after {:?} and was killed", self.timeout), |
| 311 | 420 | }; |
| 312 | 421 | eprintln!("braid verify: {} {said}", changeset.short()); |
| 313 | - Ok(passed) | |
| 422 | + Ok(Some(passed)) | |
| 314 | 423 | } |
| 315 | 424 | |
| 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 | + } | |
| 319 | 441 | let (program, args) = self.command.split_first().context("no command to run")?; |
| 320 | 442 | let mut command = Command::new(program); |
| 321 | 443 | command |
| @@ -325,7 +447,9 @@ | ||
| 325 | 447 | .stdout(to_stderr()?) |
| 326 | 448 | .stderr(to_stderr()?) |
| 327 | 449 | .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"); | |
| 329 | 453 | for (name, _) in std::env::vars_os() { |
| 330 | 454 | if is_credential(&name) { |
| 331 | 455 | command.env_remove(&name); |
| @@ -334,21 +458,39 @@ | ||
| 334 | 458 | #[cfg(unix)] |
| 335 | 459 | { |
| 336 | 460 | 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. | |
| 339 | 462 | command.process_group(0); |
| 340 | 463 | } |
| 341 | 464 | let mut child = command |
| 342 | 465 | .spawn() |
| 343 | 466 | .with_context(|| format!("cannot run {}", program.to_string_lossy()))?; |
| 467 | + let watchdog = match Watchdog::start(&child, dir) { | |
| 468 | + Ok(watchdog) => watchdog, | |
| 469 | + Err(err) => { | |
| 470 | + kill_group(&mut child); | |
| 471 | + let _ = child.wait(); | |
| 472 | + return Err(err); | |
| 473 | + } | |
| 474 | + }; | |
| 475 | + let end = self.wait(&mut child); | |
| 476 | + watchdog.done(); | |
| 477 | + end.map(Some) | |
| 478 | + } | |
| 479 | + | |
| 480 | + /// Waits for the command, at most until the timeout, then kills its | |
| 481 | + /// group: whatever it left running, or all of it on a timeout. | |
| 482 | + fn wait(&self, child: &mut Child) -> Result<RunEnd> { | |
| 344 | 483 | let deadline = Instant::now() + self.timeout; |
| 345 | 484 | 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()?)); | |
| 348 | 490 | } |
| 349 | 491 | let now = Instant::now(); |
| 350 | 492 | if now >= deadline { |
| 351 | - kill(&mut child); | |
| 493 | + kill_group(child); | |
| 352 | 494 | let _ = child.wait(); |
| 353 | 495 | return Ok(RunEnd::TimedOut); |
| 354 | 496 | } |
| @@ -357,16 +499,115 @@ | ||
| 357 | 499 | } |
| 358 | 500 | } |
| 359 | 501 | |
| 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 | + | |
| 360 | 600 | /// 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`. | |
| 363 | 603 | fn is_credential(name: &std::ffi::OsStr) -> bool { |
| 364 | 604 | let name = name.to_string_lossy(); |
| 365 | 605 | name == "BRAID_TOKEN" || name.starts_with("BRAID_HUB") |
| 366 | 606 | } |
| 367 | 607 | |
| 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) { | |
| 370 | 611 | #[cfg(unix)] |
| 371 | 612 | { |
| 372 | 613 | let group = rustix::process::Pid::from_child(child); |
| @@ -405,7 +646,7 @@ | ||
| 405 | 646 | loop { |
| 406 | 647 | let n = COUNTER.fetch_add(1, Ordering::Relaxed); |
| 407 | 648 | let dir = base.join(format!( |
| 408 | - "braid-verify-{}-{nanos:08x}-{n}", | |
| 649 | + "{SCRATCH_PREFIX}{}-{nanos:08x}-{n}", | |
| 409 | 650 | std::process::id() |
| 410 | 651 | )); |
| 411 | 652 | let mut builder = fs::DirBuilder::new(); |
| @@ -443,6 +684,16 @@ | ||
| 443 | 684 | Ok(Some(chain)) |
| 444 | 685 | } |
| 445 | 686 | |
| 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 | + | |
| 446 | 697 | /// Everything one pass needs. |
| 447 | 698 | struct Pass<'a> { |
| 448 | 699 | args: &'a VerifyArgs, |
| @@ -451,49 +702,56 @@ | ||
| 451 | 702 | branch: &'a str, |
| 452 | 703 | tip: ObjectId, |
| 453 | 704 | green_before: Option<ObjectId>, |
| 705 | + /// `--from`, resolved. | |
| 706 | + from: Option<ObjectId>, | |
| 454 | 707 | } |
| 455 | 708 | |
| 456 | 709 | 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<()> { | |
| 462 | 711 | if self.green_before == Some(self.tip) { |
| 463 | 712 | verdict.outcome = "pass"; |
| 464 | 713 | 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); | |
| 484 | 739 | } |
| 740 | + if !reasons.is_empty() { | |
| 741 | + verdict.reason = Some(reasons.join("; ")); | |
| 742 | + } | |
| 743 | + Ok(()) | |
| 744 | + } | |
| 485 | 745 | |
| 746 | + /// The tests fail on the head: find the first changeset that fails. | |
| 747 | + fn red(&self, tester: &mut Tester<'_>, verdict: &mut Verdict) -> Result<()> { | |
| 486 | 748 | 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 { | |
| 492 | 750 | verdict.reason = Some( |
| 493 | 751 | "the tests fail on the head, and with no green changeset there is nothing to bisect from: --from names one" |
| 494 | 752 | .to_owned(), |
| 495 | 753 | ); |
| 496 | - return Ok(verdict); | |
| 754 | + return Ok(()); | |
| 497 | 755 | }; |
| 498 | 756 | let Some(range) = range(self.repo, self.tip, good)? else { |
| 499 | 757 | verdict.reason = Some(format!( |
| @@ -501,36 +759,87 @@ | ||
| 501 | 759 | good.short(), |
| 502 | 760 | self.branch |
| 503 | 761 | )); |
| 504 | - return Ok(verdict); | |
| 762 | + return Ok(()); | |
| 505 | 763 | }; |
| 506 | 764 | 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(()); | |
| 520 | 770 | } |
| 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); | |
| 531 | 842 | } |
| 532 | - verdict.culprit = Some(culprit); | |
| 533 | - self.revert(culprit, verdict) | |
| 534 | 843 | } |
| 535 | 844 | |
| 536 | 845 | /// Moves the green ref from where it was to the tip, unless someone |
| @@ -559,46 +868,45 @@ | ||
| 559 | 868 | } |
| 560 | 869 | |
| 561 | 870 | /// 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<()> { | |
| 563 | 872 | let first = format!( |
| 564 | 873 | "the tests fail from {}, the first changeset that fails", |
| 565 | 874 | culprit.short() |
| 566 | 875 | ); |
| 567 | 876 | if !self.args.revert { |
| 568 | 877 | verdict.reason = Some(format!("{first}; --revert would revert it")); |
| 569 | - return Ok(verdict); | |
| 878 | + return Ok(()); | |
| 570 | 879 | } |
| 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)?; | |
| 574 | 881 | let path = Record::path(self.repo, self.branch); |
| 575 | 882 | let mut record = Record::load(&path)?; |
| 576 | 883 | 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 { | |
| 578 | 887 | Some(format!( |
| 579 | 888 | "{first}, and it is a merge: verify does not revert merges" |
| 580 | 889 | )) |
| 581 | - } else if record.made(culprit) { | |
| 890 | + } else if is_verify_revert(&changeset) || record.made(culprit) { | |
| 582 | 891 | Some(format!( |
| 583 | 892 | "{first}, and it is a revert verify made: verify does not revert its own reverts" |
| 584 | 893 | )) |
| 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 { | |
| 586 | 895 | Some(format!( |
| 587 | 896 | "{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"), | |
| 589 | 898 | self.branch |
| 590 | 899 | )) |
| 591 | 900 | } else { |
| 592 | 901 | None |
| 593 | 902 | }; |
| 594 | 903 | 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(()); | |
| 598 | 906 | } |
| 599 | 907 | if self.args.dry_run { |
| 600 | 908 | verdict.reason = Some(format!("{first}; dry run: verify would revert it")); |
| 601 | - return Ok(verdict); | |
| 909 | + return Ok(()); | |
| 602 | 910 | } |
| 603 | 911 | let author = identity(&self.args.identity, self.repo)?; |
| 604 | 912 | let change = braid_wc::create_revert( |
| @@ -611,46 +919,117 @@ | ||
| 611 | 919 | }, |
| 612 | 920 | )?; |
| 613 | 921 | verdict.revert = Some(change); |
| 614 | - let mut report = land_revert( | |
| 922 | + let landed = land_revert( | |
| 615 | 923 | self.repo, |
| 616 | 924 | self.link.as_ref(), |
| 617 | 925 | self.branch, |
| 618 | 926 | change, |
| 619 | 927 | AGENT, |
| 620 | 928 | &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() { | |
| 623 | 947 | "fast-forward" | "rebased" => { |
| 948 | + verdict.red( | |
| 949 | + "reverted", | |
| 950 | + format!("{first}; its revert landed on {}", self.branch), | |
| 951 | + ); | |
| 624 | 952 | record.reverts.push(Reverted { |
| 625 | 953 | culprit: culprit.to_hex(), |
| 626 | 954 | revert: change.to_hex(), |
| 627 | 955 | landed: report.head.map(|id| id.to_hex()), |
| 628 | 956 | time: now, |
| 629 | 957 | }); |
| 958 | + verdict.land = Some(report); | |
| 630 | 959 | record.save(&path)?; |
| 631 | - verdict.outcome = "reverted"; | |
| 632 | - verdict.reason = Some(format!("{first}; its revert landed on {}", self.branch)); | |
| 960 | + return Ok(()); | |
| 633 | 961 | } |
| 634 | 962 | "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 | + ); | |
| 640 | 970 | report.next = None; |
| 641 | 971 | } |
| 642 | - "already-applied" => { | |
| 643 | - verdict.outcome = "refused"; | |
| 644 | - verdict.reason = Some(format!( | |
| 972 | + "already-applied" => verdict.red( | |
| 973 | + "refused", | |
| 974 | + format!( | |
| 645 | 975 | "{first}, but {} has what its revert would change already", |
| 646 | 976 | self.branch |
| 647 | - )); | |
| 977 | + ), | |
| 978 | + ), | |
| 979 | + other => { | |
| 980 | + verdict.land = Some(report); | |
| 981 | + bail!("the revert's landing ended with {other}"); | |
| 648 | 982 | } |
| 649 | - other => bail!("the revert's landing ended with {other}"), | |
| 650 | 983 | } |
| 651 | 984 | 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 | + } | |
| 653 | 1031 | } |
| 1032 | + Ok(None) | |
| 654 | 1033 | } |
| 655 | 1034 | |
| 656 | 1035 | pub(crate) fn verify(cli: &Cli, args: &VerifyArgs) -> Result<ExitCode> { |
| @@ -670,6 +1049,10 @@ | ||
| 670 | 1049 | let Some(tip) = refs.get(&branch) else { |
| 671 | 1050 | bail!("there is no branch {branch:?} to verify"); |
| 672 | 1051 | }; |
| 1052 | + let from = match &args.from { | |
| 1053 | + Some(revision) => Some(resolve_changeset(&repo, revision)?), | |
| 1054 | + None => None, | |
| 1055 | + }; | |
| 673 | 1056 | let green_before = refs.get(&green_ref(&branch)); |
| 674 | 1057 | let pass = Pass { |
| 675 | 1058 | args, |
| @@ -678,6 +1061,7 @@ | ||
| 678 | 1061 | branch: &branch, |
| 679 | 1062 | tip, |
| 680 | 1063 | green_before, |
| 1064 | + from, | |
| 681 | 1065 | }; |
| 682 | 1066 | let mut tester = Tester { |
| 683 | 1067 | repo: &repo, |
| @@ -687,20 +1071,19 @@ | ||
| 687 | 1071 | reruns: args.reruns, |
| 688 | 1072 | runs: 0, |
| 689 | 1073 | }; |
| 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() | |
| 703 | 1077 | }; |
| 1078 | + if let Err(err) = pass.run(&mut tester, &mut verdict) { | |
| 1079 | + // Before anything ran or was made, an error is only an error. | |
| 1080 | + if tester.runs == 0 && verdict.revert.is_none() { | |
| 1081 | + return Err(err); | |
| 1082 | + } | |
| 1083 | + eprintln!("braid: error: {err:#}"); | |
| 1084 | + verdict.outcome = "error"; | |
| 1085 | + verdict.reason = Some(format!("{err:#}")); | |
| 1086 | + } | |
| 704 | 1087 | if cli.json { |
| 705 | 1088 | print_json(&json!({ |
| 706 | 1089 | "branch": branch, |
| @@ -710,6 +1093,7 @@ | ||
| 710 | 1093 | "outcome": verdict.outcome, |
| 711 | 1094 | "culprit": hex(verdict.culprit), |
| 712 | 1095 | "revert": hex(verdict.revert), |
| 1096 | + "skipped": verdict.skipped.iter().map(ObjectId::to_hex).collect::<Vec<_>>(), | |
| 713 | 1097 | "tests_run": tester.runs, |
| 714 | 1098 | "reason": verdict.reason, |
| 715 | 1099 | "dry_run": args.dry_run, |
| @@ -722,7 +1106,7 @@ | ||
| 722 | 1106 | } |
| 723 | 1107 | |
| 724 | 1108 | 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"); | |
| 726 | 1110 | match verdict.outcome { |
| 727 | 1111 | "pass" | "flaky" => println!( |
| 728 | 1112 | "{branch} is green at {} ({}, {ran})", |
| @@ -734,6 +1118,12 @@ | ||
| 734 | 1118 | if let Some(reason) = &verdict.reason { |
| 735 | 1119 | println!("{reason}"); |
| 736 | 1120 | } |
| 1121 | + if let Some(revert) = verdict.revert { | |
| 1122 | + println!("Revert: {}", revert.short()); | |
| 1123 | + } | |
| 1124 | + if !verdict.skipped.is_empty() { | |
| 1125 | + println!("Not tested here: {}", listed(&verdict.skipped)); | |
| 1126 | + } | |
| 737 | 1127 | if let Some(report) = &verdict.land |
| 738 | 1128 | && report.conflicted() |
| 739 | 1129 | { |
| @@ -772,15 +1162,13 @@ | ||
| 772 | 1162 | } |
| 773 | 1163 | |
| 774 | 1164 | #[test] |
| 775 | - fn record_paths_escape_branch_names() { | |
| 1165 | + fn record_files_are_named_in_hex_and_kept_whole() { | |
| 776 | 1166 | let temp = tempfile::tempdir().unwrap(); |
| 777 | 1167 | 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")); | |
| 784 | 1172 | let mut record = Record::default(); |
| 785 | 1173 | record.reverts.push(Reverted { |
| 786 | 1174 | culprit: "c".repeat(64), |
| @@ -790,9 +1178,33 @@ | ||
| 790 | 1178 | }); |
| 791 | 1179 | let landed: ObjectId = "b".repeat(64).parse().unwrap(); |
| 792 | 1180 | 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); | |
| 795 | 1183 | record.save(&path).unwrap(); |
| 796 | 1184 | assert_eq!(Record::load(&path).unwrap().reverts.len(), 1); |
| 1185 | + assert!(!path.with_extension("json.new").exists()); | |
| 1186 | + | |
| 1187 | + // A damaged record says how to recover. | |
| 1188 | + fs::write(&path, "{").unwrap(); | |
| 1189 | + let err = format!("{:#}", Record::load(&path).unwrap_err()); | |
| 1190 | + assert!(err.contains("delete it"), "{err}"); | |
| 1191 | + } | |
| 1192 | + | |
| 1193 | + #[test] | |
| 1194 | + fn ids_are_listed_in_words() { | |
| 1195 | + let ids: Vec<ObjectId> = ["a", "b", "c"] | |
| 1196 | + .iter() | |
| 1197 | + .map(|c| c.repeat(64).parse().unwrap()) | |
| 1198 | + .collect(); | |
| 1199 | + assert_eq!(listed(&ids[..1]), "a".repeat(12)); | |
| 1200 | + assert_eq!( | |
| 1201 | + listed(&ids), | |
| 1202 | + format!( | |
| 1203 | + "{}, {} and {}", | |
| 1204 | + "a".repeat(12), | |
| 1205 | + "b".repeat(12), | |
| 1206 | + "c".repeat(12) | |
| 1207 | + ) | |
| 1208 | + ); | |
| 797 | 1209 | } |
| 798 | 1210 | } |
modified crates/cli/tests/verify.rs +207 −3
| @@ -153,7 +153,14 @@ | ||
| 153 | 153 | } |
| 154 | 154 | |
| 155 | 155 | 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(); | |
| 157 | 164 | } |
| 158 | 165 | } |
| 159 | 166 | |
| @@ -321,9 +328,12 @@ | ||
| 321 | 328 | 4, |
| 322 | 329 | ); |
| 323 | 330 | 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. | |
| 325 | 334 | assert_eq!(r.verify(&[], 0)["outcome"], "pass"); |
| 326 | 335 | let again = r.land(&[("broken", "again\n")], &[], "Break again"); |
| 336 | + r.forget_record(); | |
| 327 | 337 | let second = r.verify( |
| 328 | 338 | &["--revert", "--reruns", "0", "--max-reverts-per-hour", "1"], |
| 329 | 339 | 4, |
| @@ -350,8 +360,10 @@ | ||
| 350 | 360 | let revert = r.head().unwrap(); |
| 351 | 361 | |
| 352 | 362 | // 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. | |
| 354 | 365 | std::fs::write(&list, format!("{revert}\n")).unwrap(); |
| 366 | + r.forget_record(); | |
| 355 | 367 | let out = r.verify_env(&["--revert", "--reruns", "0"], &command, &[], 4); |
| 356 | 368 | assert_eq!(out["outcome"], "refused"); |
| 357 | 369 | assert_eq!(out["culprit"], revert.as_str()); |
| @@ -400,6 +412,13 @@ | ||
| 400 | 412 | let out = r.verify_env(&[], &["sh", "-c", &script], &[], 0); |
| 401 | 413 | assert_eq!(out["outcome"], "flaky"); |
| 402 | 414 | 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"); | |
| 403 | 422 | assert_eq!(out["green"], r.head().unwrap().as_str()); |
| 404 | 423 | } |
| 405 | 424 | |
| @@ -422,6 +441,29 @@ | ||
| 422 | 441 | let leak = "test -n \"$BRAID_AGENT\""; |
| 423 | 442 | let out = r.verify_env(&["--dry-run"], &["sh", "-c", leak], &envs, 0); |
| 424 | 443 | 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")); | |
| 425 | 467 | // A command that cannot run is an error, not a red branch. |
| 426 | 468 | let out = braid_with(&r.dir, &["verify", "--", "no-such-command-for-braid"], &[]); |
| 427 | 469 | assert_eq!(out.status.code(), Some(1)); |
| @@ -464,3 +506,165 @@ | ||
| 464 | 506 | } |
| 465 | 507 | assert!(!alive, "the background process {pid} outlived the timeout"); |
| 466 | 508 | } |
| 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 | +} |