Skip to content

d3d12-shader: read CARGO_MANIFEST_DIR at runtime in build.rs - #2882

Open
lixonik wants to merge 1 commit into
ProjectLeonida:mainfrom
lixonik:fix/shader-build-runtime-manifest-dir
Open

lixonik wants to merge 1 commit into
ProjectLeonida:mainfrom
lixonik:fix/shader-build-runtime-manifest-dir

Conversation

@lixonik

@lixonik lixonik commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Claim: D3D12-SHADER-BUILD-MANIFEST-DIR (#2570 (comment))

Fixes @Neutron-0's finding in d3d12/crates/leonida-shader/build.rs.

Root cause

build.rs read env!("CARGO_MANIFEST_DIR") at build-script compile time and silently returned on std::fs::read_dir / std::fs::read errors. Whenever Cargo reruns a cached build.rs executable against a different or moved/removed checkout (for example, a modified source file in another worktree sharing CARGO_TARGET_DIR, or a relocated checkout), it hashed the stale baked path -- or silently emitted the empty seed hash (cbf29ce48422232584222325cbf29ce4) and empty LEONIDA_SHADER_SWITCHES if that original directory was gone.

Note on scope: sharing a single CARGO_TARGET_DIR across two identical checkouts at the same commit still produces a Cargo no-op (Cargo does not rerun the build script at all), so sharing CARGO_TARGET_DIR across checkouts remains unsupported in general. This change guarantees correct hashing and fail-loud behavior whenever the build script runs.

Changes

  • d3d12/crates/leonida-shader/build.rs:
    • Read CARGO_MANIFEST_DIR at runtime via std::env::var_os("CARGO_MANIFEST_DIR") instead of compile-time env!.
    • Emit cargo:rerun-if-changed=build.rs.
    • Fail loudly (panic!) on read_dir / read errors or an empty non-test source list instead of silently emitting an empty fingerprint.
  • d3d12/crates/leonida-shader/src/source_hash_tests.rs:
    • Added build_script_uses_runtime_manifest_dir_and_rejects_missing_src, which compiles build.rs once and drives the compiled binary directly with distinct temporary CARGO_MANIFEST_DIR trees (verifying distinct hashes and switches) and a missing directory (verifying non-zero failure) to validate runtime path resolution and fail-loud behavior whenever the script runs.

Verification

GPUs tested: NVIDIA GeForce RTX 5070 12 GB (driver 621.40, Windows 10 Pro 22H2 build 19045, Ryzen 9 5950X 16C/32T)

AI-assisted: Antigravity

@KelboLive KelboLive left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Direction is right, and the fail-loud paths are a real improvement: with the original checkout gone and the build script forced to rerun, base emits the empty cbf29ce4… hash and empty LEONIDA_SHADER_SWITCHES, while this branch emits the correct hash. rerun-if-changed gains exactly build.rs, which is right because the script now affects the hash, and I confirmed the rerun behaviour: build → no-op → touch src/lib.rs → rebuild → no-op. It also builds correctly from the repo root, from an unrelated cwd, with a custom CARGO_TARGET_DIR, and as a path dependency (same hash as in-tree).

One overclaim, though: with two checkouts at the same commit sharing a CARGO_TARGET_DIR, the second is still a 0.04 s no-op and ships the first checkout's hash — before and after this change — because Cargo never runs the script at all, and a runtime read cannot help that. What is fixed is the case where the script does rerun against a stale baked path. The new test drives the compiled binary directly with a forced CARGO_MANIFEST_DIR, so it validates the mechanism but not the Cargo-level reuse described in the body.

Please narrow the claim to "correct whenever the build script reruns", or state that sharing a target dir across checkouts remains unsupported (the build dir is literally shared — leonida-shader-8d2ca1f295c0ab1e for both).

Two mutations worth recording, both of which the change now catches: a cwd-relative base passes an in-tree cargo build (Cargo runs the script with cwd = package root) and is only caught by the test, while a wrong base now panics loudly where base silently emitted the seed hash. That is the right kind of failure.

@merzleckeier

Copy link
Copy Markdown
Contributor

I exercised the real Cargo reuse path on Linux with Rust 1.98.1, at bfa275ea merged onto b3910e5e. I used two worktrees per arm and a target directory shared by those two worktrees. Only B had a new LEONIDA_REVIEW_CHECKOUT_B string in a non-test source. Cargo compiled the build program once in A and reran that same executable without recompiling it in B, in both arms.

  • On main, A and B emitted identical fingerprints, and B's switch was missing. The existing source-hash check caught it in B (2 passed, 1 failed).
  • With this PR, B got a different fingerprint and contained its new switch. The four source-hash tests passed in both worktrees.

The experiment specifically exercises the case where B's edited source makes Cargo rerun the cached build program. It agrees with the distinction in the previous review about an identical checkout that produces a Cargo no-op. No game files or GPU dependency. MEASURED, AI-assisted (Codex).

@lixonik

lixonik commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@KelboLive Thanks for the careful review! I have updated the PR description to narrow the claim to "correct whenever the build script reruns" and explicitly note that identical-commit checkouts sharing a CARGO_TARGET_DIR still produce a Cargo no-op (so sharing CARGO_TARGET_DIR across checkouts remains unsupported in general). Also clarified that the new test drives the compiled build.rs binary directly.

@merzleckeier Thanks for exercising the two-worktree Cargo rerun path with a modified source file!

@imShangLi

Copy link
Copy Markdown
Contributor

VERIFY-2882 — Linux, Rust 1.98.1 (the pinned toolchain), no GPU device, no game files

Verdict: PASS. The fix closes a hole where the build script would hash nothing and say so with exit code 0. I measured the wrong hash and the loud failure side by side.

Head bfa275ea, base the current main 88a9f133, merge base 3e7b34a5, 1 commit, 2 files, +84/−7: d3d12/crates/leonida-shader/build.rs and the new d3d12/crates/leonida-shader/src/source_hash_tests.rs.

1. What was wrong

The build script hashes the translator's own sources so the shader cache can tell whether a cached translation is still current. It found them like this:

let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
…
let Ok(entries) = std::fs::read_dir(dir) else { return; };   // a directory that cannot be read: no sources
…
let text = std::fs::read(p).unwrap_or_default();               // a file that cannot be read: an empty file

Two problems:

  • env!("CARGO_MANIFEST_DIR") is expanded when build.rs is compiled, so the path is baked into the build-script binary. The pull request reads it when the script runs: std::env::var_os("CARGO_MANIFEST_DIR").
  • Every failure was silent. A directory that cannot be read gave an empty source list, and a file that cannot be read hashed as an empty file — so the "source hash" was quietly the hash of nothing, and the build carried on with exit code 0.

2. What that cost, measured

I compiled main's build script with the path baked in, deleted the directory it pointed at, and ran it:

$ CARGO_MANIFEST_DIR=$PWD/a ./a/probe          # main's build.rs, a/src removed
  退出码: 0                                        <-- silent success
cargo:rerun-if-changed=src
cargo:rerun-if-changed=Cargo.toml
cargo:rustc-env=LEONIDA_SHADER_SOURCE_HASH=cbf29ce48422232584222325cbf29ce4
cargo:rustc-env=LEONIDA_SHADER_SWITCHES=

cbf29ce48422232584222325cbf29ce4 is the FNV-1a offset basis — the hash of the empty set. Every shader would then get the same cache key, so the shader cache could hand back the wrong translation, and nothing would say so. The same run of the pull request's build script:

$ CARGO_MANIFEST_DIR=$PWD/b ./b/probe          # the pull request's build.rs, b/src removed
  退出码: 101                                      <-- loud failure
thread 'main' panicked at b/build.rs:11:29:
reading /tmp/opencode/bt/b/src: No such file or directory (os error 2)

The pull request also adds cargo:rerun-if-changed=build.rs and assert!(!list.is_empty(), "no translator sources found in …"), so the two ways of coming up with nothing are now both loud.

3. The behaviour difference, measured

With the pull request's build script, CARGO_MANIFEST_DIR decides what is hashed. With main's, the baked path does and the environment variable is ignored — the pull request's own test shows it, and I ran it:

# main's build.rs, run with CARGO_MANIFEST_DIR=checkout_a
cargo:rustc-env=LEONIDA_SHADER_SWITCHES=LEONIDA_BVH_BOUNDS,LEONIDA_BVH_FENCES,…   <-- the real crate's list

That is, checkout_a's own file was never read; the crate it was compiled against was hashed instead.

4. The new test

build_script_uses_runtime_manifest_dir_and_rejects_missing_src does not only read the script: it compiles build.rs with rustc and runs it:

let compiled = std::process::Command::new(rustc).arg("--edition").arg("2024").arg(&build_rs).arg("-o").arg(&exe).output().unwrap();
let out_a = run_with(&dir_a);   // CARGO_MANIFEST_DIR=checkout_a
let out_b = run_with(&dir_b);   // CARGO_MANIFEST_DIR=checkout_b
let out_missing = run_with(&dir_missing);

and then requires that checkout_a and checkout_b give different output, that each names its own switch, and that the missing directory fails rather than emitting an empty hash.

5. Red and green, and the discrimination

cargo test -p leonida-shader on the pull request's branch: 247 passed, 0 failed, 2 ignored.

With only build.rs put back to main's (the pull request's tests kept):

test source_hash_tests::build_script_uses_runtime_manifest_dir_and_rejects_missing_src ... FAILED
  panicked at crates/leonida-shader/src/source_hash_tests.rs:100:5:
  build.rs must read CARGO_MANIFEST_DIR at runtime, not bake it at compile time

That is the test's first assertion, a check of the script's text. To see the behaviour rather than the text, I removed that one assertion and ran again with main's build.rs:

test source_hash_tests::build_script_uses_runtime_manifest_dir_and_rejects_missing_src ... FAILED
  panicked at crates/leonida-shader/src/source_hash_tests.rs:150:5:
  cargo:rustc-env=LEONIDA_SHADER_SWITCHES=LEONIDA_BVH_BOUNDS,…     <-- the real crate's list, not checkout_a's

So the behavioural half of the test also fails against main's script, for the reason §3 describes.

6. A small note on the test's first assertion

The text check (!source.contains("env!(\"CARGO_MANIFEST_DIR\")")) is the brittle kind: it would also fire on a spelling that is not actually wrong, and it does not fire on a wrong spelling that is not env!. The behavioural part of the same test is the one that matters, and it is there; I would not ask for the text check to be dropped, but it is worth knowing which half carries the weight.

7. What I did not check

  • Windows. Linux (Fedora 45, x86_64) with the pinned toolchain (rustc 1.98.1). The build script's behaviour is the same on both; the test compiles it with rustc --edition 2024 and runs the binary, and on Windows it would name the probe build_probe.exe.
  • When the stale path actually bites in a real build. I demonstrated the mechanism (a build script whose baked path does not exist, and one that ignores the runtime variable) rather than a real Cargo build that went wrong. A build cache that restores the build-script binary keyed on the script's content, or a package directory that moves after the script was compiled, are the situations it needs; I did not reproduce one end to end through Cargo.
  • The rest of the workspace — leonida-gpu, leonida-hle and leonida-loader do not build on Linux for reasons that predate this pull request (upstream: "The crates are Windows-only today … Linux follows Linux: build leonida.exe and run it under Proton or Wine #2577"), so I ran leonida-shader on its own.
  • The other cargo:rustc-env values the build script emits beyond the source hash and the switches list.
  • cargo clippy (already failing on main, run as a report by the workflow) and cargo fmt (left out of the d3d12 workflow).

AI-assisted: MiniMax M3.1 Flash.

@Neutron-0

Copy link
Copy Markdown

Verified on Windows 11, Rust 1.98.1, no GPU and no game files.

The head's own test passes. cargo test -p leonida-shader --lib source_hash_tests on bfa275eaa: 4 passed, 0 failed (the three tests that were there before, plus build_script_uses_runtime_manifest_dir_and_rejects_missing_src).

The hazard is real, and here is exactly when it bites. The build script is reused when the second checkout's files are older than the fingerprint Cargo recorded - a fresh checkout's files are newer, so Cargo recompiles and the fingerprint is right. Measured with two worktrees of different trees (origin/main and the PSV0 branch) sharing one CARGO_TARGET_DIR:

  • Fresh checkout (newer mtimes): Cargo recompiles the build script; it names the checkout being built, and the fingerprint is that tree's (e2b9d9a2fc8a22526a3a3019fe3d1927 for the second tree).
  • Second checkout's files made to look old: Cargo reuses the compiled build script - the binary still names the first checkout (when-a) - and the fingerprint stays the first tree's (269bc6c85de256e6ec282019707158db) while a different tree is being built.

So the failure is not "sharing a target directory" in general, but sharing one across checkouts whose files are older than the recorded fingerprint, or after a checkout was deleted and rebuilt in place. The fix removes the whole class: the path is read at run time, so the script hashes the tree that is there, and a missing tree fails the build instead of hashing nothing.

Two notes, neither blocking.

  1. The test compiles build.rs with rustc --edition 2024 directly. The crate's own edition is what Cargo.toml says; if the repository ever moves off edition 2024 this probe would still compile the file as 2024 while Cargo would compile it as the crate's edition. Pinning the edition to the crate's (include_str!("../Cargo.toml") parsed, or a fixed constant checked against it) would keep the probe honest. Today both are 2024, so the test measures the right thing.
  2. cargo:rerun-if-changed=build.rs is a good addition on its own: without it, a change to the build script alone is not a reason to rerun it.

The fix is right, and the test is the right shape: it drives the compiled script with two different CARGO_MANIFEST_DIR trees and with a missing one, so it fails on the old env! version and passes on this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants