Repository navigation
perf(self-scan): build the gate binary under the dev profile, add build provenance - #1780
Merged
Merged
Conversation
`make self-scan`, `self-scan-headroom`, both `write-baseline` recipes and `vcs` ran `cargo run --release`, whose `lto = true` / `codegen-units = 1` relink costs ~100 s after any `src/` edit. The scan itself is ~0.2 s for the whole tree, so the build was the entire per-step cost of the baseline-refresh discipline — once per conflicting commit in a rebase. The dev build is ~5 s for the same edit, 0.1 s when nothing changed, and writes a byte-identical baseline. Two knobs on `SELF_SCAN_BCA`: `BCA_SELF_SCAN_PROFILE=release` restores CI's profile, and `BCA_SELF_SCAN_BINARY=<path>` runs a prebuilt binary without building. `pages.yml` and `baseline-freshness.yml` set the latter to the release binary they install from the checkout, so the gate is measured by the same binary as the reports; `baseline-freshness.yml` gains that install step rather than paying a cold dev build on a release-only cache. Two targets check the baseline file: `self-scan-baseline-fresh` regenerates to a temporary sibling and runs `diff-baseline --exit-code` against the committed file (the quarterly job's question, locally, 0.4 s warm); `self-scan-profile-parity` regenerates under both profiles and `cmp`s them, which is the check the dev default rests on — `pages.yml` runs it per PR. The five vendored grammar build scripts now watch `src/tree_sitter/` too: they named only `parser.c` and `scanner.c`, so a header-only edit kept the stale object. Verified by touching `parser.h` and reading cargo's `Dirty` line. `.bcaignore` joins `pages.yml`'s path filters; an edit to the walk deny-set must re-run the gate and did not. Measured on a 14-core host, warm target/: release relink after a lib touch 101 s; dev rebuild 4.8 s; dev no-op 0.11 s; the scan 0.15 s (release) / 0.31 s (dev). Refs #1773
`-V` stays the one-line `bca <version>`. `--version` now follows it with a provenance block: build inputs: <sha256 | unavailable> git: <sha>[-dirty] | unavailable built: <rfc3339> (profile, rustc, target, debug-assertions) binary id: <GNU build-id | unavailable> `build inputs` is the one field that decides anything: a SHA-256 over every file compiled into the binary (the workspace Rust, manifests and the five vendored grammars, by extension allow-list so a `.snap` accept is not a code change), keyed on content alone. Two builds of one tree share it regardless of mtimes or branch; two binaries that both say `2.4.0` from different commits do not. That is what the self-scan resolver needs to tell whether an installed `bca` implements the checkout it is about to measure — an mtime cannot say so, as the #1773 review established. The rest is forensic. `build.rs` emits the fields and registers every hashed file with cargo — files only, never a directory, since cargo's directory watch is recursive and would fire on a grammar's untracked `target/` or on every `.snap`. Outside a workspace checkout (a crates.io tarball) the digest is `unavailable` and nothing but `build.rs` is watched, so a registry build cannot go permanently dirty on an absent path. Verified by extracting `cargo package`'s crate and building its `build.rs` standalone. Git discovery is fenced at the workspace and `GIT_DIR` / `GIT_INDEX_FILE` are scrubbed, so a packaged copy on a developer host cannot stamp the parent checkout and a pre-commit hook's temporary index cannot leak in. The digest is reproduced in `utils/self_scan_digest.py`, and one shared fixture pins both implementations to one hex; the Rust side also checks the baked digest against a fresh walk of the checkout. The vendored grammar build scripts watched only `parser.c` and `scanner.c`, so a header-only edit left a stale object behind a fresh digest; they now watch `src/tree_sitter/` too. `long_version` is attached inside `parse_cli_with_legacy_hint`, to the `Command` that parses, and a test pins that the derive carries none — `xtask` renders man pages from a bare `Cli::command()`, so `man/bca.1` is unchanged (drift gate green). `clap`'s `string` feature is enabled for the owned string. `check-role-coverage.py` reads `-V` for its `observer` header; its reader rejects any extra line, and the old whole-stdout capture would have written a file it could not load. SARIF: a new additive `write_sarif_with_provenance` + `SarifProvenance` stamp `bca.buildInputs` / `bca.buildGit` under `tool.driver.properties` (the only producer extension point `toolComponent` admits; validated against the vendored schema). The two existing writers forward with an empty provenance and emit byte-identical documents. The `bca report` footer abbreviates the digest after the version. `elf.rs` reads the GNU build-id note from the running executable: ELF64 little-endian only, checked arithmetic and bounded reads throughout, every failure `None`; synthetic fixtures cover the positive path, an unrelated preceding note, wrong magic, ELF32, big-endian, truncation and out-of-range offsets. Mach-O and PE readers are deferred. Refs #1773
…pper
Every `make self-scan*` recipe now runs `utils/self-scan-bca.py`
rather than `cargo run` directly. It decides which `bca` to execute,
prints one `bca: self-scan via …` line saying what it chose and why,
and `exec`s it, so a recipe's exit status, signals and stdin are the
binary's own. In order:
BCA_SELF_SCAN_FROM_SOURCE=1 build from the tree, whatever else is set
BCA_SELF_SCAN_BINARY=<path> run that executable, trusted as given
a `bca` on PATH used iff its `--version` reports a
`build inputs:` digest equal to the
digest of this checkout's compiled-in
sources, recomputed each run
cargo run under BCA_SELF_SCAN_PROFILE (dev|release)
The PATH rule is the one the first round of review blocked when it
was an mtime comparison: a binary installed from a newer `main` reads
as fresh in an older worktree by time, and as what it is by digest.
A `bca` from before the field existed, or from crates.io, reports no
digest and falls through to the build. The wrapper never hashes the
executable; it trusts the self-report exactly as CI trusts its own
`cargo install`, and a disagreement between the Rust and Python digest
walkers can only cost the fast path, never select a wrong binary.
`self-scan-profile-parity` sets `BCA_SELF_SCAN_FROM_SOURCE=1` on both
legs, so an inherited binary override or a matching PATH `bca` cannot
turn it into a comparison of one binary with itself; verified with a
matching `bca` first on PATH, both legs logged the from-source reason
and the files were byte-identical.
The self-test builds the same fixture the Rust digest test pins, a
fake `bca` on a controlled PATH, and launches the wrapper for real
where dry-run cannot make the claim: the user's arguments reach the
binary, its exit status is the wrapper's, and the pid is unchanged
across the `exec`. Each selection case was checked by perturbation —
skipping the digest comparison, trusting any digest, reading the
knobs in the other order, forking instead of exec'ing, dropping the
arguments — and each fails the test that names it. Wired into `make
pre-commit`, `make ci`, `.pre-commit-config.yaml` and `ci.yml` like
the other `utils/*-test.py` gates.
What this buys on the clock is bounded, and AGENTS.md now says so: a
tree whose inputs match an installed binary is one cargo already
finds fresh in ~0.1 s. The route earns its place through the forensic
trail in every gate log and CI's one-build guarantee, not the wait.
Fixes #1773
Review pass over the #1773 provenance work: - `digest::classify` builds the relative path only on the two arms that use it, and the file-name sort inside one directory is noted as determinism for the first error, not the output order. - `build.rs` factors the scrubbed `git` invocation into one helper and stops watching the index: git rewrites it on every `status` and on each hook's refresh, and each rewrite cost a rebuild of this crate — the relink #1773 removes. `-dirty` now describes the tree as of the last build that saw a source or ref change; the digest, the only field that decides anything, is exact regardless. - `elf::current_build_id` reads the first 64 KiB of the executable rather than all 140 MB; the program headers and every `PT_NOTE` sit in the first page of a GNU-linked image. - The three little-endian readers collapse into one `as_array`-based helper (MSRV 1.94 already admits it). - Tests: the debug-assertions line is asserted against this crate's own `cfg`, which a hardcoded `off` had passed; the long-version and SARIF tests compare the stamped digest to the baked value and to `--version` rather than to a shape. Every production line the new tests claim to guard was perturbed and failed exactly the test that names it; the one perturbation that passed (byte vs code-point sort in the Python walker) is unobservable because UTF-8 preserves code-point order, and the comment now says so. Refs #1773
Findings from review, code-review (max), an algorithmic-performance audit, an under-reviewed-areas pass, astra-review and an architecture audit, each verified before being applied: Correctness - `elf.rs`: the parser is compiled only where it has a caller (`cfg(any(target_os = "linux", test))`), so a macOS or Windows build under `-D warnings` no longer fails on dead code. Simulated by retargeting the cfg to `macos` and running clippy both ways. - `build.rs`: `GIT_CEILING_DIRECTORIES` is the workspace's parent, not the workspace — git never excludes the directory it starts in — so a tree exported inside another checkout reports `unavailable` instead of stamping the enclosing repository. Verified with a nested probe. - `build.rs` no longer watches `.git/HEAD`, the branch ref or `packed-refs`: `BCA_BUILD_GIT` is an `env!` the library reads, so a changed value recompiled the library and relinked `bca` on every commit — including every step of the rebase loop #1773 exists to make cheap. An empty commit now costs 0.07 s (was 3.4 s). `git:` is exact as of the last build whose inputs changed; the digest is exact always, and the docs say so. - Digest roots: `Cargo.lock` is in (the resolver bypasses cargo's fingerprint, and ranged dependencies decide which files a walk sees); a crate's `tests/`, `benches/`, `examples/` and every `.json` are out (not compiled into `bca`; a tests/ touch cost a 4.3 s rebuild, now 0.08 s). Shared fixture re-pinned on both sides and extended with a row per rule, including the pure dotfile a `rpartition`-based Python extension check hashed while Rust did not. - Resolver: `./bca` and a relative PATH entry are made absolute before the `chdir` that preceded the exec; an unreadable input falls back to building instead of a traceback; an exec failure is one `error:` line; `BCA_SELF_SCAN_PROFILE` errors carry the `error:` prefix the other utils use. Each guarded by a test shown to fail without its fix. - Makefile: `self-scan-profile-parity` gains the `trap` its sibling had, keeps both files only on a mismatch, and both recipes trap `INT TERM`; `.gitignore` carries `.bca-baseline.*.toml` so a leak cannot be staged. Verified: a failed leg removes both files, a mismatch keeps them. - Grammar `build.rs`: `rerun-if-changed` uses `Display`, so a non-UTF-8 header name is watched rather than silently skipped. API shape - `SarifProvenance` follows `MetricsOptions`: `#[non_exhaustive]`, private fields, `Default` + `with_*` setters. The positional `new` it shipped with froze its arity in a 2.x crate. STABILITY.md names the shape, adds the writer to the signature table, and carves out the `build inputs:` line's prefix as the one stable field after the first — what the resolver keys on. - The `unavailable` sentinel stays in `--version` text only; `build_inputs()` / `build_git()` map it to `None` once, so a crates.io `bca` omits the SARIF properties and the footer digest rather than emitting the word as a value. - `build.rs` warns (`cargo:warning=`) when a real checkout cannot be digested — symlink, non-UTF-8 name, unreadable file — rather than reporting `unavailable` silently; a missing root stays silent, it is what a crates.io build looks like. - `sha2` is a `[workspace.dependencies]` pin used from all three places; `binary id:` is `build id:`, the term the code uses. Performance - `long_version()` renders only when `--version` is on the command line, not on every run; `elf` reads a pre-sized 64 KiB buffer; `classify` uses `DirEntry::file_type` instead of a second `stat`; `build.rs` walks the tree once. Tests - `python_digest_agrees_with_the_rust_digest_over_this_checkout` pins the two walkers over the live tree, the shape of `python_reader_agrees_with_the_compiled_tables`; the shared fixture only covers the rules it exercises. The Windows `skipIf` no longer evaluates `os.geteuid` at import. Docs - The wrapper docstring is the one full statement of the resolution order; the Makefile header, bca.toml and the book point at it. The book's report page lists the footer's digest; the parity step in pages.yml runs on `success()`, the job timeout is 45 min, and its path filter includes the gate's own runner. Refs #1773
…x-up - The grammar build scripts watch a header's exact path again, and a name cargo cannot be told exactly (non-UTF-8) watches the `tree_sitter/` directory instead: `Display` had handed cargo a lossy spelling that names no file, which rebuilds on every run rather than tracking the header. The previous commit's claim was wrong; this is what it meant. - `digest::lookup_root`: only `NotFound` is the registry layout. A root whose lookup fails another way — a symlink loop, an unsearchable parent — is `DigestError::Io` with its message, so `build.rs` warns about it instead of filing it under "not a workspace". The test builds a self-referential symlink and asserts the `Io` variant; with the discrimination removed it is the one failure. - Two resolver diagnostics gain the tests their commit message claimed: an explicit binary that is absent or not executable ends in one `error: cannot run …` line with no traceback (launched for real), and the bad-profile error asserts its `error:` prefix. Each shown to fail with its fix reverted. Refs #1773
dekobon
force-pushed
the
fix/1773-self-scan-binary
branch
from
November 3, 2026 01:11
b42dcd8 to
a938b74
Compare
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #1780 +/- ##
==========================================
- Coverage 98.36% 98.35% -0.01%
==========================================
Files 385 388 +3
Lines 116188 116529 +341
Branches 115753 116094 +341
==========================================
+ Hits 114283 114614 +331
+ Misses 1230 1223 -7
- Partials 675 692 +17
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
Patch coverage on #1780 read 86 % against a 98 % project: the misses were the digest's error arms, the ELF reader's short reads and the two `unavailable` branches. Closable in a checkout build: - `DigestError`: every `Display` arm; a symlinked root (the input case existed); a non-UTF-8 name; an unreadable file and an unlistable directory, each asserting the path the `Io` error names. The two permission tests skip for an effective root (`id -u`, which every Unix has; `/proc` does not exist on macOS), and hold the mode in an RAII guard so an assertion failure cannot leave a `0o000` directory that `TempDir::drop` silently fails to remove — verified by forcing a panic after the guard and checking the tempdir was gone. - ELF: truncation at every byte of a valid image (each `?` in the header and program-header readers), a `phnum` past the table, a `phoff` past the end, a `namesz` and a `descsz` that overrun, and 4/8/12-byte note segments so the note reader's own short reads run. The last pin the outcome, not the mechanism: a short note yields no id whichever read refuses it, and the comment says so. - `build_info::known` pinned directly on the sentinel; `check_format` gains `provenance_from(Option, Option)` so the registry build's shape — neither field known — is asserted from a checkout build, across all four combinations. Each new assertion was perturbed and fails only the test that names it. What remains uncovered is the class `codecov.yml` documents: `?` on a bounds-checked read whose `None` side no input reaches, and `current_exe` / `File::open` failures. Not folded into the provenance commit: the tests name `lookup_root`, `provenance_from` and the ELF `reader` module, which the review commits introduced, so the fold conflicts mid-history. Refs #1773
…indows flags Two CI legs red on 126adf7, both in the new coverage tests: - macOS: `walk_refuses_a_non_utf8_path` panicked at the fixture write with `EILSEQ` — APFS refuses to create a file whose name is not valid UTF-8, so the case this test exercises cannot exist there. Gated to Linux, where the filesystem permits it and the production branch is reachable; Windows names are UTF-16 and have no portable analogue in this fixture. - Windows: `PathBuf` was imported at the top of the test file but used only by the `cfg(unix)` permission guard, so the Windows test build saw an unused import under `-D warnings` and did not compile. The guard names the type in full instead. Verified by compiling the file with every `cfg(unix)` / `cfg(target_os = "linux")` item removed. Neither is one of the follow-ups (#1776, #1777, #1778): #1777 is about reading Mach-O and PE build ids at run time and is unrelated to how a test fixture writes a file name. Refs #1773
dekobon
added a commit
that referenced
this pull request
Nov 3, 2026
`build id:` printed `unavailable` on macOS and Windows because only the
ELF reader existed. `build_info/elf.rs` becomes
`build_info/build_id/{mod,elf,macho,pe}.rs`: `mod.rs` dispatches per
OS and owns the shared primitives — `HEAD_BYTES`, `read_head` /
`read_at`, one `hex_lower` (`digest.rs` keeps its own for the
`build.rs` `#[path]` share), the LE width readers — each gated
`any(linux, macos, windows, test)` so an unsupported target compiles
with no dead items under `-D warnings`. Each reader mirrors the ELF
shape: `current()` gated on its OS only, the parser in `mod reader`
under `any(<os>, test)`.
`macho.rs` reads the 16-byte `LC_UUID` of a thin little-endian 64-bit
image, the shape `aarch64-apple-darwin` ships. The walk is bounded by
`sizeofcmds` and the slice; a `cmdsize` under 8 inverts the body range
so the read fails rather than re-reading one command `ncmds` times.
`MH_MAGIC`, `MH_CIGAM_64` and `FAT_MAGIC` read as absent — universal
binaries are a documented non-goal, since nothing here is `lipo`d.
`pe.rs` reads the 20 bytes after `RSDS` — the GUID as stored plus the
age — of the first `CodeView` entry, for PE32 and PE32+. The directory
and record routinely sit past 64 KiB, so the parser is two-stage and
takes its second-stage reader as a closure, which is also how the
fixtures drive it without files. Entry 6 must lie inside the declared
`SizeOfOptionalHeader`, the directory's RVA inside one section's
`SizeOfRawData`; only complete 28-byte entries are walked, capped at
64 — the one bound between a declared 4 GiB `size` and a `Vec` of that
capacity; a non-`RSDS` or short entry is skipped for a later one.
The ELF reader now refuses an `e_phentsize` below 56: `phentsize = 0`
with `phnum = 65535` aliased every index onto one `PT_NOTE` and cost
272 ms against 31 µs. Rendering is lowercase hex of the raw bytes for
all three. STABILITY.md names the formats, the per-format lengths
(including lld's 8-byte `fast` default before LLVM 19) and the
`unavailable` cases: FAT Mach-O, `-no_uuid`, no `CodeView`, ELF
without `--build-id`.
The readers' `any(<os>, test)` gate is pruned by `bca check
--exclude-tests`, so they sit outside the self-scan and their
`bca: suppress(nexits)` markers hold nothing there; `elf.rs`'s module
doc says so and names the unpruned command, under which all three
measure clean (a fn and the closure inside it are separate spaces and
each carries a marker).
Tests: 14 in `build_id_tests.rs` — pinned-hex positives for both
formats, the PE32+ one with its directory and record past 64 KiB, a
PE32 one, and a fixture whose section is mapped 0x2000 above its file
offset behind an unrelated section so the RVA translation is
observable; every malformed shape; truncation sweeps over every prefix;
the 65-entry cap; a Linux-gated test that the dispatcher reaches the
ELF reader. Perturbation sweep: 17 guards, 16 caught by the test that
names each; the miss is the documented Mach-O `cmdsize < 8` non-guard.
cfg rotation on this Linux host — the crate compiled as if for macOS,
Windows and FreeBSD — clean under clippy `--lib`, `--all-targets` and
the tests. macOS and Windows cannot be exercised natively here; that
and the fixtures are the evidence.
Reviewed by simplify-rust, rust-optimize, audit-tests, six reviewers
and two astra closure checks; every finding fixed or rejected with a
reason: the inner `cfg(any(os, test))` on `mod reader` is kept (it
carries the self-scan note and mirrors #1780's shape); `build_id` stays
`pub(crate)` for the `cfg(test)` re-export; three `.map(hex_lower)`
sites, the ELF test naming and re-opening the executable per PE read
are cosmetic.
Fixes #1777
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1773.
Why
make self-scan-write-baseline-headroomcost ~70 s per invocation, once per conflicting commit in a rebase. The premise in the issue — that the scan was ~60 s of that — was wrong: the scan is 0.15 s for 503 files; the rest wascargo run --releaserelinking the CLI underlto = true/codegen-units = 1after anysrc/edit (101 s measured).What
9debac69bcaunder the dev profile.BCA_SELF_SCAN_PROFILE=releaserestores CI's profile;BCA_SELF_SCAN_BINARY=<path>runs a prebuilt binary — whatpages.ymlandbaseline-freshness.ymlnow do with the release binary theycargo installfrom HEAD. New targetsself-scan-baseline-fresh(the quarterly job's question, locally, 0.5 s warm) andself-scan-profile-parity(dev vs release regenerationscmpequal; the guard the default rests on, run per PR inpages.yml)..bcaignorejoins the pages path filter; the five vendored grammarbuild.rsfiles watch theirsrc/tree_sitter/headers.f6514d98-Vunchanged;--versionaddsbuild inputs:(SHA-256 content digest of every source compiled in),git:,built:,build id:(GNU build-id). Stamped intobca checkSARIF undertool.driver.propertiesand abbreviated in thebca reportfooter. Library: additiveSarifProvenance+write_sarif_with_provenance(MetricsOptionsshape); existing writers byte-identical.check-role-coverage.pyreads-V.3b433250utils/self-scan-bca.py: forced source → explicit binary → a PATHbcaiff its digest equals a fresh digest of the checkout (utils/self_scan_digest.py, held to the Rust walker by a shared fixture and a live-tree test) →cargo run.1c70a11ecbe99afcb42dcd87simplify-rust,rust-optimize,audit-tests, then six review agents and an astra re-review of the fix-up. Every applied finding re-verified by perturbation.Measured (14-core host, warm
target/)src/tests/,.snap)make pre-commitcritical path on asrc/changemake self-scan-profile-parityTwo regressions of the issue's own goal were caught in review and fixed before merge: watching
.git/HEADfrombuild.rsrecompiled the library on every commit (3.4 s → 0.07 s), and hashingtests/relinked on every integration-test edit (4.3 s → 0.08 s).The honest bound on the PATH-reuse route: a tree whose inputs match an installed binary is one cargo already finds fresh in 0.1 s, so it earns its place through the forensic trail in every gate log and CI's one-build guarantee, not the clock. AGENTS.md says so.
Design history
The first resolver design compared the installed binary's mtime against the newest metric-code commit. Two plan reviewers independently blocked it — a binary installed from a newer
mainreads as fresh in an older worktree — which is why the content digest exists. TheSTABILITY.mdcarve-out makes thebuild inputs:line's prefix the one stable field after the first, so a third-party CI can key on the same thing.Stability
Library additions are additive and documented in
STABILITY.md(writer table row +SarifProvenanceshape) andCHANGELOG.md(Added+Changed). No existing public signature moves;man/is unchanged (drift gate green).Validation
make pre-commit→BCA_GATE: passon the tip. Non-Linux-D warningsbuild simulated by retargeting the ELF reader's cfg tomacosunder clippy both ways.cargo packagelayout verified to yieldunavailablewith onlybuild.rswatched.Follow-ups
#1776 (agent hooks prefer a now-stale
target/release/bca), #1777 (Mach-O / PE build ids), #1778 (gate the grammar header watch against regeneration).