1use crate::accept::Acceptances;
13use crate::config::SELF_TOOL;
14use crate::record::{Record, is_builtin_metric};
15use std::collections::{BTreeMap, BTreeSet};
16
17pub const GATED_METRIC: &str = "instructions";
19
20pub(crate) const WALL_METRIC: &str = "wall_min_ms";
22
23const ALLOC_METRICS: [(&str, &str); 3] = [
27 ("alloc_blocks", "allocations"),
28 ("alloc_bytes", "bytes allocated"),
29 ("alloc_peak_bytes", "peak heap"),
30];
31
32pub type Key = (String, String, String);
40
41#[derive(Debug, Clone, PartialEq)]
43pub struct Change {
44 pub bench: String,
45 pub tool: String,
46 pub runner: String,
47 pub metric: String,
48 pub base: f64,
49 pub head: f64,
50}
51
52impl Change {
53 pub fn pct(&self) -> Option<f64> {
60 if self.base == 0.0 {
61 return None;
62 }
63 Some((self.head - self.base) / self.base * 100.0)
64 }
65
66 pub fn exceeds(&self, gate: &Gate) -> bool {
83 if self.metric != GATED_METRIC {
84 return false;
85 }
86 if self.head - self.base <= gate.min_delta as f64 {
88 return false;
89 }
90 match self.pct() {
91 Some(p) => p > gate.pct,
92 None => self.head > 0.0,
93 }
94 }
95}
96
97#[derive(Debug, Clone, Copy, PartialEq)]
105pub struct Gate {
106 pub pct: f64,
108 pub min_delta: u64,
110 pub enabled: bool,
113}
114
115impl Gate {
116 pub fn new(pct: f64, min_delta: u64) -> anyhow::Result<Self> {
118 check_pct(pct)?;
119 Ok(Self {
120 pct,
121 min_delta,
122 enabled: true,
123 })
124 }
125
126 pub(crate) fn threshold(&self) -> String {
128 if self.min_delta == 0 {
129 format!("{}%", self.pct)
130 } else {
131 format!("{}%, floor {}", self.pct, thousands(self.min_delta as f64))
132 }
133 }
134
135 pub(crate) fn describe(&self) -> String {
137 if self.enabled {
138 self.threshold()
139 } else {
140 format!("report only ({})", self.threshold())
141 }
142 }
143}
144
145pub fn check_pct(pct: f64) -> anyhow::Result<()> {
152 if !pct.is_finite() || pct < 0.0 {
153 anyhow::bail!("a gate percentage must be a finite number, 0 or more, not {pct}");
154 }
155 Ok(())
156}
157
158#[derive(Debug, Clone, PartialEq)]
164pub struct Gates {
165 pub global: Gate,
167 benches: BTreeMap<String, Gate>,
170 series: BTreeMap<(String, String), Gate>,
172}
173
174impl Gates {
175 pub fn uniform(global: Gate) -> Self {
177 Self {
178 global,
179 benches: BTreeMap::new(),
180 series: BTreeMap::new(),
181 }
182 }
183
184 pub fn set_bench(&mut self, bench: &str, gate: Gate) {
185 self.benches.insert(bench.to_string(), gate);
186 }
187
188 pub fn set_series(&mut self, bench: &str, tool: &str, gate: Gate) {
189 self.series
190 .insert((bench.to_string(), tool.to_string()), gate);
191 }
192
193 pub fn get(&self, bench: &str, tool: &str) -> Gate {
201 self.series
202 .get(&(bench.to_string(), tool.to_string()))
203 .or_else(|| self.benches.get(bench))
204 .copied()
205 .unwrap_or(self.global)
206 }
207
208 fn of(&self, c: &Change) -> Gate {
209 self.get(&c.bench, &c.tool)
210 }
211
212 pub fn changes_from(&self, base: &Gates, measured: &BTreeSet<(String, String)>) -> Vec<String> {
227 let mut out = Vec::new();
228 if self.global != base.global {
229 out.push(code("[gate]"));
230 }
231 let follows = |g: &Gates, gate: Gate| gate == g.global;
232 let mut named = BTreeSet::new();
233 for bench in self.benches.keys().chain(base.benches.keys()) {
235 let of = |g: &Gates| g.benches.get(bench).copied().unwrap_or(g.global);
236 let (mine, theirs) = (of(self), of(base));
237 if mine != theirs && !(follows(self, mine) && follows(base, theirs)) {
238 named.insert(bench.clone());
239 }
240 }
241 let series = self
242 .series
243 .keys()
244 .chain(base.series.keys())
245 .chain(measured.iter());
246 for (bench, tool) in series {
247 let (mine, theirs) = (self.get(bench, tool), base.get(bench, tool));
248 if mine != theirs && !(follows(self, mine) && follows(base, theirs)) {
249 named.insert(name(bench, tool));
250 }
251 }
252 out.extend(named.iter().map(|n| code(n)));
253 out
254 }
255}
256
257#[derive(Debug, Default, PartialEq)]
258pub struct Comparison {
259 pub changes: Vec<Change>,
261 pub added: Vec<Key>,
265 pub removed: Vec<Key>,
269 pub accepted: Acceptances,
276 pub ignored_trailers: Acceptances,
279 pub gate_source: Option<String>,
284 pub allowed_empty: bool,
288}
289
290impl Comparison {
291 pub fn regressions(&self, gates: &Gates) -> Vec<&Change> {
293 self.changes
294 .iter()
295 .filter(|c| {
296 let gate = gates.of(c);
297 gate.enabled && c.exceeds(&gate)
298 })
299 .collect()
300 }
301
302 pub fn failures(&self, gates: &Gates) -> Vec<&Change> {
309 self.regressions(gates)
310 .into_iter()
311 .filter(|c| !self.accepted.covers(&c.bench))
312 .collect()
313 }
314
315 pub fn accepted_regressions(&self, gates: &Gates) -> Vec<&Change> {
317 self.regressions(gates)
318 .into_iter()
319 .filter(|c| self.accepted.covers(&c.bench))
320 .collect()
321 }
322
323 pub fn with_accepted(mut self, accepted: Acceptances) -> Self {
327 self.accepted = accepted;
328 self
329 }
330
331 pub fn with_ignored_trailers(mut self, ignored: Acceptances) -> Self {
334 self.ignored_trailers = ignored;
335 self
336 }
337
338 pub fn reported(&self, gates: &Gates) -> Vec<&Change> {
340 self.changes
341 .iter()
342 .filter(|c| {
343 let gate = gates.of(c);
344 !gate.enabled && c.exceeds(&gate)
345 })
346 .collect()
347 }
348
349 pub fn gated_uniformly(&self, gates: &Gates) -> bool {
356 self.changes
357 .iter()
358 .filter(|c| c.metric == GATED_METRIC)
359 .all(|c| gates.of(c) == gates.global)
360 }
361
362 pub fn is_empty(&self) -> bool {
364 self.changes.is_empty()
365 }
366}
367
368pub(crate) fn index(records: &[Record]) -> BTreeMap<(Key, String), f64> {
376 let mut out: BTreeMap<(Key, String), f64> = BTreeMap::new();
377 for r in records {
378 let key: Key = (r.bench.clone(), r.tool.clone(), r.runner.clone());
379 for (metric, value) in &r.metrics {
380 out.entry((key.clone(), metric.clone()))
381 .and_modify(|existing| {
382 if value < existing {
383 *existing = *value;
384 }
385 })
386 .or_insert(*value);
387 }
388 }
389 out
390}
391
392pub fn compare(base: &[Record], head: &[Record]) -> Comparison {
394 let (b, h) = (index(base), index(head));
395
396 let mut changes = Vec::new();
397 for ((key, metric), head_value) in &h {
398 if let Some(base_value) = b.get(&(key.clone(), metric.clone())) {
399 changes.push(Change {
400 bench: key.0.clone(),
401 tool: key.1.clone(),
402 runner: key.2.clone(),
403 metric: metric.clone(),
404 base: *base_value,
405 head: *head_value,
406 });
407 }
408 }
409
410 let base_keys: BTreeSet<Key> = b.keys().map(|(k, _)| k.clone()).collect();
411 let head_keys: BTreeSet<Key> = h.keys().map(|(k, _)| k.clone()).collect();
412
413 Comparison {
414 changes,
415 added: head_keys.difference(&base_keys).cloned().collect(),
416 removed: base_keys.difference(&head_keys).cloned().collect(),
417 accepted: Acceptances::default(),
418 ignored_trailers: Acceptances::default(),
419 gate_source: None,
420 allowed_empty: false,
421 }
422}
423
424pub type Trend = BTreeMap<Key, Vec<f64>>;
426
427pub fn build_trend(
437 walked: &[(String, Vec<Record>)],
438 head_sha: &str,
439 head_records: &[Record],
440) -> Trend {
441 let mut trend = Trend::new();
442 let mut head_in_history = false;
443 for (sha, records) in walked {
444 if sha == head_sha {
445 head_in_history = true;
446 add_point(&mut trend, head_records);
448 } else {
449 add_point(&mut trend, records);
450 }
451 }
452 if !head_in_history {
453 add_point(&mut trend, head_records);
454 }
455 trend
456}
457
458fn add_point(trend: &mut Trend, records: &[Record]) {
465 let mut lowest: BTreeMap<Key, f64> = BTreeMap::new();
466 for r in records {
467 if let Some(v) = r.metrics.get(GATED_METRIC) {
468 lowest
469 .entry((r.bench.clone(), r.tool.clone(), r.runner.clone()))
470 .and_modify(|e| {
471 if v < e {
472 *e = *v;
473 }
474 })
475 .or_insert(*v);
476 }
477 }
478 for (key, value) in lowest {
479 trend.entry(key).or_default().push(value);
480 }
481}
482
483const BARS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
485
486pub fn sparkline(values: &[f64]) -> String {
497 if values.len() < 2 {
498 return String::new();
499 }
500 let min = values.iter().copied().fold(f64::INFINITY, f64::min);
501 let max = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
502 if max <= min {
503 return BARS[BARS.len() / 2].to_string().repeat(values.len());
504 }
505 values
506 .iter()
507 .map(|v| {
508 let t = (v - min) / (max - min);
509 let i = (t * (BARS.len() - 1) as f64).round() as usize;
510 BARS[i.min(BARS.len() - 1)]
511 })
512 .collect()
513}
514
515pub(crate) fn thousands(v: f64) -> String {
517 let n = format!("{:.0}", v.abs());
518 let mut out = String::new();
519 for (i, c) in n.chars().enumerate() {
520 if i > 0 && (n.len() - i) % 3 == 0 {
521 out.push(',');
522 }
523 out.push(c);
524 }
525 if v < 0.0 { format!("-{out}") } else { out }
526}
527
528pub(crate) fn signed_pct(p: Option<f64>) -> String {
530 match p {
531 Some(p) => format!("{}{:.2}%", if p >= 0.0 { "+" } else { "" }, p),
532 None => "new".to_string(),
533 }
534}
535
536pub(crate) const CREDIT: &str = "\n<sub>Measured by [tak](https://github.com/jdx/tak) — instruction-counted \
549 CLI benchmarks, stored in this repository's git notes.</sub>\n";
550
551pub const ALLOWED_EMPTY: &str = "This passes with a warning instead of failing, because \
559 `allow_empty` is on. That is expected on a new runner class, for a new benchmark, or on \
560 a first recording. It is also what history that was never recorded or never fetched \
561 looks like, so check which this is.";
562
563pub fn markdown(c: &Comparison, trend: &Trend, gates: &Gates, credit: bool) -> String {
564 let mut out = String::new();
565
566 if c.is_empty() {
567 out.push_str(
571 "**Nothing was compared, and so nothing was gated.** No series \
572 appears on both sides: either the base has no measurements \
573 recorded, or the two were measured on different runner classes, \
574 which are deliberately not comparable — counts shift between \
575 machine types by more than a real regression does.\n",
576 );
577 if c.allowed_empty {
583 out.push_str(&format!("\n{ALLOWED_EMPTY}\n"));
584 }
585 } else {
586 out.push_str(&table(c, trend, gates));
587 out.push_str(&allocations(c));
588 out.push_str(&custom_table(c));
589 }
590
591 if let Some(line) = &c.gate_source {
592 out.push_str(&format!("\n{line}\n"));
593 }
594 out.push_str(&unused_acceptances(c, gates));
595 out.push_str(&ignored_trailers(c));
596 out.push_str(&outliers(c));
597 out.push_str(
598 "\n<sub>Only instruction counts gate. Wall clock is shown for context — \
599 on identical hardware it moves 4-20% run to run.</sub>\n",
600 );
601 if credit {
602 out.push_str(CREDIT);
603 }
604 out
605}
606
607fn row_name<'a>(key: &Key, keys: impl IntoIterator<Item = &'a Key>) -> String {
616 let (bench, tool, runner) = key;
617 let shared = keys
618 .into_iter()
619 .any(|(b, t, r)| b == bench && t == tool && r != runner);
620 let text = if shared {
621 format!("{} on {}", name(bench, tool), escape_control(runner))
622 } else {
623 name(bench, tool)
624 };
625 cell(&text)
626}
627
628fn name(bench: &str, tool: &str) -> String {
635 let bench = escape_control(bench);
636 if tool == SELF_TOOL {
637 bench.into_owned()
638 } else {
639 format!("{bench} ({})", escape_control(tool))
640 }
641}
642
643fn table(c: &Comparison, trend: &Trend, gates: &Gates) -> String {
645 let mut out = String::new();
646 let mut series: BTreeMap<Key, (Option<&Change>, Option<&Change>)> = BTreeMap::new();
649 for change in &c.changes {
650 let key = (
651 change.bench.clone(),
652 change.tool.clone(),
653 change.runner.clone(),
654 );
655 let slot = series.entry(key).or_insert((None, None));
656 match change.metric.as_str() {
657 GATED_METRIC => slot.0 = Some(change),
658 WALL_METRIC => slot.1 = Some(change),
659 _ => {}
660 }
661 }
662
663 let any_trend = series
664 .keys()
665 .any(|k| trend.get(k).is_some_and(|v| v.len() > 1));
666 let uniform = c.gated_uniformly(gates);
670
671 let mut header = vec![("benchmark", "---")];
672 if any_trend {
673 header.push(("trend", "---"));
674 }
675 header.extend([("instructions", "---:"), ("Δ", "---:")]);
676 if !uniform {
677 header.push(("gate", "---"));
678 }
679 header.extend([("wall (min)", "---:"), ("Δ", "---:")]);
680 let row = |cells: &[String]| format!("| {} |\n", cells.join(" | "));
681 out.push_str(&row(&header
682 .iter()
683 .map(|(h, _)| h.to_string())
684 .collect::<Vec<_>>()));
685 out.push_str(&format!(
686 "|{}|\n",
687 header.iter().map(|(_, a)| *a).collect::<Vec<_>>().join("|")
688 ));
689
690 for (key, (ins, wall)) in &series {
691 let (bench, tool, _runner) = key;
692 let gate = gates.get(bench, tool);
693 let mut cells = vec![row_name(key, series.keys())];
694 if any_trend {
695 cells.push(
696 trend
697 .get(key)
698 .map(|v| sparkline(v))
699 .filter(|s| !s.is_empty())
700 .map(|s| format!("`{s}`"))
701 .unwrap_or_else(|| "—".into()),
702 );
703 }
704 match ins {
705 Some(ch) => {
706 let flag = match (ch.exceeds(&gate), gate.enabled) {
712 (true, true) if c.accepted.covers(bench) => " (accepted)",
713 (true, true) => " ⚠️",
714 (true, false) => " (not gated)",
715 (false, _) => "",
716 };
717 cells.push(format!("{} → {}", thousands(ch.base), thousands(ch.head)));
718 cells.push(format!("**{}**{flag}", signed_pct(ch.pct())));
719 }
720 None => cells.extend(["—".into(), "—".into()]),
721 }
722 if !uniform {
723 cells.push(if ins.is_some() {
725 gate.describe()
726 } else {
727 "—".into()
728 });
729 }
730 match wall {
731 Some(ch) => {
732 cells.push(format!("{:.2} → {:.2}ms", ch.base, ch.head));
733 cells.push(signed_pct(ch.pct()));
734 }
735 None => cells.extend(["—".into(), "—".into()]),
736 }
737 out.push_str(&row(&cells));
738 }
739
740 out.push('\n');
741 out.push_str(&verdict(c, gates, uniform));
742 out
743}
744
745fn verdict(c: &Comparison, gates: &Gates, uniform: bool) -> String {
752 let mut out = String::new();
753 let global = gates.global;
754 let listed = |changes: &[&Change], annotate: bool| {
755 changes
756 .iter()
757 .map(|ch| {
758 let mut s = format!("`{}` {}", name(&ch.bench, &ch.tool), signed_pct(ch.pct()));
759 if annotate {
760 s.push_str(&format!(" (gate {})", gates.of(ch).threshold()));
761 }
762 s
763 })
764 .collect::<Vec<_>>()
765 .join(", ")
766 };
767
768 let regressions = c.regressions(gates);
769 let failures = c.failures(gates);
770 let accepted = c.accepted_regressions(gates);
771 if uniform {
772 let floor = if global.min_delta == 0 {
776 String::new()
777 } else {
778 format!(
779 " (rises of {} instructions or fewer are not counted)",
780 thousands(global.min_delta as f64)
781 )
782 };
783 if regressions.is_empty() {
784 out.push_str(&format!(
785 "No instruction-count regression above {}%{floor}.\n",
786 global.pct,
787 ));
788 } else if !failures.is_empty() {
789 out.push_str(&format!(
790 "**{} benchmark(s) above the {}% gate{floor}:** {}\n",
791 failures.len(),
792 global.pct,
793 listed(&failures, false)
794 ));
795 }
796 out.push_str(&accepted_line(
797 c,
798 &accepted,
799 &format!("the {}% gate", global.pct),
800 !failures.is_empty(),
801 |_| String::new(),
802 ));
803 return out;
804 }
805
806 let any_gated = c
807 .changes
808 .iter()
809 .any(|ch| ch.metric == GATED_METRIC && gates.of(ch).enabled);
810 if !any_gated {
811 out.push_str("Every benchmark here is report-only, so none can fail the gate.\n");
814 } else if regressions.is_empty() {
815 out.push_str("No gated benchmark rose beyond its gate.\n");
816 } else if !failures.is_empty() {
817 out.push_str(&format!(
818 "**{} benchmark(s) above their gate:** {}\n",
819 failures.len(),
820 listed(&failures, true)
821 ));
822 }
823 out.push_str(&accepted_line(
824 c,
825 &accepted,
826 "their gate",
827 !failures.is_empty(),
828 |ch| format!(" (gate {})", gates.of(ch).threshold()),
829 ));
830 let reported = c.reported(gates);
831 if !reported.is_empty() {
832 out.push_str(&format!(
833 "\n**{} report-only benchmark(s) above their gate, not failing:** {}\n",
834 reported.len(),
835 listed(&reported, true)
836 ));
837 }
838 out
839}
840
841fn allocations(c: &Comparison) -> String {
849 let mut series: BTreeMap<Key, BTreeMap<&str, &Change>> = BTreeMap::new();
850 for change in &c.changes {
851 if ALLOC_METRICS.iter().any(|(m, _)| *m == change.metric) {
852 series
853 .entry((
854 change.bench.clone(),
855 change.tool.clone(),
856 change.runner.clone(),
857 ))
858 .or_default()
859 .insert(change.metric.as_str(), change);
860 }
861 }
862 if series.is_empty() {
863 return String::new();
864 }
865 let mut out = String::from("\nHeap allocations, counted by DHAT; reported, not gated:\n\n");
866 out.push_str("| benchmark |");
867 for (_, title) in ALLOC_METRICS {
868 out.push_str(&format!(" {title} | Δ |"));
869 }
870 out.push_str("\n|---|");
871 out.push_str(&"---:|---:|".repeat(ALLOC_METRICS.len()));
872 out.push('\n');
873 for (key, metrics) in &series {
874 out.push_str(&format!("| {} |", row_name(key, series.keys())));
875 for (metric, _) in ALLOC_METRICS {
876 match metrics.get(metric) {
877 Some(ch) => out.push_str(&format!(
878 " {} → {} | {} |",
879 thousands(ch.base),
880 thousands(ch.head),
881 count_delta(ch)
882 )),
883 None => out.push_str(" — | — |"),
884 }
885 }
886 out.push('\n');
887 }
888 out
889}
890
891fn custom_table(c: &Comparison) -> String {
905 let rows: Vec<&Change> = c
906 .changes
907 .iter()
908 .filter(|ch| !is_builtin_metric(&ch.metric))
909 .collect();
910 if rows.is_empty() {
911 return String::new();
912 }
913 let mut out = String::from("\n| benchmark | metric | value | Δ |\n|---|---|---:|---:|\n");
914 for ch in rows {
919 out.push_str(&format!(
920 "| {} | {} | {} → {} | {} |\n",
921 cell(&name(&ch.bench, &ch.tool)),
922 cell(&escape_control(&ch.metric)),
923 plain(ch.base),
924 plain(ch.head),
925 signed_pct(ch.pct())
926 ));
927 }
928 out.push_str(
929 "\n<sub>Metrics declared in tak.toml are reported, never gated. As for every \
930 metric, lower is taken as better.</sub>\n",
931 );
932 out
933}
934
935fn plain(v: f64) -> String {
939 if v.fract() == 0.0 && v.abs() < 1e15 {
940 thousands(v)
941 } else {
942 v.to_string()
943 }
944}
945
946fn accepted_line(
957 c: &Comparison,
958 accepted: &[&Change],
959 which: &str,
960 after_failures: bool,
961 gate_of: impl Fn(&Change) -> String,
962) -> String {
963 if accepted.is_empty() {
964 return String::new();
965 }
966 format!(
967 "{}**{} accepted regression(s) above {which}, not failing it:** {}\n",
968 if after_failures { "\n" } else { "" },
969 accepted.len(),
970 accepted
971 .iter()
972 .map(|ch| format!(
973 "{} on {} {}{} ({})",
974 code(&name(&ch.bench, &ch.tool)),
975 code(&ch.runner),
976 signed_pct(ch.pct()),
977 gate_of(ch),
978 c.accepted.describe(&ch.bench)
979 ))
980 .collect::<Vec<_>>()
981 .join(", ")
982 )
983}
984
985pub(crate) fn code(text: &str) -> String {
1005 let text = escape_control(text);
1006 let text = text.as_ref();
1007 let mut longest = 0;
1008 let mut run = 0;
1009 for ch in text.chars() {
1010 run = if ch == '`' { run + 1 } else { 0 };
1011 longest = longest.max(run);
1012 }
1013 let fence = "`".repeat(longest + 1);
1014 let edge_space = text.starts_with(' ') || text.ends_with(' ');
1015 let only_spaces = text.chars().all(|c| c == ' ');
1016 if (longest > 0 || edge_space) && !only_spaces {
1017 format!("{fence} {text} {fence}")
1018 } else {
1019 format!("{fence}{text}{fence}")
1020 }
1021}
1022
1023pub(crate) fn cell(text: &str) -> String {
1033 text.replace('\\', "\\\\").replace('|', "\\|")
1034}
1035
1036pub(crate) fn code_cell(text: &str) -> String {
1047 text.replace('|', "\\|")
1048}
1049
1050pub fn gate_source(path: Option<&str>, at: &str, changed: &[String]) -> Option<String> {
1060 let later = (!changed.is_empty()).then(|| {
1061 format!(
1062 " This revision changes the gate policy ({}), and the change takes effect \
1063 once it is merged.",
1064 changed.join(", ")
1065 )
1066 });
1067 match (path, later) {
1068 (None, later) => Some(format!(
1069 "No {} at the base, {}, so the gate is tak's defaults plus any flags and \
1070 environment variables.{}",
1071 code(crate::config::FILE_NAME),
1072 code(at),
1073 later.unwrap_or_default()
1074 )),
1075 (Some(path), Some(later)) => Some(format!(
1076 "The gate comes from {} at the base, {}.{later}",
1077 code(path),
1078 code(at)
1079 )),
1080 (Some(_), None) => None,
1081 }
1082}
1083
1084fn ignored_trailers(c: &Comparison) -> String {
1087 if c.ignored_trailers.is_empty() {
1088 return String::new();
1089 }
1090 format!(
1091 "\n`{}` trailers were found but not honoured, because `gate.accept_trailers` is \
1092 off: {}\n",
1093 crate::accept::TRAILER,
1094 c.ignored_trailers
1095 .iter()
1096 .map(|(bench, _)| format!("{} ({})", code(bench), c.ignored_trailers.describe(bench)))
1097 .collect::<Vec<_>>()
1098 .join(", ")
1099 )
1100}
1101
1102fn unused_acceptances(c: &Comparison, gates: &Gates) -> String {
1111 let mut quiet = Vec::new();
1112 let mut report_only = Vec::new();
1113 let mut unknown = Vec::new();
1114 for (bench, _) in c.accepted.iter() {
1115 let entry = format!("{} ({})", code(bench), c.accepted.describe(bench));
1116 let counted: Vec<&Change> = c
1117 .changes
1118 .iter()
1119 .filter(|ch| ch.bench == bench && ch.metric == GATED_METRIC)
1120 .collect();
1121 if !c.changes.iter().any(|ch| ch.bench == bench) {
1122 unknown.push(entry);
1123 } else if counted.iter().any(|ch| {
1124 let gate = gates.of(ch);
1125 gate.enabled && ch.exceeds(&gate)
1126 }) {
1127 } else if !counted.is_empty() && counted.iter().all(|ch| !gates.of(ch).enabled) {
1129 report_only.push(entry);
1130 } else {
1131 quiet.push(entry);
1132 }
1133 }
1134 let mut out = String::new();
1135 if !quiet.is_empty() {
1136 out.push_str(&format!(
1137 "\nAccepted, but not above its gate, so nothing was accepted: {}\n",
1138 quiet.join(", ")
1139 ));
1140 }
1141 if !report_only.is_empty() {
1142 out.push_str(&format!(
1143 "\nAccepted, but report-only, so it can never fail and nothing was accepted: {}\n",
1144 report_only.join(", ")
1145 ));
1146 }
1147 if !unknown.is_empty() {
1148 out.push_str(&format!(
1149 "\nAccepted, but no benchmark by that name was compared on both sides: {}\n",
1150 unknown.join(", ")
1151 ));
1152 }
1153 out
1154}
1155
1156fn count_delta(ch: &Change) -> String {
1165 match ch.pct() {
1166 Some(p) => signed_pct(Some(p)),
1167 None if ch.head == ch.base => signed_pct(Some(0.0)),
1168 None => format!("+{} (from 0)", thousands(ch.head - ch.base)),
1169 }
1170}
1171
1172pub fn escape_control(text: &str) -> std::borrow::Cow<'_, str> {
1179 if !text.chars().any(char::is_control) {
1180 return std::borrow::Cow::Borrowed(text);
1181 }
1182 text.chars()
1183 .map(|c| {
1184 if c.is_control() {
1185 c.escape_default().to_string()
1186 } else {
1187 c.to_string()
1188 }
1189 })
1190 .collect::<String>()
1191 .into()
1192}
1193
1194pub fn describe(key: &Key) -> String {
1204 let (bench, tool, runner) = key;
1205 let (bench, tool, runner) = (
1206 escape_control(bench),
1207 escape_control(tool),
1208 escape_control(runner),
1209 );
1210 if tool == "self" {
1211 format!("`{bench}` on `{runner}`")
1212 } else {
1213 format!("`{bench}` ({tool}) on `{runner}`")
1214 }
1215}
1216
1217fn outliers(c: &Comparison) -> String {
1220 let mut out = String::new();
1221 if !c.added.is_empty() {
1222 out.push_str(&format!(
1223 "\nNew, nothing to compare against: {}\n",
1224 c.added.iter().map(describe).collect::<Vec<_>>().join(", ")
1225 ));
1226 }
1227 if !c.removed.is_empty() {
1228 out.push_str(&format!(
1229 "\nMeasured on the base but not here — a benchmark that stops \
1230 running also stops gating: {}\n",
1231 c.removed
1232 .iter()
1233 .map(describe)
1234 .collect::<Vec<_>>()
1235 .join(", ")
1236 ));
1237 }
1238 out
1239}
1240
1241#[cfg(test)]
1242mod tests {
1243 use super::*;
1244 use crate::accept::Source;
1245
1246 fn key(bench: &str) -> Key {
1247 (bench.to_string(), "self".to_string(), "gha".to_string())
1248 }
1249
1250 fn rec(bench: &str, runner: &str, ins: f64, wall: f64) -> Record {
1251 Record {
1252 v: 1,
1253 bench: bench.into(),
1254 tool: "self".into(),
1255 version: None,
1256 runner: runner.into(),
1257 ts: "2026-01-01T00:00:00Z".into(),
1258 metrics: BTreeMap::from([
1259 (GATED_METRIC.to_string(), ins),
1260 (WALL_METRIC.to_string(), wall),
1261 ]),
1262 }
1263 }
1264
1265 fn g(pct: f64) -> Gates {
1267 Gates::uniform(Gate::new(pct, 0).unwrap())
1268 }
1269
1270 fn gate(pct: f64, min_delta: u64, enabled: bool) -> Gate {
1271 Gate {
1272 pct,
1273 min_delta,
1274 enabled,
1275 }
1276 }
1277
1278 #[test]
1282 fn a_gate_source_path_with_a_backtick_stays_one_code_span() {
1283 let changed = [code("[gate]")];
1284 let line = gate_source(Some("we`ird/tak.toml"), "a1b2c3d4e5f6", &changed).unwrap();
1285 assert_eq!(
1286 line,
1287 "The gate comes from `` we`ird/tak.toml `` at the base, `a1b2c3d4e5f6`. \
1288 This revision changes the gate policy (`[gate]`), and the change takes \
1289 effect once it is merged."
1290 );
1291 let line = gate_source(Some("a\nb/tak.toml"), "a1b2c3d4e5f6", &changed).unwrap();
1292 assert!(!line.contains('\n'), "{line}");
1293 assert_eq!(gate_source(Some("tak.toml"), "a1b2c3d4e5f6", &[]), None);
1294 assert_eq!(
1295 gate_source(None, "a1b2c3d4e5f6", &[]).unwrap(),
1296 "No `tak.toml` at the base, `a1b2c3d4e5f6`, so the gate is tak's defaults \
1297 plus any flags and environment variables."
1298 );
1299 }
1300
1301 #[test]
1302 fn gate_changes_are_effective_and_escaped() {
1303 let global = gate(1.0, 0, true);
1304 let base = Gates::uniform(global);
1305 let mut head = Gates::uniform(global);
1306 head.set_bench("new", global);
1307 head.set_series("new", SELF_TOOL, global);
1308 assert!(head.changes_from(&base, &BTreeSet::new()).is_empty());
1309
1310 let evil = "a\n**0 benchmark(s) above the 1% gate:**".to_string();
1311 head.set_series(&evil, SELF_TOOL, gate(1.0, 0, false));
1312 let measured = BTreeSet::from([(evil, SELF_TOOL.to_string())]);
1313 let changes = head.changes_from(&base, &measured);
1314 assert_eq!(changes.len(), 1, "{changes:?}");
1315 assert!(!changes[0].contains('\n'), "{changes:?}");
1316 assert!(changes[0].starts_with('`'), "{changes:?}");
1317 }
1318
1319 fn startup_and_install() -> Comparison {
1322 compare(
1323 &[
1324 rec("startup", "gha", 450_000.0, 1.0),
1325 rec("install", "gha", 100_000_000.0, 100.0),
1326 ],
1327 &[
1328 rec("startup", "gha", 459_000.0, 1.0),
1329 rec("install", "gha", 102_000_000.0, 100.0),
1330 ],
1331 )
1332 }
1333
1334 fn benches(c: &[&Change]) -> Vec<String> {
1335 c.iter().map(|c| c.bench.clone()).collect()
1336 }
1337
1338 #[test]
1341 fn a_regression_crosses_both_the_percentage_and_the_floor() {
1342 let rise = Change {
1343 bench: "a".into(),
1344 tool: SELF_TOOL.into(),
1345 runner: "gha".into(),
1346 metric: GATED_METRIC.into(),
1347 base: 1_000_000.0,
1348 head: 1_020_000.0,
1349 };
1350 let cases = [
1351 (1.0, 0, true), (5.0, 0, false), (1.0, 10_000, true), (1.0, 20_000, false), (1.0, 50_000, false), (5.0, 10_000, false), (2.0, 0, false), (0.0, 0, true), ];
1361 for (pct, min_delta, want) in cases {
1362 assert_eq!(
1363 rise.exceeds(&gate(pct, min_delta, true)),
1364 want,
1365 "pct {pct}, min_delta {min_delta}"
1366 );
1367 assert_eq!(rise.exceeds(&gate(pct, min_delta, false)), want);
1369 }
1370
1371 let fall = Change {
1372 head: 500_000.0,
1373 ..rise.clone()
1374 };
1375 assert!(
1376 !fall.exceeds(&gate(0.0, 0, true)),
1377 "an improvement never gates"
1378 );
1379 let wall = Change {
1380 metric: WALL_METRIC.into(),
1381 ..rise
1382 };
1383 assert!(!wall.exceeds(&gate(0.0, 0, true)), "wall clock never gates");
1384 }
1385
1386 #[test]
1389 fn a_zero_base_is_still_held_to_the_floor() {
1390 let c = compare(
1391 &[rec("a", "gha", 0.0, 1.0)],
1392 &[rec("a", "gha", 5_000.0, 1.0)],
1393 );
1394 assert_eq!(c.regressions(&g(1.0)).len(), 1);
1395 let floored = Gates::uniform(Gate::new(1.0, 10_000).unwrap());
1396 assert!(c.regressions(&floored).is_empty());
1397 }
1398
1399 #[test]
1402 fn a_gate_percentage_must_be_finite_and_not_negative() {
1403 assert!(Gate::new(0.0, 0).is_ok());
1404 assert!(Gate::new(250.0, 0).is_ok());
1405 for bad in [-1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
1406 let err = Gate::new(bad, 0).unwrap_err();
1407 assert!(format!("{err}").contains("gate percentage"), "{err}");
1408 }
1409 }
1410
1411 #[test]
1412 fn a_series_gate_beats_its_benchmarks_which_beats_the_global_one() {
1413 let mut gates = g(1.0);
1414 gates.set_bench("install", gate(5.0, 0, true));
1415 gates.set_series("install", "pnpm", gate(10.0, 0, false));
1416 assert_eq!(gates.get("install", "pnpm"), gate(10.0, 0, false));
1417 assert_eq!(
1418 gates.get("install", "npm"),
1419 gate(5.0, 0, true),
1420 "a subject the benchmark no longer declares gets the benchmark's"
1421 );
1422 assert_eq!(
1423 gates.get("gone", SELF_TOOL),
1424 gate(1.0, 0, true),
1425 "a benchmark no longer in tak.toml gets the global gate"
1426 );
1427 }
1428
1429 #[test]
1432 fn a_per_benchmark_gate_decides_its_own_series_only() {
1433 let c = startup_and_install();
1434 assert_eq!(benches(&c.regressions(&g(1.0))), ["install", "startup"]);
1435
1436 let mut gates = g(1.0);
1437 gates.set_series("startup", SELF_TOOL, gate(5.0, 0, true));
1438 assert_eq!(benches(&c.regressions(&gates)), ["install"]);
1439
1440 let mut gates = g(5.0);
1442 gates.set_series("install", SELF_TOOL, gate(1.0, 0, true));
1443 assert_eq!(benches(&c.regressions(&gates)), ["install"]);
1444 }
1445
1446 #[test]
1449 fn subjects_of_one_benchmark_take_their_own_gates() {
1450 let with_tool = |tool: &str, ins: f64| Record {
1451 tool: tool.into(),
1452 ..rec("install", "gha", ins, 1.0)
1453 };
1454 let c = compare(
1455 &[
1456 with_tool("mine", 1_000_000.0),
1457 with_tool("theirs", 1_000_000.0),
1458 ],
1459 &[
1460 with_tool("mine", 1_100_000.0),
1461 with_tool("theirs", 1_100_000.0),
1462 ],
1463 );
1464 let mut gates = g(1.0);
1465 gates.set_series("install", "theirs", gate(1.0, 0, false));
1466 let tools = |v: Vec<&Change>| v.iter().map(|c| c.tool.clone()).collect::<Vec<_>>();
1467 assert_eq!(tools(c.regressions(&gates)), ["mine"]);
1468 assert_eq!(tools(c.reported(&gates)), ["theirs"]);
1469 }
1470
1471 #[test]
1474 fn a_report_only_series_is_flagged_and_never_fails() {
1475 let c = startup_and_install();
1476 let mut gates = g(1.0);
1477 gates.set_series("startup", SELF_TOOL, gate(1.0, 0, false));
1478 assert_eq!(benches(&c.regressions(&gates)), ["install"]);
1479 assert_eq!(benches(&c.reported(&gates)), ["startup"]);
1480
1481 let md = markdown(&c, &Trend::new(), &gates, false);
1482 assert!(md.contains("| gate |"), "{md}");
1483 assert!(md.contains("report only (1%)"), "{md}");
1484 assert!(md.contains("**+2.00%** (not gated)"), "{md}");
1485 assert!(
1486 md.contains("**1 benchmark(s) above their gate:** `install` +2.00% (gate 1%)"),
1487 "{md}"
1488 );
1489 assert!(
1490 md.contains(
1491 "**1 report-only benchmark(s) above their gate, not failing:** \
1492 `startup` +2.00% (gate 1%)"
1493 ),
1494 "{md}"
1495 );
1496 }
1497
1498 #[test]
1501 fn uniform_gates_render_the_report_unchanged() {
1502 let md = markdown(&startup_and_install(), &Trend::new(), &g(1.0), false);
1503 assert_eq!(
1504 md,
1505 "| benchmark | instructions | Δ | wall (min) | Δ |\n\
1506 |---|---:|---:|---:|---:|\n\
1507 | install | 100,000,000 → 102,000,000 | **+2.00%** ⚠️ | 100.00 → 100.00ms | +0.00% |\n\
1508 | startup | 450,000 → 459,000 | **+2.00%** ⚠️ | 1.00 → 1.00ms | +0.00% |\n\
1509 \n\
1510 **2 benchmark(s) above the 1% gate:** `install` +2.00%, `startup` +2.00%\n\
1511 \n\
1512 <sub>Only instruction counts gate. Wall clock is shown for context — \
1513 on identical hardware it moves 4-20% run to run.</sub>\n"
1514 );
1515
1516 let mut same = g(1.0);
1518 same.set_series("startup", SELF_TOOL, gate(1.0, 0, true));
1519 assert_eq!(
1520 markdown(&startup_and_install(), &Trend::new(), &same, false),
1521 md
1522 );
1523 }
1524
1525 #[test]
1526 fn a_differing_gate_adds_a_column_with_every_rows_gate() {
1527 let mut gates = g(1.0);
1528 gates.set_series("startup", SELF_TOOL, gate(5.0, 20_000, true));
1529 let md = markdown(&startup_and_install(), &Trend::new(), &gates, false);
1530 assert!(
1531 md.contains("| benchmark | instructions | Δ | gate | wall (min) | Δ |\n|---|---:|---:|---|---:|---:|\n"),
1532 "{md}"
1533 );
1534 assert!(md.contains("| **+2.00%** | 5%, floor 20,000 |"), "{md}");
1535 assert!(md.contains("| **+2.00%** ⚠️ | 1% |"), "{md}");
1536 assert!(
1537 md.contains("above their gate:** `install` +2.00% (gate 1%)\n"),
1538 "{md}"
1539 );
1540 }
1541
1542 #[test]
1543 fn nothing_over_any_gate_says_so() {
1544 let mut gates = g(5.0);
1545 gates.set_series("startup", SELF_TOOL, gate(10.0, 0, true));
1546 let md = markdown(&startup_and_install(), &Trend::new(), &gates, false);
1547 assert!(
1548 md.contains("No gated benchmark rose beyond its gate."),
1549 "{md}"
1550 );
1551 assert!(!md.contains("report-only"), "{md}");
1552 }
1553
1554 #[test]
1556 fn a_table_with_nothing_gated_says_so() {
1557 let mut gates = g(1.0);
1558 gates.set_series("startup", SELF_TOOL, gate(1.0, 0, false));
1559 gates.set_series("install", SELF_TOOL, gate(50.0, 0, false));
1560 let md = markdown(&startup_and_install(), &Trend::new(), &gates, false);
1561 assert!(
1562 md.contains("Every benchmark here is report-only, so none can fail the gate."),
1563 "{md}"
1564 );
1565 assert!(!md.contains("No gated benchmark"), "{md}");
1566 assert!(
1567 md.contains("**1 report-only benchmark(s) above their gate, not failing:** `startup`"),
1568 "{md}"
1569 );
1570 }
1571
1572 #[test]
1575 fn a_global_floor_is_named_in_the_verdict() {
1576 let gates = Gates::uniform(Gate::new(1.0, 20_000).unwrap());
1577 let md = markdown(&startup_and_install(), &Trend::new(), &gates, false);
1578 assert!(
1579 !md.contains("| gate |"),
1580 "the global gate needs no column: {md}"
1581 );
1582 assert!(
1583 md.contains(
1584 "**1 benchmark(s) above the 1% gate \
1585 (rises of 20,000 instructions or fewer are not counted):** `install` +2.00%"
1586 ),
1587 "{md}"
1588 );
1589 let c = compare(
1590 &[rec("a", "gha", 1_000.0, 1.0)],
1591 &[rec("a", "gha", 1_500.0, 1.0)],
1592 );
1593 let md = markdown(&c, &Trend::new(), &gates, false);
1594 assert!(
1595 md.contains(
1596 "No instruction-count regression above 1% \
1597 (rises of 20,000 instructions or fewer are not counted)."
1598 ),
1599 "{md}"
1600 );
1601 }
1602
1603 #[test]
1604 fn a_rise_beyond_the_gate_is_a_regression() {
1605 let c = compare(
1606 &[rec("a", "gha", 1_000_000.0, 10.0)],
1607 &[rec("a", "gha", 1_020_000.0, 10.0)],
1608 );
1609 assert_eq!(c.regressions(&g(1.0)).len(), 1, "2% should trip a 1% gate");
1610 assert!(c.regressions(&g(5.0)).is_empty(), "2% should not trip 5%");
1611 }
1612
1613 #[test]
1614 fn an_improvement_never_gates() {
1615 let c = compare(
1616 &[rec("a", "gha", 1_000_000.0, 10.0)],
1617 &[rec("a", "gha", 500_000.0, 10.0)],
1618 );
1619 assert!(c.regressions(&g(1.0)).is_empty());
1620 let ins = c.changes.iter().find(|c| c.metric == GATED_METRIC).unwrap();
1621 assert_eq!(ins.pct().unwrap().round(), -50.0);
1622 }
1623
1624 #[test]
1627 fn wall_clock_never_gates_however_bad_it_looks() {
1628 let c = compare(
1629 &[rec("a", "gha", 1_000_000.0, 10.0)],
1630 &[rec("a", "gha", 1_000_000.0, 100.0)],
1631 );
1632 assert!(c.regressions(&g(0.001)).is_empty());
1633 let wall = c.changes.iter().find(|c| c.metric == WALL_METRIC).unwrap();
1634 assert_eq!(wall.pct().unwrap().round(), 900.0);
1635 }
1636
1637 #[test]
1640 fn a_different_runner_is_not_a_comparison() {
1641 let c = compare(
1642 &[rec("a", "gha-linux", 1_000_000.0, 10.0)],
1643 &[rec("a", "gha-macos", 2_000_000.0, 10.0)],
1644 );
1645 assert!(c.is_empty(), "nothing should line up");
1646 assert_eq!(c.added.len(), 1);
1647 assert_eq!(c.removed.len(), 1);
1648 assert!(c.regressions(&g(1.0)).is_empty());
1649
1650 let md = markdown(&c, &Trend::new(), &g(1.0), false);
1653 assert!(md.contains("nothing was gated"), "{md}");
1654 assert!(md.contains("gha-macos"), "the new runner is unnamed: {md}");
1655 assert!(md.contains("gha-linux"), "the old runner is unnamed: {md}");
1656 }
1657
1658 #[test]
1663 fn allowing_an_empty_comparison_keeps_the_first_line() {
1664 const FIRST: &str = "**Nothing was compared, and so nothing was gated.** No series \
1665 appears on both sides: either the base has no measurements recorded, or the two \
1666 were measured on different runner classes, which are deliberately not \
1667 comparable — counts shift between machine types by more than a real regression \
1668 does.";
1669 let mut c = compare(
1670 &[rec("a", "gha-old", 1e6, 1.0)],
1671 &[rec("a", "gha-new", 1e6, 1.0)],
1672 );
1673 let refused = markdown(&c, &Trend::new(), &g(1.0), false);
1674 assert_eq!(refused.lines().next(), Some(FIRST), "{refused}");
1675 assert!(!refused.contains(ALLOWED_EMPTY), "{refused}");
1676
1677 c.allowed_empty = true;
1678 let allowed = markdown(&c, &Trend::new(), &g(1.0), false);
1679 assert_eq!(allowed.lines().next(), Some(FIRST), "{allowed}");
1680 assert_eq!(allowed.lines().nth(2), Some(ALLOWED_EMPTY), "{allowed}");
1682 assert!(ALLOWED_EMPTY.contains("`allow_empty`"));
1683 assert!(
1685 allowed.contains("gha-new") && allowed.contains("gha-old"),
1686 "{allowed}"
1687 );
1688 }
1689
1690 #[test]
1694 fn a_head_with_no_measurements_names_what_vanished() {
1695 let c = compare(
1696 &[
1697 rec("a", "gha", 1_000_000.0, 10.0),
1698 rec("b", "gha", 2.0, 2.0),
1699 ],
1700 &[],
1701 );
1702 let md = markdown(&c, &Trend::new(), &g(1.0), false);
1703 assert!(c.regressions(&g(1.0)).is_empty());
1704 assert!(md.contains("nothing was gated"), "{md}");
1705 assert!(md.contains("`a`") && md.contains("`b`"), "{md}");
1706 assert!(md.contains("stops gating"), "{md}");
1707 }
1708
1709 #[test]
1712 fn the_gating_caveat_survives_an_empty_comparison() {
1713 let md = markdown(&compare(&[], &[]), &Trend::new(), &g(1.0), false);
1714 assert!(md.contains("Only instruction counts gate"), "{md}");
1715 }
1716
1717 #[test]
1718 fn a_new_benchmark_is_reported_but_not_gated() {
1719 let c = compare(
1720 &[rec("a", "gha", 1_000_000.0, 10.0)],
1721 &[
1722 rec("a", "gha", 1_000_000.0, 10.0),
1723 rec("b", "gha", 9.9e9, 10.0),
1724 ],
1725 );
1726 assert_eq!(
1727 c.added,
1728 vec![("b".to_string(), "self".to_string(), "gha".to_string())]
1729 );
1730 assert!(c.regressions(&g(1.0)).is_empty());
1731 }
1732
1733 #[test]
1736 fn a_vanished_benchmark_is_surfaced() {
1737 let c = compare(
1738 &[
1739 rec("a", "gha", 1_000_000.0, 10.0),
1740 rec("b", "gha", 1.0, 1.0),
1741 ],
1742 &[rec("a", "gha", 1_000_000.0, 10.0)],
1743 );
1744 assert_eq!(c.removed.len(), 1);
1745 assert!(markdown(&c, &Trend::new(), &g(1.0), false).contains("stops gating"));
1746 }
1747
1748 #[test]
1751 fn duplicate_records_reduce_to_the_minimum() {
1752 let c = compare(
1753 &[rec("a", "gha", 1_000_000.0, 10.0)],
1754 &[
1755 rec("a", "gha", 3_000_000.0, 30.0),
1756 rec("a", "gha", 1_000_000.0, 10.0),
1757 ],
1758 );
1759 assert!(
1760 c.regressions(&g(1.0)).is_empty(),
1761 "the clean sample should win"
1762 );
1763 }
1764
1765 #[test]
1766 fn nothing_in_common_says_so_rather_than_passing_quietly() {
1767 let c = compare(&[], &[rec("a", "gha", 1.0, 1.0)]);
1768 assert!(c.is_empty());
1769 assert!(markdown(&c, &Trend::new(), &g(1.0), false).contains("nothing was gated"));
1770 }
1771
1772 #[test]
1776 fn a_rise_from_a_zero_base_still_gates() {
1777 let c = compare(
1778 &[rec("a", "gha", 0.0, 10.0)],
1779 &[rec("a", "gha", 5_000_000.0, 10.0)],
1780 );
1781 let ins = c.changes.iter().find(|c| c.metric == GATED_METRIC).unwrap();
1782 assert_eq!(ins.pct(), None, "no percentage exists against zero");
1783 assert_eq!(
1784 c.regressions(&g(1.0)).len(),
1785 1,
1786 "it must still fail the gate"
1787 );
1788 assert!(markdown(&c, &Trend::new(), &g(1.0), false).contains("new"));
1789 }
1790
1791 #[test]
1793 fn zero_to_zero_is_not_a_regression() {
1794 let c = compare(&[rec("a", "gha", 0.0, 1.0)], &[rec("a", "gha", 0.0, 1.0)]);
1795 assert!(c.regressions(&g(1.0)).is_empty());
1796 }
1797
1798 #[test]
1802 fn outliers_keep_their_tool() {
1803 let mut pnpm = rec("install", "gha", 1.0, 1.0);
1804 pnpm.tool = "pnpm".into();
1805 let c = compare(&[], &[rec("install", "gha", 1.0, 1.0), pnpm]);
1806 let md = markdown(&c, &Trend::new(), &g(1.0), false);
1807 assert!(md.contains("`install` on `gha`"), "{md}");
1808 assert!(md.contains("`install` (pnpm) on `gha`"), "{md}");
1809 }
1810
1811 #[test]
1814 fn a_branch_head_is_appended_last() {
1815 let walked = vec![
1816 ("c1".to_string(), vec![rec("a", "gha", 10.0, 1.0)]),
1817 ("c2".to_string(), vec![rec("a", "gha", 20.0, 1.0)]),
1818 ];
1819 let t = build_trend(&walked, "branch", &[rec("a", "gha", 30.0, 1.0)]);
1820 assert_eq!(t[&key("a")], vec![10.0, 20.0, 30.0]);
1821 }
1822
1823 #[test]
1827 fn a_head_inside_history_stays_in_its_place() {
1828 let walked = vec![
1829 ("c1".to_string(), vec![rec("a", "gha", 10.0, 1.0)]),
1830 ("head".to_string(), vec![rec("a", "gha", 20.0, 1.0)]),
1831 ("c3".to_string(), vec![rec("a", "gha", 30.0, 1.0)]),
1832 ];
1833 let t = build_trend(&walked, "head", &[rec("a", "gha", 99.0, 1.0)]);
1834 assert_eq!(
1835 t[&key("a")],
1836 vec![10.0, 99.0, 30.0],
1837 "the head's own measurement belongs where the head is, once"
1838 );
1839 }
1840
1841 #[test]
1844 fn a_commit_contributes_one_point() {
1845 let walked = vec![(
1846 "c1".to_string(),
1847 vec![rec("a", "gha", 50.0, 1.0), rec("a", "gha", 10.0, 1.0)],
1848 )];
1849 let t = build_trend(&walked, "branch", &[]);
1850 assert_eq!(t[&key("a")], vec![10.0]);
1851 }
1852
1853 #[test]
1854 fn a_sparkline_spans_the_full_range() {
1855 let s = sparkline(&[1.0, 2.0, 3.0, 4.0, 5.0]);
1856 assert_eq!(s.chars().count(), 5);
1857 assert_eq!(s.chars().next().unwrap(), '▁');
1858 assert_eq!(s.chars().last().unwrap(), '█');
1859 }
1860
1861 #[test]
1864 fn a_flat_series_sits_mid_height() {
1865 let s = sparkline(&[7.0, 7.0, 7.0]);
1866 assert_eq!(s, "▅▅▅");
1867 }
1868
1869 #[test]
1872 fn one_point_draws_nothing() {
1873 assert_eq!(sparkline(&[1.0]), "");
1874 assert_eq!(sparkline(&[]), "");
1875 }
1876
1877 #[test]
1880 fn series_are_scaled_independently() {
1881 let small = sparkline(&[7_000_000.0, 7_100_000.0]);
1882 let large = sparkline(&[100_000_000.0, 101_000_000.0]);
1883 assert_eq!(small, large, "both rise by the same shape");
1884 }
1885
1886 #[test]
1887 fn the_trend_column_appears_only_when_there_is_a_trend() {
1888 let c = compare(
1889 &[rec("a", "gha", 1_000_000.0, 10.0)],
1890 &[rec("a", "gha", 1_000_000.0, 10.0)],
1891 );
1892 assert!(!markdown(&c, &Trend::new(), &g(1.0), false).contains("| trend |"));
1893
1894 let mut trend = Trend::new();
1895 trend.insert(
1896 ("a".into(), "self".into(), "gha".into()),
1897 vec![1.0, 2.0, 3.0],
1898 );
1899 let md = markdown(&c, &trend, &g(1.0), false);
1900 assert!(md.contains("| trend |"), "{md}");
1901 assert!(md.contains('█'), "{md}");
1902 }
1903
1904 fn with_allocs(mut r: Record, blocks: f64, bytes: f64, peak: f64) -> Record {
1905 r.metrics.insert("alloc_blocks".into(), blocks);
1906 r.metrics.insert("alloc_bytes".into(), bytes);
1907 r.metrics.insert("alloc_peak_bytes".into(), peak);
1908 r
1909 }
1910
1911 #[test]
1914 fn the_allocation_table_appears_only_when_both_sides_have_allocations() {
1915 let plain = compare(
1916 &[rec("a", "gha", 1_000_000.0, 10.0)],
1917 &[rec("a", "gha", 1_000_000.0, 10.0)],
1918 );
1919 let md = markdown(&plain, &Trend::new(), &g(1.0), false);
1920 assert!(!md.contains("Heap allocations"), "{md}");
1921 assert!(md.contains("| benchmark | instructions | Δ | wall (min) | Δ |"));
1922
1923 let first = compare(
1925 &[rec("a", "gha", 1_000_000.0, 10.0)],
1926 &[with_allocs(
1927 rec("a", "gha", 1_000_000.0, 10.0),
1928 3.0,
1929 4140.0,
1930 4140.0,
1931 )],
1932 );
1933 assert!(!markdown(&first, &Trend::new(), &g(1.0), false).contains("Heap allocations"));
1934 }
1935
1936 #[test]
1939 fn allocations_are_reported_and_never_gate() {
1940 let c = compare(
1941 &[with_allocs(
1942 rec("a", "gha", 1_000_000.0, 10.0),
1943 31.0,
1944 7_119.0,
1945 6_847.0,
1946 )],
1947 &[with_allocs(
1948 rec("a", "gha", 1_000_000.0, 10.0),
1949 62.0,
1950 14_238.0,
1951 6_847.0,
1952 )],
1953 );
1954 assert!(c.regressions(&g(0.001)).is_empty());
1955 let md = markdown(&c, &Trend::new(), &g(1.0), false);
1956 assert!(md.contains("reported, not gated"), "{md}");
1957 assert!(
1958 md.contains(
1959 "| a | 31 → 62 | +100.00% | 7,119 → 14,238 | +100.00% | 6,847 → 6,847 | +0.00% |"
1960 ),
1961 "{md}"
1962 );
1963 assert!(md.contains("No instruction-count regression"), "{md}");
1964 }
1965
1966 #[test]
1969 fn rows_name_their_runner_only_when_another_shares_the_series() {
1970 let on = |runner| with_allocs(rec("a", runner, 1_000_000.0, 10.0), 3.0, 30.0, 20.0);
1971 let both = [on("linux-x64"), on("linux-arm64")];
1972 let md = markdown(&compare(&both, &both), &Trend::new(), &g(1.0), false);
1973 for runner in ["linux-x64", "linux-arm64"] {
1974 let rows = md
1975 .lines()
1976 .filter(|l| l.starts_with(&format!("| a on {runner} |")))
1977 .count();
1978 assert_eq!(
1979 rows, 2,
1980 "instructions and allocations rows for {runner}: {md}"
1981 );
1982 }
1983
1984 let one = [on("linux-x64")];
1985 let md = markdown(&compare(&one, &one), &Trend::new(), &g(1.0), false);
1986 assert!(
1987 md.contains("| a |") && !md.contains(" on linux-x64 |"),
1988 "{md}"
1989 );
1990 }
1991
1992 #[test]
1995 fn custom_metrics_are_a_separate_table_and_never_gate() {
1996 let with = |bytes: f64, kb: f64| {
1997 let mut r = rec("a", "gha", 1_000_000.0, 10.0);
1998 r.metrics.insert("binary_bytes".into(), bytes);
1999 r.metrics.insert("bundle_kb".into(), kb);
2000 r
2001 };
2002 let c = compare(&[with(4_000_000.0, 10.5)], &[with(8_000_000.0, 12.25)]);
2003 assert!(
2004 c.regressions(&g(0.0)).is_empty(),
2005 "a doubled binary must not fail the gate"
2006 );
2007 let md = markdown(&c, &Trend::new(), &g(1.0), false);
2008 assert!(md.contains("| benchmark | metric | value | Δ |"), "{md}");
2009 assert!(
2010 md.contains("| a | binary_bytes | 4,000,000 → 8,000,000 | +100.00% |"),
2011 "{md}"
2012 );
2013 assert!(
2014 md.contains("| a | bundle_kb | 10.5 → 12.25 | +16.67% |"),
2015 "{md}"
2016 );
2017 assert!(md.contains("No instruction-count regression"), "{md}");
2018 assert!(md.contains("never gated"), "{md}");
2019
2020 let plain = compare(
2021 &[rec("a", "gha", 1_000_000.0, 10.0)],
2022 &[rec("a", "gha", 1_000_000.0, 10.0)],
2023 );
2024 let md = markdown(&plain, &Trend::new(), &g(1.0), false);
2025 assert!(!md.contains("| metric |"), "{md}");
2026 assert!(!md.contains("tak.toml"), "{md}");
2027 let header = |md: &str| md.lines().next().unwrap().to_string();
2029 assert_eq!(
2030 header(&markdown(&c, &Trend::new(), &g(1.0), false)),
2031 header(&md)
2032 );
2033 }
2034
2035 #[test]
2038 fn built_in_metrics_stay_out_of_the_custom_table() {
2039 let with = |p50: f64| {
2040 let mut r = rec("a", "gha", 1_000_000.0, 10.0);
2041 r.metrics.insert("wall_p50_ms".into(), p50);
2042 r
2043 };
2044 let md = markdown(
2045 &compare(&[with(11.0)], &[with(12.0)]),
2046 &Trend::new(),
2047 &g(1.0),
2048 false,
2049 );
2050 assert!(!md.contains("wall_p50_ms"), "{md}");
2051 }
2052
2053 #[test]
2057 fn allocations_and_custom_metrics_each_get_their_own_table() {
2058 let with = |blocks: f64, bytes: f64| {
2059 let mut r = with_allocs(rec("a", "gha", 1_000_000.0, 10.0), blocks, 80.0, 40.0);
2060 r.metrics.insert("binary_bytes".into(), bytes);
2061 r
2062 };
2063 let c = compare(&[with(10.0, 100.0)], &[with(20.0, 200.0)]);
2064 let md = markdown(&c, &Trend::new(), &g(1.0), false);
2065 assert!(md.contains("Heap allocations"), "{md}");
2066 assert!(
2067 md.contains("| a | binary_bytes | 100 → 200 | +100.00% |"),
2068 "{md}"
2069 );
2070 assert!(
2071 !md.contains("| alloc_"),
2072 "allocations leaked into the custom table: {md}"
2073 );
2074 assert!(c.regressions(&g(0.0)).is_empty());
2075 }
2076
2077 #[test]
2081 fn custom_metric_labels_are_escaped() {
2082 let with = |v: f64| {
2083 let mut r = rec("a|b", "gha", 1_000_000.0, 10.0);
2084 r.metrics.insert("x|y\n**Nothing was compared".into(), v);
2085 r
2086 };
2087 let md = markdown(
2088 &compare(&[with(1.0)], &[with(2.0)]),
2089 &Trend::new(),
2090 &g(1.0),
2091 false,
2092 );
2093 assert!(
2094 md.contains(r"| a\|b | x\|y\\n**Nothing was compared | 1 → 2 | +100.00% |"),
2095 "{md}"
2096 );
2097 assert!(
2098 !md.lines().any(|l| l.starts_with("**Nothing was compared")),
2099 "{md}"
2100 );
2101 }
2102
2103 fn accepting(names: &str, source: Source) -> Acceptances {
2106 let mut a = Acceptances::default();
2107 for name in names.split(',') {
2108 a.add_name(name.trim(), source.clone()).unwrap();
2109 }
2110 a
2111 }
2112
2113 #[test]
2116 fn a_control_character_in_a_name_is_escaped() {
2117 assert_eq!(code("a\nb"), "`a\\nb`");
2118 assert_eq!(
2119 describe(&("a\nb".into(), "self".into(), "r\r".into())),
2120 "`a\\nb` on `r\\r`"
2121 );
2122 assert_eq!(describe(&key("a")), "`a` on `gha`");
2124 let c = compare(&[], &[]).with_accepted(accepting(
2125 "x\n**1 benchmark(s) above the 1% gate:** `x`",
2126 Source::Flag,
2127 ));
2128 let md = markdown(&c, &Trend::new(), &g(1.0), false);
2129 assert!(
2130 md.lines().all(|l| !l.starts_with("**1 benchmark(s)")),
2131 "{md}"
2132 );
2133 }
2134
2135 const SHA: &str = "0123456789abcdef0123456789abcdef01234567";
2136
2137 #[test]
2140 fn an_acceptance_covers_only_the_benchmark_it_names() {
2141 let c = compare(
2142 &[
2143 rec("a", "gha", 1_000_000.0, 10.0),
2144 rec("b", "gha", 1_000_000.0, 10.0),
2145 ],
2146 &[
2147 rec("a", "gha", 1_100_000.0, 10.0),
2148 rec("b", "gha", 1_100_000.0, 10.0),
2149 ],
2150 )
2151 .with_accepted(accepting("a", Source::Trailer(SHA.into())));
2152 assert_eq!(
2153 c.regressions(&g(1.0)).len(),
2154 2,
2155 "both still count as regressed"
2156 );
2157 let failures = c.failures(&g(1.0));
2158 assert_eq!(failures.len(), 1);
2159 assert_eq!(failures[0].bench, "b");
2160 }
2161
2162 #[test]
2165 fn an_accepted_regression_stays_visible_with_its_source() {
2166 let c = compare(
2167 &[rec("a", "gha", 1_000_000.0, 10.0)],
2168 &[rec("a", "gha", 1_100_000.0, 10.0)],
2169 )
2170 .with_accepted(accepting("a", Source::Trailer(SHA.into())));
2171 assert!(c.failures(&g(1.0)).is_empty());
2172 let md = markdown(&c, &Trend::new(), &g(1.0), false);
2173 assert!(md.contains("**+10.00%** (accepted)"), "{md}");
2174 assert!(
2175 md.contains("**1 accepted regression(s) above the 1% gate, not failing it:** `a` on `gha` +10.00% (`Tak-Accept` in `0123456789ab`)"),
2176 "{md}"
2177 );
2178 assert!(!md.contains("No instruction-count regression"), "{md}");
2179 assert!(!md.contains("⚠️"), "{md}");
2180 }
2181
2182 #[test]
2183 fn failures_and_acceptances_are_reported_separately() {
2184 let c = compare(
2185 &[
2186 rec("a", "gha", 1_000_000.0, 10.0),
2187 rec("b", "gha", 1_000_000.0, 10.0),
2188 ],
2189 &[
2190 rec("a", "gha", 1_100_000.0, 10.0),
2191 rec("b", "gha", 1_200_000.0, 10.0),
2192 ],
2193 )
2194 .with_accepted(accepting("a", Source::Flag));
2195 let md = markdown(&c, &Trend::new(), &g(1.0), false);
2196 assert!(
2197 md.contains("**1 benchmark(s) above the 1% gate:** `b` +20.00%"),
2198 "{md}"
2199 );
2200 assert!(md.contains("`a` on `gha` +10.00% (`--accept`)"), "{md}");
2201 }
2202
2203 #[test]
2205 fn an_acceptance_covers_every_series_of_its_benchmark() {
2206 let mut other = rec("a", "gha", 1_000_000.0, 10.0);
2207 other.tool = "other".into();
2208 let mut other_head = other.clone();
2209 other_head.metrics.insert(GATED_METRIC.into(), 2_000_000.0);
2210 let c = compare(
2211 &[
2212 rec("a", "gha", 1_000_000.0, 10.0),
2213 rec("a", "arm", 1_000_000.0, 10.0),
2214 other,
2215 ],
2216 &[
2217 rec("a", "gha", 2_000_000.0, 10.0),
2218 rec("a", "arm", 2_000_000.0, 10.0),
2219 other_head,
2220 ],
2221 )
2222 .with_accepted(accepting("a", Source::Flag));
2223 assert_eq!(c.regressions(&g(1.0)).len(), 3);
2224 assert!(c.failures(&g(1.0)).is_empty());
2225 let md = markdown(&c, &Trend::new(), &g(1.0), false);
2226 assert!(md.contains("`a (other)` on `gha` +100.00%"), "{md}");
2227 }
2228
2229 #[test]
2233 fn an_acceptance_with_nothing_to_accept_is_reported() {
2234 let c = compare(
2235 &[
2236 rec("a", "gha", 1_000_000.0, 10.0),
2237 rec("b", "gha", 1_000_000.0, 10.0),
2238 ],
2239 &[
2240 rec("a", "gha", 1_000_000.0, 10.0),
2241 rec("b", "gha", 1_100_000.0, 10.0),
2242 ],
2243 )
2244 .with_accepted(accepting("a,bb", Source::Flag));
2245 assert_eq!(c.failures(&g(1.0)).len(), 1, "a typo must not accept `b`");
2246 let md = markdown(&c, &Trend::new(), &g(1.0), false);
2247 assert!(
2248 md.contains(
2249 "Accepted, but not above its gate, so nothing was accepted: `a` (`--accept`)"
2250 ),
2251 "{md}"
2252 );
2253 assert!(
2254 md.contains("no benchmark by that name was compared on both sides: `bb` (`--accept`)"),
2255 "{md}"
2256 );
2257 }
2258
2259 #[test]
2261 fn a_pipe_in_a_row_name_is_escaped() {
2262 let on = |runner| rec("a|b", runner, 1_000_000.0, 10.0);
2263 let both = [on("ci|x64"), on("ci|arm64")];
2264 let md = markdown(&compare(&both, &both), &Trend::new(), &g(1.0), false);
2265 assert!(md.contains("| a\\|b on ci\\|x64 |"), "{md}");
2266 let row = md.lines().find(|l| l.contains("ci\\|arm64")).unwrap();
2267 let cells = row.replace("\\|", "").matches('|').count();
2268 assert_eq!(cells, 6, "a benchmark cell and four numbers: {row}");
2269 }
2270
2271 #[test]
2276 fn allocation_labels_are_escaped_like_the_rest_of_the_report() {
2277 let on = |runner| {
2278 let mut r = with_allocs(rec("a\nb", runner, 1.0, 1.0), 3.0, 30.0, 20.0);
2279 r.tool = "t\\x".into();
2280 r
2281 };
2282 let both = [on("ci\rx64"), on("ci-arm64")];
2283 let md = markdown(&compare(&both, &both), &Trend::new(), &g(1.0), false);
2284 let allocs = md
2285 .lines()
2286 .skip_while(|l| !l.starts_with("Heap allocations"))
2287 .collect::<Vec<_>>();
2288 assert!(
2289 allocs
2290 .iter()
2291 .any(|l| l.starts_with(r"| a\\nb (t\\x) on ci\\rx64 |")),
2292 "{md}"
2293 );
2294 assert!(!md.contains('\r'), "{md:?}");
2295 }
2296
2297 #[test]
2300 fn a_zero_allocation_base_is_a_measurement_not_new() {
2301 let c = compare(
2302 &[with_allocs(
2303 rec("a", "gha", 1_000_000.0, 10.0),
2304 0.0,
2305 0.0,
2306 0.0,
2307 )],
2308 &[with_allocs(
2309 rec("a", "gha", 1_000_000.0, 10.0),
2310 0.0,
2311 4_140.0,
2312 0.0,
2313 )],
2314 );
2315 let md = markdown(&c, &Trend::new(), &g(1.0), false);
2316 let row = md
2317 .lines()
2318 .skip_while(|l| !l.starts_with("Heap allocations"))
2319 .find(|l| l.starts_with("| a |"))
2320 .unwrap();
2321 assert_eq!(
2322 row,
2323 "| a | 0 → 0 | +0.00% | 0 → 4,140 | +4,140 (from 0) | 0 → 0 | +0.00% |"
2324 );
2325 assert!(!row.contains("new"), "{row}");
2326 assert!(c.regressions(&g(0.001)).is_empty(), "still never gates");
2327 }
2328
2329 #[test]
2332 fn an_acceptance_is_reported_when_nothing_was_compared() {
2333 let c =
2334 compare(&[], &[rec("a", "gha", 1.0, 1.0)]).with_accepted(accepting("a", Source::Flag));
2335 let md = markdown(&c, &Trend::new(), &g(1.0), false);
2336 assert!(md.contains("nothing was gated"), "{md}");
2337 assert!(
2338 md.contains("no benchmark by that name was compared"),
2339 "{md}"
2340 );
2341 }
2342
2343 #[test]
2346 fn an_acceptance_never_invents_a_regression() {
2347 let c = compare(
2348 &[rec("a", "gha", 1_000_000.0, 10.0)],
2349 &[rec("a", "gha", 500_000.0, 10.0)],
2350 )
2351 .with_accepted(accepting("a", Source::Flag));
2352 let md = markdown(&c, &Trend::new(), &g(1.0), false);
2353 assert!(
2354 md.contains("No instruction-count regression above 1%"),
2355 "{md}"
2356 );
2357 assert!(!md.contains("(accepted)"), "{md}");
2358 }
2359
2360 #[test]
2363 fn an_ignored_trailer_is_named_and_accepts_nothing() {
2364 let c = compare(
2365 &[rec("a", "gha", 1_000_000.0, 10.0)],
2366 &[rec("a", "gha", 1_100_000.0, 10.0)],
2367 )
2368 .with_ignored_trailers(accepting("a", Source::Trailer(SHA.into())));
2369 assert_eq!(c.failures(&g(1.0)).len(), 1);
2370 let md = markdown(&c, &Trend::new(), &g(1.0), false);
2371 assert!(
2372 md.contains("trailers were found but not honoured, because `gate.accept_trailers` is off: `a` (`Tak-Accept` in `0123456789ab`)"),
2373 "{md}"
2374 );
2375 assert!(!md.contains("(accepted)"), "{md}");
2376 }
2377
2378 #[test]
2380 fn a_name_with_backticks_keeps_its_code_span() {
2381 assert_eq!(code("startup"), "`startup`");
2382 assert_eq!(code("a`b"), "`` a`b ``");
2383 assert_eq!(code("``x"), "``` ``x ```");
2384 let c = compare(&[], &[]).with_accepted(accepting("we`ird", Source::Flag));
2385 let md = markdown(&c, &Trend::new(), &g(1.0), false);
2386 assert!(md.contains("`` we`ird `` (`--accept`)"), "{md}");
2387 }
2388
2389 #[test]
2393 fn a_name_with_edge_spaces_keeps_them() {
2394 assert_eq!(code(" startup "), "` startup `");
2395 assert_eq!(code(" startup"), "` startup `");
2396 assert_eq!(code("startup "), "` startup `");
2397 assert_ne!(code(" startup "), code("startup"));
2398 assert_eq!(code(" "), "` `");
2400 }
2401
2402 #[test]
2403 fn a_cell_escapes_backslashes_before_pipes() {
2404 assert_eq!(cell("startup"), "startup");
2405 assert_eq!(cell("a|b"), r"a\|b");
2406 assert_eq!(cell(r"a\|b"), r"a\\\|b");
2409 assert_eq!(cell(r"win\arm"), r"win\\arm");
2410 }
2411
2412 #[test]
2416 fn a_code_cell_escapes_only_pipes() {
2417 assert_eq!(code_cell("`win\\arm`"), "`win\\arm`");
2418 assert_eq!(code_cell("`a|b`"), r"`a\|b`");
2419 assert_eq!(code_cell(r"`a\|b`"), r"`a\\|b`");
2421 }
2422
2423 #[test]
2426 fn a_pipe_in_a_name_does_not_split_the_row() {
2427 let mut base = rec("a|b", "gha", 100.0, 1.0);
2428 let mut head = rec("a|b", "gha", 101.0, 1.0);
2429 base.tool = "x|y".into();
2430 head.tool = "x|y".into();
2431 let md = markdown(&compare(&[base], &[head]), &Trend::new(), &g(1.0), false);
2432 assert!(md.contains(r"| a\|b (x\|y) |"), "{md}");
2433 let columns = |l: &str| l.replace(r"\|", "").matches('|').count();
2434 let rows: Vec<&str> = md.lines().filter(|l| l.starts_with('|')).collect();
2435 assert_eq!(rows.len(), 3, "{md}");
2436 assert!(rows.iter().all(|r| columns(r) == columns(rows[0])), "{md}");
2437 }
2438
2439 #[test]
2442 fn an_accepted_entry_names_its_runner() {
2443 let c = compare(
2444 &[
2445 rec("a", "gha", 1_000_000.0, 10.0),
2446 rec("a", "arm", 1_000_000.0, 10.0),
2447 ],
2448 &[
2449 rec("a", "gha", 1_100_000.0, 10.0),
2450 rec("a", "arm", 1_200_000.0, 10.0),
2451 ],
2452 )
2453 .with_accepted(accepting("a", Source::Flag));
2454 let md = markdown(&c, &Trend::new(), &g(1.0), false);
2455 assert!(md.contains("`a` on `arm` +20.00% (`--accept`)"), "{md}");
2456 assert!(md.contains("`a` on `gha` +10.00% (`--accept`)"), "{md}");
2457 }
2458
2459 #[test]
2463 fn an_acceptance_is_judged_against_the_series_own_gate() {
2464 let mut gates = g(1.0);
2465 gates.set_series("startup", SELF_TOOL, gate(5.0, 20_000, true));
2466 let c = startup_and_install().with_accepted(accepting("startup, install", Source::Flag));
2467 assert!(c.failures(&gates).is_empty());
2468 assert_eq!(benches(&c.accepted_regressions(&gates)), ["install"]);
2469 let md = markdown(&c, &Trend::new(), &gates, false);
2470 assert!(
2471 md.contains(
2472 "**1 accepted regression(s) above their gate, not failing it:** \
2473 `install` on `gha` +2.00% (gate 1%) (`--accept`)\n"
2474 ),
2475 "{md}"
2476 );
2477 assert!(
2478 md.contains("Accepted, but not above its gate, so nothing was accepted: `startup`"),
2479 "{md}"
2480 );
2481 assert!(!md.contains("No gated benchmark rose"), "{md}");
2482 }
2483
2484 #[test]
2487 fn an_acceptance_does_not_count_a_rise_under_the_floor() {
2488 let gates = Gates::uniform(Gate::new(1.0, 10_000).unwrap());
2489 let c = startup_and_install().with_accepted(accepting("startup, install", Source::Flag));
2490 assert!(c.failures(&gates).is_empty());
2491 assert_eq!(benches(&c.accepted_regressions(&gates)), ["install"]);
2492 let md = markdown(&c, &Trend::new(), &gates, false);
2493 assert!(
2494 md.contains(
2495 "**1 accepted regression(s) above the 1% gate, not failing it:** \
2496 `install` on `gha` +2.00% (`--accept`)\n"
2497 ),
2498 "{md}"
2499 );
2500 assert!(
2501 md.contains("not above its gate, so nothing was accepted: `startup`"),
2502 "{md}"
2503 );
2504 }
2505
2506 #[test]
2510 fn accepting_a_report_only_benchmark_accepts_nothing() {
2511 let mut gates = g(1.0);
2512 gates.set_series("startup", SELF_TOOL, gate(1.0, 0, false));
2513 let c = startup_and_install().with_accepted(accepting("startup", Source::Flag));
2514 assert_eq!(benches(&c.failures(&gates)), ["install"]);
2515 assert!(c.accepted_regressions(&gates).is_empty());
2516 let md = markdown(&c, &Trend::new(), &gates, false);
2517 assert!(md.contains("**+2.00%** (not gated)"), "{md}");
2518 assert!(!md.contains("(accepted)"), "{md}");
2519 assert!(
2520 md.contains(
2521 "Accepted, but report-only, so it can never fail and nothing was \
2522 accepted: `startup` (`--accept`)"
2523 ),
2524 "{md}"
2525 );
2526 assert!(
2527 md.contains("**1 report-only benchmark(s) above their gate, not failing:**"),
2528 "{md}"
2529 );
2530 }
2531
2532 #[test]
2535 fn an_empty_acceptance_leaves_a_per_benchmark_report_unchanged() {
2536 let mut gates = g(1.0);
2537 gates.set_series("startup", SELF_TOOL, gate(5.0, 20_000, true));
2538 let plain = markdown(&startup_and_install(), &Trend::new(), &gates, false);
2539 let c = startup_and_install()
2540 .with_accepted(Acceptances::default())
2541 .with_ignored_trailers(Acceptances::default());
2542 assert_eq!(markdown(&c, &Trend::new(), &gates, false), plain);
2543 assert!(!plain.contains("accepted"), "{plain}");
2544 }
2545
2546 #[test]
2547 fn thousands_separates() {
2548 assert_eq!(thousands(1234567.0), "1,234,567");
2549 assert_eq!(thousands(999.0), "999");
2550 assert_eq!(thousands(1000.0), "1,000");
2551 }
2552}