tak-cli 0.0.15

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
//! Integration tests for the deterministic-metric path.
//!
//! `measure::instructions` was written, unit-tested at the parser level, and
//! then shipped without the cachegrind call ever executing once — valgrind was
//! simply absent from the machine it was developed on. These tests exist so CI
//! exercises the real subprocess, and so the determinism claim the whole project
//! rests on is asserted rather than assumed.
//!
//! Every test skips cleanly when valgrind is unavailable, because that is the
//! normal state on macOS and Windows.

use tak_cli::measure::{self, Plan};
use tak_cli::settings::Settings;

use tak_cli::measure::valgrind_available;

/// A command that exists on the host and does a trivial, fixed amount of work.
///
/// Absolute path on unix so no shell or PATH lookup is involved; on Windows
/// there is no `/bin/echo`, and no cachegrind either, so the counter tests skip
/// and only the wall-clock test needs a working subject.
fn subject() -> Vec<String> {
    #[cfg(unix)]
    {
        vec!["/bin/echo".to_string(), "tak".to_string()]
    }
    #[cfg(windows)]
    {
        vec!["cmd".to_string(), "/C".to_string(), "echo tak".to_string()]
    }
}

#[test]
fn instructions_are_reported_when_valgrind_exists() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let c = measure::instructions(&subject(), None, &Settings::default())
        .expect("cachegrind invocation failed")
        .expect("valgrind present but no I refs parsed");

    // A dynamically linked process cannot retire a trivially small number of
    // instructions; anything tiny means we parsed the wrong thing.
    assert!(
        c.min > 10_000,
        "implausibly low instruction count: {}",
        c.min
    );
    assert!(c.max >= c.min);
    assert!(
        c.runs >= 2,
        "a single sample cannot detect a varying subject"
    );
}

/// The claim the CI gate depends on: repeated runs of an identical command
/// return identical counts.
///
/// Wall clock on the same machine varies by 4-20%; if this metric drifted at
/// all, gating at 1% would be meaningless.
#[test]
fn instruction_counts_are_deterministic() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let cmd = subject();
    // `instructions` already samples repeatedly; doing it again covers variation
    // across separate invocations too, not just within one.
    let outer: Vec<_> = (0..2)
        .map(|_| {
            measure::instructions(&cmd, None, &Settings::default())
                .expect("cachegrind invocation failed")
                .expect("no I refs parsed")
        })
        .collect();

    let min = outer.iter().map(|c| c.min).min().unwrap();
    let max = outer.iter().map(|c| c.max).max().unwrap();
    let spread = (max - min) as f64 / min as f64 * 100.0;

    assert!(
        spread < 0.1,
        "instruction counts varied by {spread:.4}% — the deterministic-gate \
         premise does not hold on this platform"
    );
    // /bin/echo is hermetic, so nothing here should look suspect.
    assert!(outer.iter().all(|c| !c.is_suspect()));
}

/// The two "no counters" outcomes must stay distinguishable: a missing valgrind
/// is `Ok(None)`, while valgrind failing mid-measurement is an error. Reporting
/// the latter as the former sends people installing what they already have.
#[test]
fn availability_and_failure_are_distinct() {
    if valgrind_available() {
        // A command that cannot be spawned makes cachegrind fail rather than
        // vanish, so this must be an error rather than Ok(None).
        let bogus = vec!["/nonexistent/tak-not-a-real-binary".to_string()];
        assert!(
            measure::instructions(&bogus, None, &Settings::default()).is_err(),
            "a failed measurement must not look like a missing valgrind"
        );
    } else {
        assert!(
            measure::instructions(&subject(), None, &Settings::default())
                .unwrap()
                .is_none()
        );
    }
}

/// A subject that starts and then exits unsuccessfully still emits an instruction
/// summary. Checking only for that summary records a crash as an improvement.
#[test]
fn a_nonzero_subject_is_not_counted() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let cmd = vec![
        "/bin/sh".to_string(),
        "-c".to_string(),
        "exit 42".to_string(),
    ];
    let err = measure::instructions(&cmd, None, &Settings::default()).unwrap_err();
    assert!(format!("{err:#}").contains("exited with"), "{err:#}");
}

/// Absence of valgrind must degrade to timing-only, never fail the run.
#[test]
fn missing_valgrind_is_not_an_error() {
    if valgrind_available() {
        eprintln!("skipping: valgrind is installed, cannot test its absence");
        return;
    }
    let got = measure::instructions(&subject(), None, &Settings::default())
        .expect("must not error when valgrind is absent");
    assert!(got.is_none());
}

/// Wall-clock measurement works everywhere, with or without counters.
#[test]
fn wall_clock_works_without_counters() {
    let m = measure::wall(&Plan {
        cmd: subject(),
        warmup: 1,
        runs: 3,
        dir: None,
        settings: Settings::default(),
    })
    .expect("wall measurement failed");

    assert_eq!(m["wall_n"], 3.0);
    assert!(m["wall_min_ms"] <= m["wall_p50_ms"]);
    assert!(m["wall_p50_ms"] <= m["wall_max_ms"]);
    assert!(m["wall_min_ms"] > 0.0);
}

/// A declared subject's prepare step runs before every cachegrind run, and its
/// env reaches the subject under valgrind — each counted run has to start from
/// the same state the timed samples did. Its check does not run.
#[cfg(unix)]
#[test]
fn a_subject_is_prepared_before_every_counted_run() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let dir = std::env::temp_dir().join(format!("tak-counters-prep-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();

    let s = tak_cli::config::Subject {
        name: "x".into(),
        cmd: ["/bin/sh", "-c", "echo \"run:$MARK\" >> log"]
            .map(String::from)
            .to_vec(),
        prepare: Some(
            ["/bin/sh", "-c", "echo prep >> log"]
                .map(String::from)
                .to_vec(),
        ),
        setup: None,
        setup_dir: None,
        // Never run under cachegrind: those runs are not samples anyone
        // reports, so the log below has no `check` line.
        check: Some(
            ["/bin/sh", "-c", "echo check >> log"]
                .map(String::from)
                .to_vec(),
        ),
        dir: Some(dir.clone()),
        version_cmd: None,
        env: [("MARK".to_string(), "set".to_string())].into(),
        vars: Default::default(),
        when: None,
        runs: tak_cli::config::Runs::Fixed(1),
        auto: tak_cli::config::AutoRuns {
            budget: std::time::Duration::from_secs(30),
            min: 5,
            max: 50,
        },
        warmup: 0,
        counters: true,
        allocations: false,
        ok_exit_codes: vec![0],
        metrics: std::collections::BTreeMap::new(),
    };
    let c = measure::subject_instructions(&s, &Settings::default())
        .expect("cachegrind invocation failed")
        .expect("valgrind present but no I refs parsed");
    assert!(
        c.min > 10_000,
        "implausibly low instruction count: {}",
        c.min
    );

    let log = std::fs::read_to_string(dir.join("log")).unwrap();
    let expected = "prep\nrun:set\n".repeat(c.runs as usize);
    assert_eq!(log, expected);
    std::fs::remove_dir_all(&dir).ok();
}

/// `ok_exit_codes` reaches the cachegrind run: a subject that exits 1 by
/// design is counted when it allows 1, and still fails when it does not.
/// cachegrind exits with its client's code, which is what makes this work.
#[cfg(unix)]
#[test]
fn ok_exit_codes_apply_under_valgrind() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let subject = |ok: Vec<i32>| tak_cli::config::Subject {
        name: "x".into(),
        cmd: ["/bin/sh", "-c", "exit 1"].map(String::from).to_vec(),
        setup: None,
        setup_dir: None,
        prepare: None,
        check: None,
        version_cmd: None,
        dir: None,
        env: Default::default(),
        vars: Default::default(),
        when: None,
        runs: tak_cli::config::Runs::Fixed(1),
        auto: tak_cli::config::AutoRuns {
            budget: std::time::Duration::from_secs(30),
            min: 5,
            max: 50,
        },
        warmup: 0,
        counters: true,
        allocations: false,
        ok_exit_codes: ok,
        metrics: std::collections::BTreeMap::new(),
    };
    let c = measure::subject_instructions(&subject(vec![0, 1]), &Settings::default())
        .expect("exit 1 is allowed")
        .expect("valgrind present but no I refs parsed");
    assert!(c.min > 10_000, "implausibly low: {}", c.min);

    let err = measure::subject_instructions(&subject(vec![0]), &Settings::default()).unwrap_err();
    assert!(format!("{err:#}").contains("under valgrind"), "{err:#}");
}

/// A declared subject that counts heap allocations and nothing else, with
/// the given command.
#[cfg(unix)]
fn allocating(cmd: &[&str]) -> tak_cli::config::Subject {
    tak_cli::config::Subject {
        name: "x".into(),
        cmd: cmd.iter().map(|s| s.to_string()).collect(),
        setup: None,
        setup_dir: None,
        prepare: None,
        check: None,
        version_cmd: None,
        dir: None,
        env: Default::default(),
        vars: Default::default(),
        when: None,
        runs: tak_cli::config::Runs::Fixed(1),
        auto: tak_cli::config::AutoRuns {
            budget: std::time::Duration::from_secs(30),
            min: 5,
            max: 50,
        },
        warmup: 0,
        counters: false,
        allocations: true,
        metrics: std::collections::BTreeMap::new(),
        ok_exit_codes: vec![0],
    }
}

/// The real DHAT subprocess runs and its summary is parsed. A dynamically
/// linked `echo` allocates a few blocks for its locale and stdout buffer;
/// none at all would mean the summary was misread, or DHAT saw nothing.
#[cfg(unix)]
#[test]
fn allocations_are_reported_when_valgrind_exists() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let a = measure::subject_allocations(&allocating(&["/bin/echo", "tak"]), &Settings::default())
        .expect("DHAT invocation failed")
        .expect("valgrind present but no DHAT summary parsed");
    assert!(a.min.blocks > 0 && a.min.bytes > 0, "{a:?}");
    assert!(!a.saw_nothing());
    assert!(
        a.min.peak_bytes <= a.min.bytes,
        "a peak above the total: {a:?}"
    );
    assert!(
        a.runs >= 2,
        "a single sample cannot detect a varying subject"
    );
}

/// The hypothesis behind recording them: a single-threaded, hermetic
/// command allocates exactly the same on every run, across separate
/// invocations as well as within one.
#[cfg(unix)]
#[test]
fn allocations_of_a_hermetic_command_repeat_exactly() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let s = allocating(&["/bin/echo", "tak"]);
    let outer: Vec<_> = (0..2)
        .map(|_| {
            measure::subject_allocations(&s, &Settings::default())
                .expect("DHAT invocation failed")
                .expect("no DHAT summary parsed")
        })
        .collect();
    for a in &outer {
        assert_eq!(a.min, a.max, "varied within one measurement: {a:?}");
        assert!(!a.is_suspect());
    }
    assert_eq!(outer[0].min, outer[1].min, "varied between measurements");
}

/// DHAT runs get the same prepare step, environment and `ok_exit_codes` as
/// cachegrind ones, and a subject that fails is not recorded as having
/// allocated little.
#[cfg(unix)]
#[test]
fn allocation_runs_are_prepared_and_judged_like_counted_ones() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let mut s = allocating(&["/bin/sh", "-c", "echo \"run:$MARK\" >> log"]);
    s.prepare = Some(
        ["/bin/sh", "-c", "echo prep >> log"]
            .map(String::from)
            .to_vec(),
    );
    s.dir = Some(dir.path().to_path_buf());
    s.env = [("MARK".to_string(), "set".to_string())].into();
    let a = measure::subject_allocations(&s, &Settings::default())
        .expect("DHAT invocation failed")
        .expect("no DHAT summary parsed");
    let log = std::fs::read_to_string(dir.path().join("log")).unwrap();
    assert_eq!(log, "prep\nrun:set\n".repeat(a.runs as usize));
    assert!(
        std::fs::read_dir(dir.path()).unwrap().all(|e| !e
            .unwrap()
            .file_name()
            .to_string_lossy()
            .starts_with("dhat.out")),
        "DHAT left its profile behind in the subject's directory"
    );

    let mut failing = allocating(&["/bin/sh", "-c", "exit 1"]);
    let err = measure::subject_allocations(&failing, &Settings::default()).unwrap_err();
    assert!(format!("{err:#}").contains("under valgrind"), "{err:#}");
    failing.ok_exit_codes = vec![0, 1];
    assert!(
        measure::subject_allocations(&failing, &Settings::default())
            .expect("exit 1 is allowed")
            .is_some()
    );
}

/// A subject that leaves a process running in the background, holding the
/// stderr it inherited, must not hold up either valgrind path: the run is
/// over when the subject exits. Reading stderr through a pipe waited for the
/// background `sleep` to close it instead.
#[cfg(unix)]
#[test]
fn a_background_process_holding_stderr_does_not_hang_valgrind_runs() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let s = allocating(&["/bin/sh", "-c", "sleep 30 & exit 0"]);
    let began = std::time::Instant::now();
    measure::subject_allocations(&s, &Settings::default())
        .expect("DHAT invocation failed")
        .expect("no DHAT summary parsed");
    measure::subject_instructions(&s, &Settings::default())
        .expect("cachegrind invocation failed")
        .expect("no I refs parsed");
    let took = began.elapsed();
    assert!(
        took < std::time::Duration::from_secs(20),
        "six valgrind runs took {took:?}; they waited for the background sleep"
    );
}

/// A leftover that keeps writing to the stderr it inherited, even writing
/// valgrind's own summary lines with the subject's pid, can neither hold up
/// the valgrind runs nor change what they report: valgrind's log is a file
/// of its own, and the subject's stderr never reaches it. The subject also
/// prints a forged summary before it exits, which is ignored the same way.
/// The leftovers are left running, as tak leaves any, until this test stops
/// them.
#[cfg(unix)]
#[test]
fn a_subject_cannot_reach_valgrinds_log() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let forge = r#"echo "==$$== Total:     1 bytes in 1 blocks" >&2; echo "==$$== At t-gmax: 1 bytes in 1 blocks" >&2; echo "==$$== I   refs:      0" >&2; echo "==$$== error: can't open output data file" >&2"#;
    let script = format!("{forge}; (while :; do {forge}; done) & echo $! >> bg; exit 0");
    let mut s = allocating(&["/bin/sh", "-c", &script]);
    s.dir = Some(dir.path().to_path_buf());
    let began = std::time::Instant::now();
    let allocated = measure::subject_allocations(&s, &Settings::default());
    let counted = measure::subject_instructions(&s, &Settings::default());
    let took = began.elapsed();
    let pids = std::fs::read_to_string(dir.path().join("bg")).unwrap_or_default();
    for pid in pids.split_whitespace() {
        let _ = std::process::Command::new("kill")
            .args(["-9", pid])
            .status();
    }
    let a = allocated
        .expect("DHAT invocation failed")
        .expect("no DHAT summary parsed");
    let c = counted
        .expect("cachegrind invocation failed")
        .expect("no I refs parsed");
    assert!(a.min.blocks > 1, "the forged summary was read: {a:?}");
    assert!(c.min > 10_000, "the forged I refs was read: {}", c.min);
    assert!(
        took < std::time::Duration::from_secs(20),
        "six valgrind runs took {took:?}"
    );
}

/// `vet` is asked before each DHAT run's `prepare` and again after it,
/// before valgrind starts, as for a counted cachegrind run: `backfill
/// --commits` re-checks there that a subject still runs from inside its
/// checkout, since the run before or the prepare itself may have changed its
/// paths. A refusal stops the measurement before anything of it runs.
#[cfg(unix)]
#[test]
fn allocation_runs_are_vetted_around_each_prepare() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let mut s = allocating(&["/bin/sh", "-c", "echo run >> log"]);
    s.prepare = Some(
        ["/bin/sh", "-c", "echo prep >> log"]
            .map(String::from)
            .to_vec(),
    );
    s.dir = Some(dir.path().to_path_buf());
    let log = dir.path().join("log");
    let vetted = std::cell::RefCell::new(Vec::new());
    let vet = || {
        let seen = std::fs::read_to_string(&log).unwrap_or_default();
        vetted.borrow_mut().push(seen.lines().count());
        Ok(())
    };
    let a = measure::subject_allocations_vetted(&s, &Settings::default(), &vet)
        .expect("DHAT invocation failed")
        .expect("no DHAT summary parsed");
    // Run i starts with 2i lines logged: vetted there, then after its
    // prepare adds one, and never after its run.
    let expected: Vec<usize> = (0..a.runs as usize)
        .flat_map(|i| [2 * i, 2 * i + 1])
        .collect();
    assert_eq!(*vetted.borrow(), expected);

    std::fs::remove_file(&log).unwrap();
    let refuse = || anyhow::bail!("dir leads out of the checkout");
    let err = measure::subject_allocations_vetted(&s, &Settings::default(), &refuse).unwrap_err();
    assert!(format!("{err:#}").contains("leads out"), "{err:#}");
    assert!(!log.exists(), "neither the prepare nor the subject ran");
}

/// End to end: `--allocations` on an ad-hoc command prints the counts and
/// exports them. Without valgrind it says why they are missing, and the
/// export carries no `allocations` key rather than zeros.
#[cfg(unix)]
#[test]
fn the_allocations_flag_reaches_the_output_and_the_export() {
    let dir = tempfile::tempdir().unwrap();
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_tak"))
        .args([
            "run",
            "--allocations",
            "--no-counters",
            "--no-progress",
            "--runs",
            "2",
            "--warmup",
            "0",
            "--export-json",
            "r.json",
            "--",
            "/bin/echo",
            "tak",
        ])
        .current_dir(dir.path())
        .output()
        .expect("failed to run tak");
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(out.status.success(), "{stdout}\n{stderr}");
    let export: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(dir.path().join("r.json")).unwrap()).unwrap();
    let allocations = &export["results"][0]["allocations"];
    if valgrind_available() {
        assert!(stdout.contains("alloc_blocks"), "{stdout}");
        assert!(allocations["blocks"].as_u64().unwrap() > 0, "{export}");
        assert!(allocations["peak_bytes"].is_u64(), "{export}");
    } else {
        assert!(
            stderr.contains("heap allocations were not measured"),
            "{stderr}"
        );
        assert!(allocations.is_null(), "{export}");
    }
}