tak-cli 0.0.14

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
//! `tak run --profile-dir` and `tak explain` against real cachegrind output.
//!
//! The parser's unit tests run on small hand-written fixtures, which say what
//! the format should look like. These say what valgrind on this machine
//! actually writes, and that the profile kept is the one behind the count
//! reported — an attribution that does not add up to the recorded number
//! explains some other run.
//!
//! Tests that need valgrind skip without it, as in `tests/counters.rs`.

use std::path::Path;
use std::process::{Command, Output};
use tak_cli::measure::{self, valgrind_available};
use tak_cli::profile::{self, Profile};
use tak_cli::settings::Settings;

fn tak(dir: &Path, args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_tak"))
        .args(args)
        .current_dir(dir)
        .output()
        .expect("failed to run tak")
}

fn text(out: &Output) -> String {
    format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    )
}

#[cfg(unix)]
fn echo() -> tak_cli::config::Subject {
    tak_cli::config::Subject {
        name: "x".into(),
        cmd: ["/bin/echo", "tak"].map(String::from).to_vec(),
        prepare: None,
        setup: None,
        setup_dir: None,
        check: None,
        dir: None,
        version_cmd: 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: vec![0],
        metrics: std::collections::BTreeMap::new(),
    }
}

/// The kept profile is the one whose count was reported: its total is the
/// minimum, and its functions add up to that total.
#[cfg(unix)]
#[test]
fn a_kept_profile_adds_up_to_the_reported_count() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let (counted, raw) = measure::subject_profile(&echo(), &Settings::default())
        .expect("cachegrind invocation failed")
        .expect("valgrind present but nothing counted");
    let raw = raw.expect("the profile was kept");
    let p = profile::parse(&String::from_utf8(raw).unwrap()).expect("cachegrind's own output");

    assert_eq!(p.total, counted.min);
    assert_eq!(p.functions.values().map(|f| f.ir).sum::<u64>(), p.total);
    assert!(
        p.functions.len() > 10,
        "a dynamically linked process runs more than {} functions",
        p.functions.len()
    );
    assert_eq!(p.cmd.as_deref(), Some("/bin/echo tak"));
}

/// The CLI end to end: two runs of the same benchmark doing different work
/// leave profiles at the documented path, and `explain` pairs them and names
/// what changed.
#[cfg(unix)]
#[test]
fn explain_names_the_functions_between_two_runs() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    for (side, arg) in [("base", "/"), ("head", "/usr")] {
        let out = tak(
            dir.path(),
            &[
                "run",
                "--no-progress",
                "--runs",
                "1",
                "--warmup",
                "0",
                "--bench",
                "list",
                "--profile-dir",
                side,
                "--",
                "/bin/ls",
                "-l",
                arg,
            ],
        );
        assert!(out.status.success(), "{}", text(&out));
        assert!(text(&out).contains("wrote 1 profile(s)"), "{}", text(&out));
    }
    let kept = dir.path().join("head/list/self.cachegrind.out");
    let p = Profile::load(&kept).unwrap();
    assert!(p.runner().is_some(), "the runner class is recorded");

    let out = tak(dir.path(), &["explain", "base", "head", "--top", "3"]);
    assert!(out.status.success(), "{}", text(&out));
    let md = String::from_utf8_lossy(&out.stdout);
    assert!(md.contains("### list\n"), "{md}");
    assert!(md.contains("| function | Δ | base | head | file |"), "{md}");
    // Three rows and one for the rest: listing /usr is not the same work as
    // listing /.
    assert!(md.contains(" more | "), "{md}");
}

/// Everything below runs without valgrind.
#[test]
fn explain_reads_two_profile_files() {
    let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/profile");
    let out = tak(
        &fixtures,
        &[
            "explain",
            "base.cachegrind.out",
            "head.cachegrind.out",
            "--top",
            "1",
        ],
    );
    assert!(out.status.success(), "{}", text(&out));
    let md = String::from_utf8_lossy(&out.stdout);
    assert!(md.contains("1,500 → 2,110 instructions"), "{md}");
    assert!(md.contains("| `mycli::render` | **+900** |"), "{md}");
    assert!(md.contains("| 3 more | -290 |"), "{md}");
}

#[test]
fn profiles_need_counters() {
    let dir = tempfile::tempdir().unwrap();
    let out = tak(
        dir.path(),
        &[
            "run",
            "--no-counters",
            "--profile-dir",
            "p",
            "--",
            "/bin/echo",
        ],
    );
    assert!(!out.status.success());
    assert!(text(&out).contains("--no-counters"), "{}", text(&out));
    assert!(!dir.path().join("p").exists());
}

/// A benchmark name that is not a plain file name fails before anything runs,
/// rather than writing outside the profile directory — or, with a newline,
/// writing a heading of its own into the report. The newline is refused by
/// the check every recorded name passes, the path by the one file names add.
#[test]
fn a_benchmark_name_that_is_not_a_file_name_is_refused_up_front() {
    for (bench, why) in [
        ("../escape", "not a plain file name"),
        ("a\n## All clear", "control character"),
    ] {
        let dir = tempfile::tempdir().unwrap();
        let out = tak(
            dir.path(),
            &[
                "run",
                "--bench",
                bench,
                "--profile-dir",
                "p",
                "--",
                "/bin/sh",
                "-c",
                "touch ran",
            ],
        );
        assert!(!out.status.success(), "{bench:?}");
        assert!(text(&out).contains(why), "{}", text(&out));
        assert!(!dir.path().join("ran").exists(), "nothing was measured");
    }
}

/// cachegrind that cannot write its profile reports zero instructions. A
/// subject that removes the scratch directory must cost the count, loudly,
/// never record as zero.
#[cfg(unix)]
#[test]
fn a_profile_cachegrind_could_not_write_is_not_a_count_of_zero() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let tmp = dir.path().join("tmp");
    std::fs::create_dir(&tmp).unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_tak"))
        .args(["run", "--no-progress", "--runs", "1", "--warmup", "0"])
        .args(["--profile-dir", "p", "--", "/bin/sh", "-c"])
        .arg("rm -rf \"$TMPDIR\"/.tmp*")
        .current_dir(dir.path())
        .env("TMPDIR", &tmp)
        .output()
        .unwrap();
    let all = text(&out);
    assert!(all.contains("could not write its profile"), "{all}");
    assert!(!all.contains("instructions "), "{all}");
    assert!(all.contains("wrote 0 profile(s)"), "{all}");
}

/// The subject shares valgrind's stderr. One that prints valgrind's own
/// words — the unwritable-output error, a zero summary — keeps its real
/// count, with or without a profile being kept.
#[cfg(unix)]
#[test]
fn a_subject_printing_valgrinds_words_keeps_its_count() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let mut s = echo();
    s.cmd = [
        "/bin/sh",
        "-c",
        "echo \"error: can't open output data file 'x'\" >&2; echo 'I refs: 0' >&2",
    ]
    .map(String::from)
    .to_vec();
    let plain = measure::subject_instructions(&s, &Settings::default())
        .expect("a count, not a failure")
        .expect("valgrind present");
    assert!(plain.min > 10_000, "implausibly low: {}", plain.min);
    let (kept, raw) = measure::subject_profile(&s, &Settings::default())
        .expect("a count, not a failure")
        .expect("valgrind present");
    // Against the profile from the same measurement, not against `plain`: two
    // separate measurements need not agree to the instruction.
    assert!(kept.min > 10_000, "implausibly low: {}", kept.min);
    let raw = raw.expect("the profile was kept");
    let p = profile::parse(&String::from_utf8(raw).unwrap()).expect("cachegrind's own output");
    assert_eq!(p.total, kept.min);
}

/// `TAK_TOOL` renames a single command's series, and its profile with it, so
/// two tools measured into one directory are two files that each say which
/// series they belong to.
#[cfg(unix)]
#[test]
fn a_single_command_profile_is_named_by_its_series() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    for tool in ["one", "two"] {
        let out = Command::new(env!("CARGO_BIN_EXE_tak"))
            .args(["run", "--no-progress", "--runs", "1", "--warmup", "0"])
            .args([
                "--bench",
                "b",
                "--profile-dir",
                "p",
                "--",
                "/bin/echo",
                tool,
            ])
            .current_dir(dir.path())
            .env("TAK_TOOL", tool)
            .output()
            .unwrap();
        assert!(out.status.success(), "{}", text(&out));
    }
    for tool in ["one", "two"] {
        let p = Profile::load(&dir.path().join(format!("p/b/{tool}.cachegrind.out"))).unwrap();
        assert_eq!(p.origin().unwrap().subject, tool);
        assert_eq!(p.cmd.as_deref(), Some(format!("/bin/echo {tool}").as_str()));
    }
    assert!(!dir.path().join("p/b/self.cachegrind.out").exists());
}

/// A `TAK_TOOL` that cannot be a file name is refused before anything runs,
/// like a benchmark name.
#[test]
fn a_tak_tool_that_is_a_path_is_refused_up_front() {
    let dir = tempfile::tempdir().unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_tak"))
        .args([
            "run",
            "--profile-dir",
            "p",
            "--",
            "/bin/sh",
            "-c",
            "touch ran",
        ])
        .current_dir(dir.path())
        .env("TAK_TOOL", "../escape")
        .output()
        .unwrap();
    assert!(!out.status.success());
    assert!(
        text(&out).contains("not a plain file name"),
        "{}",
        text(&out)
    );
    assert!(!dir.path().join("ran").exists(), "nothing was measured");
}

#[cfg(unix)]
fn git(dir: &Path, args: &[&str]) {
    let out = Command::new("git")
        .args(["-c", "user.name=tak-test", "-c", "user.email=t@example.com"])
        .args(args)
        .current_dir(dir)
        .output()
        .expect("git failed to spawn");
    assert!(out.status.success(), "git {args:?}: {}", text(&out));
}

/// A local-baseline loop keeps its profiles: save a baseline, measure against
/// it, and the two runs' profiles explain the comparison.
#[cfg(unix)]
#[test]
fn profiles_are_kept_by_baseline_runs() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    git(dir.path(), &["init", "-q"]);
    git(dir.path(), &["commit", "-q", "--allow-empty", "-m", "c"]);
    for (flag, profiles, arg) in [
        ("--save-baseline", "before", "/usr"),
        ("--baseline", "after", "/"),
    ] {
        let out = tak(
            dir.path(),
            &[
                "run",
                "--no-progress",
                "--runs",
                "1",
                "--warmup",
                "0",
                "--bench",
                "list",
                flag,
                "good",
                "--profile-dir",
                profiles,
                "--",
                "/bin/ls",
                "-l",
                arg,
            ],
        );
        assert!(out.status.success(), "{}", text(&out));
        assert!(text(&out).contains("wrote 1 profile(s)"), "{}", text(&out));
    }
    let out = tak(dir.path(), &["explain", "before", "after"]);
    assert!(out.status.success(), "{}", text(&out));
    let md = String::from_utf8_lossy(&out.stdout);
    assert!(md.contains("### list\n"), "{md}");
    assert!(md.contains(" function(s) changed"), "{md}");
}

/// Measure the same commit twice and the profile left behind is the second
/// run's, while the notes' lowest count is the first's. `explain` says so
/// instead of attributing a count the gate never used.
#[cfg(unix)]
#[test]
fn a_profile_replaced_after_the_recorded_minimum_is_called_out() {
    if !valgrind_available() {
        eprintln!("skipping: valgrind not installed");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    git(dir.path(), &["init", "-q"]);
    git(dir.path(), &["commit", "-q", "--allow-empty", "-m", "c"]);
    // Less work first, then more, both recorded against the same commit.
    for arg in ["/usr", "/"] {
        let out = tak(
            dir.path(),
            &[
                "run",
                "--no-progress",
                "--runs",
                "1",
                "--warmup",
                "0",
                "--bench",
                "list",
                "--record",
                "--profile-dir",
                "p",
                "--",
                "/bin/ls",
                "-l",
                arg,
            ],
        );
        assert!(out.status.success(), "{}", text(&out));
    }
    let out = tak(dir.path(), &["explain", "p", "p"]);
    assert!(out.status.success(), "{}", text(&out));
    let md = String::from_utf8_lossy(&out.stdout);
    assert!(
        md.contains("The base profile totals") && md.contains("The head profile totals"),
        "{md}"
    );
    assert!(md.contains("in git notes is"), "{md}");
}