tak-cli 0.0.16

Pre-v1 command-line benchmarking and performance tracking
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
//! Local baselines, through the real binary in a scratch repository.
//!
//! The loop under test is the one a developer runs by hand: save, change the
//! command, measure again, read the report. What matters is observable from
//! outside — where the file lands, what is printed, the exit status, and that
//! nothing reaches `refs/notes/tak` — so that is what these check.

#![cfg(unix)]

use std::path::{Path, PathBuf};
use std::process::{Command, Output};

fn git(dir: &Path, args: &[&str]) -> String {
    let out = Command::new("git")
        .args(["-c", "user.name=tak-test", "-c", "user.email=t@example.com"])
        .args(args)
        .current_dir(dir)
        .output()
        .unwrap_or_else(|e| panic!("git {args:?} failed to spawn: {e}"));
    assert!(
        out.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8_lossy(&out.stdout).trim_end().to_string()
}

struct Repo {
    _tmp: tempfile::TempDir,
    dir: PathBuf,
}

impl Repo {
    fn new() -> Self {
        let tmp = tempfile::Builder::new()
            .prefix("tak-baseline-")
            .tempdir()
            .unwrap();
        let dir = tmp.path().join("repo");
        std::fs::create_dir(&dir).unwrap();
        git(&dir, &["init", "-q"]);
        Repo { _tmp: tmp, dir }
    }

    fn baseline_file(&self, name: &str) -> PathBuf {
        self.dir
            .join(".git/tak/baselines")
            .join(format!("{name}.jsonl"))
    }
}

/// `tak run` in `dir`, quick and quiet: one warmup-free pass of a few runs, no
/// counters unless a test asks for them, and a fixed runner class so a CI host
/// and a laptop produce the same series names. An empty `cmd` runs what the
/// directory's tak.toml declares.
fn tak_run(dir: &Path, flags: &[&str], cmd: &[&str]) -> Output {
    tak_run_env(dir, flags, cmd, &[])
}

/// As [`tak_run`], with variables set for the run. `allow_empty` and
/// `GITHUB_ACTIONS` are cleared first, so neither the caller's environment
/// nor CI's decides whether comparing nothing fails or how that is worded.
fn tak_run_env(dir: &Path, flags: &[&str], cmd: &[&str], env: &[(&str, &str)]) -> Output {
    let mut c = Command::new(env!("CARGO_BIN_EXE_tak"));
    c.args(["run", "--no-progress", "--runs", "3", "--warmup", "0"])
        .args(["--runner", "test-runner"])
        .args(flags);
    if !cmd.is_empty() {
        c.arg("--").args(cmd);
    }
    c.env_remove("TAK_ALLOW_EMPTY")
        .env_remove("GITHUB_ACTIONS")
        .envs(env.iter().copied())
        .current_dir(dir)
        .output()
        .expect("failed to run tak")
}

/// Write a baseline by hand, for states a host without valgrind cannot
/// produce by measuring: an instruction count on the baseline side.
fn write_baseline(repo: &Repo, name: &str, lines: &[&str]) {
    let path = repo.baseline_file(name);
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(path, lines.join("\n") + "\n").unwrap();
}

fn counted_line(bench: &str) -> String {
    format!(
        r#"{{"v":1,"bench":"{bench}","tool":"self","runner":"test-runner","ts":"2026-09-29T00:00:00Z","metrics":{{"instructions":1000000.0,"wall_min_ms":1.0}}}}"#
    )
}

fn stdout(o: &Output) -> String {
    String::from_utf8_lossy(&o.stdout).into_owned()
}

fn stderr(o: &Output) -> String {
    String::from_utf8_lossy(&o.stderr).into_owned()
}

fn ok(o: &Output) -> &Output {
    assert!(
        o.status.success(),
        "tak failed\nstdout:\n{}\nstderr:\n{}",
        stdout(o),
        stderr(o)
    );
    o
}

fn fail(o: &Output) -> String {
    assert!(
        !o.status.success(),
        "tak should have failed\nstdout:\n{}",
        stdout(o)
    );
    stderr(o)
}

/// Nothing a baseline does may touch the notes ref: it would attach a
/// measurement of an uncommitted tree to a commit, and `tak push` would
/// publish it.
fn assert_no_notes(dir: &Path) {
    assert_eq!(git(dir, &["for-each-ref", "refs/notes"]), "");
}

const NC: &str = "--no-counters";

#[test]
fn a_saved_baseline_is_compared_against_without_writing_notes() {
    let repo = Repo::new();
    let out = tak_run(
        &repo.dir,
        &[NC, "--bench", "startup", "--save-baseline", "before"],
        &["true"],
    );
    assert!(stdout(ok(&out)).contains("saved 1 measurement(s) to baseline `before`"));
    let saved = std::fs::read_to_string(repo.baseline_file("before")).unwrap();
    assert!(saved.contains(r#""bench":"startup""#), "{saved}");
    assert!(saved.contains(r#""runner":"test-runner""#), "{saved}");

    // The edit: same benchmark, different work.
    let out = tak_run(
        &repo.dir,
        &[NC, "--bench", "startup", "--baseline", "before"],
        &["sleep", "0.02"],
    );
    let report = stdout(ok(&out));
    assert!(
        report.contains("compared against baseline `before`"),
        "{report}"
    );
    assert!(report.contains("| startup |"), "{report}");
    // The wall-clock column moved from `true` to a 20ms sleep.
    assert!(report.contains("ms | +"), "{report}");
    assert!(report.contains("Only instruction counts gate"), "{report}");
    assert!(!report.contains("Measured by [tak]"), "{report}");

    assert_no_notes(&repo.dir);
    // Comparing is read-only; the baseline is exactly what was saved.
    assert_eq!(
        std::fs::read_to_string(repo.baseline_file("before")).unwrap(),
        saved
    );
}

/// A mistyped name has to cost a second, not a full run and then an error.
#[test]
fn a_missing_baseline_fails_before_anything_is_measured() {
    let repo = Repo::new();
    ok(&tak_run(
        &repo.dir,
        &[NC, "--save-baseline", "main"],
        &["true"],
    ));
    let marker = repo.dir.join("ran");
    let err = fail(&tak_run(
        &repo.dir,
        &[NC, "--baseline", "mian"],
        &["touch", marker.to_str().unwrap()],
    ));
    assert!(err.contains("no baseline `mian` (saved: main)"), "{err}");
    assert!(
        !marker.exists(),
        "the command ran before the name was checked"
    );
}

#[test]
fn a_name_that_is_not_a_file_name_is_rejected() {
    let repo = Repo::new();
    let err = fail(&tak_run(
        &repo.dir,
        &[NC, "--save-baseline", "../escape"],
        &["true"],
    ));
    assert!(err.contains("invalid baseline name"), "{err}");
    assert!(!repo.dir.join(".git/tak/escape.jsonl").exists());
}

/// No fallback location outside a repository: anywhere else is shared between
/// unrelated projects or may be committed.
#[test]
fn baselines_need_a_git_repository() {
    let tmp = tempfile::tempdir().unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_tak"))
        .args(["run", NC, "--runs", "1", "--warmup", "0"])
        .args(["--save-baseline", "x", "--", "true"])
        .current_dir(tmp.path())
        // Stop git from finding a repository above the scratch directory.
        .env("GIT_CEILING_DIRECTORIES", tmp.path().parent().unwrap())
        .output()
        .unwrap();
    let err = fail(&out);
    assert!(err.contains("need a git repository"), "{err}");
}

#[test]
fn gate_without_a_baseline_is_an_error() {
    let repo = Repo::new();
    let err = fail(&tak_run(&repo.dir, &[NC, "--gate"], &["true"]));
    assert!(err.contains("--gate applies to --baseline"), "{err}");
}

/// A baseline taken on another runner class must not be compared, and must
/// not look like a clean comparison either.
#[test]
fn a_baseline_from_another_runner_is_named_and_not_compared() {
    let repo = Repo::new();
    ok(&tak_run(
        &repo.dir,
        &[NC, "--runner", "laptop", "--save-baseline", "before"],
        &["true"],
    ));
    // Report only: says so, exits 0.
    let out = tak_run(
        &repo.dir,
        &[NC, "--runner", "ci", "--baseline", "before"],
        &["true"],
    );
    let (report, warn) = (stdout(ok(&out)), stderr(&out));
    assert!(report.contains("Nothing was compared"), "{report}");
    assert!(
        warn.contains("holds `default` on `ci` only for runner class `laptop`"),
        "{warn}"
    );
    // Gated: comparing nothing is a failure, not a pass.
    let err = fail(&tak_run(
        &repo.dir,
        &[NC, "--runner", "ci", "--baseline", "before", "--gate"],
        &["true"],
    ));
    assert!(err.contains("nothing to gate"), "{err}");
}

/// Without instruction counts there is nothing a gate may fire on, and a gate
/// that passed anyway would pass every edit.
#[test]
fn a_gate_with_only_wall_clock_fails_rather_than_passing() {
    let repo = Repo::new();
    ok(&tak_run(
        &repo.dir,
        &[NC, "--save-baseline", "b"],
        &["true"],
    ));
    let err = fail(&tak_run(
        &repo.dir,
        &[NC, "--baseline", "b", "--gate"],
        &["true"],
    ));
    assert!(err.contains("nothing to gate"), "{err}");
}

/// Running one benchmark against a baseline saved by several must not report
/// the others as vanished, and saving it must keep them.
#[test]
fn a_subset_run_neither_reports_nor_discards_the_rest() {
    let repo = Repo::new();
    ok(&tak_run(
        &repo.dir,
        &[NC, "--bench", "a", "--save-baseline", "x"],
        &["true"],
    ));
    ok(&tak_run(
        &repo.dir,
        &[NC, "--bench", "b", "--save-baseline", "x"],
        &["true"],
    ));
    let saved = std::fs::read_to_string(repo.baseline_file("x")).unwrap();
    assert_eq!(saved.lines().count(), 2, "{saved}");

    let out = tak_run(
        &repo.dir,
        &[NC, "--bench", "a", "--baseline", "x"],
        &["true"],
    );
    let report = stdout(ok(&out));
    assert!(report.contains("| a |"), "{report}");
    assert!(!report.contains("`b`"), "b was not run: {report}");
}

/// `--record` and `--save-baseline` together write both; the baseline flags
/// alone never write notes (checked in the first test).
#[test]
fn record_and_save_baseline_combine() {
    let repo = Repo::new();
    git(&repo.dir, &["commit", "-q", "--allow-empty", "-m", "init"]);
    let out = tak_run(
        &repo.dir,
        &[NC, "--bench", "s", "--record", "--save-baseline", "x"],
        &["true"],
    );
    let text = stdout(ok(&out));
    assert!(text.contains("recorded 1 measurement(s)"), "{text}");
    assert!(repo.baseline_file("x").exists());
    assert!(
        git(
            &repo.dir,
            &["notes", "--ref", "refs/notes/tak", "show", "HEAD"]
        )
        .contains("\"s\"")
    );
}

/// Baselines live in the common git directory, so a second worktree sees the
/// first's — which is how two branches checked out side by side compare.
#[test]
fn worktrees_share_baselines() {
    let repo = Repo::new();
    git(&repo.dir, &["commit", "-q", "--allow-empty", "-m", "init"]);
    let wt = repo.dir.parent().unwrap().join("wt");
    git(
        &repo.dir,
        &["worktree", "add", "-q", "--detach", wt.to_str().unwrap()],
    );
    ok(&tak_run(
        &repo.dir,
        &[NC, "--save-baseline", "main"],
        &["true"],
    ));
    let out = tak_run(&wt, &[NC, "--baseline", "main"], &["true"]);
    assert!(stdout(ok(&out)).contains("compared against baseline `main`"));
}

/// A benchmark counted in the baseline but not in this run — its count
/// failed, or counters were turned off — has not been checked, so a gate
/// that passed would be vouching for it anyway.
#[test]
fn a_gate_fails_when_a_counted_benchmark_went_uncounted() {
    let repo = Repo::new();
    write_baseline(&repo, "x", &[&counted_line("a"), &counted_line("b")]);
    let out = tak_run(
        &repo.dir,
        &[NC, "--bench", "a", "--baseline", "x", "--gate"],
        &["true"],
    );
    let err = fail(&out);
    assert!(
        err.contains("`a` on `test-runner` (not counted in this run)"),
        "{err}"
    );
    assert!(
        stdout(&out).contains("Not gated: `a` on `test-runner` (not counted in this run)"),
        "{}",
        stdout(&out)
    );
    // Report only: said, not failed.
    ok(&tak_run(
        &repo.dir,
        &[NC, "--bench", "a", "--baseline", "x"],
        &["true"],
    ));
}

/// A gate that measured nothing has checked nothing. `git bisect run` would
/// otherwise mark the revision good.
#[test]
fn a_gate_with_nothing_to_run_fails() {
    let repo = Repo::new();
    write_baseline(&repo, "x", &[&counted_line("off")]);

    std::fs::write(
        repo.dir.join("tak.toml"),
        "[bench.off]\ncmd = \"true\"\nwhen = \"false\"\n",
    )
    .unwrap();
    let err = fail(&tak_run(&repo.dir, &["--baseline", "x", "--gate"], &[]));
    assert!(
        err.contains("nothing to gate against baseline `x`"),
        "{err}"
    );
    assert!(err.contains("false `when`"), "{err}");
    ok(&tak_run(&repo.dir, &["--baseline", "x"], &[]));

    std::fs::write(repo.dir.join("tak.toml"), "").unwrap();
    let err = fail(&tak_run(&repo.dir, &["--baseline", "x", "--gate"], &[]));
    assert!(err.contains("declares no benchmarks"), "{err}");
}

/// A subject whose check fails usually got faster by skipping its work. The
/// report has to say so beside the table, and a gate must not pass it.
#[test]
fn a_failed_check_is_flagged_and_fails_the_gate() {
    let repo = Repo::new();
    write_baseline(&repo, "x", &[&counted_line("c")]);
    std::fs::write(
        repo.dir.join("tak.toml"),
        "[bench.c]\ncmd = \"true\"\ncheck = \"false\"\n",
    )
    .unwrap();

    let out = tak_run(&repo.dir, &[NC, "--baseline", "x"], &[]);
    let report = stdout(ok(&out));
    assert!(
        report.contains(
            "Check failed, so this comparison is not evidence of an improvement:** c failed 3 of 3"
        ),
        "{report}"
    );

    let err = fail(&tak_run(&repo.dir, &[NC, "--baseline", "x", "--gate"], &[]));
    assert!(err.contains("check failed, so nothing is gated"), "{err}");
}

/// The baseline is written before the notes, and a failed recording says the
/// baseline was saved, so a retry of the same command is the whole fix.
#[test]
fn a_failed_record_after_a_saved_baseline_says_which_was_written() {
    // No commit: there is no HEAD to record against.
    let repo = Repo::new();
    let err = fail(&tak_run(
        &repo.dir,
        &[NC, "--record", "--save-baseline", "x"],
        &["true"],
    ));
    assert!(
        err.contains("baseline `x` was saved, but nothing was recorded"),
        "{err}"
    );
    assert!(repo.baseline_file("x").exists());
    assert_no_notes(&repo.dir);
}

/// Several processes saving different benchmarks to one baseline at once, as
/// parallel worktrees do, keep every benchmark.
#[test]
fn concurrent_saves_from_separate_processes_keep_every_benchmark() {
    let repo = Repo::new();
    let children: Vec<_> = (0..6)
        .map(|i| {
            Command::new(env!("CARGO_BIN_EXE_tak"))
                .args(["run", NC, "--no-progress", "--runs", "1", "--warmup", "0"])
                .args(["--bench", &format!("b{i}"), "--save-baseline", "x"])
                .args(["--", "true"])
                .current_dir(&repo.dir)
                .stdout(std::process::Stdio::null())
                .spawn()
                .unwrap()
        })
        .collect();
    for mut c in children {
        assert!(c.wait().unwrap().success());
    }
    let saved = std::fs::read_to_string(repo.baseline_file("x")).unwrap();
    assert_eq!(saved.lines().count(), 6, "{saved}");
}

/// The gate itself, on real instruction counts. Skips without valgrind, the
/// normal state on macOS and Windows.
#[test]
fn the_gate_fires_on_an_instruction_count_regression() {
    if !tak_cli::measure::valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let repo = Repo::new();
    let quick = ["sh", "-c", "exit 0"];
    // Enough shell arithmetic to retire far more than 1% extra instructions.
    let slow = [
        "sh",
        "-c",
        "i=0; while [ $i -lt 20000 ]; do i=$((i+1)); done",
    ];
    ok(&tak_run(
        &repo.dir,
        &["--bench", "loop", "--save-baseline", "b"],
        &quick,
    ));

    // Same work: the gate passes.
    let out = tak_run(
        &repo.dir,
        &["--bench", "loop", "--baseline", "b", "--gate"],
        &quick,
    );
    assert!(stdout(ok(&out)).contains("No instruction-count regression"));

    // More work: reported, and failed.
    let out = tak_run(
        &repo.dir,
        &["--bench", "loop", "--baseline", "b", "--gate"],
        &slow,
    );
    let err = fail(&out);
    assert!(err.contains("regressed by more than"), "{err}");
    assert!(
        stdout(&out).contains("above the 1% gate"),
        "{}",
        stdout(&out)
    );

    // Without --gate the same regression is reported and exits 0.
    ok(&tak_run(
        &repo.dir,
        &["--bench", "loop", "--baseline", "b"],
        &slow,
    ));
    assert_no_notes(&repo.dir);

    // Saving over `b` on a failed gate keeps `b`, so a retry fails again
    // rather than comparing the regression with itself.
    let replace = [
        "--bench",
        "loop",
        "--baseline",
        "b",
        "--save-baseline",
        "b",
        "--gate",
    ];
    for _ in 0..2 {
        let err = fail(&tak_run(&repo.dir, &replace, &slow));
        assert!(err.contains("regressed by more than"), "{err}");
        assert!(err.contains("baseline `b` was not replaced"), "{err}");
    }
}

/// The partial case on real counts: `a` compares cleanly, `b` was counted in
/// the baseline and not now. Passing on `a` alone would leave `b` unchecked.
#[test]
fn a_gate_that_could_check_only_some_benchmarks_fails() {
    if !tak_cli::measure::valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let repo = Repo::new();
    let toml = |b_counters: bool| {
        format!(
            "[bench.m.subject.a]\ncmd = [\"sh\", \"-c\", \"exit 0\"]\ncounters = true\n\n\
             [bench.m.subject.b]\ncmd = [\"sh\", \"-c\", \"exit 0\"]\ncounters = {b_counters}\n"
        )
    };
    std::fs::write(repo.dir.join("tak.toml"), toml(true)).unwrap();
    ok(&tak_run(&repo.dir, &["--save-baseline", "x"], &[]));
    ok(&tak_run(&repo.dir, &["--baseline", "x", "--gate"], &[]));

    std::fs::write(repo.dir.join("tak.toml"), toml(false)).unwrap();
    let err = fail(&tak_run(&repo.dir, &["--baseline", "x", "--gate"], &[]));
    assert!(
        err.contains("`m` (b) on `test-runner` (not counted in this run)"),
        "{err}"
    );
}

/// A baseline saved on two runner classes gates on either one against its
/// own series, and fails on a third with the classes it does hold named.
#[test]
fn a_baseline_saved_on_two_runners_gates_on_each() {
    if !tak_cli::measure::valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let repo = Repo::new();
    let cmd = ["sh", "-c", "exit 0"];
    for runner in ["r1", "r2"] {
        ok(&tak_run(
            &repo.dir,
            &["--runner", runner, "--bench", "s", "--save-baseline", "x"],
            &cmd,
        ));
    }
    for runner in ["r1", "r2"] {
        let out = tak_run(
            &repo.dir,
            &[
                "--runner",
                runner,
                "--bench",
                "s",
                "--baseline",
                "x",
                "--gate",
            ],
            &cmd,
        );
        let report = stdout(ok(&out));
        assert!(
            report.contains("No instruction-count regression"),
            "{report}"
        );
        assert!(
            !stderr(&out).contains("only for runner class"),
            "{}",
            stderr(&out)
        );
    }
    let err = fail(&tak_run(
        &repo.dir,
        &[
            "--runner",
            "r3",
            "--bench",
            "s",
            "--baseline",
            "x",
            "--gate",
        ],
        &cmd,
    ));
    assert!(
        err.contains("`s` on `r3` (saved only on runner class `r1`, `r2`)"),
        "{err}"
    );
}

/// The same, without valgrind: a hand-written baseline on two classes, and a
/// run on a third that counts nothing, is reported as another class's data
/// and not compared.
#[test]
fn a_baseline_on_two_other_runners_is_named_and_not_compared() {
    let repo = Repo::new();
    let line = |runner: &str| counted_line("s").replace("test-runner", runner);
    write_baseline(&repo, "x", &[&line("r1"), &line("r2")]);
    let out = tak_run(
        &repo.dir,
        &[NC, "--runner", "r3", "--bench", "s", "--baseline", "x"],
        &["true"],
    );
    ok(&out);
    assert!(
        stderr(&out).contains("holds `s` on `r3` only for runner class `r1`, `r2`"),
        "{}",
        stderr(&out)
    );
    assert!(
        stdout(&out).contains("Nothing was compared"),
        "{}",
        stdout(&out)
    );
}

/// An ad-hoc `tak run -- CMD` never depended on the declared benchmarks, and
/// `--baseline` must not make it: a broken, unrelated `[bench.x]` does not
/// stop the report. `--gate` is different: its verdict needs the real gates.
#[test]
fn an_invalid_unrelated_benchmark_does_not_block_an_ad_hoc_baseline_run() {
    let repo = Repo::new();
    std::fs::write(
        repo.dir.join("tak.toml"),
        "[bench.broken]\nruns = \"lots\"\n",
    )
    .unwrap();
    // The premise: a plain ad-hoc run ignores the broken benchmark.
    ok(&tak_run(&repo.dir, &[NC, "--bench", "s"], &["true"]));

    ok(&tak_run(
        &repo.dir,
        &[NC, "--bench", "s", "--save-baseline", "x"],
        &["true"],
    ));
    let out = tak_run(
        &repo.dir,
        &[NC, "--bench", "s", "--baseline", "x"],
        &["true"],
    );
    assert!(stdout(ok(&out)).contains("compared against baseline `x`"));
    assert!(
        !stderr(&out).contains("per-benchmark gates"),
        "{}",
        stderr(&out)
    );

    // Gated: the verdict needs the file's gates, so a file that will not
    // load fails the run up front — the command never runs — rather than
    // gating against a threshold the project did not choose.
    let marker = repo.dir.join("ran");
    let out = tak_run(
        &repo.dir,
        &[NC, "--bench", "s", "--baseline", "x", "--gate"],
        &["touch", marker.to_str().unwrap()],
    );
    let err = fail(&out);
    assert!(
        err.contains("--gate needs a valid tak.toml to find per-benchmark gates"),
        "{err}"
    );
    assert!(err.contains("broken"), "the config error is shown: {err}");
    assert!(!err.contains("nothing to gate"), "{err}");
    assert!(
        !marker.exists(),
        "the command ran before the file was checked"
    );
}

/// Saving over the baseline a run was gated against, when the gate fails,
/// would make a retry compare the failure with itself and pass. So the
/// baseline is kept, and the error says so. Another name is saved as usual.
#[test]
fn a_failed_gate_does_not_replace_the_baseline_it_was_gated_against() {
    let repo = Repo::new();
    write_baseline(&repo, "good", &[&counted_line("s")]);
    let before = std::fs::read_to_string(repo.baseline_file("good")).unwrap();

    // No counters here, so the gate fails: `s` is not counted in this run.
    let flags = [NC, "--bench", "s", "--baseline", "good", "--gate"];
    let err = fail(&tak_run(
        &repo.dir,
        &[&flags[..], &["--save-baseline", "good"]].concat(),
        &["true"],
    ));
    assert!(
        err.contains("baseline `good` was not replaced because the gate failed"),
        "{err}"
    );
    assert!(err.contains("not counted in this run"), "{err}");
    assert_eq!(
        std::fs::read_to_string(repo.baseline_file("good")).unwrap(),
        before
    );

    let err = fail(&tak_run(
        &repo.dir,
        &[&flags[..], &["--save-baseline", "other"]].concat(),
        &["true"],
    ));
    assert!(!err.contains("was not replaced"), "{err}");
    assert!(repo.baseline_file("other").exists());
}

/// A shell loop of `n` iterations: about 11,500 instructions each, so 2000
/// against 2500 is a rise of roughly 25% and 5.8M instructions.
fn shell_loop(n: u32) -> String {
    format!(r#"["sh", "-c", "i=0; while [ $i -lt {n} ]; do i=$((i+1)); done"]"#)
}

/// `--baseline --gate` holds each benchmark to its own gate, as `tak compare`
/// does: a loosened `pct` absorbs a rise, a report-only benchmark never
/// fails, and the global `min_delta` floor applies.
#[test]
fn a_baseline_gate_holds_each_benchmark_to_its_own_gate() {
    if !tak_cli::measure::valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let repo = Repo::new();
    let toml = |strict: u32, other: u32| {
        format!(
            "[bench.strict]\ncmd = {}\n\n\
             [bench.loose]\ncmd = {}\ngate = {{ pct = 50.0 }}\n\n\
             [bench.watch]\ncmd = {}\ngate = {{ enabled = false }}\n",
            shell_loop(strict),
            shell_loop(other),
            shell_loop(other)
        )
    };
    let write =
        |strict, other| std::fs::write(repo.dir.join("tak.toml"), toml(strict, other)).unwrap();

    write(2000, 2000);
    ok(&tak_run(&repo.dir, &["--save-baseline", "x"], &[]));

    // `loose` and `watch` rise ~25%: within 50%, and report only.
    write(2000, 2500);
    let out = tak_run(&repo.dir, &["--baseline", "x", "--gate"], &[]);
    let report = stdout(ok(&out));
    assert!(report.contains("report only"), "{report}");

    // `strict` rises too, past the global 1%.
    write(2500, 2500);
    let err = fail(&tak_run(&repo.dir, &["--baseline", "x", "--gate"], &[]));
    assert!(
        err.contains("1 benchmark(s) regressed beyond their gate against baseline `x`"),
        "{err}"
    );

    // A floor above the rise lets it through.
    ok(&tak_run(
        &repo.dir,
        &["--baseline", "x", "--gate", "--gate-min-delta", "100000000"],
        &[],
    ));
}

/// A subject this run did not count, whose count the baseline holds only for
/// another runner class, must not be skipped while its neighbour passes.
#[test]
fn an_uncounted_subject_counted_only_on_another_runner_fails_the_gate() {
    if !tak_cli::measure::valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let repo = Repo::new();
    let toml = |b_counters: bool| {
        format!(
            "[bench.m.subject.a]\ncmd = [\"sh\", \"-c\", \"exit 0\"]\ncounters = true\n\n\
             [bench.m.subject.b]\ncmd = [\"sh\", \"-c\", \"exit 0\"]\ncounters = {b_counters}\n"
        )
    };
    std::fs::write(repo.dir.join("tak.toml"), toml(true)).unwrap();
    // Both subjects on `r1`; only `a` on `r2`.
    ok(&tak_run(
        &repo.dir,
        &["--runner", "r1", "--save-baseline", "x"],
        &[],
    ));
    ok(&tak_run(
        &repo.dir,
        &["--runner", "r2", "--subject", "a", "--save-baseline", "x"],
        &[],
    ));

    std::fs::write(repo.dir.join("tak.toml"), toml(false)).unwrap();
    let err = fail(&tak_run(
        &repo.dir,
        &["--runner", "r2", "--baseline", "x", "--gate"],
        &[],
    ));
    assert!(
        err.contains(
            "`m` (b) on `r2` (not counted in this run, and counted in the baseline only on \
             runner class `r1`)"
        ),
        "{err}"
    );
}

/// The same gap, reported without valgrind: nothing is counted here, and the
/// baseline counted the benchmark only on another class.
#[test]
fn an_uncounted_benchmark_counted_only_elsewhere_is_reported() {
    let repo = Repo::new();
    write_baseline(
        &repo,
        "x",
        &[&counted_line("s").replace("test-runner", "r1")],
    );
    let out = tak_run(
        &repo.dir,
        &[NC, "--runner", "r2", "--bench", "s", "--baseline", "x"],
        &["true"],
    );
    assert!(
        stdout(ok(&out)).contains(
            "Not gated: `s` on `r2` (not counted in this run, and counted in the baseline \
             only on runner class `r1`)"
        ),
        "{}",
        stdout(&out)
    );
}

/// A report-only benchmark's failed check is still flagged, but does not fail
/// the gate on its own; a gated one's does.
#[test]
fn a_report_only_failed_check_is_flagged_not_failed() {
    if !tak_cli::measure::valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let repo = Repo::new();
    let toml = |check: &str| {
        format!(
            "[bench.gated]\ncmd = [\"sh\", \"-c\", \"exit 0\"]\n\n\
             [bench.watch]\ncmd = [\"sh\", \"-c\", \"exit 0\"]\ncheck = \"{check}\"\n\
             gate = {{ enabled = false }}\n"
        )
    };
    std::fs::write(repo.dir.join("tak.toml"), toml("true")).unwrap();
    ok(&tak_run(&repo.dir, &["--save-baseline", "x"], &[]));

    std::fs::write(repo.dir.join("tak.toml"), toml("false")).unwrap();
    let out = tak_run(&repo.dir, &["--baseline", "x", "--gate"], &[]);
    assert!(
        stdout(ok(&out)).contains("Check failed"),
        "{}",
        stdout(&out)
    );
}

/// A failed metric stops a baseline being saved as it stops `--record`: a
/// baseline missing a declared metric would be compared against as if the
/// metric had been removed. An existing baseline of that name is left alone.
#[test]
fn a_failing_metric_saves_no_baseline() {
    let repo = Repo::new();
    std::fs::write(
        repo.dir.join("tak.toml"),
        "[bench.startup]\ncmd = \"true\"\n[bench.startup.metric.binary_bytes]\nfile = \"bin\"\n",
    )
    .unwrap();
    std::fs::write(repo.dir.join("bin"), vec![0u8; 100]).unwrap();
    ok(&tak_run(&repo.dir, &[NC, "--save-baseline", "before"], &[]));
    let saved = std::fs::read_to_string(repo.baseline_file("before")).unwrap();
    assert!(saved.contains(r#""binary_bytes":100.0"#), "{saved}");

    std::fs::remove_file(repo.dir.join("bin")).unwrap();
    let err = fail(&tak_run(&repo.dir, &[NC, "--save-baseline", "before"], &[]));
    assert!(
        err.contains("not saving baseline `before`: a run missing a declared metric"),
        "{err}"
    );
    assert!(err.contains("1 metric(s) failed"), "{err}");
    assert_eq!(
        std::fs::read_to_string(repo.baseline_file("before")).unwrap(),
        saved,
        "the earlier baseline was replaced"
    );
    let err = fail(&tak_run(&repo.dir, &[NC, "--save-baseline", "after"], &[]));
    assert!(err.contains("not saving baseline `after`"), "{err}");
    assert!(!repo.baseline_file("after").exists());
    assert_no_notes(&repo.dir);
}

/// A baseline report shares `compare`'s renderer, custom-metrics table
/// included.
#[test]
fn a_baseline_report_shows_custom_metrics() {
    let repo = Repo::new();
    std::fs::write(
        repo.dir.join("tak.toml"),
        "[bench.startup]\ncmd = \"true\"\n[bench.startup.metric.binary_bytes]\nfile = \"bin\"\n",
    )
    .unwrap();
    std::fs::write(repo.dir.join("bin"), vec![0u8; 1000]).unwrap();
    ok(&tak_run(&repo.dir, &[NC, "--save-baseline", "before"], &[]));
    std::fs::write(repo.dir.join("bin"), vec![0u8; 1500]).unwrap();
    let out = tak_run(&repo.dir, &[NC, "--baseline", "before"], &[]);
    let report = stdout(ok(&out));
    assert!(
        report.contains("| startup | binary_bytes | 1,000 → 1,500 | +50.00% |"),
        "{report}"
    );
}

/// Report-only benchmarks never fail `--gate`, including when none of them
/// has an instruction count to compare. The run passes and says nothing was
/// gated, rather than failing for want of a count it was never going to gate.
#[test]
fn a_gate_over_only_report_only_benchmarks_passes_and_says_so() {
    let repo = Repo::new();
    std::fs::write(
        repo.dir.join("tak.toml"),
        "[bench.w]\ncmd = \"true\"\ngate = { enabled = false }\n",
    )
    .unwrap();
    ok(&tak_run(&repo.dir, &[NC, "--save-baseline", "x"], &[]));
    let out = tak_run(&repo.dir, &[NC, "--baseline", "x", "--gate"], &[]);
    assert!(
        stderr(ok(&out)).contains(
            "nothing was gated against baseline `x`: every benchmark measured is report-only"
        ),
        "{}",
        stderr(&out)
    );
}

/// A baseline holding a newer tak's records is not saved over, and that is
/// decided before anything is measured.
#[test]
fn saving_over_a_newer_schema_baseline_fails_before_measuring() {
    let repo = Repo::new();
    let newer = counted_line("s").replace(r#""v":1"#, r#""v":99"#);
    write_baseline(&repo, "x", &[&newer]);
    let before = std::fs::read_to_string(repo.baseline_file("x")).unwrap();
    let marker = repo.dir.join("ran");
    let err = fail(&tak_run(
        &repo.dir,
        &[NC, "--bench", "s", "--save-baseline", "x"],
        &["touch", marker.to_str().unwrap()],
    ));
    assert!(
        err.contains("holds records from a newer tak (schema 99"),
        "{err}"
    );
    assert!(
        !marker.exists(),
        "the command ran before the file was checked"
    );
    assert_eq!(
        std::fs::read_to_string(repo.baseline_file("x")).unwrap(),
        before
    );
}

/// A command that exits 3 under valgrind and 0 otherwise: its timed samples
/// pass, and its instruction count fails. Valgrind's tool is mapped into the
/// shell's address space; the `grep` it spawns runs natively and sees it.
const FAILS_UNDER_VALGRIND: &str =
    r#"["sh", "-c", "grep -q -e cachegrind -e valgrind /proc/$$/maps && exit 3; exit 0"]"#;

/// A benchmark added since the baseline, whose count was asked for and
/// failed, is a gap: it used to be skipped as though counters were off by
/// design, and `--gate` passed on the strength of the others.
#[test]
fn a_new_benchmark_whose_count_failed_fails_the_gate() {
    if !tak_cli::measure::valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let repo = Repo::new();
    std::fs::write(
        repo.dir.join("tak.toml"),
        format!(
            "[bench.a]\ncmd = [\"sh\", \"-c\", \"exit 0\"]\n\n\
             [bench.new]\ncmd = {FAILS_UNDER_VALGRIND}\n"
        ),
    )
    .unwrap();
    ok(&tak_run(
        &repo.dir,
        &["--bench", "a", "--save-baseline", "x"],
        &[],
    ));
    let err = fail(&tak_run(&repo.dir, &["--baseline", "x", "--gate"], &[]));
    assert!(err.contains("instruction counting failed:"), "{err}");
    assert!(
        err.contains("`new` on `test-runner` (instruction counting failed in this run)"),
        "{err}"
    );
}

/// Counts compared, but only for a report-only subject; the gated one is
/// wall-clock only by design. That passes, and says nothing was gated.
#[test]
fn only_report_only_counts_compared_passes_and_says_so() {
    if !tak_cli::measure::valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let repo = Repo::new();
    std::fs::write(
        repo.dir.join("tak.toml"),
        "[bench.m.subject.a]\ncmd = [\"sh\", \"-c\", \"exit 0\"]\ncounters = true\n\
         gate = { enabled = false }\n\n\
         [bench.m.subject.b]\ncmd = [\"sh\", \"-c\", \"exit 0\"]\n",
    )
    .unwrap();
    ok(&tak_run(&repo.dir, &["--save-baseline", "x"], &[]));
    let out = tak_run(&repo.dir, &["--baseline", "x", "--gate"], &[]);
    assert!(
        stderr(ok(&out)).contains("every benchmark compared by instruction count is report-only"),
        "{}",
        stderr(&out)
    );
}

const ALLOW: &str = "[gate]\nallow_empty = true\n";

/// The line `allow_empty` adds to a report it let through.
const ALLOWED: &str = "passes with a warning instead of failing, because `allow_empty` is on";

/// The runner-class churn case against a baseline: saved on one class, gated
/// on another, so nothing is on both sides. `[gate] allow_empty = true` passes
/// it with the report's line and one warning; off, it fails as before; the
/// environment and the flag override the file as for every gate setting.
#[test]
fn allow_empty_passes_an_empty_baseline_gate_with_a_warning() {
    let repo = Repo::new();
    ok(&tak_run(
        &repo.dir,
        &[NC, "--runner", "laptop", "--save-baseline", "before"],
        &["true"],
    ));
    let gate = [NC, "--runner", "ci", "--baseline", "before", "--gate"];
    let err = fail(&tak_run(&repo.dir, &gate, &["true"]));
    assert!(err.contains("nothing to gate"), "{err}");

    std::fs::write(repo.dir.join("tak.toml"), ALLOW).unwrap();
    let out = tak_run(&repo.dir, &gate, &["true"]);
    let report = stdout(ok(&out));
    assert!(
        report
            .lines()
            .any(|l| l.starts_with("**Nothing was compared, and so nothing was gated.**")),
        "{report}"
    );
    assert!(report.contains(ALLOWED), "{report}");
    assert!(
        stderr(&out).contains(
            "warning: nothing was compared against baseline `before`; passing because \
             `allow_empty` is on\n"
        ),
        "{}",
        stderr(&out)
    );

    // Without --gate there is nothing to waive, so the report does not claim it.
    let out = tak_run(
        &repo.dir,
        &[NC, "--runner", "ci", "--baseline", "before"],
        &["true"],
    );
    assert!(!stdout(ok(&out)).contains(ALLOWED), "{}", stdout(&out));
    assert!(!stderr(&out).contains("allow_empty"), "{}", stderr(&out));

    let err = fail(&tak_run_env(
        &repo.dir,
        &gate,
        &["true"],
        &[("TAK_ALLOW_EMPTY", "0")],
    ));
    assert!(err.contains("nothing to gate"), "{err}");

    std::fs::remove_file(repo.dir.join("tak.toml")).unwrap();
    let mut flagged = gate.to_vec();
    flagged.push("--allow-empty");
    ok(&tak_run_env(
        &repo.dir,
        &flagged,
        &["true"],
        &[("TAK_ALLOW_EMPTY", "0")],
    ));
}

/// Only the empty case is waived. Wall clock compared on both sides is not
/// empty, and a gate with no instruction count to check still fails.
#[test]
fn allow_empty_does_not_waive_a_wall_clock_only_gate() {
    let repo = Repo::new();
    std::fs::write(repo.dir.join("tak.toml"), ALLOW).unwrap();
    ok(&tak_run(
        &repo.dir,
        &[NC, "--save-baseline", "b"],
        &["true"],
    ));
    let out = tak_run(&repo.dir, &[NC, "--baseline", "b", "--gate"], &["true"]);
    let err = fail(&out);
    assert!(err.contains("nothing to gate"), "{err}");
    assert!(!stdout(&out).contains(ALLOWED), "{}", stdout(&out));
}

/// A failed check is this run doing the wrong work, not history that is
/// missing, so it fails the gate even when nothing was compared.
#[test]
fn allow_empty_does_not_waive_a_failed_check() {
    let repo = Repo::new();
    let elsewhere = counted_line("c").replace("test-runner", "other");
    write_baseline(&repo, "x", &[&elsewhere]);
    std::fs::write(
        repo.dir.join("tak.toml"),
        format!("{ALLOW}\n[bench.c]\ncmd = \"true\"\ncheck = \"false\"\n"),
    )
    .unwrap();
    let out = tak_run(&repo.dir, &[NC, "--baseline", "x", "--gate"], &[]);
    let err = fail(&out);
    assert!(err.contains("check failed, so nothing is gated"), "{err}");
    assert!(!stdout(&out).contains(ALLOWED), "{}", stdout(&out));
}

/// The same on real counts: counted here, saved only on another runner class.
/// That is one gap per series, and `allow_empty` passes it.
#[test]
fn allow_empty_passes_a_counted_run_against_another_runners_baseline() {
    if !tak_cli::measure::valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let repo = Repo::new();
    let cmd = ["sh", "-c", "exit 0"];
    ok(&tak_run(
        &repo.dir,
        &["--runner", "old", "--bench", "s", "--save-baseline", "x"],
        &cmd,
    ));
    let gate = [
        "--runner",
        "new",
        "--bench",
        "s",
        "--baseline",
        "x",
        "--gate",
    ];
    let err = fail(&tak_run(&repo.dir, &gate, &cmd));
    assert!(err.contains("saved only on runner class `old`"), "{err}");

    std::fs::write(repo.dir.join("tak.toml"), ALLOW).unwrap();
    let out = tak_run(&repo.dir, &gate, &cmd);
    assert!(stdout(ok(&out)).contains(ALLOWED), "{}", stdout(&out));
    assert!(
        stderr(&out).contains("passing because `allow_empty` is on"),
        "{}",
        stderr(&out)
    );
}

/// A regression against the baseline still fails with the setting on.
#[test]
fn allow_empty_still_fails_a_baseline_regression() {
    if !tak_cli::measure::valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let repo = Repo::new();
    std::fs::write(repo.dir.join("tak.toml"), ALLOW).unwrap();
    let quick = ["sh", "-c", "exit 0"];
    let slow = [
        "sh",
        "-c",
        "i=0; while [ $i -lt 20000 ]; do i=$((i+1)); done",
    ];
    ok(&tak_run(
        &repo.dir,
        &["--bench", "loop", "--save-baseline", "b"],
        &quick,
    ));
    let out = tak_run(
        &repo.dir,
        &["--bench", "loop", "--baseline", "b", "--gate"],
        &slow,
    );
    let err = fail(&out);
    assert!(err.contains("regressed by more than"), "{err}");
    assert!(!err.contains("allow_empty"), "{err}");
}

/// A count that failed is this run's measurement breaking, so it fails the
/// gate with the setting on even when nothing else could be compared.
#[test]
fn allow_empty_does_not_waive_a_failed_count() {
    if !tak_cli::measure::valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let repo = Repo::new();
    std::fs::write(
        repo.dir.join("tak.toml"),
        format!(
            "{ALLOW}\n[bench.a]\ncmd = [\"sh\", \"-c\", \"exit 0\"]\n\n\
             [bench.new]\ncmd = {FAILS_UNDER_VALGRIND}\n"
        ),
    )
    .unwrap();
    ok(&tak_run(
        &repo.dir,
        &["--bench", "a", "--save-baseline", "x"],
        &[],
    ));
    let out = tak_run(
        &repo.dir,
        &["--bench", "new", "--baseline", "x", "--gate"],
        &[],
    );
    let err = fail(&out);
    assert!(
        err.contains("`new` on `test-runner` (instruction counting failed in this run)"),
        "{err}"
    );
    assert!(!stdout(&out).contains(ALLOWED), "{}", stdout(&out));
}