mbx 1.20.0

A build cache for Rust projects
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
use super::*;
use model::{CacheMix, segments};

#[test]
fn segments_partition_exactly_and_handle_extremes() {
    for mix in [
        CacheMix::default(),
        CacheMix {
            hits: 7,
            misses: 2,
            bypasses: 1,
            saved_ns: 0,
            unconsulted: 0,
        },
        CacheMix {
            hits: u64::MAX,
            misses: u64::MAX,
            bypasses: u64::MAX,
            saved_ns: 0,
            unconsulted: 0,
        },
    ] {
        for width in 0..=80 {
            assert_eq!(segments(&mix, width).iter().sum::<usize>(), width);
        }
    }
    assert_eq!(
        segments(
            &CacheMix {
                hits: 7,
                misses: 2,
                bypasses: 1,
                saved_ns: 0,
                unconsulted: 0
            },
            20
        ),
        [14, 4, 2]
    );
}

#[test]
fn cache_mix_matches_existing_stats_and_excludes_probes() {
    let mut stats = AgentStats::default();
    stats.lookups = 10;
    stats.hits = 6;
    stats.verifications = 1;
    stats.compiler = BTreeMap::from([("miss".into(), mbx_cache_core::CompilerStats::new(3, 0))]);
    stats.bypasses = BTreeMap::from([("compiler-query".into(), 4), ("unsupported".into(), 2)]);
    stats.avoided_compiler_duration_ns = 42;
    let mix = CacheMix::from(stats);
    assert_eq!(
        (mix.hits, mix.misses, mix.bypasses, mix.saved_ns),
        (6, 3, 2, 42)
    );
}

#[test]
fn fresh_artifacts_are_not_cache_hits_and_missing_timings_stay_unknown() {
    let mut model = Model::new(&["build".into()]);
    assert!(model.cargo(r##"{"reason":"compiler-artifact","package_id":"registry+url#demo@1.0.0","target":{"name":"demo"},"fresh":true}"##));
    assert_eq!(model.fresh, 1);
    assert_eq!(model.mix.hits, 0);
    assert_eq!(model.done[0].duration, None);
    assert_eq!(model.units_total, None);
    assert!(model.status("    Building [======> ] 2/10: demo"));
    assert_eq!((model.units_done, model.units_total), (2, Some(10)));
}

#[test]
fn native_test_output_tracks_suites_and_failures_without_fabricated_times() {
    let mut model = Model::new(&["test".into()]);
    assert!(model.test_line("running 2 tests"));
    assert!(model.test_line("test good ... ok"));
    assert!(model.test_line("test bad ... FAILED"));
    model.test_line("failures:");
    assert!(!model.test_line("---- bad stdout ----"));
    model.test_line("panic at src/lib.rs:3:4");
    model.test_line("failures:");
    assert_eq!((model.tests_passed, model.tests_failed), (1, 1));
    assert!(model.failures[0].1.contains("panic at"));
    assert_eq!(model.done[0].duration, None);
    assert!(model.test_line("running 1 test"));
    assert_eq!((model.suite_done, model.suite_total), (0, 1));
    assert!(!model.test_line("custom harness output"));
}

/// On a terminal, libtest colours each result and resets with the terminal's
/// sgr0, which on xterm starts with a charset escape.
#[test]
fn coloured_test_results_count_as_they_arrive() {
    assert_eq!(strip_ansi("a\x1b(Bb\x1b=c\x1b[1;31md\x1b"), "abcd");
    let mut model = Model::new(&["test".into()]);
    assert!(model.test_line("running 2 tests"));
    for line in [
        "test a ... \x1b[31mFAILED\x1b(B\x1b[m",
        "test b ... \x1b[32mok\x1b(B\x1b[m",
    ] {
        assert!(model.test_line(&strip_ansi(line)), "{line:?}");
    }
    assert_eq!(
        (model.tests_failed, model.tests_passed, model.suite_done),
        (1, 1, 2)
    );
}

/// Check that display options leave application arguments untouched and that
/// toolchain selectors and placement configuration do not hide the Cargo verb.
#[test]
fn argument_injection_preserves_command_and_program_arguments() {
    let args = vec![
        "run".into(),
        "--bin=server".into(),
        "--".into(),
        "--message-format=custom".into(),
    ];
    assert_eq!(
        cargo_arguments(&args),
        [
            "run",
            "--bin=server",
            "--message-format=json,json-diagnostic-rendered-ansi",
            "--",
            "--message-format=custom"
        ]
    );
    assert!(eligible(&args));
    let prefixed = vec!["+stable".into(), "test".into(), "--".into(), "works".into()];
    assert!(eligible(&prefixed));
    assert_eq!(cargo_verb(&prefixed), Some("test"));
    let placed = vec![
        "--config".into(),
        "build.target-dir='checkout/target'".into(),
        "test".into(),
    ];
    // Eligibility is checked before mbx adds its own placement config, but
    // the renderer still needs the verb from the final Cargo arguments.
    assert_eq!(cargo_verb(&placed), Some("test"));
    assert_eq!(
        cargo_arguments(&prefixed),
        [
            "+stable",
            "test",
            "--message-format=json,json-diagnostic-rendered-ansi",
            "--",
            "works"
        ]
    );
    for args in [
        vec!["test", "--message-format=json"],
        vec!["build", "-q"],
        vec!["check", "--config=foo"],
        vec!["metadata"],
    ] {
        assert!(!eligible(
            &args.iter().map(|s| s.to_string()).collect::<Vec<_>>()
        ));
    }
}

#[cfg(unix)]
#[test]
fn preserves_signalled_exit_status() {
    use std::os::unix::process::ExitStatusExt;
    let status = portable_pty::ExitStatus::from(std::process::ExitStatus::from_raw(libc::SIGTERM));
    assert_eq!(status_code(&status), 143);
}

#[test]
fn presentation_keeps_reserved_rows_and_clips_diagnostics() {
    let mut model = Model::new(&["build".into()]);
    let empty = view::render(&mut model, None, 80, 27);
    assert_eq!(empty.size().1, 27);
    assert!(strip_ansi(&empty.to_string()).contains("total unknown"));
    assert!(model.status("   Compiling a-crate v0.1.0 (/tmp/a-crate)"));
    assert!(model.cargo(r##"{"reason":"compiler-artifact","package_id":"path+file:///tmp/a-crate#0.1.0","target":{"name":"a_crate"},"fresh":false}"##));
    assert!(model.live.is_empty());
    assert!(model.done[0].duration.is_some());
    let populated = view::render(&mut model, None, 80, 27);
    assert_eq!(populated.size().1, 27);
    model.warnings.push(model::Warning {
        message: "warning".into(),
        rendered: "wide 文本\n".repeat(100),
        location: None,
        help: None,
    });
    let mut browser = view::Browser {
        inspecting: true,
        scroll: usize::MAX,
        selected: 0,
    };
    let block = view::render(&mut model, Some(&mut browser), 20, 12);
    assert!(block.size().0 <= 20);
    assert_eq!(block.size().1, 12);
    assert!(browser.scroll < 200);
}

#[test]
fn terse_and_ignored_test_summaries_remain_accurate() {
    let mut model = Model::new(&["test".into()]);
    model.test_line("running 3 tests");
    model.test_line("..i");
    model.test_line("test result: ok. 2 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s");
    assert_eq!(
        (
            model.tests_passed,
            model.tests_failed,
            model.tests_ignored,
            model.suite_done
        ),
        (2, 0, 1, 3)
    );
}

#[test]
fn failed_build_does_not_fill_unfinished_units() {
    let mut model = Model::new(&["build".into()]);
    model.units_total = Some(10);
    model.units_done = 3;
    model.build_finished = true;
    model.build_ok = Some(false);
    let text = strip_ansi(&view::render(&mut model, None, 110, 30).to_string());
    assert!(text.contains("3/10 units"));
    assert!(text.contains(&"░".repeat(20)));
    model.units_total = None;
    model.build_ok = Some(true);
    let text = strip_ansi(&view::render(&mut model, None, 110, 30).to_string());
    assert!(text.contains("total unknown"));
}

#[test]
fn status_words_in_child_output_are_preserved() {
    let mut model = Model::new(&["build".into()]);
    for line in [
        "Compiling assets",
        "Checking configuration",
        "   Compiling assets",
        "    Checking configuration",
        "Finished generating assets",
        "Building [assets] 1/2: images",
    ] {
        assert!(!model.status(line), "consumed child output: {line}");
    }
    assert!(model.live.is_empty());
    assert!(model.status("   Compiling demo v1.2.3 (/tmp/demo)"));
    assert!(model.status("    Checking demo v1.2.3"));
    assert!(model.status("    Finished `dev` profile [unoptimized] target(s) in 0.2s"));
}

#[test]
fn final_summary_keeps_only_its_content_rows() {
    let mut model = Model::new(&["build".into()]);
    model.finished = Some((true, Duration::from_secs(2)));
    let block = view::render(&mut model, None, 80, 27);
    assert_eq!(block.size().1, view::summary(&model).size().1);
    assert!(block.size().1 < 10);
}

#[test]
fn passing_test_stdout_does_not_open_failure_browser() {
    let mut model = Model::new(&["test".into()]);
    for line in [
        "running 1 test",
        "test works ... ok",
        "successes:",
        "---- works stdout ----",
        "hello",
        "test result: ok. 1 passed; 0 failed; 0 ignored;",
    ] {
        model.test_line(line);
    }
    assert!(model.failures.is_empty());
    for line in [
        "running 1 test",
        "test fails ... FAILED",
        "failures:",
        "---- fails stdout ----",
        "panic detail",
    ] {
        model.test_line(line);
    }
    assert_eq!(model.failures.len(), 1);
    assert!(model.failures[0].1.contains("panic detail"));
}

#[test]
fn active_rows_keep_slots_and_cache_outcomes_remain_explicit() {
    let mut model = Model::new(&["build".into()]);
    model.status("   Compiling zeta v1.0.0");
    model.status("   Compiling alpha v1.0.0");
    let original = model.slots.clone();
    assert!(model.cargo(r#"{"reason":"compiler-artifact","package_id":"path+file:///zeta#zeta@1.0.0","target":{"name":"zeta"},"filenames":["/tmp/libzeta-1111111111111111.rmeta"],"fresh":false}"#));
    assert_eq!(model.slots[1], original[1]);
    let mut stats = AgentStats::default();
    stats
        .unit_outcomes
        .insert("zeta:1111111111111111".into(), ["hit".into()].into());
    model.update_stats(stats.clone());
    assert!(strip_ansi(&view::render(&mut model, None, 110, 27).to_string()).contains("hit"));
    stats
        .unit_outcomes
        .get_mut("zeta:1111111111111111")
        .unwrap()
        .insert("miss".into());
    model.update_stats(stats);
    assert!(strip_ansi(&view::render(&mut model, None, 110, 27).to_string()).contains("mixed"));
}

#[test]
fn malformed_versions_and_large_exit_codes_stay_failures_or_passthrough() {
    let mut model = Model::new(&["build".into()]);
    assert!(!model.status("   Compiling assets v1.2.not-a-version"));
    assert_eq!(
        status_code(&portable_pty::ExitStatus::with_exit_code(256)),
        1
    );
}

#[test]
fn small_viewports_promote_waiting_crates_without_moving_visible_crates() {
    let mut model = Model::new(&["build".into()]);
    for name in ["first", "second", "third", "fourth", "fifth", "sixth"] {
        model.status(&format!("   Compiling {name} v1.0.0"));
    }
    view::render(&mut model, None, 80, 14);
    assert_eq!(model.slots.len(), 1);
    assert!(model.cargo(r#"{"reason":"compiler-artifact","package_id":"path+file:///first#first@1.0.0","target":{"name":"first"},"fresh":false}"#));
    assert_eq!(model.slots[0].as_deref(), Some("second v1.0.0"));
    let text = strip_ansi(&view::render(&mut model, None, 80, 14).to_string());
    assert!(text.contains("second"));
    view::render(&mut model, None, 80, 24);
    assert_eq!(model.slots[0].as_deref(), Some("second v1.0.0"));
    assert_eq!(model.slots.len(), 6);
}

#[test]
fn a_long_build_is_summarized_in_minutes_rather_than_hundreds_of_seconds() {
    let mut model = Model::new(&["build".into()]);
    model.finished = Some((true, std::time::Duration::from_secs(813)));
    model.mix.saved_ns = 6_600_000_000_000;
    let text = strip_ansi(&view::summary(&model).to_string());
    assert!(text.contains("Built in 13m 33s"), "{text}");
    assert!(text.contains("saved ~1h 50m compiler work"), "{text}");
}

#[test]
fn summary_uses_the_cargo_verb_and_build_scripts_normalize_like_rustc() {
    for (arguments, expected) in [
        (vec!["c".into()], "Checked"),
        (vec!["+stable".into(), "check".into()], "Checked"),
        (
            vec!["build".into(), "--features".into(), "unchecked".into()],
            "Built",
        ),
    ] {
        let model = Model::new(&arguments);
        assert!(strip_ansi(&view::summary(&model).to_string()).contains(expected));
    }
    let mut model = Model::new(&["build".into()]);
    model.cargo(r#"{"reason":"compiler-artifact","package_id":"path+file:///demo#demo@1.0.0","target":{"name":"build-script-build","kind":["custom-build"]},"filenames":["/tmp/demo-1111111111111111/build-script-build"],"fresh":false}"#);
    assert_eq!(
        model.done[0].cache_target.as_deref(),
        Some("build_script_build:1111111111111111")
    );
}

#[test]
fn cargo_fingerprints_isolate_versions_and_match_compiler_arguments() {
    let mut model = Model::new(&["build".into()]);
    for (version, hash) in [("1.0.0", "1111111111111111"), ("2.0.0", "2222222222222222")] {
        model.cargo(&serde_json::json!({"reason":"compiler-artifact", "package_id":format!("serde@{version}"), "target":{"name":"serde"}, "filenames":[format!("/tmp/libserde-{hash}.rmeta")], "fresh":false}).to_string());
    }
    assert_ne!(model.done[0].cache_target, model.done[1].cache_target);
    assert_eq!(
        model.done[0].cache_target,
        crate::session::compiler_unit_key(
            "serde",
            ["-C".into(), "extra-filename=-1111111111111111".into()]
        )
    );
    assert!(
        crate::session::compiler_unit_key("serde", ["--crate-name".into(), "serde".into()])
            .is_none()
    );
}

#[test]
fn uplifted_artifacts_match_shim_outcomes_without_merging_packages_or_tests() {
    use std::path::Path;
    for (name, kind, filename) in [
        ("my-app", "bin", "/tmp/target/debug/my-app"),
        ("foo", "lib", "/tmp/target/debug/libfoo.rlib"),
        ("foo", "cdylib", "/tmp/target/debug/libfoo.dylib"),
    ] {
        let mut model = Model::new(&["build".into()]);
        let manifest = "/tmp/project/Cargo.toml";
        let message = serde_json::json!({
            "reason":"compiler-artifact", "package_id":"project@1.0.0",
            "manifest_path":manifest, "target":{"name":name,"crate_types":[kind]},
            "profile":{"test":false}, "filenames":[filename], "fresh":false
        });
        model.cargo(&message.to_string());
        let arguments = vec![
            "--crate-type".into(),
            kind.into(),
            "--out-dir=/tmp/target/debug/deps".into(),
            "-Cextra-filename=-1111111111111111".into(),
        ];
        let shim = crate::session::compiler_uplifted_unit_key(
            &name.replace('-', "_"),
            Path::new(manifest),
            &arguments,
        )
        .unwrap();
        assert_eq!(model.done[0].cache_target.as_deref(), Some(shim.as_str()));
        assert_ne!(
            Some(shim.clone()),
            crate::session::compiler_uplifted_unit_key(
                name,
                Path::new("/tmp/other-version/Cargo.toml"),
                &arguments,
            )
        );
        let mut test_arguments = arguments.clone();
        test_arguments.push("--test".into());
        assert!(
            crate::session::compiler_uplifted_unit_key(name, Path::new(manifest), &test_arguments,)
                .is_none()
        );
        model.outcomes.insert(shim, ["hit".into()].into());
        let text = strip_ansi(&view::render(&mut model, None, 80, 24).to_string());
        assert!(text.contains("hit"), "{text}");
    }
}

#[test]
fn mascot_keeps_progress_readable_and_leaves_successful_builds() {
    let mut model = Model::new(&["build".into()]);
    model.units_total = Some(100);
    model.units_done = 91;
    for width in [50, 80, 95, 96, 110] {
        let block = view::render(&mut model, None, width, 27);
        assert!(block.size().0 <= width);
        assert_eq!(block.size().1, 27);
        let text = strip_ansi(&block.to_string());
        // Only the mascot draws half blocks.
        assert_eq!(text.contains('▀'), width >= 96, "{text}");
        if width >= 80 {
            assert!(text.contains("91/100 units"), "{text}");
        }
    }
    // A compiler error shows the failure pose, and its monocle chain, before
    // Cargo reports the build.
    let chain = "189;125;35";
    assert!(
        !view::render(&mut model, None, 110, 27)
            .to_string()
            .contains(chain)
    );
    model
        .errors
        .push("error[E0425]: cannot find value `x` in this scope".into());
    assert!(
        view::render(&mut model, None, 110, 27)
            .to_string()
            .contains(chain)
    );
    // A failed build keeps the knocked-over box beside its summary.
    model.finished = Some((false, Duration::from_secs(1)));
    let failed = view::render(&mut model, None, 110, 27);
    assert_eq!(failed.size().1, 9);
    assert!(strip_ansi(&failed.to_string()).contains("Failed"));
    // Each mascot cell reaches the terminal with its own glyph, fg and bg.
    use crate::cli::mascot::{self, Pose};
    use norimel::Color;
    let paint =
        |color: Option<mascot::Rgb>| color.map_or(Color::Reset, |(r, g, b)| Color::Rgb(r, g, b));
    let mut painted = vec![Vec::new(); mascot::HEIGHT];
    let mascot_x = failed.size().0 - mascot::WIDTH as u16;
    for (x, y, text, style) in failed.runs() {
        for (i, glyph) in text.chars().enumerate() {
            if usize::from(x) + i >= usize::from(mascot_x) {
                painted[usize::from(y)].push((glyph, style.fg, style.bg));
            }
        }
    }
    let knocked = mascot::draw(Pose {
        failed: true,
        ..Pose::default()
    });
    let expected: Vec<Vec<_>> = knocked
        .iter()
        .map(|row| {
            row.iter()
                .map(|cell| (cell.glyph, paint(cell.fg), paint(cell.bg)))
                .collect()
        })
        .collect();
    assert_eq!(painted, expected);
    // A successful build leaves only its summary.
    model.errors.clear();
    model.finished = Some((true, Duration::from_secs(1)));
    let done = view::render(&mut model, None, 110, 27);
    let text = strip_ansi(&done.to_string());
    assert!(text.contains("Built"), "{text}");
    assert!(!text.contains('▀'), "{text}");
    assert_eq!(done.size().1, view::summary(&model).size().1);
}

/// Cargo's counts arrive in jumps: an incremental build's first progress line
/// is already 97/98, and a burst of cache hits finishes many units between two
/// frames. The drawn lid still comes down a pixel at a time and never rises,
/// including through the test phase, whose suite counts restart per binary.
#[test]
fn mascot_lid_descends_a_pixel_per_frame_through_jumps_in_progress() {
    use crate::cli::mascot::LID_MAX;
    let replay = |lines: &[&str]| {
        let mut model = Model::new(&["test".into()]);
        let mut lids = vec![model.lid_shown];
        let mut frame = |model: &mut Model| {
            view::render(model, None, 110, 27);
            lids.push(model.lid_shown);
        };
        frame(&mut model);
        for line in lines {
            // As the decoder routes lines: Cargo's until the build finishes.
            if model.build_finished || !(model.cargo(line) || model.status(line)) {
                model.test_line(line);
            }
            frame(&mut model);
            frame(&mut model);
        }
        lids
    };
    let finished = r#"{"reason":"build-finished","success":true}"#;
    for lines in [
        &[
            "    Building [=======================> ] 97/98: mbx(bin)",
            finished,
            "running 2 tests",
            "test first ... ok",
        ][..],
        &[
            "    Building [          ] 0/60",
            "    Building [          ] 3/60",
            "    Building [========> ] 58/60",
            "    Building [========> ] 59/60",
            finished,
        ],
        &[
            "    Building [   ] 0/3",
            "    Building [=> ] 3/3",
            finished,
            "running 0 tests",
        ],
    ] {
        let lids = replay(lines);
        assert_eq!(lids[0], LID_MAX);
        // Each render holds the lid or lowers it by one pixel.
        let steps = lids.windows(2).map(|pair| pair[0].checked_sub(pair[1]));
        assert!(
            steps.clone().all(|step| matches!(step, Some(0 | 1))),
            "{lids:?}"
        );
        let moves = steps.filter(|step| *step == Some(1)).count();
        assert_eq!(moves, usize::from(LID_MAX), "{lids:?}");
        assert_eq!(lids.last(), Some(&0), "{lids:?}");
    }
}