Skip to main content

agentmux_common/
checkout.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Is a test binary running the code of the checkout that runs it?
5//!
6//! Cargo names a workspace's own crates the same in every clone of the
7//! repository. Two clones that share one target directory (`CARGO_TARGET_DIR`)
8//! therefore write the same artifacts, and cargo, which checks the source files
9//! the existing artifact was built from, can call another clone's build fresh:
10//! `cargo test` in one clone then runs the other clone's code and reports its
11//! results as this clone's. Seen on 2026-10-17, with four clones sharing a
12//! target dir: passes and failures that belonged to other branches, and a
13//! "cannot find type" for code that was plainly there.
14//!
15//! Every test binary of the workspace (each crate's unit tests and each file
16//! under `tests/`) invokes [`checkout_guard!`]. It runs [`guard`] when the
17//! binary starts, before the test harness, so a test-name filter can't skip
18//! it. The crate folder compiled into the binary (`CARGO_MANIFEST_DIR` at build
19//! time) must be the one cargo runs it for (`CARGO_MANIFEST_DIR` at run time);
20//! and each workspace library it links must have been compiled in the same
21//! workspace, since cargo can rebuild the test binary yet link another
22//! checkout's library it thinks fresh. Each library exports the folder it was
23//! compiled in (`COMPILED_IN` here, `CHECKOUT_DIR` in the others) for that.
24
25/// The folder this library was compiled in, for [`checkout_guard!`].
26pub const COMPILED_IN: &str = env!("CARGO_MANIFEST_DIR");
27
28use std::path::Path;
29
30/// `Err` with what to do when the test binary was compiled from another
31/// checkout than the one running it. `compiled` is the invoking crate's
32/// `env!("CARGO_MANIFEST_DIR")`. `Ok` when the binary isn't run by cargo (no
33/// `CARGO_MANIFEST_DIR` at run time), so it can't tell.
34pub fn check(compiled: &str) -> Result<(), String> {
35    match std::env::var("CARGO_MANIFEST_DIR") {
36        Ok(running) if !running.is_empty() => compare(Path::new(compiled), Path::new(&running)),
37        _ => Ok(()),
38    }
39}
40
41/// `Err` when a workspace library `linked` into the test binary was compiled
42/// in another workspace than the binary itself (`compiled`): their workspace
43/// roots, two folders up, must be the same folder.
44pub fn check_linked(compiled: &str, linked: &[&str]) -> Result<(), String> {
45    let root = |dir: &str| Path::new(dir).parent().and_then(Path::parent).map(Path::to_path_buf);
46    let Some(mine) = root(compiled) else { return Ok(()) };
47    for lib in linked {
48        let Some(theirs) = root(lib) else { continue };
49        if !same_folder(&mine, &theirs) {
50            return Err(format!(
51                "this test binary was built from {compiled} but links a workspace library compiled from {lib}: \
52                 checkouts sharing a cargo target directory reuse each other's libraries, so the tests would run \
53                 the other checkout's code. Give each checkout its own target directory (unset CARGO_TARGET_DIR, \
54                 or point it at a folder of this checkout's own), then build again."
55            ));
56        }
57    }
58    Ok(())
59}
60
61/// What [`checkout_guard!`] runs at a test binary's start: on a mismatch, the
62/// reason on stderr and exit code 101, as a failed test run would. Only under
63/// cargo: a binary run by hand elsewhere may name folders that aren't there.
64#[doc(hidden)]
65pub fn guard(compiled: &str, linked: &[&str]) {
66    if std::env::var_os("CARGO_MANIFEST_DIR").is_none() {
67        return;
68    }
69    if let Err(e) = check(compiled).and_then(|()| check_linked(compiled, linked)) {
70        eprintln!("error: {e}");
71        std::process::exit(101);
72    }
73}
74
75/// Runs [`guard`] for the invoking crate when its test binary starts, from the
76/// platform's initializer section (as the `ctor` crate does). Invoke it once
77/// per test binary: at a crate's root, behind `#[cfg(test)]` where the crate
78/// has `agentmux-common` only as a dev-dependency, and at the top of each
79/// file under `tests/`. Pass the `CHECKOUT_DIR` of each other workspace
80/// library the binary links (`agentmux_common`'s is always checked).
81#[macro_export]
82macro_rules! checkout_guard {
83    ($($lib:expr),* $(,)?) => {
84        const _: () = {
85            extern "C" fn agentmux_checkout_guard() {
86                $crate::checkout::guard(env!("CARGO_MANIFEST_DIR"), &[$crate::checkout::COMPILED_IN, $($lib),*]);
87            }
88            #[used]
89            #[cfg_attr(any(target_os = "linux", target_os = "android", target_os = "freebsd"), link_section = ".init_array")]
90            #[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")]
91            #[cfg_attr(target_vendor = "apple", link_section = "__DATA,__mod_init_func")]
92            static AGENTMUX_CHECKOUT_GUARD: extern "C" fn() = agentmux_checkout_guard;
93        };
94    };
95}
96
97fn compare(compiled: &Path, running: &Path) -> Result<(), String> {
98    if same_folder(compiled, running) {
99        return Ok(());
100    }
101    Err(format!(
102        "this test binary was compiled from {} but cargo is running it for {}: the two checkouts share a \
103         cargo target directory, so their builds overwrite each other and tests can run the other checkout's \
104         code. Give each checkout its own target directory (unset CARGO_TARGET_DIR, or point it at a folder \
105         of this checkout's own), then build again.",
106        compiled.display(),
107        running.display()
108    ))
109}
110
111/// The same folder: the same path once links and `..` are resolved, or, when
112/// the paths differ (a `subst` drive, a junction), the same `Cargo.toml` file
113/// on disk, by file identity, never by look-alike metadata.
114fn same_folder(a: &Path, b: &Path) -> bool {
115    if let (Ok(ca), Ok(cb)) = (a.canonicalize(), b.canonicalize()) {
116        if ca == cb {
117            return true;
118        }
119    }
120    same_file::is_same_file(a.join("Cargo.toml"), b.join("Cargo.toml")).unwrap_or(false)
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    /// The guard only works while cargo tells a test where it runs: under
128    /// cargo (`CARGO` set), `CARGO_MANIFEST_DIR` must be there too, or every
129    /// guard would pass without checking anything.
130    #[test]
131    fn cargo_says_which_checkout_runs_the_test() {
132        if std::env::var_os("CARGO").is_some() {
133            assert!(std::env::var_os("CARGO_MANIFEST_DIR").is_some(), "cargo ran this test without CARGO_MANIFEST_DIR");
134        }
135    }
136
137    fn checkout(root: &Path) {
138        std::fs::create_dir_all(root).unwrap();
139        std::fs::write(root.join("Cargo.toml"), "[package]\n").unwrap();
140    }
141
142    #[test]
143    fn another_checkouts_binary_is_refused_and_says_what_to_do() {
144        let base = std::env::temp_dir().join(format!("agentmux-checkout-test-{}", std::process::id()));
145        let (a, b) = (base.join("clone-a"), base.join("clone-b"));
146        checkout(&a);
147        checkout(&b);
148        let err = compare(&a, &b).unwrap_err();
149        assert!(err.contains("share a cargo target directory"), "{err}");
150        assert!(err.contains("CARGO_TARGET_DIR"), "{err}");
151        // Two copies with the same contents and timestamps are still two.
152        let stamp = std::fs::metadata(a.join("Cargo.toml")).unwrap().modified().unwrap();
153        std::fs::File::options().write(true).open(b.join("Cargo.toml")).unwrap().set_modified(stamp).unwrap();
154        assert!(compare(&a, &b).is_err(), "look-alike copies aren't the same checkout");
155        // The same folder by another spelling is the same checkout.
156        assert!(compare(&a, &a.join("..").join("clone-a")).is_ok());
157        let _ = std::fs::remove_dir_all(&base);
158    }
159
160    /// A test binary rebuilt in one checkout that links a library cargo
161    /// thought fresh from another (#5097).
162    #[test]
163    fn a_library_from_another_checkout_is_refused() {
164        let base = std::env::temp_dir().join(format!("agentmux-linked-test-{}", std::process::id()));
165        for clone in ["clone-a", "clone-b"] {
166            checkout(&base.join(clone));
167            std::fs::create_dir_all(base.join(clone).join("crates").join("lib")).unwrap();
168            std::fs::create_dir_all(base.join(clone).join("crates").join("app")).unwrap();
169        }
170        let dir = |clone: &str, krate: &str| base.join(clone).join("crates").join(krate).to_string_lossy().into_owned();
171        assert!(check_linked(&dir("clone-a", "app"), &[&dir("clone-a", "lib")]).is_ok());
172        let err = check_linked(&dir("clone-a", "app"), &[&dir("clone-a", "lib"), &dir("clone-b", "lib")]).unwrap_err();
173        assert!(err.contains("links a workspace library compiled from") && err.contains("clone-b"), "{err}");
174        let _ = std::fs::remove_dir_all(&base);
175    }
176}