Skip to main content

tak_cli/
worktree.rs

1//! Throwaway checkouts of historical commits, for `tak backfill --commits`.
2//!
3//! Each commit is built and measured in a detached `git worktree` under an
4//! owner-only temporary directory, never in the user's own checkout: a build
5//! that rewrites `target/` or a fixture there would leave the working tree in
6//! the state of whatever commit was measured last. Worktrees share the
7//! repository's object store and refs, so a checkout costs only the files it
8//! writes, and a note recorded from the main checkout lands on the same
9//! `refs/notes/tak`.
10//!
11//! Git is a subprocess here for the same reason it is in [`crate::notes`].
12
13use anyhow::{Context, Result, bail};
14use std::collections::BTreeMap;
15use std::path::{Path, PathBuf};
16use std::process::Command;
17use std::sync::Mutex;
18use std::sync::atomic::{AtomicBool, Ordering};
19
20fn git(args: &[&std::ffi::OsStr]) -> Result<String> {
21    let out = Command::new("git").args(args).output().with_context(|| {
22        format!(
23            "failed to run `git {}`",
24            args.iter()
25                .map(|a| a.to_string_lossy())
26                .collect::<Vec<_>>()
27                .join(" ")
28        )
29    })?;
30    if !out.status.success() {
31        bail!(
32            "git {} failed: {}",
33            args.iter()
34                .map(|a| a.to_string_lossy())
35                .collect::<Vec<_>>()
36                .join(" "),
37            String::from_utf8_lossy(&out.stderr).trim()
38        );
39    }
40    Ok(String::from_utf8_lossy(&out.stdout).trim_end().to_string())
41}
42
43fn git_str(args: &[&str]) -> Result<String> {
44    let args: Vec<&std::ffi::OsStr> = args.iter().map(std::ffi::OsStr::new).collect();
45    git(&args)
46}
47
48/// When `sha` was committed, as seconds since the epoch, read from the raw
49/// commit object.
50///
51/// Not `git show --format=%ct`, for two reasons. With `log.showSignature`
52/// set, `show` writes a signature's verification text onto stdout ahead of
53/// the format. And a commit dated before 1970, which only an import or a
54/// hand-written object can produce, has a negative timestamp that `%ct`
55/// prints as nothing at all. `cat-file` prints the object as stored, so the
56/// committer line says exactly what the commit says.
57pub fn commit_time(sha: &str) -> Result<i64> {
58    let out = git_str(&["cat-file", "commit", sha])?;
59    parse_commit_time(&out).with_context(|| format!("no readable committer date in {sha}"))
60}
61
62/// The timestamp on the `committer` header: `committer NAME <EMAIL> TS TZ`.
63/// Only headers are searched, which end at the first blank line, so a
64/// message line starting with `committer` cannot be taken for it. Taken from
65/// the right, since the name and email may hold spaces.
66fn parse_commit_time(object: &str) -> Option<i64> {
67    let line = object
68        .lines()
69        .take_while(|l| !l.is_empty())
70        .find_map(|l| l.strip_prefix("committer "))?;
71    let mut fields = line.rsplit(' ');
72    let _tz = fields.next()?;
73    fields.next()?.parse().ok()
74}
75
76/// The root of the work tree containing `dir`.
77pub fn toplevel(dir: &Path) -> Result<PathBuf> {
78    let out = git(&[
79        "-C".as_ref(),
80        dir.as_os_str(),
81        "rev-parse".as_ref(),
82        "--show-toplevel".as_ref(),
83    ])
84    .context("not inside a git repository")?;
85    Ok(PathBuf::from(out))
86}
87
88/// Forget worktrees whose directories no longer exist.
89///
90/// A run killed outright — SIGKILL, or a signal during a step that handles
91/// its own, like a subject's `version_cmd` — cannot remove its checkout. The
92/// directory is in the system temporary directory and goes with it; this
93/// clears the bookkeeping git keeps for it, so stale entries do not pile up
94/// in `git worktree list`.
95pub fn prune() {
96    let _ = git_str(&["worktree", "prune"]);
97}
98
99/// Worktrees this process has created and not yet removed, for the interrupt
100/// handler to clean up. Held for the whole of [`Worktree::add`], so a
101/// checkout being created while an interrupt arrives is either finished and
102/// listed here, or never started.
103static LIVE: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
104/// Set once an interrupt is being handled: nothing new may be checked out.
105static STOPPING: AtomicBool = AtomicBool::new(false);
106
107/// The running build's process group, or 0 when none is running.
108///
109/// The build gets a group of its own so that stopping tak stops all of it,
110/// compilers and linkers included, even when the signal was sent to tak
111/// alone: CI cancelling a job, or `kill <pid>`, reaches tak but not its
112/// children. A terminal's Ctrl-C no longer reaches the build directly either,
113/// since it is out of the foreground group; the interrupt handler kills the
114/// group on tak's behalf.
115#[cfg(unix)]
116static BUILD_GROUP: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);
117
118/// The build has been spawned as the leader of process group `pid`.
119///
120/// If an interrupt is already being handled, the handler may have looked for
121/// a group before this one was recorded, so the build is killed here. Each
122/// side writes its own flag before reading the other's, all `SeqCst`, so at
123/// least one of them sees the group.
124#[cfg(unix)]
125pub fn build_started(pid: u32) {
126    BUILD_GROUP.store(pid as i32, Ordering::SeqCst);
127    if STOPPING.load(Ordering::SeqCst) {
128        kill_build();
129    }
130}
131
132/// Whether an interrupt is being handled. A build that fails from here on
133/// was killed by tak, not broken by its commit.
134pub fn stopping() -> bool {
135    STOPPING.load(Ordering::SeqCst) || SIGNALED.load(Ordering::SeqCst)
136}
137
138/// Set by the signal handler itself, before the cleanup thread wakes.
139static SIGNALED: AtomicBool = AtomicBool::new(false);
140
141/// Never return once an interrupt has arrived: wait for the cleanup thread
142/// to exit the process.
143///
144/// The thread kills the build or the measured command, and the main thread,
145/// seeing it fail, would otherwise finish the loop and exit with its own
146/// status first — 1 for a range with nothing recorded, where the signal's
147/// 130 or 143 was due — and possibly before the checkout was removed. The
148/// main thread calls this after every commit and before it returns, so the
149/// exit is always the handler's.
150pub fn wait_if_interrupted() {
151    if stopping() {
152        loop {
153            std::thread::park();
154        }
155    }
156}
157
158/// The build has been reaped; its group id may be reused from here on.
159#[cfg(unix)]
160pub fn build_finished() {
161    BUILD_GROUP.store(0, Ordering::SeqCst);
162}
163
164/// SIGKILL rather than SIGTERM: the checkout it is writing into is about to
165/// be deleted, and a build given time to clean up would only race that.
166#[cfg(unix)]
167fn kill_build() {
168    let pgid = BUILD_GROUP.load(Ordering::SeqCst);
169    if pgid > 0 {
170        // SAFETY: killpg has no memory-safety preconditions.
171        unsafe {
172            libc::killpg(pgid, libc::SIGKILL);
173        }
174    }
175}
176
177/// How a remembered commit failed.
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub enum Failure {
180    /// The build failed, or the tree it would run in could not be used. The
181    /// whole commit is passed over.
182    Build,
183    /// It built, and measuring this benchmark failed: it errored, a subject
184    /// was dropped, a check or an instruction count failed. Only this
185    /// benchmark is passed over; the commit's others are still measured.
186    Measure(String),
187}
188
189/// Stop the measured command — a subject, its setup, prepare or check, or
190/// valgrind — that is running now, and any the main thread starts from here
191/// on. Each runs in a process group of its own during a backfill (see
192/// [`crate::measure::use_own_groups`]), so this reaches exactly it and what
193/// it started. Never tak's own group, which may hold other commands, such as
194/// the rest of a shell pipeline.
195#[cfg(unix)]
196fn kill_measured() {
197    crate::measure::stop_running();
198}
199
200/// Commits that failed in an earlier run, with how and under what.
201///
202/// Without a memory of these, a commit that can never be recorded is chosen
203/// again at the top of every run, and with `--limit` a backfill stops making
204/// progress at the first one. That holds for a failed measurement as much as
205/// for a failed build: at a fixed commit, a benchmark that errors or a
206/// fixture that is missing fails the same way every time. A flaky one costs
207/// a point `--force` can recover, where not remembering it cost every older
208/// commit behind it.
209///
210/// A build failure is per commit, and keyed on the runner class and
211/// `[build]`, so changing the build — usually to fix exactly that failure —
212/// or moving to a new toolchain tries the commit again. A measurement failure
213/// is per benchmark, so a run of other benchmarks (`--bench B` after `--bench
214/// A` failed) still measures them, and it is keyed on those and on the
215/// contents of tak.toml as well, since editing a benchmark is how one of
216/// those gets fixed. Not on `--runs`: a benchmark that errors at five runs
217/// errors at ten, and one that only fails sometimes is what `--force` is for.
218/// Kept in git's common directory: shared by the repository's worktrees,
219/// never committed, and local to this clone, since a failure says as much
220/// about this machine as about the commit.
221///
222/// One line per failure: `SHA \t build-failed \t KEY`, or `SHA \t
223/// measure-failed \t BENCH \t KEY` with the benchmark's name as a JSON
224/// string, which cannot hold a tab. A line written before reasons were
225/// recorded, `SHA \t KEY`, is a build failure.
226pub struct FailedCommits {
227    path: PathBuf,
228    build_key: String,
229    measure_key: String,
230    known: BTreeMap<String, Known>,
231}
232
233/// What is remembered about one commit under this run's keys.
234#[derive(Debug, Default)]
235struct Known {
236    build: bool,
237    measure: std::collections::BTreeSet<String>,
238}
239
240impl FailedCommits {
241    /// The commits that failed under these keys: `build_key` describes the
242    /// runner class and `[build]`, `measure_key` those and the benchmarks.
243    pub fn load(build_key: String, measure_key: String) -> Result<FailedCommits> {
244        // Plain `--git-common-dir` and `std::path::absolute`, as the baseline
245        // store resolves it: `--path-format=absolute` would need git 2.31,
246        // newer than anything else tak asks of git. The output is relative
247        // to the current directory at the top of a checkout (`.git`) and
248        // absolute from inside a worktree; both resolve the same way here.
249        let common = PathBuf::from(git_str(&["rev-parse", "--git-common-dir"])?);
250        let common = std::path::absolute(&common)
251            .with_context(|| format!("could not resolve {}", common.display()))?;
252        let path = common.join("tak").join("backfill-build-failed");
253        let text = std::fs::read_to_string(&path).unwrap_or_default();
254        let mut known: BTreeMap<String, Known> = BTreeMap::new();
255        for line in text.lines() {
256            if let Some((sha, failure)) = parse_failure(line, &build_key, &measure_key) {
257                let k = known.entry(sha.to_string()).or_default();
258                match failure {
259                    Failure::Build => k.build = true,
260                    Failure::Measure(bench) => {
261                        k.measure.insert(bench);
262                    }
263                }
264            }
265        }
266        Ok(FailedCommits {
267            path,
268            build_key,
269            measure_key,
270            known,
271        })
272    }
273
274    /// Whether `sha`'s build failed before under these keys.
275    pub fn build_failed(&self, sha: &str) -> bool {
276        self.known.get(sha).is_some_and(|k| k.build)
277    }
278
279    /// Whether measuring `bench` at `sha` failed before under these keys.
280    pub fn measure_failed(&self, sha: &str, bench: &str) -> bool {
281        self.known
282            .get(sha)
283            .is_some_and(|k| k.measure.contains(bench))
284    }
285
286    /// Remember a failure at `sha`.
287    pub fn add(&mut self, sha: &str, failure: Failure) -> Result<()> {
288        let k = self.known.entry(sha.to_string()).or_default();
289        let new = match &failure {
290            Failure::Build => !std::mem::replace(&mut k.build, true),
291            Failure::Measure(bench) => k.measure.insert(bench.clone()),
292        };
293        if !new {
294            return Ok(());
295        }
296        let line = self.line(sha, &failure)?;
297        self.rewrite(|lines, _| lines.push(line))
298    }
299
300    /// `sha` built, and `benches` were recorded there (none, when measuring
301    /// failed): forget its build failure and theirs. Failures of other
302    /// benchmarks stay.
303    pub fn recorded(&mut self, sha: &str, benches: &[String]) -> Result<()> {
304        let Some(k) = self.known.get_mut(sha) else {
305            return Ok(());
306        };
307        let before = (k.build, k.measure.len());
308        k.build = false;
309        k.measure.retain(|b| !benches.contains(b));
310        if before == (k.build, k.measure.len()) {
311            return Ok(());
312        }
313        self.rewrite(|lines, this| {
314            lines.retain(
315                |l| match parse_failure(l, &this.build_key, &this.measure_key) {
316                    Some((s, Failure::Build)) => s != sha,
317                    Some((s, Failure::Measure(b))) => s != sha || !benches.contains(&b),
318                    None => true,
319                },
320            )
321        })
322    }
323
324    fn line(&self, sha: &str, failure: &Failure) -> Result<String> {
325        Ok(match failure {
326            Failure::Build => format!("{sha}\tbuild-failed\t{}", self.build_key),
327            Failure::Measure(bench) => format!(
328                "{sha}\tmeasure-failed\t{}\t{}",
329                serde_json::to_string(bench)?,
330                self.measure_key
331            ),
332        })
333    }
334
335    /// Re-read, change and replace the file.
336    ///
337    /// Re-read rather than written from this process's own view, so entries
338    /// another backfill added since this one loaded are kept. Replaced by
339    /// renaming a complete temporary file over it, so a concurrent reader,
340    /// or a run killed mid-write, never sees half a file. Two backfills
341    /// writing at the same instant can still lose one's entry. There is no
342    /// lock, because the cost of that is small: a commit that failed gets
343    /// tried once more.
344    fn rewrite(&self, change: impl FnOnce(&mut Vec<String>, &Self)) -> Result<()> {
345        let text = std::fs::read_to_string(&self.path).unwrap_or_default();
346        let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
347        change(&mut lines, self);
348        lines.sort();
349        lines.dedup();
350        let dir = self.path.parent().context("no directory for build state")?;
351        std::fs::create_dir_all(dir)?;
352        let mut body = lines.join("\n");
353        body.push('\n');
354        let mut tmp = tempfile::NamedTempFile::new_in(dir)
355            .with_context(|| format!("could not write in {}", dir.display()))?;
356        std::io::Write::write_all(&mut tmp, body.as_bytes())?;
357        tmp.persist(&self.path)
358            .with_context(|| format!("could not write {}", self.path.display()))?;
359        Ok(())
360    }
361}
362
363/// One line of the failure file, if it applies under these keys.
364fn parse_failure<'a>(
365    line: &'a str,
366    build_key: &str,
367    measure_key: &str,
368) -> Option<(&'a str, Failure)> {
369    let (sha, rest) = line.split_once('\t')?;
370    if let Some(rest) = rest.strip_prefix("measure-failed\t") {
371        let (bench, key) = rest.split_once('\t')?;
372        let bench: String = serde_json::from_str(bench).ok()?;
373        return (key == measure_key).then_some((sha, Failure::Measure(bench)));
374    }
375    // Written before failures had a reason, only builds were kept.
376    let key = rest.strip_prefix("build-failed\t").unwrap_or(rest);
377    (key == build_key).then_some((sha, Failure::Build))
378}
379
380/// A 64-bit FNV-1a hash, as lowercase hex: a stable fingerprint of
381/// tak.toml for [`FailedCommits`]'s measurement key. Not std's `Hasher`,
382/// whose output is allowed to change between Rust releases, which would
383/// forget every remembered failure on a toolchain upgrade.
384pub fn fingerprint(bytes: &[u8]) -> String {
385    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
386    for b in bytes {
387        h ^= u64::from(*b);
388        h = h.wrapping_mul(0x0000_0100_0000_01b3);
389    }
390    format!("{h:016x}")
391}
392
393/// A detached checkout of one commit, removed when dropped.
394pub struct Worktree {
395    path: PathBuf,
396}
397
398impl Worktree {
399    /// Check `sha` out at `path`, which must not exist yet.
400    ///
401    /// `hooks` is an empty directory used as `core.hooksPath`: `worktree add`
402    /// runs the repository's `post-checkout` hook, and a project hook that
403    /// installs dependencies or regenerates files would run at every commit
404    /// of the backfill, unasked, and change what the build starts from.
405    pub fn add(path: &Path, sha: &str, hooks: &Path) -> Result<Worktree> {
406        let mut live = LIVE.lock().unwrap_or_else(|e| e.into_inner());
407        if STOPPING.load(Ordering::SeqCst) {
408            bail!("interrupted");
409        }
410        let mut hooks_cfg = std::ffi::OsString::from("core.hooksPath=");
411        hooks_cfg.push(hooks);
412        // No `--quiet`: `worktree add` only gained it in git 2.25, and its
413        // output is captured and discarded anyway.
414        git(&[
415            "-c".as_ref(),
416            &hooks_cfg,
417            "worktree".as_ref(),
418            "add".as_ref(),
419            "--detach".as_ref(),
420            path.as_os_str(),
421            sha.as_ref(),
422        ])
423        .with_context(|| format!("could not check out {sha}"))?;
424        live.push(path.to_path_buf());
425        Ok(Worktree {
426            path: path.to_path_buf(),
427        })
428    }
429
430    pub fn path(&self) -> &Path {
431        &self.path
432    }
433
434    /// Check that `p`, symlinks resolved, is inside this checkout.
435    ///
436    /// Refusing `..` in the configured path is not enough: an old commit can
437    /// hold a symlink where the current tak.toml expects a directory, and one
438    /// pointing at the live tree would build or measure that tree at every
439    /// commit of the backfill.
440    pub fn check_contains(&self, p: &Path) -> Result<()> {
441        let shown = p.strip_prefix(&self.path).unwrap_or(p).display();
442        let real = p
443            .canonicalize()
444            .with_context(|| format!("{shown} does not exist at this commit"))?;
445        if !real.starts_with(self.path.canonicalize()?) {
446            bail!("{shown} leads outside the checkout, to {}", real.display());
447        }
448        Ok(())
449    }
450}
451
452/// Remove a checkout and git's record of it.
453///
454/// `--force` because the build has just filled it with untracked output.
455/// Falling back to deleting the directory and pruning covers a worktree git
456/// no longer recognises, so the temporary directory is emptied either way.
457fn remove(path: &Path) {
458    let ok = git(&[
459        "worktree".as_ref(),
460        "remove".as_ref(),
461        "--force".as_ref(),
462        path.as_os_str(),
463    ])
464    .is_ok();
465    if !ok || path.exists() {
466        let _ = std::fs::remove_dir_all(path);
467        prune();
468    }
469}
470
471impl Drop for Worktree {
472    fn drop(&mut self) {
473        let mut live = LIVE.lock().unwrap_or_else(|e| e.into_inner());
474        remove(&self.path);
475        live.retain(|p| p != &self.path);
476    }
477}
478
479/// Remove this process's worktrees and `scratch` when tak is interrupted.
480///
481/// Destructors do not run when a signal ends the process, and without this a
482/// Ctrl-C during a long build leaves a full checkout in the temporary
483/// directory and a stale entry in `git worktree list` for every interrupted
484/// run.
485///
486/// The handler only writes the signal number to a socket; a thread blocked on
487/// the other end does the cleanup, since running git from inside a signal
488/// handler is not safe. It kills the build's process group first (see
489/// [`BUILD_GROUP`]), so a build never outlives the checkout it was writing
490/// into. Measured commands share tak's own group and get a terminal's Ctrl-C
491/// directly.
492///
493/// While a subject's `version_cmd` runs, [`crate::measure`] installs its own
494/// handlers, which stop tak at once; [`prune`] at the start of the next run
495/// tidies up after that.
496#[cfg(unix)]
497pub fn clean_up_on_interrupt(scratch: &Path) -> Result<()> {
498    use std::io::Read;
499    use std::os::fd::IntoRawFd;
500    use std::os::unix::net::UnixStream;
501    use std::sync::atomic::AtomicI32;
502
503    static WRITE_FD: AtomicI32 = AtomicI32::new(-1);
504
505    extern "C" fn on_signal(sig: libc::c_int) {
506        // An atomic store is async-signal-safe, and set here rather than by
507        // the thread so the main thread sees it the moment the signal lands.
508        SIGNALED.store(true, Ordering::SeqCst);
509        let fd = WRITE_FD.load(Ordering::SeqCst);
510        if fd >= 0 {
511            let byte = sig as u8;
512            // SAFETY: write is async-signal-safe; the buffer outlives the call.
513            unsafe {
514                libc::write(fd, (&byte as *const u8).cast(), 1);
515            }
516        }
517    }
518
519    // Once per process. The write end is deliberately never closed: the
520    // handler may fire at any moment until tak exits, and closing it would
521    // leave the handler writing to a descriptor that has been reused. A
522    // second call would replace it, leaking the first and starting a second
523    // thread, so it is a no-op instead.
524    if WRITE_FD.load(Ordering::SeqCst) >= 0 {
525        return Ok(());
526    }
527    // A socket pair rather than `pipe`, because std creates it close-on-exec
528    // on every Unix: the build and the measured commands must not inherit
529    // either end.
530    let (mut rx, tx) = UnixStream::pair().context("could not set up interrupt handling")?;
531    WRITE_FD.store(tx.into_raw_fd(), Ordering::SeqCst);
532    // Measured commands leave tak's group from here, so the handler can stop
533    // them without signalling anything else in it; a terminal's Ctrl-C no
534    // longer reaches them directly, which is why the handler must.
535    crate::measure::use_own_groups();
536    let scratch = scratch.to_path_buf();
537    std::thread::spawn(move || {
538        let mut sig = [0u8; 1];
539        if rx.read_exact(&mut sig).is_err() {
540            return;
541        }
542        STOPPING.store(true, Ordering::SeqCst);
543        kill_build();
544        kill_measured();
545        // Never released: the process exits while holding it, so nothing
546        // can be checked out after the sweep.
547        let live = LIVE.lock().unwrap_or_else(|e| e.into_inner());
548        for p in live.iter() {
549            remove(p);
550        }
551        let _ = std::fs::remove_dir_all(&scratch);
552        eprintln!("\n  interrupted — removed backfill worktrees");
553        std::process::exit(128 + i32::from(sig[0]));
554    });
555    for sig in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
556        // SAFETY: plain-data struct, filled in before use; the handler is an
557        // `extern "C" fn(c_int)`, as sa_sigaction expects without SA_SIGINFO.
558        // SA_RESTART so a wait on the build is not cut short by the signal.
559        unsafe {
560            let mut new: libc::sigaction = std::mem::zeroed();
561            new.sa_sigaction = on_signal as extern "C" fn(libc::c_int) as libc::sighandler_t;
562            new.sa_flags = libc::SA_RESTART;
563            libc::sigemptyset(&mut new.sa_mask);
564            libc::sigaction(sig, &new, std::ptr::null_mut());
565        }
566    }
567    Ok(())
568}
569
570/// Windows has no equivalent wired up yet: an interrupted run leaves its
571/// checkout for [`prune`] and the temporary directory's own cleanup.
572#[cfg(not(unix))]
573pub fn clean_up_on_interrupt(_scratch: &Path) -> Result<()> {
574    Ok(())
575}
576
577#[cfg(test)]
578mod tests {
579    use super::{Failure, fingerprint, parse_commit_time, parse_failure};
580
581    /// Each line applies only under the key its reason is kept with, and a
582    /// line from before reasons were recorded is a build failure.
583    #[test]
584    fn failure_lines_apply_under_their_own_key() {
585        let (b, m) = ("B", "B f00d");
586        assert_eq!(
587            parse_failure("abc\tbuild-failed\tB", b, m),
588            Some(("abc", Failure::Build))
589        );
590        assert_eq!(
591            parse_failure("abc\tmeasure-failed\t\"startup\"\tB f00d", b, m),
592            Some(("abc", Failure::Measure("startup".into())))
593        );
594        // A name JSON escapes, which is how a tab in it cannot split the line.
595        assert_eq!(
596            parse_failure("abc\tmeasure-failed\t\"a\\tb\"\tB f00d", b, m),
597            Some(("abc", Failure::Measure("a\tb".into())))
598        );
599        assert_eq!(parse_failure("abc\tB", b, m), Some(("abc", Failure::Build)));
600        // Another build, another tak.toml, no benchmark, or a reason from the
601        // future.
602        assert_eq!(parse_failure("abc\tbuild-failed\tC", b, m), None);
603        assert_eq!(
604            parse_failure("abc\tmeasure-failed\t\"startup\"\tB beef", b, m),
605            None
606        );
607        assert_eq!(parse_failure("abc\tmeasure-failed\tB f00d", b, m), None);
608        assert_eq!(parse_failure("abc\tflaky\tB", b, m), None);
609        assert_eq!(parse_failure("", b, m), None);
610    }
611
612    /// FNV-1a's published test vectors: the fingerprint must not change
613    /// between releases, or every remembered failure would be retried.
614    #[test]
615    fn the_fingerprint_is_stable() {
616        assert_eq!(fingerprint(b""), "cbf29ce484222325");
617        assert_eq!(fingerprint(b"a"), "af63dc4c8601ec8c");
618        assert_eq!(fingerprint(b"foobar"), "85944171f73967e8");
619    }
620
621    #[test]
622    fn a_commit_time_is_the_committer_header_timestamp() {
623        let object = "tree abc\nparent def\n\
624                      author A Person <a@x> 1600000000 +0200\n\
625                      committer The Committer <c@x> 1700000000 -0700\n\n\
626                      subject\n";
627        assert_eq!(parse_commit_time(object), Some(1_700_000_000));
628        let before_1970 = "tree abc\ncommitter T <t@x> -14182940 +0000\n\nv2\n";
629        assert_eq!(parse_commit_time(before_1970), Some(-14_182_940));
630    }
631
632    /// A signed commit carries a multi-line `gpgsig` header, and a message
633    /// can say anything; neither may be read as the committer line.
634    #[test]
635    fn signatures_and_messages_are_not_the_committer_line() {
636        let object = "tree abc\n\
637                      committer T <t@x> 1700000000 +0000\n\
638                      gpgsig -----BEGIN SSH SIGNATURE-----\n \
639                      U1NIU0lH 1234 +0000\n -----END SSH SIGNATURE-----\n\n\
640                      committer X <x@x> 1 +0000\n";
641        assert_eq!(parse_commit_time(object), Some(1_700_000_000));
642        let no_header = "tree abc\n\ncommitter X <x@x> 1 +0000\n";
643        assert_eq!(parse_commit_time(no_header), None);
644    }
645}