mbx 1.24.1

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
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
//! Test binaries under the machine-wide permit pool.
//!
//! The pool paces compilers, but test commands spend much of their time running
//! test binaries, and libtest sizes itself to the whole machine. Three
//! worktrees testing at once are three suites each starting a thread per CPU.
//! With `scheduler.tests`, mbx installs itself as Cargo's target runner for
//! `cargo test` and `cargo nextest`; each test binary then waits for permits
//! like a compiler does, and chains to whatever runner was configured before.
//!
//! Work a test starts is charged to the test's own permits: its children see
//! scheduling turned off. Otherwise a test that builds something -- trybuild,
//! compile-fail suites, mbx's own integration tests -- would hold permits
//! while its compilers waited for more, and two of them could hold the whole
//! pool between them and wait on each other forever.
use eyre::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};

const SHIM: &str = "mbx-test-runner";
/// Shortest run whose CPU use is worth measuring. Below this, start-up
/// dominates the average, so a complete run is remembered as one core.
const MIN_CPU_SAMPLE: std::time::Duration = std::time::Duration::from_secs(1);
/// The [`Overlay`] the shim reads back.
const RUNNERS: &str = "MBX_TEST_RUNNERS";

/// What the shim needs from the command that installed it.
#[derive(Debug, Default, Serialize, Deserialize)]
struct Overlay {
    /// The runner each target had before this one, by target triple.
    runners: BTreeMap<String, Option<Runner>>,
    /// The caller's value of each runner key this overlay replaced, handed
    /// back to the test so a Cargo command it runs finds its own runners
    /// rather than a shim its `PATH` may no longer reach.
    restore: BTreeMap<String, Option<String>>,
    /// The repository the tests belong to, as [`repository_identity`] names
    /// it, so unrelated projects keep separate history.
    #[serde(default)]
    project: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
struct Runner {
    path: PathBuf,
    args: Vec<OsString>,
}

pub(super) struct TestRunner {
    /// Runner environment keys, each paired with the triple it names.
    keys: Vec<(String, String)>,
    runners: BTreeMap<String, Option<Runner>>,
    project: Option<String>,
    shim: PathBuf,
}

impl TestRunner {
    /// Wrap this command's test binaries when scheduling them is on. `None`
    /// leaves Cargo's runners alone.
    pub(super) fn prepare(
        config: &crate::config::Config,
        arguments: &[String],
        workspace_root: &Path,
        directory: &Path,
    ) -> Result<Option<Self>> {
        if !config.scheduler.enabled || !config.scheduler.tests {
            return Ok(None);
        }
        // What Cargo will run, not what was typed: an alias such as
        // `nt = "nextest run"` runs tests as surely as the command it names.
        let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
        let expanded = super::cargo_invocation::expanded_arguments(&cargo, arguments);
        let arguments = expanded.as_deref().unwrap_or(arguments);
        if !wraps(arguments) {
            return Ok(None);
        }
        // Resolution is best-effort, like the pool itself: a configuration
        // mbx cannot read runs the tests unscheduled rather than failing.
        let resolved = (|| -> Result<_> {
            let cargo = super::launch::load_cargo_config()?;
            let inherited = inherited_overlay().runners;
            let mut keys = Vec::new();
            let mut runners = BTreeMap::new();
            let mut targets = super::launch::requested_targets(&cargo, arguments)?;
            let host = cargo.host_triple()?.to_owned();
            if !targets
                .iter()
                .any(|target| target.triple() == host.as_str())
            {
                targets.extend(cargo.build_target_for_config([host])?);
            }
            for target in targets {
                let triple = target.triple().to_owned();
                let runner = cargo.runner(&target)?.map(|runner| Runner {
                    path: runner.path,
                    args: runner.args,
                });
                // A nested mbx sees the outer one's shim as the configured
                // runner. Chaining to it would loop; chain to what it wraps.
                // Only when there is an outer overlay for this target, though:
                // otherwise the runner merely shares the shim's name.
                let runner = match (runner, inherited.get(&triple)) {
                    (Some(runner), Some(wrapped)) if is_shim(&runner.path) => wrapped.clone(),
                    (runner, _) => runner,
                };
                keys.push((super::launch::runner_key(&target), triple.clone()));
                runners.insert(triple, runner);
            }
            Ok((keys, runners))
        })();
        let (keys, runners) = match resolved {
            Ok(resolved) => resolved,
            Err(error) => {
                log::debug!("running tests without machine-wide permits: {error:#}");
                return Ok(None);
            }
        };
        let shim = crate::session::install_shim_named(
            &std::env::current_exe()?,
            directory,
            SHIM,
            crate::session::ShimLink::Tracking,
        )?;
        Ok(Some(Self {
            keys,
            runners,
            project: repository_identity(workspace_root),
            shim,
        }))
    }

    pub(super) fn environment(&self, environment: &mut BTreeMap<String, String>) -> Result<()> {
        // Cargo splits a runner from the environment on whitespace, so the
        // shim is named through PATH, as `cargo run`'s launch shim is, and
        // the triple rides along as its first argument.
        let path = environment
            .get("PATH")
            .map(OsString::from)
            .or_else(|| std::env::var_os("PATH"))
            .unwrap_or_default();
        let path = std::env::join_paths(
            std::iter::once(self.shim.parent().unwrap().to_path_buf())
                .chain(std::env::split_paths(&path)),
        )?;
        environment.insert("PATH".into(), path.to_string_lossy().into_owned());
        let mut restore = BTreeMap::new();
        for (key, triple) in &self.keys {
            restore.insert(key.clone(), std::env::var(key).ok());
            environment.insert(key.clone(), format!("{SHIM} {triple}"));
        }
        let overlay = Overlay {
            runners: self.runners.clone(),
            restore,
            project: self.project.clone(),
        };
        environment.insert(RUNNERS.into(), serde_json::to_string(&overlay)?);
        Ok(())
    }
}

/// Whether a Cargo command line runs test binaries mbx can wrap.
///
/// Configuration overrides on the command line are out of reach for the same
/// reason as in `cargo run`'s launch: cargo-config2 cannot resolve them, and
/// an unknown runner must never be replaced. A directory change is one too:
/// Cargo reads configuration from the new directory, cargo-config2 from this
/// one.
fn wraps(arguments: &[String]) -> bool {
    let args: Vec<_> = arguments
        .iter()
        .take_while(|arg| arg.as_str() != "--")
        .collect();
    matches!(
        super::launch::cargo_subcommand(arguments),
        Some("test" | "t" | "nextest")
    ) && !args.iter().any(|arg| {
        arg.starts_with('+')
            || arg.starts_with("-C")
            || matches!(
                arg.as_str(),
                "--config" | "--directory" | "--help" | "-h" | "--no-run"
            )
            || arg.starts_with("--config=")
            || arg.starts_with("--directory=")
    })
}

fn is_shim(path: &Path) -> bool {
    path.file_stem() == Some(OsStr::new(SHIM))
}

fn inherited_overlay() -> Overlay {
    std::env::var(RUNNERS)
        .ok()
        .and_then(|value| serde_json::from_str(&value).ok())
        .unwrap_or_default()
}

/// Run one test binary once the pool has room for it.
pub fn dispatch() -> Option<ExitCode> {
    let mut arguments = std::env::args_os();
    if arguments.next().is_none_or(|arg| !is_shim(Path::new(&arg))) {
        return None;
    }
    let result = (|| -> Result<ExitCode> {
        let triple = arguments
            .next()
            .ok_or_else(|| eyre::eyre!("missing target triple"))?;
        let executable = arguments
            .next()
            .ok_or_else(|| eyre::eyre!("Cargo supplied no test binary"))?;
        let rest: Vec<OsString> = arguments.collect();
        let mut overlay = inherited_overlay();
        let runner = overlay.runners.remove(&*triple.to_string_lossy()).flatten();
        let mut command = match &runner {
            Some(runner) => {
                let mut command = Command::new(&runner.path);
                command.args(&runner.args).arg(&executable);
                command
            }
            None => Command::new(&executable),
        };
        command
            .args(&rest)
            // Explicitly off for shims the test's own builds run, and for any
            // mbx command it starts: that work is charged to this permit.
            .env(crate::scheduler::SCHED_DIR_ENV, "")
            .env("MBX_SCHEDULER", "0")
            .env("MBX_CONTROL_CHILD", "1")
            .env_remove(RUNNERS);
        for (key, value) in &overlay.restore {
            match value {
                Some(value) => command.env(key, value),
                None => command.env_remove(key),
            };
        }
        let package = std::env::var("CARGO_PKG_NAME").ok();
        let nextest_phase = std::env::var("NEXTEST_TEST_PHASE").ok();
        let nextest_identity = nextest_test_identity(NextestIdentityInput {
            phase: nextest_phase.as_deref(),
            execution_mode: std::env::var("NEXTEST_EXECUTION_MODE").ok().as_deref(),
            binary_id: std::env::var("NEXTEST_BINARY_ID").ok().as_deref(),
            test_name: std::env::var("NEXTEST_TEST_NAME").ok().as_deref(),
            package: package.as_deref(),
            project: overlay.project.as_deref(),
            executable: Path::new(&executable),
            arguments: &rest,
        });
        // Cargo names its test binaries with a metadata hash. Rustdoc runs
        // each doctest through the same runner, from a temporary binary with
        // no hash, and those run unscheduled: a permit per doctest would
        // serialize a crate's doc examples behind half the pool apiece.
        let suite_demand = test_binary_name(Path::new(&executable)).map(|name| {
            crate::scheduler::Demand::test(
                &ledger_name(overlay.project.as_deref(), package.as_deref(), &name),
                test_threads(&rest, std::env::var("RUST_TEST_THREADS").ok().as_deref()),
            )
        });
        let demand = nextest_identity
            .as_ref()
            .map_or(suite_demand, |(binary, test)| {
                Some(crate::scheduler::Demand::nextest(binary, test))
            });
        // Listing a suite starts no tests and costs nothing worth waiting for.
        let permit = demand
            .as_ref()
            .filter(|_| !lists_tests(&rest) && nextest_phase.as_deref() != Some("list"))
            .and_then(|demand| {
                let pool = crate::scheduler::pool()?;
                let permit = if nextest_identity.is_some() {
                    admit_nextest(pool, demand)
                } else {
                    pool.admit(demand)
                }?;
                Some((demand, permit))
            });
        let started = std::time::Instant::now();
        let status = command
            .status()
            .wrap_err_with(|| format!("failed to run {}", Path::new(&executable).display()))?;
        let wall = started.elapsed();
        if let Some((demand, permit)) = permit {
            // A run that exited on its own, failing tests included, ran the
            // whole suite; one a signal stopped, or one narrowed to some of
            // its tests, says little about what the suite costs. A nextest
            // test is always run narrowed to itself, which is what it is
            // remembered as.
            //
            // A suite this quick cannot keep cores busy long enough to
            // matter, but unrecorded it would ask for half the pool on every
            // run. Weigh it one core; a longer run raises that. Where CPU
            // time cannot be measured nothing could raise it, so nothing is
            // recorded.
            let cores = (status.code().is_some()
                && (nextest_identity.is_some() || !narrows_suite(&rest)))
            .then(crate::scheduler::child_cpu_time)
            .flatten()
            .map(|cpu| {
                if wall < MIN_CPU_SAMPLE {
                    1
                } else {
                    crate::scheduler::average_cores(cpu, wall)
                }
            });
            crate::scheduler::record_test_run(demand, &status, cores);
            drop(permit);
        }
        Ok(super::cargo::exit_code(status))
    })();
    Some(result.unwrap_or_else(|error| {
        eprintln!("mbx[error]: failed to run test binary: {error:#}");
        ExitCode::FAILURE
    }))
}

/// A Cargo test binary's name without the metadata hash Cargo appends to it,
/// so its memory history survives the hash changing. `None` for anything
/// without that hash, which is not a binary Cargo built.
fn test_binary_name(executable: &Path) -> Option<String> {
    let stem = executable.file_stem()?.to_str()?;
    let (name, hash) = stem.rsplit_once('-')?;
    (!name.is_empty() && hash.len() == 16 && hash.bytes().all(|byte| byte.is_ascii_hexdigit()))
        .then(|| name.to_owned())
}

/// What a test binary's history is remembered under.
///
/// The ledger is shared by every project on the machine, and both package and
/// test names repeat across projects -- `server`, `tests/integration.rs` -- so
/// the repository and the package Cargo is testing are part of the name.
/// Neither a package name nor a binary name can hold a `/`.
fn ledger_name(project: Option<&str>, package: Option<&str>, binary: &str) -> String {
    [project, package, Some(binary)]
        .into_iter()
        .flatten()
        .filter(|part| !part.is_empty())
        .collect::<Vec<_>>()
        .join("/")
}

/// A short name for the Git repository `workspace_root` is in, the same for
/// each of its worktrees and different for any other repository.
///
/// Not the checkout path, which would keep a project's worktrees from sharing
/// what one of them measured: a linked worktree's `.git` file points into the
/// main repository, whose directory every worktree shares. Read from the files
/// rather than asked of `git`, which is not guaranteed to be installed.
/// `None` outside Git, where history falls back to package and binary names.
fn repository_identity(workspace_root: &Path) -> Option<String> {
    use sha2::Digest as _;
    let checkout = workspace_root
        .ancestors()
        .find(|directory| directory.join(".git").exists())?;
    let dot_git = checkout.join(".git");
    let common = if dot_git.is_dir() {
        dot_git
    } else {
        let pointer = std::fs::read_to_string(&dot_git).ok()?;
        let git_dir = checkout.join(pointer.strip_prefix("gitdir:")?.trim());
        match std::fs::read_to_string(git_dir.join("commondir")) {
            Ok(common) => git_dir.join(common.trim()),
            // A submodule's directory is its own repository.
            Err(_) => git_dir,
        }
    };
    let common = common.canonicalize().ok()?;
    let digest = sha2::Sha256::digest(common.as_os_str().as_encoded_bytes());
    Some(hex::encode(&digest[..6]))
}

/// The thread count libtest will use, when the command or environment says.
fn test_threads(arguments: &[OsString], environment: Option<&str>) -> Option<u64> {
    let mut arguments = arguments.iter().filter_map(|arg| arg.to_str());
    let mut stated = None;
    while let Some(argument) = arguments.next() {
        if argument == "--" {
            break;
        }
        if argument == "--test-threads" {
            stated = arguments.next().and_then(|value| value.parse().ok());
        } else if let Some(value) = argument.strip_prefix("--test-threads=") {
            stated = value.parse().ok();
        }
    }
    stated.or_else(|| environment?.parse().ok())
}

/// Whether the harness arguments run only part of the suite: a name filter,
/// `--skip`, or `--ignored`.
fn narrows_suite(arguments: &[OsString]) -> bool {
    let mut arguments = arguments.iter().map(|arg| arg.to_string_lossy());
    while let Some(argument) = arguments.next() {
        match argument.as_ref() {
            "--" => return arguments.next().is_some(),
            "--skip" | "--ignored" => return true,
            argument if argument.starts_with("--skip=") => return true,
            // libtest's options that take a separate value.
            "--test-threads" | "--format" | "--logfile" | "--color" | "--shuffle-seed" | "-Z" => {
                arguments.next();
            }
            argument if !argument.starts_with('-') => return true,
            _ => {}
        }
    }
    false
}

fn lists_tests(arguments: &[OsString]) -> bool {
    arguments
        .iter()
        .take_while(|arg| arg.as_os_str() != "--")
        .any(|arg| arg == "--list")
}

/// The nextest test this runner invocation is starting, when its environment
/// and arguments identify one.
struct NextestIdentityInput<'a> {
    phase: Option<&'a str>,
    execution_mode: Option<&'a str>,
    binary_id: Option<&'a str>,
    test_name: Option<&'a str>,
    package: Option<&'a str>,
    project: Option<&'a str>,
    executable: &'a Path,
    arguments: &'a [OsString],
}

fn nextest_test_identity(input: NextestIdentityInput<'_>) -> Option<(String, String)> {
    if input.phase == Some("list") || lists_tests(input.arguments) {
        return None;
    }
    let running = input.phase == Some("run")
        || (input.phase.is_none() && input.execution_mode == Some("process-per-test"));
    if !running {
        return None;
    }
    let test = input
        .test_name
        .filter(|name| !name.is_empty())
        .map(str::to_owned)
        .or_else(|| exact_test_name(input.arguments))?;
    let binary = input
        .binary_id
        .filter(|id| !id.is_empty())
        .map(|id| ledger_name(input.project, None, id))
        .or_else(|| {
            let name = test_binary_name(input.executable)?;
            Some(ledger_name(input.project, input.package, &name))
        })?;
    Some((binary, test))
}

fn exact_test_name(arguments: &[OsString]) -> Option<String> {
    let mut arguments = arguments.iter().filter_map(|argument| argument.to_str());
    while let Some(argument) = arguments.next() {
        if argument == "--" {
            return None;
        }
        if argument == "--exact" {
            return arguments.next().map(str::to_owned);
        }
        if let Some(name) = argument.strip_prefix("--exact=") {
            return (!name.is_empty()).then(|| name.to_owned());
        }
    }
    None
}

/// How long a nextest test waits for permits before saying so.
const WAIT_NOTICE: std::time::Duration = std::time::Duration::from_secs(1);

/// Admit one nextest test, saying so on stderr when it has to wait.
///
/// nextest starts a test's slow-timeout and terminate-after clocks when it
/// starts this shim, so the wait for permits counts as test time, and nothing
/// a runner can do pauses those clocks. nextest captures the test's stderr
/// and shows it beside a SLOW, TIMEOUT or failure report, so a test killed
/// while it was still queued says so instead of looking like it hung. The
/// notice is printed while the wait is still going, because the kill
/// arrives before admission would have returned.
fn admit_nextest(
    pool: &crate::scheduler::Pool,
    demand: &crate::scheduler::Demand,
) -> Option<crate::scheduler::Permit> {
    let (admitted, wait) = std::sync::mpsc::channel::<()>();
    let notice = std::thread::spawn(move || {
        // Admission ends the wait by dropping the sender, which disconnects.
        if let Err(std::sync::mpsc::RecvTimeoutError::Timeout) = wait.recv_timeout(WAIT_NOTICE) {
            eprintln!(
                "mbx: waiting for machine-wide scheduler capacity before starting this test; nextest counts this wait toward its slow-timeout"
            );
        }
    });
    let started = std::time::Instant::now();
    let permit = pool.admit(demand);
    let waited = started.elapsed();
    drop(admitted);
    let _ = notice.join();
    if permit.is_some() && waited >= WAIT_NOTICE {
        eprintln!(
            "mbx: test started after waiting {:.1}s for scheduler capacity",
            waited.as_secs_f64()
        );
    }
    permit
}

#[cfg(test)]
mod tests {
    use super::*;

    fn strings(values: &[&str]) -> Vec<String> {
        values.iter().map(|value| value.to_string()).collect()
    }

    fn os(values: &[&str]) -> Vec<OsString> {
        values.iter().map(OsString::from).collect()
    }

    #[test]
    fn cargo_test_and_nextest_commands_are_wrapped() {
        assert!(wraps(&strings(&["test"])));
        assert!(wraps(&strings(&["t", "--workspace"])));
        assert!(wraps(&strings(&["nextest", "run"])));
        assert!(wraps(&strings(&["nextest", "r"])));
        assert!(wraps(&strings(&["nextest", "list"])));
        assert!(wraps(&strings(&["--color", "always", "test"])));
        assert!(wraps(&strings(&["test", "--", "--config"])));
        assert!(!wraps(&strings(&["build"])));
        assert!(!wraps(&strings(&["run", "--", "test"])));
        assert!(!wraps(&strings(&["test", "--no-run"])));
        assert!(!wraps(&strings(&["nextest", "run", "--no-run"])));
        assert!(!wraps(&strings(&["+nightly", "test"])));
        assert!(!wraps(&strings(&["test", "--config", "a.toml"])));
        assert!(!wraps(&strings(&["test", "--config=a.toml"])));
        assert!(!wraps(&strings(&["-C", "other", "test"])));
        assert!(!wraps(&strings(&["-Cother", "test"])));
        assert!(!wraps(&strings(&["--directory", "other", "test"])));
        assert!(!wraps(&strings(&["--directory=other", "test"])));
    }

    #[test]
    fn nextest_identity_uses_phase_environment_and_exact_filter() {
        let executable = Path::new("target/debug/deps/mbx-0123456789abcdef");
        let args = os(&["--exact", "suite::case", "--nocapture"]);
        assert_eq!(
            nextest_test_identity(NextestIdentityInput {
                phase: Some("run"),
                execution_mode: Some("process-per-test"),
                binary_id: Some("mbx::integration"),
                test_name: Some("suite::case"),
                package: Some("mbx"),
                project: Some("ab12"),
                executable,
                arguments: &args,
            }),
            Some(("ab12/mbx::integration".into(), "suite::case".into()))
        );
        let args = os(&["--exact=suite::case", "--nocapture"]);
        assert_eq!(
            nextest_test_identity(NextestIdentityInput {
                phase: None,
                execution_mode: Some("process-per-test"),
                binary_id: None,
                test_name: None,
                package: Some("mbx"),
                project: Some("ab12"),
                executable,
                arguments: &args,
            }),
            Some(("ab12/mbx/mbx".into(), "suite::case".into()))
        );
        let args = os(&["--exact", "suite::case"]);
        assert_eq!(
            nextest_test_identity(NextestIdentityInput {
                phase: Some("run"),
                execution_mode: None,
                binary_id: Some("mbx"),
                test_name: None,
                package: None,
                project: None,
                executable,
                arguments: &args,
            }),
            Some(("mbx".into(), "suite::case".into()))
        );
    }

    #[test]
    fn nextest_listing_and_unknown_runs_have_no_test_identity() {
        let executable = Path::new("target/debug/deps/mbx-0123456789abcdef");
        let args = os(&["--exact", "suite::case"]);
        assert_eq!(
            nextest_test_identity(NextestIdentityInput {
                phase: Some("list"),
                execution_mode: Some("process-per-test"),
                binary_id: Some("mbx"),
                test_name: Some("suite::case"),
                package: None,
                project: None,
                executable,
                arguments: &args,
            }),
            None
        );
        let list_args = os(&["--list"]);
        assert_eq!(
            nextest_test_identity(NextestIdentityInput {
                phase: Some("run"),
                execution_mode: None,
                binary_id: Some("mbx"),
                test_name: Some("suite::case"),
                package: None,
                project: None,
                executable,
                arguments: &list_args,
            }),
            None
        );
        assert_eq!(
            nextest_test_identity(NextestIdentityInput {
                phase: None,
                execution_mode: None,
                binary_id: Some("mbx"),
                test_name: Some("suite::case"),
                package: None,
                project: None,
                executable,
                arguments: &args,
            }),
            None
        );
        let doctest = Path::new("doctest-temp");
        assert_eq!(
            nextest_test_identity(NextestIdentityInput {
                phase: Some("run"),
                execution_mode: None,
                binary_id: None,
                test_name: None,
                package: None,
                project: None,
                executable: doctest,
                arguments: &args,
            }),
            None
        );
    }

    #[test]
    fn only_hashed_cargo_binaries_are_test_binaries() {
        assert_eq!(
            test_binary_name(Path::new("target/debug/deps/mbx-0123456789abcdef")).as_deref(),
            Some("mbx")
        );
        assert_eq!(
            test_binary_name(Path::new("deps/cache_tests-fedcba9876543210.exe")).as_deref(),
            Some("cache_tests")
        );
        assert_eq!(test_binary_name(Path::new("deps/my-tool")), None);
        assert_eq!(test_binary_name(Path::new("deps/-0123456789abcdef")), None);
        // Rustdoc's doctest binaries.
        assert_eq!(
            test_binary_name(Path::new("/tmp/rustdoctestAbC/rust_out")),
            None
        );
    }

    #[test]
    fn history_is_kept_per_repository_and_package() {
        assert_eq!(
            ledger_name(Some("ab12"), Some("parser"), "it"),
            "ab12/parser/it"
        );
        assert_ne!(
            ledger_name(Some("ab12"), Some("server"), "it"),
            ledger_name(Some("cd34"), Some("server"), "it")
        );
        assert_eq!(ledger_name(None, Some("parser"), "it"), "parser/it");
        assert_eq!(ledger_name(None, None, "it"), "it");
        assert_eq!(ledger_name(Some(""), Some(""), "it"), "it");
    }

    #[test]
    fn worktrees_share_a_repository_identity_and_other_repositories_do_not() {
        let root = tempfile::tempdir().unwrap();
        let main = root.path().join("main");
        std::fs::create_dir_all(main.join(".git/worktrees/feature")).unwrap();
        std::fs::create_dir_all(main.join("crates/app")).unwrap();
        std::fs::write(main.join(".git/worktrees/feature/commondir"), "../..\n").unwrap();
        // Linked worktrees, pointing into the main repository relatively
        // from one checkout and absolutely from another.
        let feature = root.path().join("feature");
        std::fs::create_dir_all(&feature).unwrap();
        std::fs::write(
            feature.join(".git"),
            "gitdir: ../main/.git/worktrees/feature\n",
        )
        .unwrap();
        let other_feature = root.path().join("other-feature");
        std::fs::create_dir_all(&other_feature).unwrap();
        std::fs::write(
            other_feature.join(".git"),
            format!(
                "gitdir: {}\n",
                main.join(".git/worktrees/feature").display()
            ),
        )
        .unwrap();
        let unrelated = root.path().join("unrelated");
        std::fs::create_dir_all(unrelated.join(".git")).unwrap();

        let identity = repository_identity(&main).expect("a repository has an identity");
        assert_eq!(identity.len(), 12);
        assert_eq!(
            repository_identity(&main.join("crates/app")),
            Some(identity.clone())
        );
        assert_eq!(repository_identity(&feature), Some(identity.clone()));
        assert_eq!(repository_identity(&other_feature), Some(identity.clone()));
        assert_ne!(repository_identity(&unrelated), Some(identity));
    }

    #[test]
    fn thread_counts_come_from_arguments_before_the_environment() {
        assert_eq!(test_threads(&os(&[]), None), None);
        assert_eq!(test_threads(&os(&[]), Some("3")), Some(3));
        assert_eq!(
            test_threads(&os(&["--test-threads", "2"]), Some("3")),
            Some(2)
        );
        assert_eq!(test_threads(&os(&["--test-threads=5"]), None), Some(5));
        assert_eq!(test_threads(&os(&["--", "--test-threads=5"]), None), None);
        assert_eq!(test_threads(&os(&[]), Some("many")), None);
    }

    #[test]
    fn narrowed_runs_are_recognised() {
        assert!(!narrows_suite(&os(&[])));
        assert!(!narrows_suite(&os(&["--test-threads", "4", "--nocapture"])));
        assert!(!narrows_suite(&os(&[
            "--format",
            "json",
            "--include-ignored"
        ])));
        assert!(narrows_suite(&os(&["parser"])));
        assert!(narrows_suite(&os(&["--exact", "parser::tokens"])));
        assert!(narrows_suite(&os(&["--skip", "slow"])));
        assert!(narrows_suite(&os(&["--skip=slow"])));
        assert!(narrows_suite(&os(&["--ignored"])));
        assert!(narrows_suite(&os(&["--", "parser"])));
    }

    #[test]
    fn listing_is_recognised() {
        assert!(lists_tests(&os(&["--list", "--format", "terse"])));
        assert!(!lists_tests(&os(&["--exact", "list"])));
    }

    #[test]
    fn nested_shims_are_recognised_by_name() {
        assert!(is_shim(Path::new("/tmp/mbx-session-x/mbx-test-runner")));
        assert!(is_shim(Path::new("mbx-test-runner.exe")));
        assert!(!is_shim(Path::new("/usr/bin/qemu-aarch64")));
    }
}