TExcelTAD
Home › Cargo in Depth › Field Notes: CI, MSRV & build.rs Hygiene

Field Notes: CI, MSRV & build.rs Hygiene

The second set of field notes is about the build itself: what a Rust CI pipeline should run, how to keep a minimum supported Rust version honest, and how to write build scripts that don't make everyone's builds slow or wrong.

1. CI builds with --locked

Without it, Cargo quietly re-resolves when Cargo.toml and Cargo.lock disagree, and CI tests a dependency graph nobody reviewed. With it, the mismatch is an error that points at the forgotten lockfile (lesson). Use --locked on every Cargo command in CI, including cargo install --locked for tools.

A pipeline that covers the usual failure modes, as a script you can also run locally:

bash · try it yourself
cargo new --lib shapes --vcs none -q
cd shapes
cargo add anyhow -q
cat > src/lib.rs <<'RS'
//! Shapes.

/// Area of a `w` by `h` rectangle.
///
/// ```
/// assert_eq!(shapes::area(2, 3), 6);
/// ```
pub fn area(w: u32, h: u32) -> u32 {
    w * h
}
RS
cat > ci.sh <<'SH'
set -e
step() { echo "== $*"; "$@" 2>&1 | grep -E '^(error|warning: unused|Diff in)|test result' || true; test "${PIPESTATUS[0]}" -eq 0; }
step cargo fmt --all --check
step cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
step cargo test --workspace --all-features --locked
echo "== all green"
SH
bash ci.sh
echo "--- a teammate adds a dependency but forgets Cargo.lock"
echo 'regex = "1"' >> Cargo.toml
bash ci.sh || echo "CI failed (as it should)"
== cargo fmt --all --check
== cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
== cargo test --workspace --all-features --locked
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
== all green
--- a teammate adds a dependency but forgets Cargo.lock
== cargo fmt --all --check
== cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
error: cannot update the lock file /home/learner/shapes/Cargo.lock because --locked was passed to prevent this
CI failed (as it should)

The pieces, and why each is there:

Step Catches
cargo fmt --check unformatted code (cheap, run first)
cargo clippy --all-targets --all-features --locked -- -D warnings lints in tests/examples too, features that don't compile, stale lockfile
cargo test --workspace --locked tests and doc tests of every member
cargo hack check --each-feature (optional) features that only compile together
cargo doc --no-deps with RUSTDOCFLAGS=-D warnings broken intra-doc links
cargo deny check / cargo audit licenses, bans, advisories (Toolkit)
an MSRV job (below) use of newer language or library features

In GitHub Actions the same steps look like this. Pin the toolchain (a rust-toolchain.toml in the repository is the simplest), and cache ~/.cargo/registry and target/ keyed on Cargo.lock:

yaml
jobs:
  test:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v5
      - run: rustup show            # installs the toolchain from rust-toolchain.toml
      - uses: Swatinem/rust-cache@v2
      - run: cargo fmt --all --check
      - run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
      - run: cargo test --workspace --all-features --locked
  msrv:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v5
      - run: rustup toolchain install 1.85 --profile minimal
      - run: cargo +1.85 check --workspace --all-features --locked

2. Declare and test the MSRV

rust-version is a promise, and Cargo enforces the half it can see: building with an older compiler fails up front with a clear message instead of a confusing syntax error deep in your code.

bash · try it yourself
cargo new demo --vcs none -q
cd demo
sed -i 's/^edition.*/&\nrust-version = "1.200"/' Cargo.toml
cargo build 2>&1
echo "--- override (e.g. to try anyway)"
cargo build -q --ignore-rust-version 2>&1 && echo "built"
error: rustc 1.99.1 is not supported by the following package:
  demo@0.1.0 requires rustc 1.200

--- override (e.g. to try anyway)
built

The half Cargo can't see is whether your code really builds with that version. Only a CI job with the old toolchain (cargo +1.85 check) proves it; cargo-msrv can find the real minimum. Bump the MSRV deliberately (it's a compatibility change for users: many projects treat it as a minor-version bump) and keep it in [workspace.package] so all members agree.

3. build.rs: declare every input

A build script's output is cached until one of its declared inputs changes. An input you read but don't declare gives you stale builds, the worst kind of bug because a clean build "fixes" it:

bash · try it yourself
cargo new mode --vcs none -q
cd mode
cat > build.rs <<'RS'
fn main() {
    println!("cargo::rerun-if-changed=build.rs");
    let mode = std::env::var("APP_MODE").unwrap_or_else(|_| "dev".into());
    println!("cargo::rustc-env=APP_MODE={mode}");
}
RS
echo 'fn main() { println!("mode: {}", env!("APP_MODE")); }' > src/main.rs
APP_MODE=staging cargo run -q
echo "--- change the variable: the binary is stale!"
APP_MODE=production cargo run -q
echo "--- declare the input"
sed -i 's|^    println!("cargo::rerun-if-changed=build.rs");|&\n    println!("cargo::rerun-if-env-changed=APP_MODE");|' build.rs
APP_MODE=production cargo run -q
APP_MODE=staging cargo run -q
mode: staging
--- change the variable: the binary is stale!
mode: staging
--- declare the input
mode: production
mode: staging

4. More build.rs rules

  • Write only to OUT_DIR, never into src/ or the workspace (Generated Code).
  • No network access. Builds must work offline, in sandboxes (Nix, Bazel, distro packaging) and in vendored form. Download nothing; ship the data or make it an explicit, documented step.
  • Use CARGO_CFG_TARGET_*, not cfg!(), to decide things about the target; the script itself runs on the host.
  • Keep it small and fast. A build script and its [build-dependencies] are compiled before the crate itself and sit on the critical path of every build. Heavy generators (bindgen) are often better run ahead of time with the output committed.
  • Fail loudly with a helpful message (cargo::error=libfoo not found; install libfoo-dev or set FOO_DIR), not a panic backtrace.
  • Respect the environment: honour CC, CFLAGS, PKG_CONFIG_PATH, FOO_STATIC-style overrides, and declare each with rerun-if-env-changed (the cc and pkg-config crates do this for you).

5. Know where the time goes

cargo build --timings writes an HTML report (target/cargo-timings/cargo-timing.html) with every unit's start and end, what was waiting on what, and how much parallelism was used. It's the first thing to look at when a build is slow; Build Performance covers what to do next (sccache, splitting crates, fewer proc-macros, [profile.dev.package."*"]).

Test yourself

A build script reads APP_MODE but only prints rerun-if-changed=build.rs. What happens when APP_MODE changes?

  1. The script reruns automatically
  2. Nothing reruns; the binary keeps the old value until build.rs changes or a clean build
  3. Cargo errors
  4. Cargo warns about the variable

Why add --locked to cargo test in CI?

  1. It makes tests faster
  2. It fails the build if Cargo.lock would change, so CI tests exactly the reviewed lockfile
  3. It locks the target directory
  4. It disables network

How do you actually verify that a crate builds with its declared rust-version = "1.85"?

  1. Cargo checks it on every build
  2. Run a CI job that builds/checks with the 1.85 toolchain (e.g. cargo +1.85 check --locked)
  3. cargo publish verifies it
  4. clippy checks it