Skip to main content

tak_cli/
accept.rs

1//! Declared, intentional regressions: which benchmarks a change says it made
2//! more expensive on purpose, and who said so.
3//!
4//! The only other way past a failing gate is `--no-gate`, which stops gating
5//! every benchmark at once. A team with one deliberate cost increase then either
6//! loosens the threshold for everything or stops requiring the check — both of
7//! which leave the next, unintended regression unguarded. An acceptance names
8//! one benchmark, and it is always reported with where it came from, so the
9//! override is as visible in the report as the regression it covers.
10//!
11//! Two sources, deliberately no more:
12//!
13//! - `tak compare --accept`, for a CI integration that maps something outside
14//!   the commits — a pull-request label only maintainers can apply, say — onto
15//!   an acceptance. This is the one honoured by default, because whoever
16//!   decides it is not necessarily whoever wrote the change; and
17//! - a `Tak-Accept:` trailer on a commit in the compared range, which is how a
18//!   change carries its own justification into history. Opt-in through the
19//!   `accept_trailers` setting: those commits are the change being gated, and
20//!   by default a change must not be able to waive its own gate.
21//!
22//! Names only, no bound such as `startup<=5%`. A bound invites arguing about
23//! the number in the trailer rather than looking at the change, and a second
24//! syntax is a second thing to get wrong in a line nobody tests. An accepted
25//! benchmark still shows its full change in the report.
26
27use anyhow::{Result, bail};
28use std::collections::{BTreeMap, BTreeSet};
29
30/// The trailer key. git matches trailer keys case-insensitively, so
31/// `tak-accept:` works too; this is the spelling the docs and report use.
32pub const TRAILER: &str = "Tak-Accept";
33
34/// Where an acceptance came from. Always shown beside it: an override nobody
35/// can trace is exactly the kind of quiet gate-weakening this exists to avoid.
36#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
37pub enum Source {
38    /// `tak compare --accept`.
39    Flag,
40    /// A trailer on this commit, by full SHA.
41    Trailer(String),
42}
43
44impl Source {
45    fn describe(&self) -> String {
46        match self {
47            Source::Flag => "`--accept`".to_string(),
48            // Twelve characters, matching how `tak history` names commits.
49            Source::Trailer(sha) => {
50                format!("`{TRAILER}` in `{}`", &sha[..sha.len().min(12)])
51            }
52        }
53    }
54}
55
56/// Accepted benchmark names, each with every source that accepted it.
57///
58/// Keyed on the benchmark name alone, so an acceptance covers every tool and
59/// runner that benchmark was measured with. The name is what a user declares
60/// in `tak.toml` and sees in the report; the runner in particular is something
61/// a commit author cannot know ahead of time.
62#[derive(Debug, Clone, Default, PartialEq)]
63pub struct Acceptances(BTreeMap<String, BTreeSet<Source>>);
64
65impl Acceptances {
66    /// Add one exact name, as `--accept` gives it.
67    ///
68    /// Not split on commas and not trimmed. Benchmark names are unrestricted,
69    /// so `" startup "` is a different benchmark from `startup`, and trimming
70    /// would accept the wrong one's regression — waiving a gate nobody asked
71    /// to waive. The flag is repeatable, which covers every list without a
72    /// separator. An empty value is an error rather than skipped: it is
73    /// almost always an unset variable in a CI script, and silently accepting
74    /// nothing hides that.
75    pub fn add_name(&mut self, name: &str, source: Source) -> Result<()> {
76        if name.is_empty() {
77            bail!("--accept needs a benchmark name, and was given an empty one");
78        }
79        self.insert(name, source);
80        Ok(())
81    }
82
83    fn insert(&mut self, name: &str, source: Source) {
84        self.0.entry(name.to_string()).or_default().insert(source);
85    }
86
87    /// Parse the output of [`crate::notes::trailers`]: one line per commit,
88    /// the SHA and then each trailer value, NUL-separated.
89    ///
90    /// One trailer names one benchmark, the whole value, exactly as `--accept`
91    /// takes one name per flag. It used to be split on commas, which made a
92    /// benchmark named `a,b` impossible to accept and `Tak-Accept: a,b` accept
93    /// two unrelated ones instead — waiving gates nobody named. Benchmark
94    /// names are unrestricted, so no separator inside a value is safe; several
95    /// benchmarks take several trailers.
96    ///
97    /// Nothing else is stripped: `Tak-Accept: startup (new plugin loader)`
98    /// names a benchmark that does not exist and is reported as such, which
99    /// fails closed — the real `startup` regression still gates — rather than
100    /// guessing which word was meant. git has already trimmed the value, so a
101    /// trailer cannot name a benchmark with leading or trailing spaces; that
102    /// takes `--accept`.
103    pub fn add_trailer_log(&mut self, log: &str) {
104        for line in log.lines() {
105            let mut fields = line.split('\0');
106            let Some(sha) = fields.next() else {
107                continue;
108            };
109            // Empty for a commit with no such trailer, and for a bare
110            // `Tak-Accept:` — neither names anything.
111            for name in fields.filter(|n| !n.is_empty()) {
112                self.insert(name, Source::Trailer(sha.to_string()));
113            }
114        }
115    }
116
117    pub fn is_empty(&self) -> bool {
118        self.0.is_empty()
119    }
120
121    pub fn covers(&self, bench: &str) -> bool {
122        self.0.contains_key(bench)
123    }
124
125    /// Every accepted name with its sources, in a stable order.
126    pub fn iter(&self) -> impl Iterator<Item = (&str, &BTreeSet<Source>)> {
127        self.0.iter().map(|(k, v)| (k.as_str(), v))
128    }
129
130    /// Where `bench` was accepted from, for the report.
131    pub fn describe(&self, bench: &str) -> String {
132        self.0
133            .get(bench)
134            .map(|sources| {
135                sources
136                    .iter()
137                    .map(Source::describe)
138                    .collect::<Vec<_>>()
139                    .join(", ")
140            })
141            .unwrap_or_default()
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    const A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
150    const B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
151
152    /// One trailer, one name. A comma is part of the name: splitting on it
153    /// accepted `a` and `b` for a trailer written for the benchmark `a,b`.
154    #[test]
155    fn a_trailer_value_is_one_name_commas_included() {
156        let mut a = Acceptances::default();
157        a.add_trailer_log(&format!("{A}\0a,b\0resolve\n"));
158        let names: Vec<_> = a.iter().map(|(n, _)| n).collect();
159        assert_eq!(names, ["a,b", "resolve"]);
160        assert!(!a.covers("a"));
161        assert!(!a.covers("b"));
162    }
163
164    /// A commit with no trailer still prints its SHA; it must add nothing
165    /// rather than an empty name that could never match and would be reported.
166    #[test]
167    fn a_commit_without_the_trailer_accepts_nothing() {
168        let mut a = Acceptances::default();
169        a.add_trailer_log(&format!("{A}\0\n{B}\0startup\n"));
170        assert!(a.covers("startup"));
171        assert_eq!(a.iter().count(), 1);
172        assert_eq!(a.describe("startup"), "`Tak-Accept` in `bbbbbbbbbbbb`");
173    }
174
175    /// Every source is kept, not just the first: the report has to name all
176    /// of them, or removing one trailer could silently leave another in force.
177    #[test]
178    fn every_source_of_an_acceptance_is_kept() {
179        let mut a = Acceptances::default();
180        a.add_trailer_log(&format!("{A}\0startup\0resolve\n{B}\0startup\n"));
181        a.add_name("startup", Source::Flag).unwrap();
182        assert_eq!(
183            a.describe("startup"),
184            "`--accept`, `Tak-Accept` in `aaaaaaaaaaaa`, `Tak-Accept` in `bbbbbbbbbbbb`"
185        );
186        assert_eq!(a.describe("resolve"), "`Tak-Accept` in `aaaaaaaaaaaa`");
187    }
188
189    /// The flag takes a name as given, so a benchmark whose name contains a
190    /// comma can still be accepted.
191    #[test]
192    fn a_flag_value_is_one_name() {
193        let mut a = Acceptances::default();
194        a.add_name("parse a,b", Source::Flag).unwrap();
195        assert!(a.covers("parse a,b"));
196        assert_eq!(a.iter().count(), 1);
197    }
198
199    /// Exact means exact: surrounding spaces are part of the name, and
200    /// dropping them would accept a different benchmark.
201    #[test]
202    fn a_flag_value_is_not_trimmed() {
203        let mut a = Acceptances::default();
204        a.add_name(" startup ", Source::Flag).unwrap();
205        assert!(a.covers(" startup "));
206        assert!(!a.covers("startup"));
207    }
208
209    #[test]
210    fn an_empty_flag_value_is_an_error() {
211        let mut a = Acceptances::default();
212        assert!(a.add_name("", Source::Flag).is_err());
213        assert!(a.is_empty());
214    }
215
216    /// A reason written after the name is not quietly dropped. The whole value
217    /// is the name, which matches nothing, so the regression still gates and
218    /// the report says the acceptance named no benchmark.
219    #[test]
220    fn a_reason_in_the_value_is_not_guessed_at() {
221        let mut a = Acceptances::default();
222        a.add_trailer_log(&format!("{A}\0startup (new loader)\n"));
223        assert!(!a.covers("startup"));
224        assert!(a.covers("startup (new loader)"));
225    }
226}