1use anyhow::Result;
20use std::collections::{BTreeMap, BTreeSet};
21
22use crate::accept::{Acceptances, TRAILER};
23use crate::compare::{
24 CREDIT, Change, GATED_METRIC, Gate, Gates, Key, Trend, WALL_METRIC, code, code_cell, describe,
25 signed_pct, sparkline, thousands,
26};
27use crate::notes;
28use crate::record::Record;
29
30pub const SCAN_LIMIT: usize = 10_000;
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum Cutoff {
47 Shallow,
49 ScanLimit,
51}
52
53pub fn cutoff(
61 recorded: usize,
62 window: usize,
63 truncated: bool,
64 shallow: impl FnOnce() -> Result<bool>,
65) -> Result<Option<Cutoff>> {
66 if recorded >= window {
67 return Ok(None);
68 }
69 if truncated {
70 return Ok(Some(Cutoff::ScanLimit));
71 }
72 Ok(shallow()?.then_some(Cutoff::Shallow))
73}
74
75#[derive(Debug, Clone, Copy)]
77struct Point {
78 at: usize,
80 instructions: f64,
81 wall: Option<f64>,
82}
83
84#[derive(Debug, Clone, PartialEq)]
86pub struct Step {
87 pub key: Key,
88 pub from: String,
90 pub to: String,
92 pub commits: usize,
96 pub instructions: Change,
97 pub wall: Option<Change>,
99}
100
101impl Step {
102 pub fn gate(&self, gates: &Gates) -> Gate {
106 gates.get(&self.key.0, &self.key.1)
107 }
108
109 pub fn exceeds(&self, gates: &Gates) -> bool {
113 self.instructions.exceeds(&self.gate(gates))
114 }
115
116 pub fn fails(&self, gates: &Gates) -> bool {
118 self.gate(gates).enabled && self.exceeds(gates)
119 }
120}
121
122#[derive(Debug, Clone, PartialEq)]
124pub struct Drift {
125 pub key: Key,
126 pub since: String,
128 pub points: usize,
130 pub change: Change,
131}
132
133#[derive(Debug, PartialEq)]
134pub struct Detection {
135 pub head: String,
136 pub gates: Gates,
139 pub walked: usize,
141 pub recorded: usize,
143 pub latest: Vec<Step>,
146 pub earlier: Vec<Step>,
148 pub drift: Vec<Drift>,
150 pub new_at_head: Vec<Key>,
152 pub missing_at_head: Vec<Key>,
154 pub trend: Trend,
155 pub cutoff: Option<Cutoff>,
158 pub allow_empty: bool,
162 pub no_gate: bool,
166 pub accepted: BTreeMap<Key, Acceptances>,
171 pub offered: Acceptances,
174 pub ignored_trailers: Acceptances,
176}
177
178impl Detection {
179 pub fn new(head: String, gates: Gates) -> Self {
181 Self {
182 head,
183 gates,
184 walked: 0,
185 recorded: 0,
186 latest: vec![],
187 earlier: vec![],
188 drift: vec![],
189 new_at_head: vec![],
190 missing_at_head: vec![],
191 trend: Trend::new(),
192 cutoff: None,
193 allow_empty: false,
194 no_gate: false,
195 accepted: BTreeMap::new(),
196 offered: Acceptances::default(),
197 ignored_trailers: Acceptances::default(),
198 }
199 }
200
201 pub fn accept(&mut self, flags: &Acceptances, trailer_logs: &BTreeMap<String, String>) {
209 self.offered = flags.clone();
210 for log in trailer_logs.values() {
211 self.offered.add_trailer_log(log);
212 }
213 for s in &self.latest {
214 let mut a = flags.clone();
215 if let Some(log) = trailer_logs.get(&s.from) {
216 a.add_trailer_log(log);
217 }
218 if !a.is_empty() {
219 self.accepted.insert(s.key.clone(), a);
220 }
221 }
222 }
223
224 fn acceptance(&self, s: &Step) -> Option<&Acceptances> {
228 if s.to != self.head {
229 return None;
230 }
231 self.accepted.get(&s.key).filter(|a| a.covers(&s.key.0))
232 }
233
234 pub fn accepted_steps(&self) -> Vec<&Step> {
236 self.latest
237 .iter()
238 .filter(|s| s.fails(&self.gates) && self.acceptance(s).is_some())
239 .collect()
240 }
241
242 fn unused_acceptances(&self) -> Vec<&str> {
244 let used: BTreeSet<&str> = self
245 .accepted_steps()
246 .iter()
247 .map(|s| s.key.0.as_str())
248 .collect();
249 self.offered
250 .iter()
251 .map(|(name, _)| name)
252 .filter(|name| !used.contains(name))
253 .collect()
254 }
255
256 pub fn failures(&self) -> Vec<&Step> {
262 self.latest
263 .iter()
264 .filter(|s| s.fails(&self.gates) && self.acceptance(s).is_none())
265 .collect()
266 }
267
268 pub fn reported(&self) -> Vec<&Step> {
270 self.latest
271 .iter()
272 .filter(|s| !s.gate(&self.gates).enabled && s.exceeds(&self.gates))
273 .collect()
274 }
275
276 pub fn uniform(&self) -> bool {
283 let keys = self
284 .latest
285 .iter()
286 .chain(&self.earlier)
287 .map(|s| &s.key)
288 .chain(self.drift.iter().map(|d| &d.key));
289 keys.into_iter()
290 .all(|k| self.gates.get(&k.0, &k.1) == self.gates.global)
291 }
292
293 pub fn nothing_compared(&self) -> bool {
295 self.latest.is_empty()
296 }
297
298 pub fn empty_fails(&self) -> bool {
309 self.nothing_compared() && !self.allow_empty && !self.no_gate
310 }
311}
312
313pub fn select(newest_first: &[String], annotated: &BTreeSet<String>, window: usize) -> Vec<String> {
324 let mut seen = 0;
325 let mut end = newest_first.len().min(1);
326 for (i, sha) in newest_first.iter().enumerate() {
327 if annotated.contains(sha) {
328 seen += 1;
329 end = i + 1;
330 if seen >= window {
331 break;
332 }
333 }
334 }
335 newest_first[..end].iter().rev().cloned().collect()
336}
337
338pub type Walk = Vec<(String, Vec<Record>)>;
341
342pub fn gather(head: &str, window: usize) -> Result<(Walk, Option<Cutoff>)> {
346 let mut logged = notes::log(head, Some(SCAN_LIMIT + 1))?;
354 let truncated = logged.len() > SCAN_LIMIT;
355 logged.truncate(SCAN_LIMIT);
356 let oldest = logged.last().map(|l| l.sha.clone());
359
360 let shas: Vec<String> = logged.iter().map(|l| l.sha.clone()).collect();
364 let recorded_at: BTreeSet<String> = logged
365 .iter()
366 .filter(|l| !l.records.is_empty())
367 .map(|l| l.sha.clone())
368 .collect();
369 let kept = select(&shas, &recorded_at, window).len();
372 logged.truncate(kept);
373 let walked: Walk = logged
374 .into_iter()
375 .rev()
376 .map(|l| (l.sha, l.records))
377 .collect();
378 let recorded = walked.iter().filter(|(_, r)| !r.is_empty()).count();
379
380 let cut = cutoff(recorded, window, truncated, || {
381 Ok(oldest.as_deref().is_some_and(notes::is_shallow_boundary))
382 })?;
383 Ok((walked, cut))
384}
385
386fn fold(records: &[Record]) -> BTreeMap<Key, (f64, Option<f64>)> {
394 let mut ins: BTreeMap<Key, f64> = BTreeMap::new();
395 let mut wall: BTreeMap<Key, f64> = BTreeMap::new();
396 for r in records {
397 let key: Key = (r.bench.clone(), r.tool.clone(), r.runner.clone());
398 if let Some(&v) = r.metrics.get(GATED_METRIC) {
399 ins.entry(key.clone())
400 .and_modify(|e| *e = e.min(v))
401 .or_insert(v);
402 }
403 if let Some(&v) = r.metrics.get(WALL_METRIC) {
404 wall.entry(key).and_modify(|e| *e = e.min(v)).or_insert(v);
405 }
406 }
407 ins.into_iter()
408 .map(|(k, v)| {
409 let w = wall.get(&k).copied();
410 (k, (v, w))
411 })
412 .collect()
413}
414
415fn step(key: &Key, walked: &[(String, Vec<Record>)], a: Point, b: Point) -> Step {
416 let change = |metric: &str, base: f64, head: f64| Change {
417 bench: key.0.clone(),
418 tool: key.1.clone(),
419 runner: key.2.clone(),
420 metric: metric.to_string(),
421 base,
422 head,
423 };
424 Step {
425 key: key.clone(),
426 from: walked[a.at].0.clone(),
427 to: walked[b.at].0.clone(),
428 commits: b.at - a.at,
429 instructions: change(GATED_METRIC, a.instructions, b.instructions),
430 wall: match (a.wall, b.wall) {
431 (Some(x), Some(y)) => Some(change(WALL_METRIC, x, y)),
432 _ => None,
433 },
434 }
435}
436
437pub fn analyze(walked: &[(String, Vec<Record>)], gates: &Gates) -> Detection {
448 let Some((head, _)) = walked.last() else {
449 return Detection::new(String::new(), gates.clone());
450 };
451 let head_at = walked.len() - 1;
452
453 let mut series: BTreeMap<Key, Vec<Point>> = BTreeMap::new();
454 for (at, (_, records)) in walked.iter().enumerate() {
455 for (key, (instructions, wall)) in fold(records) {
456 series.entry(key).or_default().push(Point {
457 at,
458 instructions,
459 wall,
460 });
461 }
462 }
463
464 let mut d = Detection {
465 walked: walked.len(),
466 recorded: walked.iter().filter(|(_, r)| !r.is_empty()).count(),
467 ..Detection::new(head.clone(), gates.clone())
468 };
469
470 for (key, points) in &series {
471 d.trend
472 .insert(key.clone(), points.iter().map(|p| p.instructions).collect());
473
474 let steps: Vec<Step> = points
475 .windows(2)
476 .map(|w| step(key, walked, w[0], w[1]))
477 .collect();
478 let at_head = points.last().is_some_and(|p| p.at == head_at);
479
480 match (at_head, steps.split_last()) {
481 (true, Some((last, rest))) => {
482 d.latest.push(last.clone());
483 d.earlier
484 .extend(rest.iter().filter(|s| s.exceeds(gates)).cloned());
485 }
486 (true, None) => d.new_at_head.push(key.clone()),
487 (false, _) => {
488 d.missing_at_head.push(key.clone());
489 d.earlier
490 .extend(steps.iter().filter(|s| s.exceeds(gates)).cloned());
491 }
492 }
493
494 let gate = gates.get(&key.0, &key.1);
495 if at_head && let Some(drift) = drift(key, walked, points, &steps, &gate) {
496 d.drift.push(drift);
497 }
498 }
499
500 d.earlier
503 .sort_by_key(|s| walked.iter().position(|(sha, _)| sha == &s.to));
504 d
505}
506
507fn drift(
523 key: &Key,
524 walked: &[(String, Vec<Record>)],
525 points: &[Point],
526 steps: &[Step],
527 gate: &Gate,
528) -> Option<Drift> {
529 let start = steps
531 .iter()
532 .rposition(|s| s.instructions.exceeds(gate))
533 .map_or(0, |i| i + 1);
534 let run = &points[start..];
535 if run.len() < 3 {
537 return None;
538 }
539 let total = step(key, walked, run[0], run[run.len() - 1]);
540 if !total.instructions.exceeds(gate) {
541 return None;
542 }
543 Some(Drift {
544 key: key.clone(),
545 since: total.from,
546 points: run.len(),
547 change: total.instructions,
548 })
549}
550
551pub fn short(sha: &str) -> &str {
554 &sha[..sha.len().min(12)]
555}
556
557fn span(s: &Step) -> String {
562 if s.commits <= 1 {
563 format!("`{}`", short(&s.to))
564 } else {
565 format!(
566 "`{}..{}` ({} commits)",
567 short(&s.from),
568 short(&s.to),
569 s.commits
570 )
571 }
572}
573
574fn instructions_cells(s: &Step, d: &Detection) -> (String, String) {
575 let gates = &d.gates;
576 let ch = &s.instructions;
577 let flag = match (s.exceeds(gates), s.gate(gates).enabled) {
580 (true, true) if d.acceptance(s).is_some() => " (accepted)",
581 (true, true) => " ⚠️",
582 (true, false) => " (not gated)",
583 (false, _) => "",
584 };
585 (
586 format!("{} → {}", thousands(ch.base), thousands(ch.head)),
587 format!("**{}**{flag}", signed_pct(ch.pct())),
588 )
589}
590
591pub fn markdown(d: &Detection, credit: bool) -> String {
594 let gates = &d.gates;
595 let global = gates.global;
596 let uniform = d.uniform();
597 let the_gate = if uniform {
600 format!("the {}% gate", global.pct)
601 } else {
602 "their gate".to_string()
603 };
604 let floor = if uniform && global.min_delta > 0 {
605 format!(
606 " (rises of {} instructions or fewer are not counted)",
607 thousands(global.min_delta as f64)
608 )
609 } else {
610 String::new()
611 };
612 let listed = |steps: &[&Step]| {
613 steps
614 .iter()
615 .map(|s| {
616 let mut out = format!("{} {}", describe(&s.key), signed_pct(s.instructions.pct()));
617 if !uniform {
618 out.push_str(&format!(" (gate {})", s.gate(gates).threshold()));
619 }
620 out
621 })
622 .collect::<Vec<_>>()
623 .join(", ")
624 };
625 let head = short(&d.head);
626 let mut out = format!(
627 "Walked {} first-parent commit(s) ending at `{head}`, {} with measurements recorded.\n\n",
628 d.walked, d.recorded
629 );
630
631 if d.nothing_compared() {
632 let why = if d.new_at_head.is_empty() {
633 "No instruction counts are recorded for this commit. Record it with \
634 `tak run --record` before running `tak detect`."
635 } else {
636 "No series measured here has an earlier recorded point in the window: \
637 this is the first recording, the history is too short or shallow, or \
638 the runner class changed, which deliberately starts a new series."
639 };
640 if d.no_gate {
641 out.push_str(&format!(
642 "**Nothing was compared at `{head}`, and so nothing was gated** \
643 (`--no-gate`). {why}\n"
644 ));
645 } else if !d.empty_fails() {
646 out.push_str(&format!(
649 "**Nothing was compared at `{head}`, and so nothing was gated** \
650 (`allow_empty`). {why}\n\n{}\n",
651 crate::compare::ALLOWED_EMPTY
652 ));
653 } else {
654 out.push_str(&format!(
655 "**Nothing was compared at `{head}`, so this check fails.** {why} \
656 When that is expected — the first recording, or the first on a new \
657 runner class — pass `--allow-empty` or set `[gate] allow_empty = true`, \
658 or record an earlier commit on the same runner class first.\n"
659 ));
660 }
661 } else {
662 if uniform {
663 out.push_str(
664 "| benchmark | trend | step | instructions | Δ | wall (min) | Δ |\n\
665 |---|---|---|---:|---:|---:|---:|\n",
666 );
667 } else {
668 out.push_str(
669 "| benchmark | trend | step | instructions | Δ | gate | wall (min) | Δ |\n\
670 |---|---|---|---:|---:|---|---:|---:|\n",
671 );
672 }
673 for s in &d.latest {
674 let spark = d
675 .trend
676 .get(&s.key)
677 .map(|v| sparkline(v))
678 .filter(|v| !v.is_empty())
679 .map(|v| format!("`{v}`"))
680 .unwrap_or_else(|| "—".into());
681 let (ins, ins_delta) = instructions_cells(s, d);
682 let gate_cell = if uniform {
683 String::new()
684 } else {
685 format!(" {} |", s.gate(gates).describe())
686 };
687 let (wall, wall_delta) = match &s.wall {
688 Some(w) => (
689 format!("{:.2} → {:.2}ms", w.base, w.head),
690 signed_pct(w.pct()),
691 ),
692 None => ("—".into(), "—".into()),
693 };
694 out.push_str(&format!(
695 "| {} | {spark} | {} | {ins} | {ins_delta} |{gate_cell} {wall} | {wall_delta} |\n",
696 code_cell(&describe(&s.key)),
697 span(s),
698 ));
699 }
700
701 let failures = d.failures();
702 let accepted = d.accepted_steps();
703 let any_gated = d.latest.iter().any(|s| s.gate(gates).enabled);
704 out.push('\n');
705 if !any_gated {
706 out.push_str("Every benchmark here is report-only, so none can fail the gate.\n");
709 } else if failures.is_empty() && !accepted.is_empty() {
710 } else if failures.is_empty() {
713 if uniform {
714 out.push_str(&format!(
715 "No instruction-count step above {}% at `{head}`{floor}.\n",
716 global.pct
717 ));
718 } else {
719 out.push_str(&format!(
720 "No gated benchmark stepped beyond its gate at `{head}`.\n"
721 ));
722 }
723 } else {
724 out.push_str(&format!(
725 "**{} benchmark(s) stepped above {the_gate} at `{head}`{floor}:** {}\n",
726 failures.len(),
727 listed(&failures)
728 ));
729 if failures.iter().any(|s| s.commits > 1) {
730 out.push_str(
731 "\nA step shown as a range happened somewhere in commits that were \
732 not measured individually; `git log --first-parent` over that \
733 range lists the candidates.\n",
734 );
735 }
736 }
737 if !accepted.is_empty() {
738 let gap = if failures.is_empty() { "" } else { "\n" };
742 out.push_str(&format!(
743 "{gap}**{} accepted step(s) above {the_gate} at `{head}`, not failing:** {}\n",
744 accepted.len(),
745 accepted
746 .iter()
747 .map(|s| {
748 let by = d.acceptance(s).map(|a| a.describe(&s.key.0));
749 format!("{} (accepted by {})", listed(&[*s]), by.unwrap_or_default())
750 })
751 .collect::<Vec<_>>()
752 .join(", ")
753 ));
754 }
755 let reported = d.reported();
756 if !reported.is_empty() {
757 out.push_str(&format!(
758 "\n**{} report-only benchmark(s) stepped above their gate at `{head}`, \
759 not failing:** {}\n",
760 reported.len(),
761 listed(&reported)
762 ));
763 }
764 }
765
766 let unused = d.unused_acceptances();
770 if !unused.is_empty() {
771 out.push_str(&format!(
772 "\nAccepted, but no step onto `{head}` needed it, so nothing was accepted: {}\n",
773 unused
774 .iter()
775 .map(|name| format!("{} ({})", code(name), d.offered.describe(name)))
776 .collect::<Vec<_>>()
777 .join(", ")
778 ));
779 }
780 if !d.ignored_trailers.is_empty() {
781 out.push_str(&format!(
782 "\n`{TRAILER}` trailers were found but not honoured, because \
783 `gate.accept_trailers` is off: {}\n",
784 d.ignored_trailers
785 .iter()
786 .map(|(name, _)| format!("{} ({})", code(name), d.ignored_trailers.describe(name)))
787 .collect::<Vec<_>>()
788 .join(", ")
789 ));
790 }
791
792 if !d.earlier.is_empty() {
793 out.push_str(&format!(
794 "\n**Earlier steps above {the_gate}**, reported and not gated — \
795 a step fails only the run for the commit that introduced it:\n\n"
796 ));
797 if uniform {
798 out.push_str("| benchmark | step | instructions | Δ |\n|---|---|---:|---:|\n");
799 } else {
800 out.push_str(
801 "| benchmark | step | instructions | Δ | gate |\n|---|---|---:|---:|---|\n",
802 );
803 }
804 for s in &d.earlier {
805 let (ins, delta) = instructions_cells(s, d);
806 let gate_cell = if uniform {
807 String::new()
808 } else {
809 format!(" {} |", s.gate(gates).describe())
810 };
811 out.push_str(&format!(
812 "| {} | {} | {ins} | {delta} |{gate_cell}\n",
813 code_cell(&describe(&s.key)),
814 span(s)
815 ));
816 }
817 }
818
819 if !d.drift.is_empty() {
820 out.push_str(&format!(
821 "\n**Sustained drift**, reported and not gated — every step stayed within \
822 {the_gate} and the total did not:\n\n"
823 ));
824 for dr in &d.drift {
825 let gate = if uniform {
826 String::new()
827 } else {
828 format!(" (gate {})", gates.get(&dr.key.0, &dr.key.1).describe())
829 };
830 out.push_str(&format!(
831 "- {}: {} ({} → {}) over {} recorded commits since `{}`{gate}\n",
832 describe(&dr.key),
833 signed_pct(dr.change.pct()),
834 thousands(dr.change.base),
835 thousands(dr.change.head),
836 dr.points,
837 short(&dr.since),
838 ));
839 }
840 }
841
842 if !d.new_at_head.is_empty() {
843 out.push_str(&format!(
844 "\nNo earlier point in the window, nothing to compare against: {}\n",
845 list(&d.new_at_head)
846 ));
847 }
848 if !d.missing_at_head.is_empty() {
849 out.push_str(&format!(
850 "\nRecorded earlier in the window but not at `{head}` — a benchmark that \
851 stops running also stops being checked: {}\n",
852 list(&d.missing_at_head)
853 ));
854 }
855 match d.cutoff {
856 Some(Cutoff::Shallow) => out.push_str(
857 "\nThis checkout is shallow, and the walk reached its boundary before \
858 the window filled. Fetch more history (`fetch-depth: 0` with \
859 `actions/checkout`) so earlier recordings are visible.\n",
860 ),
861 Some(Cutoff::ScanLimit) => out.push_str(&format!(
862 "\nThe walk stopped at its limit of {} first-parent commits before the \
863 window filled. Recordings older than that were not compared.\n",
864 thousands(SCAN_LIMIT as f64)
865 )),
866 None => {}
867 }
868
869 out.push_str(
870 "\n<sub>Only instruction counts gate, and only a step onto the newest commit. Wall clock \
871 is shown for context — on identical hardware it moves 4-20% run to run.</sub>\n",
872 );
873 if credit {
874 out.push_str(CREDIT);
875 }
876 out
877}
878
879fn list(keys: &[Key]) -> String {
880 keys.iter().map(describe).collect::<Vec<_>>().join(", ")
881}
882
883#[cfg(test)]
884mod tests {
885 use super::*;
886
887 fn pct(p: f64) -> Gates {
889 Gates::uniform(Gate::new(p, 0).unwrap())
890 }
891
892 fn rec(bench: &str, runner: &str, ins: f64) -> Record {
893 Record {
894 v: 1,
895 bench: bench.into(),
896 tool: "self".into(),
897 version: None,
898 runner: runner.into(),
899 ts: "2026-01-01T00:00:00Z".into(),
900 metrics: BTreeMap::from([
901 (GATED_METRIC.to_string(), ins),
902 (WALL_METRIC.to_string(), 10.0),
903 ]),
904 }
905 }
906
907 fn walk(values: &[Option<f64>]) -> Vec<(String, Vec<Record>)> {
910 values
911 .iter()
912 .enumerate()
913 .map(|(i, v)| {
914 (
915 format!("c{i}"),
916 v.map(|v| vec![rec("a", "gha", v)]).unwrap_or_default(),
917 )
918 })
919 .collect()
920 }
921
922 fn shas(names: &[&str]) -> Vec<String> {
923 names.iter().map(|s| s.to_string()).collect()
924 }
925
926 #[test]
927 fn a_step_onto_the_head_fails() {
928 let d = analyze(
929 &walk(&[Some(1000.0), Some(1000.0), Some(1100.0)]),
930 &pct(1.0),
931 );
932 let f = d.failures();
933 assert_eq!(f.len(), 1);
934 assert_eq!((f[0].from.as_str(), f[0].to.as_str()), ("c1", "c2"));
935 assert_eq!(f[0].commits, 1);
936 assert!(d.earlier.is_empty());
937 }
938
939 #[test]
943 fn a_pipe_in_a_name_does_not_split_the_row() {
944 let named = |v: f64| vec![rec("a|b", r"win\arm", v)];
945 let d = analyze(
946 &[
947 ("c0".to_string(), named(1000.0)),
948 ("c1".to_string(), named(1100.0)),
949 ("c2".to_string(), named(1100.0)),
950 ("c3".to_string(), named(1210.0)),
951 ],
952 &pct(1.0),
953 );
954 assert_eq!((d.latest.len(), d.earlier.len()), (1, 1));
955 let md = markdown(&d, false);
956 assert_eq!(md.matches(r"| `a\|b` on `win\arm` |").count(), 2, "{md}");
957 }
958
959 #[test]
960 fn a_step_below_the_gate_passes() {
961 let d = analyze(&walk(&[Some(1000.0), Some(1005.0)]), &pct(1.0));
962 assert!(d.failures().is_empty());
963 assert_eq!(d.latest.len(), 1, "it is still reported");
964 }
965
966 #[test]
967 fn an_improvement_never_fails() {
968 let d = analyze(&walk(&[Some(1000.0), Some(500.0)]), &pct(1.0));
969 assert!(d.failures().is_empty());
970 }
971
972 #[test]
975 fn an_older_step_is_reported_not_failed() {
976 let d = analyze(
977 &walk(&[Some(1000.0), Some(1100.0), Some(1100.0)]),
978 &pct(1.0),
979 );
980 assert!(d.failures().is_empty());
981 assert_eq!(d.earlier.len(), 1);
982 assert_eq!(d.earlier[0].to, "c1");
983 assert!(markdown(&d, false).contains("Earlier steps above the 1% gate"));
984 }
985
986 #[test]
990 fn a_step_across_unrecorded_commits_is_a_range() {
991 let d = analyze(&walk(&[Some(1000.0), None, None, Some(1100.0)]), &pct(1.0));
992 let f = d.failures();
993 assert_eq!(f.len(), 1, "a range onto the head still fails");
994 assert_eq!((f[0].from.as_str(), f[0].to.as_str()), ("c0", "c3"));
995 assert_eq!(f[0].commits, 3);
996 let md = markdown(&d, false);
997 assert!(md.contains("`c0..c3` (3 commits)"), "{md}");
998 assert!(md.contains("not measured individually"), "{md}");
999 }
1000
1001 #[test]
1004 fn ranges_are_per_series() {
1005 let mut w = walk(&[Some(1000.0), Some(1000.0), Some(1000.0)]);
1006 w[0].1.push(rec("b", "gha", 50.0));
1007 w[2].1.push(rec("b", "gha", 60.0));
1008 let d = analyze(&w, &pct(1.0));
1009 let b = d.latest.iter().find(|s| s.key.0 == "b").unwrap();
1010 assert_eq!(b.commits, 2);
1011 let a = d.latest.iter().find(|s| s.key.0 == "a").unwrap();
1012 assert_eq!(a.commits, 1);
1013 assert_eq!(d.failures().len(), 1);
1014 }
1015
1016 #[test]
1018 fn runners_never_line_up() {
1019 let w = vec![
1020 ("c0".to_string(), vec![rec("a", "gha-linux", 1000.0)]),
1021 ("c1".to_string(), vec![rec("a", "gha-macos", 9000.0)]),
1022 ];
1023 let d = analyze(&w, &pct(1.0));
1024 assert!(d.failures().is_empty());
1025 assert!(d.nothing_compared());
1026 assert_eq!(d.new_at_head.len(), 1);
1027 assert_eq!(d.missing_at_head.len(), 1);
1028 let md = markdown(&d, false);
1029 assert!(md.contains("Nothing was compared"), "{md}");
1030 assert!(md.contains("gha-linux") && md.contains("gha-macos"), "{md}");
1031 }
1032
1033 #[test]
1036 fn runners_are_partitioned_within_a_walk() {
1037 let w = vec![
1038 (
1039 "c0".to_string(),
1040 vec![rec("a", "fast", 1000.0), rec("a", "slow", 5000.0)],
1041 ),
1042 (
1043 "c1".to_string(),
1044 vec![rec("a", "fast", 1000.0), rec("a", "slow", 5200.0)],
1045 ),
1046 ];
1047 let d = analyze(&w, &pct(1.0));
1048 let f = d.failures();
1049 assert_eq!(f.len(), 1);
1050 assert_eq!(f[0].key.2, "slow");
1051 assert_eq!(f[0].instructions.base, 5000.0, "never the other runner's");
1052 }
1053
1054 #[test]
1055 fn creeping_sub_threshold_steps_are_drift() {
1056 let d = analyze(
1057 &walk(&[Some(1000.0), Some(1004.0), Some(1008.0), Some(1012.0)]),
1058 &pct(1.0),
1059 );
1060 assert!(d.failures().is_empty(), "drift never fails");
1061 assert!(d.earlier.is_empty());
1062 assert_eq!(d.drift.len(), 1);
1063 assert_eq!(d.drift[0].since, "c0");
1064 assert_eq!(d.drift[0].points, 4);
1065 let md = markdown(&d, false);
1066 assert!(md.contains("Sustained drift"), "{md}");
1067 assert!(md.contains("+1.20%"), "{md}");
1068 }
1069
1070 #[test]
1071 fn a_flat_series_is_not_drift() {
1072 let d = analyze(&walk(&[Some(1000.0), Some(1003.0), Some(999.0)]), &pct(1.0));
1073 assert!(d.drift.is_empty());
1074 }
1075
1076 #[test]
1079 fn drift_starts_after_the_last_step() {
1080 let d = analyze(
1081 &walk(&[
1082 Some(1000.0),
1083 Some(1100.0),
1084 Some(1105.0),
1085 Some(1110.0),
1086 Some(1115.0),
1087 ]),
1088 &pct(1.0),
1089 );
1090 assert_eq!(d.earlier.len(), 1);
1091 assert_eq!(d.drift.len(), 1);
1092 assert_eq!(d.drift[0].since, "c1");
1093 assert_eq!(d.drift[0].change.base, 1100.0);
1094
1095 let d = analyze(
1097 &walk(&[Some(1000.0), Some(1100.0), Some(1100.0)]),
1098 &pct(1.0),
1099 );
1100 assert!(d.drift.is_empty());
1101 }
1102
1103 #[test]
1106 fn an_unrecorded_head_says_so() {
1107 let d = analyze(&walk(&[Some(1000.0), Some(1000.0), None]), &pct(1.0));
1108 assert!(d.nothing_compared());
1109 assert!(d.failures().is_empty());
1110 let md = markdown(&d, false);
1111 assert!(md.contains("No instruction counts are recorded"), "{md}");
1112 assert!(md.contains("not at `c2`"), "{md}");
1113 }
1114
1115 #[test]
1116 fn a_filled_window_is_never_cut_short() {
1117 let shallow = || -> Result<bool> { panic!("no need to ask") };
1118 assert_eq!(cutoff(20, 20, true, shallow).unwrap(), None);
1119 }
1120
1121 #[test]
1124 fn hitting_the_scan_limit_is_a_cutoff() {
1125 let shallow = || -> Result<bool> { panic!("the limit decides first") };
1126 assert_eq!(
1127 cutoff(3, 20, true, shallow).unwrap(),
1128 Some(Cutoff::ScanLimit)
1129 );
1130 }
1131
1132 #[test]
1135 fn the_end_of_history_is_a_cutoff_only_when_shallow() {
1136 assert_eq!(
1137 cutoff(3, 20, false, || Ok(true)).unwrap(),
1138 Some(Cutoff::Shallow)
1139 );
1140 assert_eq!(cutoff(3, 20, false, || Ok(false)).unwrap(), None);
1141 }
1142
1143 #[test]
1144 fn each_cutoff_is_named_in_the_report() {
1145 let mut d = analyze(&walk(&[Some(1000.0), Some(1000.0)]), &pct(1.0));
1146 d.cutoff = Some(Cutoff::ScanLimit);
1147 let md = markdown(&d, false);
1148 assert!(md.contains("limit of 10,000 first-parent commits"), "{md}");
1149 d.cutoff = Some(Cutoff::Shallow);
1150 assert!(markdown(&d, false).contains("This checkout is shallow"));
1151 d.cutoff = None;
1152 let md = markdown(&d, false);
1153 assert!(!md.contains("shallow") && !md.contains("limit of"), "{md}");
1154 }
1155
1156 #[test]
1159 fn nothing_compared_fails_unless_allowed() {
1160 let mut d = analyze(&walk(&[Some(1000.0)]), &pct(1.0));
1161 assert!(d.nothing_compared());
1162 assert!(d.empty_fails(), "empty is a failure by default");
1163 let md = markdown(&d, false);
1164 assert!(md.contains("so this check fails.**"), "{md}");
1165 assert!(md.contains("pass `--allow-empty`"), "{md}");
1166 assert!(md.contains("set `[gate] allow_empty = true`"), "{md}");
1167 assert!(!md.contains("nothing was gated"), "{md}");
1168 assert!(!md.contains(crate::compare::ALLOWED_EMPTY), "{md}");
1169
1170 d.allow_empty = true;
1171 assert!(!d.empty_fails());
1172 let md = markdown(&d, false);
1173 assert!(md.contains("nothing was gated** (`allow_empty`)"), "{md}");
1176 assert!(md.contains(crate::compare::ALLOWED_EMPTY), "{md}");
1177 assert!(!md.contains("this check fails"), "{md}");
1178 }
1179
1180 #[test]
1184 fn no_gate_waives_an_empty_comparison() {
1185 let mut d = analyze(&walk(&[Some(1000.0)]), &pct(1.0));
1186 d.no_gate = true;
1187 assert!(!d.empty_fails());
1188 let md = markdown(&d, false);
1189 assert!(md.contains("nothing was gated** (`--no-gate`)"), "{md}");
1190 assert!(!md.contains("this check fails"), "{md}");
1191 d.allow_empty = true;
1192 let md = markdown(&d, false);
1193 assert!(md.contains("nothing was gated** (`--no-gate`)"), "{md}");
1194 assert!(!md.contains(crate::compare::ALLOWED_EMPTY), "{md}");
1195 }
1196
1197 #[test]
1200 fn allow_empty_does_not_waive_a_step() {
1201 let mut d = analyze(&walk(&[Some(1000.0), Some(1100.0)]), &pct(1.0));
1202 d.allow_empty = true;
1203 assert!(!d.nothing_compared());
1204 assert!(!d.empty_fails());
1205 assert_eq!(d.failures().len(), 1);
1206 assert!(!markdown(&d, false).contains(crate::compare::ALLOWED_EMPTY));
1207 }
1208
1209 #[test]
1211 fn a_real_comparison_is_not_empty() {
1212 let d = analyze(&walk(&[Some(1000.0), Some(1000.0)]), &pct(1.0));
1213 assert!(!d.empty_fails());
1214 }
1215
1216 #[test]
1219 fn wall_clock_never_gates() {
1220 let mut w = walk(&[Some(1000.0), Some(1000.0)]);
1221 w[1].1[0].metrics.insert(WALL_METRIC.into(), 1000.0);
1222 for (at, wall) in [(0, 1.0), (1, 100.0)] {
1223 let mut r = rec("w", "gha", 0.0);
1224 r.metrics = BTreeMap::from([(WALL_METRIC.to_string(), wall)]);
1225 w[at].1.push(r);
1226 }
1227 let d = analyze(&w, &pct(0.001));
1228 assert!(d.failures().is_empty());
1229 assert!(d.latest.iter().all(|s| s.key.0 == "a"));
1230 }
1231
1232 #[test]
1234 fn duplicates_reduce_to_the_minimum() {
1235 let mut w = walk(&[Some(1000.0), Some(1000.0)]);
1236 w[1].1.push(rec("a", "gha", 3000.0));
1237 assert!(analyze(&w, &pct(1.0)).failures().is_empty());
1238 }
1239
1240 #[test]
1241 fn a_rise_from_zero_fails() {
1242 let d = analyze(&walk(&[Some(0.0), Some(5.0)]), &pct(1.0));
1243 assert_eq!(d.failures().len(), 1);
1244 }
1245
1246 #[test]
1247 fn an_empty_walk_is_nothing_compared() {
1248 let d = analyze(&[], &pct(1.0));
1249 assert!(d.nothing_compared());
1250 assert!(markdown(&d, false).contains("Only instruction counts gate"));
1251 }
1252
1253 #[test]
1254 fn the_window_counts_recorded_commits() {
1255 let newest_first = shas(&["h", "x1", "r1", "x2", "r2", "r3", "x3"]);
1256 let annotated: BTreeSet<String> = shas(&["h", "r1", "r2", "r3"]).into_iter().collect();
1257 assert_eq!(
1258 select(&newest_first, &annotated, 3),
1259 shas(&["r2", "x2", "r1", "x1", "h"])
1260 );
1261 }
1262
1263 #[test]
1266 fn the_head_is_always_walked() {
1267 let newest_first = shas(&["h", "x1", "r1", "x2"]);
1268 let annotated: BTreeSet<String> = shas(&["r1"]).into_iter().collect();
1269 assert_eq!(
1270 select(&newest_first, &annotated, 20),
1271 shas(&["r1", "x1", "h"])
1272 );
1273 assert_eq!(select(&shas(&["h"]), &BTreeSet::new(), 20), shas(&["h"]));
1274 assert!(select(&[], &BTreeSet::new(), 20).is_empty());
1275 }
1276
1277 #[test]
1278 fn the_trend_covers_the_window() {
1279 let d = analyze(&walk(&[Some(1.0), None, Some(2.0), Some(3.0)]), &pct(1.0));
1280 let key = ("a".to_string(), "self".to_string(), "gha".to_string());
1281 assert_eq!(d.trend[&key], vec![1.0, 2.0, 3.0]);
1282 }
1283
1284 fn gates_with_a(a_pct: f64, min_delta: u64, enabled: bool) -> Gates {
1286 let mut g = pct(1.0);
1287 g.set_bench(
1288 "a",
1289 Gate {
1290 pct: a_pct,
1291 min_delta,
1292 enabled,
1293 },
1294 );
1295 g
1296 }
1297
1298 fn two_series_step() -> Vec<(String, Vec<Record>)> {
1300 vec![
1301 (
1302 "c0".to_string(),
1303 vec![rec("a", "gha", 1000.0), rec("b", "gha", 1000.0)],
1304 ),
1305 (
1306 "c1".to_string(),
1307 vec![rec("a", "gha", 1100.0), rec("b", "gha", 1100.0)],
1308 ),
1309 ]
1310 }
1311
1312 #[test]
1315 fn a_step_is_held_to_its_own_series_gate() {
1316 let d = analyze(&two_series_step(), &gates_with_a(20.0, 0, true));
1317 let f = d.failures();
1318 assert_eq!(f.len(), 1);
1319 assert_eq!(f[0].key.0, "b");
1320 assert!(!d.uniform());
1321 let md = markdown(&d, false);
1322 assert!(md.contains("| gate |"), "{md}");
1323 assert!(md.contains("stepped above their gate"), "{md}");
1324 assert!(md.contains("(gate 1%)"), "{md}");
1325 }
1326
1327 #[test]
1330 fn a_step_within_its_floor_passes() {
1331 let d = analyze(&two_series_step(), &gates_with_a(1.0, 500, true));
1332 let f = d.failures();
1333 assert_eq!(f.len(), 1);
1334 assert_eq!(f[0].key.0, "b");
1335 assert!(markdown(&d, false).contains("floor 500"));
1336 }
1337
1338 #[test]
1341 fn a_report_only_step_is_reported_and_never_fails() {
1342 let d = analyze(&two_series_step(), &gates_with_a(1.0, 0, false));
1343 let f = d.failures();
1344 assert_eq!(f.len(), 1, "only the gated one fails");
1345 assert_eq!(f[0].key.0, "b");
1346 assert_eq!(d.reported().len(), 1);
1347 assert_eq!(d.reported()[0].key.0, "a");
1348 let md = markdown(&d, false);
1349 assert!(md.contains("**+10.00%** (not gated)"), "{md}");
1350 assert!(md.contains("report only (1%)"), "{md}");
1351 assert!(
1352 md.contains("1 report-only benchmark(s) stepped above their gate"),
1353 "{md}"
1354 );
1355
1356 let mut all = gates_with_a(1.0, 0, false);
1358 all.set_bench(
1359 "b",
1360 Gate {
1361 pct: 1.0,
1362 min_delta: 0,
1363 enabled: false,
1364 },
1365 );
1366 let d = analyze(&two_series_step(), &all);
1367 assert!(d.failures().is_empty());
1368 assert!(!d.empty_fails());
1369 assert!(markdown(&d, false).contains("Every benchmark here is report-only"));
1370 }
1371
1372 #[test]
1374 fn earlier_steps_use_the_series_gate() {
1375 let w = walk(&[Some(1000.0), Some(1100.0), Some(1100.0)]);
1376 assert_eq!(analyze(&w, &gates_with_a(20.0, 0, true)).earlier.len(), 0);
1377 assert_eq!(analyze(&w, &gates_with_a(1.0, 0, false)).earlier.len(), 1);
1378 }
1379
1380 #[test]
1383 fn drift_uses_the_series_gate() {
1384 let w = walk(&[Some(1000.0), Some(1004.0), Some(1008.0), Some(1012.0)]);
1385 assert_eq!(analyze(&w, &pct(1.0)).drift.len(), 1);
1386 assert!(analyze(&w, &gates_with_a(5.0, 0, true)).drift.is_empty());
1387 assert!(analyze(&w, &gates_with_a(1.0, 50, true)).drift.is_empty());
1388
1389 let d = analyze(&w, &gates_with_a(1.0, 0, false));
1391 assert_eq!(d.drift.len(), 1);
1392 assert!(markdown(&d, false).contains("(gate report only (1%))"));
1393 }
1394
1395 #[test]
1398 fn a_uniform_report_keeps_its_wording() {
1399 let d = analyze(&two_series_step(), &pct(1.0));
1400 assert!(d.uniform());
1401 let md = markdown(&d, false);
1402 assert!(!md.contains("| gate |"), "{md}");
1403 assert!(md.contains("stepped above the 1% gate"), "{md}");
1404 }
1405
1406 fn flags(names: &[&str]) -> Acceptances {
1407 let mut a = Acceptances::default();
1408 for n in names {
1409 a.add_name(n, crate::accept::Source::Flag).unwrap();
1410 }
1411 a
1412 }
1413
1414 #[test]
1417 fn an_accepted_step_is_reported_and_does_not_fail() {
1418 let mut d = analyze(&two_series_step(), &pct(1.0));
1419 d.accept(&flags(&["a"]), &BTreeMap::new());
1420 let f = d.failures();
1421 assert_eq!(f.len(), 1, "b is not accepted");
1422 assert_eq!(f[0].key.0, "b");
1423 assert_eq!(d.accepted_steps().len(), 1);
1424 let md = markdown(&d, false);
1425 assert!(md.contains("**+10.00%** (accepted)"), "{md}");
1426 assert!(
1427 md.contains("1 accepted step(s) above the 1% gate at `c1`, not failing:"),
1428 "{md}"
1429 );
1430 assert!(md.contains("(accepted by `--accept`)"), "{md}");
1431
1432 d.accept(&flags(&["a", "b"]), &BTreeMap::new());
1433 assert!(d.failures().is_empty());
1434 let md = markdown(&d, false);
1436 assert!(!md.contains("No instruction-count step"), "{md}");
1437 assert!(md.contains("2 accepted step(s)"), "{md}");
1438 }
1439
1440 #[test]
1444 fn a_trailer_counts_only_in_its_steps_range() {
1445 let w = vec![
1446 ("c0".to_string(), vec![rec("a", "gha", 1000.0)]),
1447 ("c1".to_string(), vec![rec("b", "gha", 1000.0)]),
1448 (
1449 "c2".to_string(),
1450 vec![rec("a", "gha", 1100.0), rec("b", "gha", 1100.0)],
1451 ),
1452 ];
1453 let mut d = analyze(&w, &pct(1.0));
1454 let a = d.latest.iter().find(|s| s.key.0 == "a").unwrap();
1455 assert_eq!(a.from, "c0");
1456 let logs = BTreeMap::from([
1459 ("c0".to_string(), "c2\0\nc1\0a\0b\n".to_string()),
1460 ("c1".to_string(), "c2\0\n".to_string()),
1461 ]);
1462 d.accept(&Acceptances::default(), &logs);
1463 let f = d.failures();
1464 assert_eq!(f.len(), 1);
1465 assert_eq!(f[0].key.0, "b", "c1 is outside b's range");
1466 let md = markdown(&d, false);
1467 assert!(md.contains("(accepted by `Tak-Accept` in `c1`)"), "{md}");
1468 }
1469
1470 #[test]
1473 fn an_unused_acceptance_is_reported() {
1474 let mut d = analyze(&walk(&[Some(1000.0), Some(1000.0)]), &pct(1.0));
1475 d.accept(&flags(&["a", "nope"]), &BTreeMap::new());
1476 let md = markdown(&d, false);
1477 assert!(
1478 md.contains("no step onto `c1` needed it, so nothing was accepted: `a` (`--accept`), `nope` (`--accept`)"),
1479 "{md}"
1480 );
1481 }
1482
1483 #[test]
1487 fn an_unused_acceptance_is_reported_when_nothing_was_compared() {
1488 let mut d = analyze(&walk(&[Some(1000.0)]), &pct(1.0));
1489 d.allow_empty = true;
1490 d.accept(&flags(&["startupp"]), &BTreeMap::new());
1491 assert!(d.nothing_compared());
1492 let md = markdown(&d, false);
1493 assert!(md.contains("Nothing was compared"), "{md}");
1494 assert!(
1495 md.contains("so nothing was accepted: `startupp` (`--accept`)"),
1496 "{md}"
1497 );
1498 }
1499
1500 #[test]
1503 fn an_older_step_is_never_marked_accepted() {
1504 let mut d = analyze(
1505 &walk(&[Some(1000.0), Some(1100.0), Some(1100.0)]),
1506 &pct(1.0),
1507 );
1508 d.accept(&flags(&["a"]), &BTreeMap::new());
1509 assert_eq!(d.earlier.len(), 1);
1510 let md = markdown(&d, false);
1511 assert!(!md.contains("(accepted)"), "{md}");
1512 assert!(md.contains("**+10.00%** ⚠️"), "{md}");
1513 }
1514
1515 #[test]
1519 fn a_comma_trailer_names_one_benchmark() {
1520 let mut d = analyze(&two_series_step(), &pct(1.0));
1521 let logs = BTreeMap::from([
1522 ("c0".to_string(), "c1\0a,b\n".to_string()),
1523 ("c1".to_string(), "c1\0a,b\n".to_string()),
1524 ]);
1525 d.accept(&Acceptances::default(), &logs);
1526 assert_eq!(d.failures().len(), 2, "neither `a` nor `b` was named");
1527 let md = markdown(&d, false);
1528 assert!(!md.contains("(accepted"), "{md}");
1529 assert!(md.contains("so nothing was accepted: `a,b`"), "{md}");
1530 }
1531
1532 #[test]
1536 fn a_control_character_in_an_acceptance_is_escaped() {
1537 let mut d = analyze(&two_series_step(), &pct(1.0));
1538 d.accept(
1539 &flags(&["x\n**1 benchmark(s) stepped above"]),
1540 &BTreeMap::new(),
1541 );
1542 d.ignored_trailers.add_trailer_log("c1\0y\u{1b}z\n");
1543 let md = markdown(&d, false);
1544 assert!(md.contains("`x\\n**1 benchmark(s) stepped above`"), "{md}");
1545 assert!(md.contains("`y\\u{1b}z`"), "{md}");
1546 assert_eq!(
1547 md.lines()
1548 .filter(|l| l.starts_with("**1 benchmark(s) stepped above"))
1549 .count(),
1550 0,
1551 "{md}"
1552 );
1553 }
1554
1555 #[test]
1556 fn ignored_trailers_are_named() {
1557 let mut d = analyze(&two_series_step(), &pct(1.0));
1558 d.ignored_trailers.add_trailer_log("c1\0a\n");
1559 assert_eq!(d.failures().len(), 2, "an ignored trailer accepts nothing");
1560 let md = markdown(&d, false);
1561 assert!(
1562 md.contains("`Tak-Accept` trailers were found but not honoured, because `gate.accept_trailers` is off: `a` (`Tak-Accept` in `c1`)"),
1563 "{md}"
1564 );
1565 }
1566}