From 26e0bf1b95b064f94f32ff4042950f03ff6cbebc Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:28:18 -0800 Subject: [PATCH 1/8] perf(self-scan): build the gate binary under the dev profile MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `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=` 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 --- .checkmake.ini | 6 +- .github/workflows/baseline-freshness.yml | 15 +- .github/workflows/pages.yml | 26 ++++ AGENTS.md | 22 +++ CHANGELOG.md | 20 +++ Makefile | 135 +++++++++++++++--- bca.toml | 6 +- big-code-analysis-book/src/recipes/ci.md | 11 +- .../src/recipes/local-gates.md | 10 ++ docs/development/baseline_freshness.md | 31 ++-- tree-sitter-ccomment/bindings/rust/build.rs | 13 ++ tree-sitter-mozcpp/bindings/rust/build.rs | 13 ++ tree-sitter-mozjs/bindings/rust/build.rs | 13 ++ tree-sitter-preproc/bindings/rust/build.rs | 13 ++ tree-sitter-tcl/bindings/rust/build.rs | 13 ++ 15 files changed, 316 insertions(+), 31 deletions(-) diff --git a/.checkmake.ini b/.checkmake.ini index 2109a05ad..1e528b9b9 100644 --- a/.checkmake.ini +++ b/.checkmake.ini @@ -27,6 +27,10 @@ ; `recovery-oracle-test`, `perturb-test`, `coverage-diff-test`, ; `drift-common-test`) took the `help` body from 143 to 149 against a ; cap with 2 lines of headroom. 165 restores the 15. +; +; Raised from 165 to 170 in #1773: the two baseline-check targets +; (`self-scan-baseline-fresh`, `self-scan-profile-parity`) took the +; `help` body from 149 to 151, leaving 14 of the promised 15. [maxbodylength] -maxBodyLength = 165 +maxBodyLength = 170 diff --git a/.github/workflows/baseline-freshness.yml b/.github/workflows/baseline-freshness.yml index 1ce614a44..7c36679e9 100644 --- a/.github/workflows/baseline-freshness.yml +++ b/.github/workflows/baseline-freshness.yml @@ -63,6 +63,18 @@ jobs: with: shared-key: pages-scan-release + # Same install as pages.yml, for the same reason (#1773): the + # `make` recipe below would otherwise `cargo run` under the dev + # profile — a cold build on this release-only cache — and the + # `diff-baseline` call would build release separately. One + # release install, handed to the recipe through + # `BCA_SELF_SCAN_BINARY` and used directly for the diff. + - name: Install bca from current checkout + run: cargo install --path big-code-analysis-cli --locked --bin bca + + - name: Point the self-scan recipes at the installed binary + run: echo "BCA_SELF_SCAN_BINARY=$(command -v bca)" >> "$GITHUB_ENV" + # `bca diff-baseline` rather than `git diff --exit-code`: a v6 # baseline records `start_line` for the identity triples two # spaces share, and for those a `git diff` reports code moving @@ -82,8 +94,7 @@ jobs: # than let `set -e` end the step: the two mean different things # and only one of them is a finding. status=0 - cargo run --quiet --release -p big-code-analysis-cli -- \ - diff-baseline "${RUNNER_TEMP}/old.toml" "${RUNNER_TEMP}/new.toml" \ + bca diff-baseline "${RUNNER_TEMP}/old.toml" "${RUNNER_TEMP}/new.toml" \ --format markdown --exit-code > "${RUNNER_TEMP}/diff.md" || status=$? cat "${RUNNER_TEMP}/diff.md" if [ "$status" = "0" ]; then diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index f33922635..4b82d6411 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -34,6 +34,9 @@ on: - 'tree-sitter-tcl/**' - 'bca.toml' - '.bca-baseline.toml' + # The walk deny-set. An edit here changes which files the gate + # measures, so it must re-run the gate (#1773). + - '.bcaignore' - '.github/workflows/pages.yml' pull_request: paths: @@ -53,6 +56,7 @@ on: - 'tree-sitter-tcl/**' - 'bca.toml' - '.bca-baseline.toml' + - '.bcaignore' - '.github/workflows/pages.yml' workflow_dispatch: @@ -302,6 +306,17 @@ jobs: - name: bca version run: bca --version + # Hand the installed binary to the `make self-scan` recipes below + # (#1773). Without this they would `cargo run` under the dev + # profile — the local default, chosen because the release relink + # costs ~100 s per edit — which here means a cold dev build on a + # release-only cache and a gate measured by a different binary + # from the one the report steps above use. The absolute path is + # what `cargo install` printed; `~/.cargo/bin` is on PATH, but a + # path is unambiguous in the gate log. + - name: Point the self-scan recipes at the installed binary + run: echo "BCA_SELF_SCAN_BINARY=$(command -v bca)" >> "$GITHUB_ENV" + # The deny-set (`exclude_from = ".bcaignore"`) is auto-discovered # from the repo-root `bca.toml` manifest, so the report # invocations no longer pass `--exclude-from` — workflow, recipe, @@ -399,6 +414,17 @@ jobs: env: BCA_SINCE: origin/${{ github.base_ref || 'main' }} + # The dev-profile default behind `make self-scan` locally (#1773) + # rests on both profiles writing the same baseline. This builds + # the dev binary too — several minutes cold, since the cache above + # is release-only — and `cmp`s the two regenerations. Per PR + # rather than quarterly so a divergence is attributed to the + # change that caused it. Not `BCA_SELF_SCAN_BINARY`-driven: the + # recipe builds both sides from source on purpose. + - name: Profile parity (dev vs release baseline) + if: ${{ !cancelled() }} + run: make self-scan-profile-parity + # Dogfood bca's own SARIF writer: re-run the gate as a pure # emitter (`--no-fail` keeps exit 0 regardless of offenders) so # this step runs even when the gate above is red, and upload the diff --git a/AGENTS.md b/AGENTS.md index 2c946725a..53d930b90 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -518,6 +518,28 @@ that edits the baseline itself then stops the rebase with a conflict, because the file is `-merge`: regenerate, stage, and `git rebase --continue`, as for a merge. +**What a refresh costs, and why.** The scan itself is ~0.2 s for the +whole tree; what you wait for is the build. The self-scan recipes +build `bca` under the **dev** profile (#1773): ~5 s for a step that +touched Rust under `src/`, `big-code-analysis-ast/`, +`big-code-analysis-cli/` or a grammar crate, and ~0.1 s for one that +did not, because cargo finds every artifact fresh. They used to build +release, whose `lto = true` / `codegen-units = 1` relink is ~100 s +after *any* such edit — which made the nine-conflict rebase that +motivated #1773 a ten-minute job. `BCA_SELF_SCAN_PROFILE=release` +restores that build when you need CI's exact profile; `make +self-scan-profile-parity` is the per-PR check that the two profiles +write a byte-identical baseline, and the reason the default is safe. +`BCA_SELF_SCAN_BINARY=` skips the build and runs a prebuilt +binary, trusted as given: sound for a batch no commit of which touches +those compiled-in roots or `Cargo.toml` / `Cargo.lock` (the manifest, +`.bcaignore` and the baseline are read at run time, so any binary sees +the live copies), and wrong without a warning otherwise. CI sets it to +the release binary it has just installed from HEAD. `make +self-scan-baseline-fresh` answers the question the quarterly job asks +— does the committed file still describe the tree — in a few seconds +locally. + **Price a candidate limit at both tiers before calling it free.** Converging a limit onto a cluster of existing values is never free while a proportional soft tier is active — the soft tier measures *distance to diff --git a/CHANGELOG.md b/CHANGELOG.md index 899e1e2f0..e1145f86a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -157,6 +157,26 @@ for historical reference. ### Changed +- **The self-scan recipes build `bca` under the dev profile** (#1773). + `make self-scan`, `self-scan-headroom`, both `write-baseline` + recipes and `vcs` used to `cargo run --release`, whose `lto = true` + / `codegen-units = 1` relink is ~100 s after any `src/` edit — once + per conflicting commit in a rebase, per AGENTS.md's refresh + discipline. The scan itself is ~0.2 s, so the release build was the + whole cost; the dev build is ~5 s for an edit and 0.1 s when nothing + changed, and writes a byte-identical baseline. Two knobs: + `BCA_SELF_SCAN_PROFILE=release` restores the release build, and + `BCA_SELF_SCAN_BINARY=` runs a prebuilt binary without + building — which `pages.yml` and `baseline-freshness.yml` now set to + the release binary they install from the checkout, so CI's gate is + measured by the same binary as its reports. Two new targets check + the baseline file: `self-scan-baseline-fresh` (regenerate to a + temporary sibling and `diff-baseline` against the committed file; + the quarterly job's question, locally) and `self-scan-profile-parity` + (dev and release regenerations `cmp` equal; `pages.yml` runs it per + PR, which is what makes the dev default safe). `.bcaignore` joins + `pages.yml`'s path filters, so an edit to the walk deny-set re-runs + the gate. Repository tooling only; no published API moves. - **The `loc` declaration gates, the JS-family binding gate and the Python cognitive boolean-operator questions no longer climb to the root from every node** (#1767). Each asks a node's ancestors a diff --git a/Makefile b/Makefile index aaab76e31..7c10f9328 100644 --- a/Makefile +++ b/Makefile @@ -88,7 +88,7 @@ find-by-ext = $(if $(FD),$(FD) --extension $(1) $(FD_EXCLUDE) $(2),find . -name NEXTEST := $(shell command -v cargo-nextest 2>/dev/null) TEST_CMD = $(if $(NEXTEST),$(NEXTEST) nextest run --workspace --all-features,cargo test --workspace --all-features --lib --bins --tests) -.PHONY: role-census role-census-test role-coverage role-coverage-test role-coverage-observe role-bypass role-bypass-test mutation-report-test mutation-workflow-test drift-common-test drift-oracle-test drift-compare-test recovery-oracle-test perturb-test coverage-diff-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test help check-tools worktree-setup worktree-setup-test build build-release check test test-doc chain-audit fmt fmt-check markdown-fmt markdown-lint shellcheck sh-fmt sh-fmt-check toml-fmt toml-fmt-check toml-lint makefile-check actionlint snapshot-anchors snapshot-anchors-test rustfmt-bail rustfmt-bail-test grammar-marker-sync grammar-marker-sync-test check-versions check-excluded-manifests check-excluded-manifests-test check-ruff-lockstep check-ruff-lockstep-test check-publish-metadata check-publish-metadata-test check-manpage-assets check-manpage-drift-test check-diagnostic-prefix check-diagnostic-prefix-test check-feature-gates check-feature-gates-test check-test-lang-gates check-test-lang-gates-compare check-test-lang-gates-test check-safety-doc-pin check-safety-doc-pin-test gate-status-test check-tools-test enums-check enums-codegen-drift enums-codegen-drift-test self-scan self-scan-headroom self-scan-write-baseline self-scan-write-baseline-headroom vcs lint clippy udeps insta-review insta-accept clean distclean install install-cli install-web doc doc-open doc-check doc-check-docsrs book book-serve book-pot book-po-update book-ja book-deploy all pre-commit ci release-check verify-changelog pkg-deb-local pkg-rpm-local dev-env-build dev-env-run dev-env-shell dev-env-rm py-bootstrap py-sync py-relock py-clean py-fmt py-fmt-check py-lint py-typecheck py-test py-stubtest smoke smoke-cli smoke-lib bench bench-scaling bench-walk fuzz-check fuzz-smoke fuzz-replay fuzz-run fuzz-tmin _check-find _pc-all _pc-fmt _pc-clippy _pc-test _pc-doc-check _pc-udeps _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test _pc-self-scan _pc-self-scan-headroom _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest _ci-all _ci-fmt-check _ci-clippy _ci-test _ci-doc-check _ci-build _ci-udeps _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test _ci-enums-codegen-drift-test _ci-self-scan _ci-self-scan-headroom _ci-cargo-pipeline _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest +.PHONY: role-census role-census-test role-coverage role-coverage-test role-coverage-observe role-bypass role-bypass-test mutation-report-test mutation-workflow-test drift-common-test drift-oracle-test drift-compare-test recovery-oracle-test perturb-test coverage-diff-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test help check-tools worktree-setup worktree-setup-test build build-release check test test-doc chain-audit fmt fmt-check markdown-fmt markdown-lint shellcheck sh-fmt sh-fmt-check toml-fmt toml-fmt-check toml-lint makefile-check actionlint snapshot-anchors snapshot-anchors-test rustfmt-bail rustfmt-bail-test grammar-marker-sync grammar-marker-sync-test check-versions check-excluded-manifests check-excluded-manifests-test check-ruff-lockstep check-ruff-lockstep-test check-publish-metadata check-publish-metadata-test check-manpage-assets check-manpage-drift-test check-diagnostic-prefix check-diagnostic-prefix-test check-feature-gates check-feature-gates-test check-test-lang-gates check-test-lang-gates-compare check-test-lang-gates-test check-safety-doc-pin check-safety-doc-pin-test gate-status-test check-tools-test enums-check enums-codegen-drift enums-codegen-drift-test self-scan self-scan-headroom self-scan-write-baseline self-scan-write-baseline-headroom self-scan-baseline-fresh self-scan-profile-parity vcs lint clippy udeps insta-review insta-accept clean distclean install install-cli install-web doc doc-open doc-check doc-check-docsrs book book-serve book-pot book-po-update book-ja book-deploy all pre-commit ci release-check verify-changelog pkg-deb-local pkg-rpm-local dev-env-build dev-env-run dev-env-shell dev-env-rm py-bootstrap py-sync py-relock py-clean py-fmt py-fmt-check py-lint py-typecheck py-test py-stubtest smoke smoke-cli smoke-lib bench bench-scaling bench-walk fuzz-check fuzz-smoke fuzz-replay fuzz-run fuzz-tmin _check-find _pc-all _pc-fmt _pc-clippy _pc-test _pc-doc-check _pc-udeps _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test _pc-self-scan _pc-self-scan-headroom _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest _ci-all _ci-fmt-check _ci-clippy _ci-test _ci-doc-check _ci-build _ci-udeps _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test _ci-enums-codegen-drift-test _ci-self-scan _ci-self-scan-headroom _ci-cargo-pipeline _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest .PHONY: plugin-test _pc-plugin-test _ci-plugin-test @@ -181,6 +181,8 @@ help: @echo " self-scan-headroom bca threshold gate (soft: BCA_HEADROOM, default 0.95)" @echo " self-scan-write-baseline Refresh .bca-baseline.toml at the hard thresholds" @echo " self-scan-write-baseline-headroom Refresh .bca-baseline.toml at the soft thresholds" + @echo " self-scan-baseline-fresh Does .bca-baseline.toml still describe the tree? (diff-baseline, exit 2 if not)" + @echo " self-scan-profile-parity dev and release builds write a byte-identical baseline (~100 s)" @echo " vcs Change-history (VCS) risk report for this repo" @echo " bench bench-scaling + bench-walk (out-of-band; never in ci)" @echo " bench-scaling Complexity-class gate for the metric walk" @@ -886,8 +888,32 @@ enums-check: # Mirrors the `Threshold gate (baseline-ratcheted)` step in # .github/workflows/pages.yml. We build from source on purpose: # any in-progress change to metric computation is reflected in the -# values we gate on. When pages.yml bumps the pinned release -# binary, the two invocations re-sync. +# values we gate on. +# +# Which binary runs is decided by two knobs (#1773): +# +# BCA_SELF_SCAN_BINARY An explicit, trusted `bca` executable. Set, +# nothing is built: CI sets it to the release +# binary it has just `cargo install`ed from +# HEAD, so the gate and the published reports +# come from one build. Locally it is sound only +# when no commit in the work at hand touches +# `src/`, `big-code-analysis-ast/`, +# `big-code-analysis-cli/`, `tree-sitter-*/`, +# `Cargo.toml` or `Cargo.lock` — the inputs +# compiled into the binary; everything else +# (`bca.toml`, `.bcaignore`, the baseline) is +# read at run time, so a prebuilt binary sees +# the live copy. +# BCA_SELF_SCAN_PROFILE `dev` (default) or `release`. The profile +# `cargo run` builds under when no binary is +# given. `release` is what CI installs, but its +# `lto = true` / `codegen-units = 1` relink +# costs ~100 s after any `src/` edit; the dev +# profile is ~5 s for the same edit and 0.1 s +# when nothing changed, and both profiles write +# a byte-identical baseline — which +# `self-scan-profile-parity` below keeps true. # # Path selection (`paths = ["."]`), the ignore file # (`exclude_from = ".bcaignore"`), the baseline @@ -915,8 +941,35 @@ enums-check: # raising a limit): # # self-scan-write-baseline refreshes .bca-baseline.toml in place. +# +# Two checks on the baseline itself, neither in `make pre-commit`: +# +# self-scan-baseline-fresh regenerates to a temp file and runs +# `bca diff-baseline` against the committed +# one — the quarterly baseline-freshness +# job's check, runnable locally. Exits 0 +# when the file still describes the tree, +# 2 when it does not. +# self-scan-profile-parity regenerates under the dev and release +# profiles and `cmp`s the two files. The +# guard behind the dev-profile default +# above; ~100 s because of the release +# build. pages.yml runs it per PR. # --------------------------------------------------------------------------- -SELF_SCAN_BCA := cargo run --quiet --release -p big-code-analysis-cli -- +# Default to empty so `$(if …)` below does not trip +# `--warn-undefined-variables`; `?=` lets the environment override. +BCA_SELF_SCAN_BINARY ?= +BCA_SELF_SCAN_PROFILE ?= dev +ifneq ($(filter-out dev release,$(BCA_SELF_SCAN_PROFILE)),) +$(error BCA_SELF_SCAN_PROFILE must be `dev` or `release`, not `$(BCA_SELF_SCAN_PROFILE)`) +endif +SELF_SCAN_PROFILE_FLAG := $(if $(filter release,$(BCA_SELF_SCAN_PROFILE)),--release ,) +# Quoted so a binary path with spaces survives the recipe shell; the +# `cargo run` form is deliberately unquoted so bash splits it into words. +SELF_SCAN_BCA := $(if $(BCA_SELF_SCAN_BINARY),"$(BCA_SELF_SCAN_BINARY)",cargo run --quiet $(SELF_SCAN_PROFILE_FLAG)-p big-code-analysis-cli --) +# One line on stderr per recipe naming the binary, so a captured gate +# log says what measured the tree. +SELF_SCAN_NOTE := $(if $(BCA_SELF_SCAN_BINARY),bca self-scan via $(BCA_SELF_SCAN_BINARY),bca self-scan via cargo run ($(BCA_SELF_SCAN_PROFILE) profile)) # `--jobs` defaults to `auto` (effective CPU count, cgroup-/cpuset- # aware on Linux via Rust's std lib), so no `$(nproc)` plumbing is # needed for the self-scan recipes (issue #383). @@ -954,15 +1007,18 @@ SELF_SCAN_SINCE_ARGS := $(if $(BCA_SINCE),--since $(BCA_SINCE),) self-scan: @echo "bca self-scan (hard gate)..." + @echo "$(SELF_SCAN_NOTE)" >&2 @$(SELF_SCAN_BCA) check $(SELF_SCAN_SINCE_ARGS) self-scan-headroom: @echo "bca self-scan (soft gate, BCA_HEADROOM=$${BCA_HEADROOM:-0.95})..." + @echo "$(SELF_SCAN_NOTE)" >&2 @$(SELF_SCAN_BCA) check $(SELF_SCAN_SINCE_ARGS) \ --tier=soft=$${BCA_HEADROOM:-0.95} self-scan-write-baseline: @echo "Refreshing .bca-baseline.toml from current offenders..." + @echo "$(SELF_SCAN_NOTE)" >&2 @$(SELF_SCAN_BCA) check --write-baseline # Refresh `.bca-baseline.toml` against the SOFT thresholds @@ -973,10 +1029,44 @@ self-scan-write-baseline: # the new headroom band rather than firing on every commit. self-scan-write-baseline-headroom: @echo "Refreshing .bca-baseline.toml from current soft-tier offenders (BCA_HEADROOM=$${BCA_HEADROOM:-0.95})..." + @echo "$(SELF_SCAN_NOTE)" >&2 @$(SELF_SCAN_BCA) check \ --tier=soft=$${BCA_HEADROOM:-0.95} \ --write-baseline +# The temp baselines below are written as *siblings* of +# `.bca-baseline.toml`, and the recipes `cd` to the repo root first. +# Both matter for the comparison: an entry's path key is the walked +# path joined to the baseline file's directory and then stripped of +# it again (`baseline::normalize_path`), so a file written elsewhere, +# or from another working directory, keys the same functions +# differently and every entry reads as removed-and-added. The walker +# never analyses the temp file itself — `.toml` is no language it +# knows — and `trap` removes it on every exit, so nothing is left for +# `git status` to show. One `&&`-joined command because recipes run +# one line per shell here (no `.ONESHELL`). +self-scan-baseline-fresh: + @echo "bca self-scan baseline freshness (BCA_HEADROOM=$${BCA_HEADROOM:-0.95})..." + @echo "$(SELF_SCAN_NOTE)" >&2 + @cd "$(BASE_DIR)" && t=$$(mktemp ".bca-baseline.XXXXXX.toml") && trap 'rm -f "$$t"' EXIT \ + && $(SELF_SCAN_BCA) check --tier=soft=$${BCA_HEADROOM:-0.95} --write-baseline "$$t" \ + && $(SELF_SCAN_BCA) diff-baseline .bca-baseline.toml "$$t" --exit-code + +# Byte-for-byte parity of the baseline the two build profiles write. +# The dev-profile default rests on it: `debug-assertions` and +# `overflow-checks` are the only semantic differences between the +# profiles, and either firing would be a bug the release gate hides. +# On a mismatch both files are kept and named so they can be diffed. +# `BCA_SELF_SCAN_BINARY` is ignored here on purpose — the point is to +# compare two from-source builds, not whatever is installed. +self-scan-profile-parity: + @echo "bca self-scan profile parity (dev vs release, BCA_HEADROOM=$${BCA_HEADROOM:-0.95})..." + @cd "$(BASE_DIR)" && d=$$(mktemp ".bca-baseline.dev.XXXXXX.toml") && r=$$(mktemp ".bca-baseline.release.XXXXXX.toml") \ + && cargo run --quiet -p big-code-analysis-cli -- check --tier=soft=$${BCA_HEADROOM:-0.95} --write-baseline "$$d" \ + && cargo run --quiet --release -p big-code-analysis-cli -- check --tier=soft=$${BCA_HEADROOM:-0.95} --write-baseline "$$r" \ + && if cmp -s "$$d" "$$r"; then rm -f "$$d" "$$r"; echo "profile parity: dev and release baselines are byte-identical"; \ + else echo "profile parity: dev and release baselines differ; kept $$d and $$r" >&2; exit 1; fi + # --------------------------------------------------------------------------- # Change-history (VCS) risk report (issue #328). Dogfoods `bca vcs` on # this repo: ranks tracked files by composite change-history risk (churn, @@ -1815,12 +1905,19 @@ _ci-all: # ├── _pc-py-fmt # └── _pc-py-typecheck # -# _pc-self-scan and _pc-self-scan-headroom both invoke -# `cargo run --release -p big-code-analysis-cli`, which holds the -# workspace `target/` lock for the release-profile build, so they -# serialize into the cargo chain after _pc-manpages rather than -# fanning out in parallel. The hard tier runs first so a regression -# is named before the soft tier reports near-limit headroom. +# _pc-self-scan and _pc-self-scan-headroom both run `$(SELF_SCAN_BCA)`, +# which is `cargo run -p big-code-analysis-cli` unless +# BCA_SELF_SCAN_BINARY names a prebuilt binary (#1773). Make cannot +# know at parse time which it will be, and the `cargo run` form holds +# the workspace `target/` lock, so they serialize into the cargo chain +# after _pc-manpages rather than fanning out in parallel. That order +# is also what keeps the build cheap: `cargo xtask` compiles the +# library with exactly the CLI's feature set (xtask depends on the CLI +# as a library), so after it only the `bca` bin itself is left to +# link — whereas `cargo build --workspace --all-targets` unifies the +# dev-dependency features and warms a *different* library build. The +# hard tier runs first so a regression is named before the soft tier +# reports near-limit headroom. # # _pc-enums-check runs cargo on `enums/Cargo.toml`, which has its own # `target/` (the crate is workspace-excluded), so it does NOT share the @@ -2030,11 +2127,12 @@ _pc-enums-codegen-drift-test: _pc-enums-codegen-drift _pc-manpages: _pc-udeps $(MAKE) manpages-check -# bca self-scan tiers. Both build with `cargo run --release` against -# the workspace target/, so they chain after _pc-manpages (the -# tail of the workspace cargo chain) rather than fanning out in -# parallel. The hard gate runs before the soft gate so a regression -# beyond the configured limit surfaces first. +# bca self-scan tiers. Both may build with `cargo run` against the +# workspace target/ (see the DAG comment above for the profile and +# the binary override), so they chain after _pc-manpages (the tail +# of the workspace cargo chain) rather than fanning out in parallel. +# The hard gate runs before the soft gate so a regression beyond the +# configured limit surfaces first. _pc-self-scan: _pc-manpages $(MAKE) self-scan @@ -2279,9 +2377,10 @@ _ci-manpages: # bca self-scan tiers under `make ci`. Same shape as the _pc- # counterparts; chained into _ci-cargo-pipeline (not parallelised) -# because both run `cargo run --release` against the shared -# workspace target/. Mirrors `.github/workflows/pages.yml`'s -# `Threshold gate` step. +# because both may run `cargo run` against the shared workspace +# target/ (the profile and binary override are the `self-scan` +# recipes' own). Mirrors `.github/workflows/pages.yml`'s `Threshold +# gate` step. _ci-self-scan: $(MAKE) self-scan diff --git a/bca.toml b/bca.toml index 6ef37ce29..bff2ac10e 100644 --- a/bca.toml +++ b/bca.toml @@ -8,7 +8,11 @@ # CI consumes this the same way: `make self-scan` runs `bca check` # with no path / threshold / baseline flags, since they all live here. # We build the bca binary from source on purpose so any in-progress -# change to metric computation is reflected in the values we gate on. +# change to metric computation is reflected in the values we gate on — +# under the dev profile by default, since the release relink costs +# ~100 s per edit and both profiles write the same baseline (#1773); +# CI hands the recipes its freshly installed release binary instead. +# The knobs are documented at `SELF_SCAN_BCA` in the Makefile. # Scan the whole repo, honouring the ignore file. The walker re-anchors # the resolved seed to the `./`-prefixed form (#488), so the diff --git a/big-code-analysis-book/src/recipes/ci.md b/big-code-analysis-book/src/recipes/ci.md index 775936306..032926ee3 100644 --- a/big-code-analysis-book/src/recipes/ci.md +++ b/big-code-analysis-book/src/recipes/ci.md @@ -651,9 +651,18 @@ is a bare check with no path, threshold, or baseline flags, because the manifest supplies them: ```bash -cargo run --quiet --release -p big-code-analysis-cli -- check +cargo run --quiet -p big-code-analysis-cli -- check ``` +That is the dev profile. The release relink costs ~100 s after any +edit under `src/`, so the recipes build dev by default and leave the +profile to `BCA_SELF_SCAN_PROFILE=release` when CI's exact binary is +wanted; `make self-scan-profile-parity` checks per PR that the two +profiles write a byte-identical baseline. `BCA_SELF_SCAN_BINARY=` +runs a prebuilt binary instead of building at all — what CI does with +the release binary it installs from the checkout — and is sound only +when nothing compiled into that binary has changed since. + Both tiers consume the same `bca.toml` thresholds and the same `.bca-baseline.toml`; the soft tier runs the hard recipe with every threshold value multiplied by `BCA_HEADROOM`. Both exit `0` clean, diff --git a/big-code-analysis-book/src/recipes/local-gates.md b/big-code-analysis-book/src/recipes/local-gates.md index 02d2d4354..8351663ce 100644 --- a/big-code-analysis-book/src/recipes/local-gates.md +++ b/big-code-analysis-book/src/recipes/local-gates.md @@ -64,6 +64,16 @@ recipes for refreshing the baseline at each tier. | `self-scan-write-baseline` | hard | 100% of config | (write) | Absorb today's hard-tier offenders. | | `self-scan-write-baseline-headroom` | soft | tightened by `HEADROOM` | (write) | Absorb soft-tier offenders when launching or widening the band. | +This repository's own Makefile adds two checks on the baseline file +rather than on the code: `self-scan-baseline-fresh` regenerates to a +temporary file and runs `bca diff-baseline` against the committed one +(exit 2 when the file no longer describes the tree — the quarterly +freshness job's question, answerable locally), and +`self-scan-profile-parity` regenerates under both cargo profiles and +`cmp`s the results, which is what lets the repo build its gate binary +under the fast dev profile. Neither belongs in a generic adopter +skeleton; an installed `bca` has no profile to vary. + The hard tier and the soft tier consume the **same** `[thresholds]` table and the **same** `.bca-baseline.toml`. The only difference between them is the `HEADROOM` ratio applied to diff --git a/docs/development/baseline_freshness.md b/docs/development/baseline_freshness.md index 0f3437031..e50058e7e 100644 --- a/docs/development/baseline_freshness.md +++ b/docs/development/baseline_freshness.md @@ -85,18 +85,33 @@ On a green `main` only the first two can appear. ## Running it by hand {#running-it-by-hand} -The job is three commands, and they are the same ones locally: +The job's question is one `make` target locally (#1773): ```bash -old=$(mktemp "${TMPDIR:-/tmp}/bca-old-baseline.XXXXXX.toml") -cp .bca-baseline.toml "$old" -make self-scan-write-baseline-headroom -cargo run --quiet --release -p big-code-analysis-cli -- \ - diff-baseline "$old" .bca-baseline.toml --format markdown +make self-scan-baseline-fresh +``` + +It regenerates into a temporary sibling of `.bca-baseline.toml` — +a sibling because an entry's path key is relative to the baseline +file's own directory — runs `bca diff-baseline --exit-code` against +the committed file, and removes the temporary file on every exit. +Exit 0 means the committed file still describes the tree, 2 that it +does not, 1 a tool error. The committed file is never written; to +see the diff in the job's Markdown form rather than the terminal +table, the recipe's two commands are simple to run by hand: + +```bash +t=$(mktemp .bca-baseline.XXXXXX.toml) +cargo run --quiet -p big-code-analysis-cli -- \ + check --tier=soft=0.95 --write-baseline "$t" +cargo run --quiet -p big-code-analysis-cli -- \ + diff-baseline .bca-baseline.toml "$t" --format markdown +rm -f "$t" ``` -Drop `--exit-code`; as above it is informational. With the flag a -non-empty diff exits 2 and a tool error exits 1. +Both build the dev-profile binary, a few seconds warm; the job itself +installs a release binary and hands it to the recipe through +`BCA_SELF_SCAN_BINARY`, which the target honours too. Always the `-headroom` target, never the bare `self-scan-write-baseline`. The committed file carries diff --git a/tree-sitter-ccomment/bindings/rust/build.rs b/tree-sitter-ccomment/bindings/rust/build.rs index 9f7afc0b8..1fc5d882a 100644 --- a/tree-sitter-ccomment/bindings/rust/build.rs +++ b/tree-sitter-ccomment/bindings/rust/build.rs @@ -5,6 +5,19 @@ extern crate cc; fn main() { let src_dir = Path::new("src"); + // The parser and scanner include the headers under `src/tree_sitter/` + // (`parser.h`, and `alloc.h` / `array.h` where present). Watching only + // the two translation units below left a header-only edit with a stale + // object while the CLI's build-inputs digest (#1773) moved on — a + // binary advertising a tree it did not compile. + if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { + for entry in entries.flatten() { + if let Some(path) = entry.path().to_str() { + println!("cargo:rerun-if-changed={path}"); + } + } + } + let mut c_config = cc::Build::new(); c_config.include(src_dir); c_config diff --git a/tree-sitter-mozcpp/bindings/rust/build.rs b/tree-sitter-mozcpp/bindings/rust/build.rs index 1dde8d771..f07447cfd 100644 --- a/tree-sitter-mozcpp/bindings/rust/build.rs +++ b/tree-sitter-mozcpp/bindings/rust/build.rs @@ -1,6 +1,19 @@ fn main() { let src_dir = std::path::Path::new("src"); + // The parser and scanner include the headers under `src/tree_sitter/` + // (`parser.h`, and `alloc.h` / `array.h` where present). Watching only + // the two translation units below left a header-only edit with a stale + // object while the CLI's build-inputs digest (#1773) moved on — a + // binary advertising a tree it did not compile. + if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { + for entry in entries.flatten() { + if let Some(path) = entry.path().to_str() { + println!("cargo:rerun-if-changed={path}"); + } + } + } + let mut c_config = cc::Build::new(); c_config.std("c11").include(src_dir); diff --git a/tree-sitter-mozjs/bindings/rust/build.rs b/tree-sitter-mozjs/bindings/rust/build.rs index 8458c3269..bc0ed2af8 100644 --- a/tree-sitter-mozjs/bindings/rust/build.rs +++ b/tree-sitter-mozjs/bindings/rust/build.rs @@ -1,6 +1,19 @@ fn main() { let src_dir = std::path::Path::new("src"); + // The parser and scanner include the headers under `src/tree_sitter/` + // (`parser.h`, and `alloc.h` / `array.h` where present). Watching only + // the two translation units below left a header-only edit with a stale + // object while the CLI's build-inputs digest (#1773) moved on — a + // binary advertising a tree it did not compile. + if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { + for entry in entries.flatten() { + if let Some(path) = entry.path().to_str() { + println!("cargo:rerun-if-changed={path}"); + } + } + } + let mut c_config = cc::Build::new(); c_config .std("c11") diff --git a/tree-sitter-preproc/bindings/rust/build.rs b/tree-sitter-preproc/bindings/rust/build.rs index 9f7afc0b8..1fc5d882a 100644 --- a/tree-sitter-preproc/bindings/rust/build.rs +++ b/tree-sitter-preproc/bindings/rust/build.rs @@ -5,6 +5,19 @@ extern crate cc; fn main() { let src_dir = Path::new("src"); + // The parser and scanner include the headers under `src/tree_sitter/` + // (`parser.h`, and `alloc.h` / `array.h` where present). Watching only + // the two translation units below left a header-only edit with a stale + // object while the CLI's build-inputs digest (#1773) moved on — a + // binary advertising a tree it did not compile. + if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { + for entry in entries.flatten() { + if let Some(path) = entry.path().to_str() { + println!("cargo:rerun-if-changed={path}"); + } + } + } + let mut c_config = cc::Build::new(); c_config.include(src_dir); c_config diff --git a/tree-sitter-tcl/bindings/rust/build.rs b/tree-sitter-tcl/bindings/rust/build.rs index 78c414b71..9deab1bc7 100644 --- a/tree-sitter-tcl/bindings/rust/build.rs +++ b/tree-sitter-tcl/bindings/rust/build.rs @@ -1,6 +1,19 @@ fn main() { let src_dir = std::path::Path::new("src"); + // The parser and scanner include the headers under `src/tree_sitter/` + // (`parser.h`, and `alloc.h` / `array.h` where present). Watching only + // the two translation units below left a header-only edit with a stale + // object while the CLI's build-inputs digest (#1773) moved on — a + // binary advertising a tree it did not compile. + if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { + for entry in entries.flatten() { + if let Some(path) = entry.path().to_str() { + println!("cargo:rerun-if-changed={path}"); + } + } + } + let mut c_config = cc::Build::new(); c_config.include(src_dir); c_config From 982931f2d7d2ed325bad66f55f452582855a82d4 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:48:14 -0800 Subject: [PATCH 2/8] feat(cli): record build provenance in --version MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `-V` stays the one-line `bca `. `--version` now follows it with a provenance block: build inputs: git: [-dirty] | unavailable built: (profile, rustc, target, debug-assertions) binary id: `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 --- .bca-baseline.toml | 10 +- CHANGELOG.md | 22 ++ Cargo.lock | 1 + STABILITY.md | 26 +- big-code-analysis-cli/Cargo.toml | 14 +- big-code-analysis-cli/build.rs | 202 ++++++++++++ .../src/build_info/build_info_tests.rs | 294 ++++++++++++++++++ .../src/build_info/digest.rs | 224 +++++++++++++ big-code-analysis-cli/src/build_info/elf.rs | 151 +++++++++ big-code-analysis-cli/src/build_info/mod.rs | 55 ++++ big-code-analysis-cli/src/check_format.rs | 22 +- big-code-analysis-cli/src/commands.rs | 8 +- big-code-analysis-cli/src/commands/report.rs | 1 + big-code-analysis-cli/src/html_report.rs | 1 + big-code-analysis-cli/src/lib.rs | 1 + big-code-analysis-cli/src/markdown_report.rs | 1 + big-code-analysis-cli/src/provenance.rs | 40 ++- .../tests/check/check_exit_codes.rs | 55 ++++ .../tests/output/format_smoke.rs | 15 + src/lib.rs | 7 +- src/output/mod.rs | 4 +- src/output/sarif.rs | 127 ++++++++ utils/check-role-coverage-test.py | 27 ++ utils/check-role-coverage.py | 21 +- utils/self_scan_digest.py | 96 ++++++ 25 files changed, 1406 insertions(+), 19 deletions(-) create mode 100644 big-code-analysis-cli/build.rs create mode 100644 big-code-analysis-cli/src/build_info/build_info_tests.rs create mode 100644 big-code-analysis-cli/src/build_info/digest.rs create mode 100644 big-code-analysis-cli/src/build_info/elf.rs create mode 100644 big-code-analysis-cli/src/build_info/mod.rs create mode 100644 utils/self_scan_digest.py diff --git a/.bca-baseline.toml b/.bca-baseline.toml index b820d4cd4..2143c6845 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -509,13 +509,13 @@ value = 6.0 path = "big-code-analysis-cli/src/commands/report.rs" qualified = "run_command_report" metric = "abc" -value = 39.06404996924922 +value = 39.93745109543172 [[entry]] path = "big-code-analysis-cli/src/commands/report.rs" qualified = "run_command_report" metric = "halstead.effort" -value = 63991.55666020266 +value = 65001.24036761245 [[entry]] path = "big-code-analysis-cli/src/diff.rs" @@ -1393,6 +1393,12 @@ qualified = "metric_values" metric = "halstead.effort" value = 89579.4980762016 +[[entry]] +path = "src/output/sarif.rs" +qualified = "write_sarif_with_provenance" +metric = "nargs" +value = 5.0 + [[entry]] path = "src/spaces.rs" qualified = "FuncSpace::new" diff --git a/CHANGELOG.md b/CHANGELOG.md index e1145f86a..99761af05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,28 @@ for historical reference. ### Added +- **`bca --version` records build provenance** (#1773). `-V` is the + unchanged one-line `bca `; `--version` follows it with + `build inputs:` (a SHA-256 content digest of every source compiled + into the binary — the workspace's Rust, manifests and the five + vendored grammars — or `unavailable` for a crates.io build), + `git:` (``, `-dirty` when those inputs had uncommitted edits), + `built:` (RFC 3339 UTC, honouring `SOURCE_DATE_EPOCH`, with the + profile, `rustc`, target and debug-assertions state) and + `binary id:` (the linker's GNU build-id on Linux). Two builds of one + tree share a digest whatever their mtimes or branch, and two + binaries that both print `2.4.0` from different commits do not — + which is the question "is this installed `bca` the one this checkout + would build" needs answered. The digest is stamped into `bca check`'s + SARIF under `tool.driver.properties` (`bca.buildInputs`, + `bca.buildGit`) and abbreviated in the `bca report` footer. Library: + `SarifProvenance` and `write_sarif_with_provenance` are additive; the + two existing SARIF writers emit byte-identical documents. + `utils/self_scan_digest.py` reproduces the digest in Python, pinned to + the Rust implementation by one shared fixture; the vendored grammar + build scripts now watch their `src/tree_sitter/` headers, so a + header-only edit recompiles the parser instead of leaving a stale + object behind a fresh digest. - `[[thresholds.path]]` in `bca.toml` and `--config`: path-scoped threshold overrides, layered `[thresholds]` → `[thresholds.lang.]` → `[[thresholds.path]]` → tier → `--threshold`. Each entry's glob is diff --git a/Cargo.lock b/Cargo.lock index e1695a57e..fbae816ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -534,6 +534,7 @@ dependencies = [ "serde", "serde-saphyr", "serde_json", + "sha2", "tempfile", "toml", ] diff --git a/STABILITY.md b/STABILITY.md index 8f2588682..0b99fb6c5 100644 --- a/STABILITY.md +++ b/STABILITY.md @@ -680,10 +680,28 @@ may differ by up to 1 ULP. Per the value-stability carve-out above, do not treat float magnitudes as a stable cross-version identity; compare them with a tolerance. -`bca --version` prints the CLI binary's own version, not the library -version. To record the library version from a CLI run, capture it -from `Cargo.lock` or the resolved `cargo metadata` output for the -`big-code-analysis` package. +`bca -V` prints one line, `bca ` — the CLI binary's own +version, not the library version. To record the library version from +a CLI run, capture it from `Cargo.lock` or the resolved `cargo +metadata` output for the `big-code-analysis` package. + +`bca --version` prints that same line first and then a build +provenance block (#1773): `build inputs:` (a SHA-256 over every source +compiled into the binary, or `unavailable` for a build from the +crates.io tarball, where the workspace is not beside the crate), +`git:`, `built:` (RFC 3339 UTC, `SOURCE_DATE_EPOCH` when it was set +at build time, with the profile, `rustc` version, target and +debug-assertions state) and `binary id:` (the linker's GNU build-id +note on Linux; `unavailable` elsewhere). The first line is the stable +contract; the fields after it are informational, their wording may +change in a minor release, and a consumer that needs the version alone +should read `-V` or the first line. The same digest is stamped into a +`bca check` SARIF document under `tool.driver.properties` as +`bca.buildInputs` / `bca.buildGit`, and abbreviated in the `bca report` +provenance footer. The library's own `write_sarif` and +`write_sarif_with_suppressed` are unchanged; `write_sarif_with_provenance` +and `SarifProvenance` are the additive surface a host uses to stamp its +own build. The next major re-baseline at `3.0` (whenever it happens) is the point at which the value drifts accumulated across `2.x` will be diff --git a/big-code-analysis-cli/Cargo.toml b/big-code-analysis-cli/Cargo.toml index 440a72eb1..b1a64793b 100644 --- a/big-code-analysis-cli/Cargo.toml +++ b/big-code-analysis-cli/Cargo.toml @@ -14,7 +14,10 @@ name = "bca" path = "src/main.rs" [dependencies] -clap = { version = "^4.0", features = ["derive"] } +# `string` lets the `--version` provenance block (#1773) be attached as +# an owned `String` at run time; one of its fields is read from the +# linked binary and cannot be a `'static` literal. +clap = { version = "^4.0", features = ["derive", "string"] } globset = "^0.4" ignore = "^0.4" # The CLI exposes every language `bca` advertises, so it pins the @@ -48,8 +51,17 @@ toml = "^1.1" [lints] workspace = true +# `build.rs` hashes every compiled-in source into the `--version` +# provenance block (#1773). `src/build_info/digest.rs` is shared with +# the crate's tests by `#[path]`, so the pin appears under both tables; +# it is the root crate's exact pin repeated, since `sha2` is a package +# dependency there rather than a `[workspace.dependencies]` entry. +[build-dependencies] +sha2 = "=0.11.1" + [dev-dependencies] assert_cmd = "^2.0" +sha2 = "=0.11.1" csv.workspace = true insta = "1.49.0" jsonschema = "^0.59" diff --git a/big-code-analysis-cli/build.rs b/big-code-analysis-cli/build.rs new file mode 100644 index 000000000..c8c909cd8 --- /dev/null +++ b/big-code-analysis-cli/build.rs @@ -0,0 +1,202 @@ +//! Bakes build provenance into `bca` as `BCA_BUILD_*` environment +//! variables read by `src/build_info/mod.rs` through `env!` (#1773). +//! +//! The one field that *decides* anything is `BCA_BUILD_INPUTS`, the +//! content digest of everything compiled into the binary; the +//! self-scan resolver compares it against the live tree to tell +//! whether an installed `bca` implements the checkout it is about to +//! measure. The rest — git revision, build time, toolchain — is +//! forensic: it lets a baseline, report or bug report be traced to a +//! build, and nothing reads it to make a choice. +//! +//! Two layouts reach this script. From a workspace checkout every root +//! in `INPUT_ROOTS` exists beside this crate and the digest is taken. +//! From a registry tarball (`cargo install big-code-analysis-cli`, or +//! `cargo package`'s verification copy) the crate stands alone, so the +//! digest is reported `unavailable` and — this matters — *no* +//! `rerun-if-changed` is emitted for a path that does not exist, since +//! cargo treats a listed-but-absent path as permanently dirty. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +#[path = "src/build_info/digest.rs"] +#[allow(dead_code)] +mod digest; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH"); + + let manifest_dir = PathBuf::from(env_or_empty("CARGO_MANIFEST_DIR")); + let workspace = manifest_dir.parent().map(Path::to_path_buf); + let inputs = workspace.as_deref().and_then(emit_inputs_digest); + + let git = workspace + .as_deref() + .filter(|_| inputs.is_some()) + .and_then(git_revision) + .unwrap_or_else(|| "unavailable".to_owned()); + + set( + "BCA_BUILD_INPUTS", + &inputs.unwrap_or_else(|| "unavailable".to_owned()), + ); + set("BCA_BUILD_GIT", &git); + set("BCA_BUILD_TIME", &build_time()); + set("BCA_BUILD_RUSTC", &rustc_version()); + set("BCA_BUILD_TARGET", &env_or_empty("TARGET")); + set("BCA_BUILD_PROFILE", &env_or_empty("PROFILE")); +} + +fn set(key: &str, value: &str) { + println!("cargo:rustc-env={key}={value}"); +} + +fn env_or_empty(key: &str) -> String { + std::env::var(key).unwrap_or_default() +} + +/// The digest of `workspace`, after registering every hashed file with +/// cargo so an edit reruns this script. Only files, never a directory: +/// cargo's directory watch is recursive and fires on the newest mtime +/// beneath it, which under a vendored grammar includes its untracked +/// `target/` and under `src/` every `.snap` — so `make release-check` +/// or an `insta` accept would otherwise force the very relink this +/// digest exists to avoid. The price is that a *new* input file is not +/// seen until something already watched changes; an added file with no +/// edit to any existing one is rare enough that the fresh-walk test in +/// `build_info_tests.rs` is the backstop rather than a watch. +/// +/// `None` when the layout is not a workspace checkout; nothing is +/// registered then except `build.rs` itself. +fn emit_inputs_digest(workspace: &Path) -> Option { + let files = digest::input_files(workspace).ok()?; + for rel in &files { + println!("cargo:rerun-if-changed={}", workspace.join(rel).display()); + } + digest::digest(workspace).ok() +} + +/// `` or `-dirty` for the checkout `workspace` lies in, or +/// `None` outside one. The dirtiness pathspec is the digest's own +/// roots, so the two fields cannot disagree about what "dirty" means. +/// +/// Git's repository-selecting variables are scrubbed and discovery is +/// fenced at the workspace, so a packaged copy under `target/package/` +/// on a developer host cannot stamp the parent checkout's revision, and +/// a `pre-commit` hook's temporary `GIT_INDEX_FILE` cannot leak in. +fn git_revision(workspace: &Path) -> Option { + let git = |args: &[&str]| { + let out = Command::new("git") + .args(args) + .current_dir(workspace) + .env_remove("GIT_DIR") + .env_remove("GIT_WORK_TREE") + .env_remove("GIT_INDEX_FILE") + .env_remove("GIT_COMMON_DIR") + .env("GIT_CEILING_DIRECTORIES", workspace) + .output() + .ok()?; + out.status + .success() + .then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned()) + }; + let sha = git(&["rev-parse", "HEAD"])?; + let mut status = vec![ + "status", + "--porcelain", + "--untracked-files=all", + "--ignore-submodules=all", + "--", + ]; + status.extend(digest::INPUT_ROOTS); + let dirty = git(&status).is_some_and(|s| !s.is_empty()); + for watched in git_state_files(workspace) { + println!("cargo:rerun-if-changed={}", watched.display()); + } + Some(if dirty { format!("{sha}-dirty") } else { sha }) +} + +/// The files whose change means `HEAD` may have moved: `HEAD` itself, +/// the ref it names when symbolic, `packed-refs`, and the index. A +/// worktree's `.git` is a file naming its private directory, which +/// `rev-parse --git-dir` and `--git-common-dir` resolve. +fn git_state_files(workspace: &Path) -> Vec { + let resolve = |flag: &str| { + Command::new("git") + .args(["rev-parse", "--path-format=absolute", flag]) + .current_dir(workspace) + .env("GIT_CEILING_DIRECTORIES", workspace) + .output() + .ok() + .filter(|o| o.status.success()) + .map(|o| PathBuf::from(String::from_utf8_lossy(&o.stdout).trim())) + }; + let mut files = Vec::new(); + if let Some(git_dir) = resolve("--git-dir") { + files.push(git_dir.join("HEAD")); + files.push(git_dir.join("index")); + if let Ok(head) = std::fs::read_to_string(git_dir.join("HEAD")) + && let Some(reference) = head.trim().strip_prefix("ref: ") + { + let common = resolve("--git-common-dir").unwrap_or(git_dir); + files.push(common.join(reference)); + files.push(common.join("packed-refs")); + } + } + files.into_iter().filter(|p| p.exists()).collect() +} + +/// RFC 3339 UTC, from `SOURCE_DATE_EPOCH` when set (the +/// reproducible-builds convention the report footer already honours) +/// and the wall clock otherwise. +fn build_time() -> String { + let secs = std::env::var("SOURCE_DATE_EPOCH") + .ok() + .and_then(|s| s.trim().parse::().ok()) + .or_else(|| { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .ok() + .map(|d| d.as_secs()) + }) + .unwrap_or(0); + format_rfc3339(secs) +} + +/// Civil-from-days, Howard Hinnant's algorithm; the same one +/// `src/provenance.rs` uses for the report footer date. The names are +/// the algorithm's own. +#[allow(clippy::many_single_char_names)] +fn format_rfc3339(secs: u64) -> String { + let days = secs / 86_400; + let rem = secs % 86_400; + let (hour, min, sec) = (rem / 3600, (rem % 3600) / 60, rem % 60); + let z = days + 719_468; + let era = z / 146_097; + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let year = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = if month <= 2 { year + 1 } else { year }; + format!("{year:04}-{month:02}-{day:02}T{hour:02}:{min:02}:{sec:02}Z") +} + +/// `rustc 1.99.0 (b940084d7 2026-09-28)` from the compiler cargo is +/// driving (`RUSTC`), not whatever `rustc` is first on PATH. +fn rustc_version() -> String { + let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned()); + Command::new(rustc) + .arg("--version") + .output() + .ok() + .filter(|o| o.status.success()) + .map_or_else( + || "unavailable".to_owned(), + |o| String::from_utf8_lossy(&o.stdout).trim().to_owned(), + ) +} diff --git a/big-code-analysis-cli/src/build_info/build_info_tests.rs b/big-code-analysis-cli/src/build_info/build_info_tests.rs new file mode 100644 index 000000000..27b893f68 --- /dev/null +++ b/big-code-analysis-cli/src/build_info/build_info_tests.rs @@ -0,0 +1,294 @@ +use std::path::Path; + +use super::digest::{DigestError, INPUT_ROOTS, digest, input_files}; +use super::elf::{build_id, hex_lower}; + +/// The fixture `utils/self-scan-bca-test.py` builds byte-for-byte, and +/// the hex both implementations must produce from it. One file per rule +/// the walker has: a nested input, a NUL byte in content, an empty +/// file, a `.snap` that must be ignored, a top-level `target/` that +/// must be skipped, and a nested `build/` that must *not* be. +const SHARED_FIXTURE_DIGEST: &str = + "564b792dc7b3e4fca571038d165a8d89ca9069bccc956ea4af0413c572345299"; + +fn shared_fixture(dir: &Path) { + let write = |rel: &str, bytes: &[u8]| { + let p = dir.join(rel); + std::fs::create_dir_all(p.parent().expect("fixture paths have parents")).expect("mkdir"); + std::fs::write(p, bytes).expect("write"); + }; + write("Cargo.toml", b"[workspace]\n"); + write("src/lib.rs", b"fn a() {}\n"); + write("src/nested/b.rs", b"fn b() {\0}\n"); + write("src/empty.rs", b""); + write("src/snapshots/x.snap", b"ignored\n"); + write("src/build/generated.rs", b"// nested build dir is hashed\n"); + write("big-code-analysis-ast/Cargo.toml", b"[package]\n"); + write("big-code-analysis-cli/Cargo.toml", b"[package]\n"); + write("big-code-analysis-cli/build.rs", b"fn main() {}\n"); + write("tree-sitter-ccomment/src/parser.c", b"int p;\n"); + write("tree-sitter-ccomment/target/junk.rs", b"skipped\n"); + write( + "tree-sitter-mozcpp/src/tree_sitter/parser.h", + b"#define X\n", + ); + write("tree-sitter-mozjs/src/scanner.c", b"int s;\n"); + write("tree-sitter-preproc/src/node-types.json", b"[]\n"); + write("tree-sitter-tcl/src/grammar.json", b"{}\n"); +} + +#[test] +fn shared_fixture_hashes_to_the_pinned_digest() { + let dir = tempfile::tempdir().expect("tempdir"); + shared_fixture(dir.path()); + assert_eq!( + input_files(dir.path()).expect("walk"), + [ + "Cargo.toml", + "big-code-analysis-ast/Cargo.toml", + "big-code-analysis-cli/Cargo.toml", + "big-code-analysis-cli/build.rs", + "src/build/generated.rs", + "src/empty.rs", + "src/lib.rs", + "src/nested/b.rs", + "tree-sitter-ccomment/src/parser.c", + "tree-sitter-mozcpp/src/tree_sitter/parser.h", + "tree-sitter-mozjs/src/scanner.c", + "tree-sitter-preproc/src/node-types.json", + "tree-sitter-tcl/src/grammar.json", + ] + ); + assert_eq!(digest(dir.path()).expect("digest"), SHARED_FIXTURE_DIGEST); +} + +#[test] +fn digest_is_independent_of_creation_order_and_moves_on_every_input_kind() { + let a = tempfile::tempdir().expect("tempdir"); + shared_fixture(a.path()); + let base = digest(a.path()).expect("digest"); + + // Same bytes, written in a different order. + let b = tempfile::tempdir().expect("tempdir"); + std::fs::create_dir_all(b.path().join("src/nested")).expect("mkdir"); + std::fs::write(b.path().join("src/nested/b.rs"), b"fn b() {\0}\n").expect("write"); + shared_fixture(b.path()); + assert_eq!(digest(b.path()).expect("digest"), base); + + let perturb = |rel: &str, bytes: &[u8]| { + let d = tempfile::tempdir().expect("tempdir"); + shared_fixture(d.path()); + let p = d.path().join(rel); + std::fs::create_dir_all(p.parent().expect("parent")).expect("mkdir"); + std::fs::write(p, bytes).expect("write"); + digest(d.path()).expect("digest") + }; + assert_ne!( + perturb("src/lib.rs", b"fn a() { }\n"), + base, + "content change" + ); + assert_ne!(perturb("src/added.rs", b""), base, "an added empty file"); + assert_ne!( + perturb("src/lib2.rs", b"fn a() {}\n"), + base, + "same bytes, new path" + ); + assert_eq!( + perturb("src/snapshots/y.snap", b"more"), + base, + "a snapshot is not an input" + ); + assert_eq!( + perturb("tree-sitter-tcl/target/out.rs", b"x"), + base, + "a grammar's top-level target/ is not an input" + ); +} + +#[test] +fn walk_refuses_a_partial_tree_rather_than_hashing_it() { + let dir = tempfile::tempdir().expect("tempdir"); + shared_fixture(dir.path()); + std::fs::remove_dir_all(dir.path().join("tree-sitter-tcl")).expect("rm"); + assert_eq!( + digest(dir.path()), + Err(DigestError::MissingRoot("tree-sitter-tcl".into())) + ); +} + +#[cfg(unix)] +#[test] +fn walk_refuses_a_symlinked_input() { + let dir = tempfile::tempdir().expect("tempdir"); + shared_fixture(dir.path()); + std::os::unix::fs::symlink("lib.rs", dir.path().join("src/link.rs")).expect("symlink"); + assert_eq!( + digest(dir.path()), + Err(DigestError::Symlink("src/link.rs".into())) + ); +} + +#[test] +fn input_roots_name_what_the_build_script_and_the_resolver_agree_on() { + // `Cargo.lock` is deliberately absent (cargo fingerprints it) and so + // is every runtime input; the resolver's copy of this list is + // checked against the same fixture, so this pins the Rust side. + assert!(!INPUT_ROOTS.contains(&"Cargo.lock")); + assert!(!INPUT_ROOTS.contains(&"bca.toml")); + assert!(INPUT_ROOTS.contains(&"big-code-analysis-cli")); +} + +/// The baked digest equals a fresh walk of the checkout this test runs +/// in. Cargo reruns `build.rs` whenever an input moves, so the two can +/// disagree only if the `rerun-if-changed` set it emits is incomplete — +/// which is the defect this pins. +#[test] +fn baked_digest_matches_a_fresh_walk_of_the_checkout() { + let workspace = Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("the CLI crate sits one below the workspace root"); + match digest(workspace) { + Ok(live) => assert_eq!(super::BUILD_INPUTS, live), + Err(DigestError::MissingRoot(_)) => assert_eq!(super::BUILD_INPUTS, "unavailable"), + Err(e) => panic!("walk failed: {e}"), + } +} + +#[test] +fn long_version_starts_with_the_bare_version_and_carries_every_field() { + let text = super::long_version(); + let mut lines = text.lines(); + assert_eq!(lines.next(), Some(env!("CARGO_PKG_VERSION"))); + let rest: Vec<_> = lines.collect(); + assert_eq!(rest.len(), 4, "{text}"); + assert!(rest[0].starts_with("build inputs: "), "{text}"); + assert!(rest[1].starts_with("git: "), "{text}"); + assert!( + rest[2].starts_with("built: ") && rest[2].contains("debug-assertions "), + "{text}" + ); + assert!(rest[3].starts_with("binary id: "), "{text}"); + let inputs = rest[0].trim_start_matches("build inputs: "); + assert!( + inputs == "unavailable" + || (inputs.len() == 64 && inputs.bytes().all(|b| b.is_ascii_hexdigit())), + "{inputs}" + ); +} + +#[test] +fn the_derive_carries_no_long_version_so_the_man_page_cannot_absorb_one() { + use clap::CommandFactory as _; + assert!(crate::Cli::command().get_long_version().is_none()); +} + +/// A minimal little-endian ELF64 image: header, one program header of +/// `kind`, and a note segment built from `notes`. +fn elf64(kind: u32, notes: &[u8]) -> Vec { + let mut out = vec![0u8; 0x40]; + out[..4].copy_from_slice(b"\x7fELF"); + out[4] = 2; + out[5] = 1; + out[0x20..0x28].copy_from_slice(&0x40u64.to_le_bytes()); + out[0x36..0x38].copy_from_slice(&0x38u16.to_le_bytes()); + out[0x38..0x3a].copy_from_slice(&1u16.to_le_bytes()); + let seg_at = 0x40u64 + 0x38; + let mut ph = vec![0u8; 0x38]; + ph[..4].copy_from_slice(&kind.to_le_bytes()); + ph[0x08..0x10].copy_from_slice(&seg_at.to_le_bytes()); + ph[0x20..0x28].copy_from_slice(&(notes.len() as u64).to_le_bytes()); + out.extend(ph); + out.extend_from_slice(notes); + out +} + +fn note(name: &[u8], kind: u32, desc: &[u8]) -> Vec { + let len = |s: &[u8]| u32::try_from(s.len()).expect("fixture notes are tiny"); + let mut out = Vec::new(); + out.extend(len(name).to_le_bytes()); + out.extend(len(desc).to_le_bytes()); + out.extend(kind.to_le_bytes()); + out.extend(name); + out.resize(out.len().next_multiple_of(4), 0); + out.extend(desc); + out.resize(out.len().next_multiple_of(4), 0); + out +} + +#[test] +fn build_id_is_read_past_an_unrelated_note_and_hex_rendered() { + let id = [0xde, 0xad, 0xbe, 0xef, 0x01]; + let mut notes = note(b"GNU\0", 1, b"\0\0\0\0\x03\0\0\0\x02\0\0\0\0\0\0\0"); + notes.extend(note(b"GNU\0", 3, &id)); + let image = elf64(4, ¬es); + assert_eq!(build_id(&image), Some(&id[..])); + assert_eq!( + build_id(&image).map(hex_lower).as_deref(), + Some("deadbeef01") + ); +} + +#[test] +fn build_id_is_none_for_every_shape_the_reader_does_not_support() { + let id = [1u8, 2, 3]; + let good = elf64(4, ¬e(b"GNU\0", 3, &id)); + assert_eq!( + build_id(&good), + Some(&id[..]), + "the fixture itself must parse" + ); + + let mut wrong_magic = good.clone(); + wrong_magic[0] = 0; + assert_eq!(build_id(&wrong_magic), None, "wrong magic"); + + let mut elf32 = good.clone(); + elf32[4] = 1; + assert_eq!(build_id(&elf32), None, "ELF32"); + + let mut big_endian = good.clone(); + big_endian[5] = 2; + assert_eq!(build_id(&big_endian), None, "big-endian"); + + assert_eq!(build_id(&good[..0x30]), None, "truncated header"); + assert_eq!(build_id(&good[..0x50]), None, "truncated program header"); + assert_eq!( + build_id(&elf64(1, ¬e(b"GNU\0", 3, &id))), + None, + "not a PT_NOTE segment" + ); + assert_eq!( + build_id(&elf64(4, ¬e(b"XYZ\0", 3, &id))), + None, + "not the GNU note" + ); + assert_eq!( + build_id(&elf64(4, ¬e(b"GNU\0", 7, &id))), + None, + "not NT_GNU_BUILD_ID" + ); + + let mut overflow = good.clone(); + overflow[0x40 + 0x20..0x40 + 0x28].copy_from_slice(&u64::MAX.to_le_bytes()); + assert_eq!(build_id(&overflow), None, "segment size past the end"); + let mut far_offset = good; + far_offset[0x40 + 0x08..0x40 + 0x10].copy_from_slice(&u64::MAX.to_le_bytes()); + assert_eq!(build_id(&far_offset), None, "segment offset past the end"); +} + +/// A capability probe, not a contract: the linker on this host is what +/// decides whether the test binary carries a note at all. When it does, +/// the reader must find it and render 40 hex digits; when it does not, +/// `unavailable` is the documented answer. +#[cfg(target_os = "linux")] +#[test] +fn running_executable_yields_hex_or_nothing() { + match super::elf::current_build_id() { + Some(id) => assert!( + !id.is_empty() && id.bytes().all(|b| b.is_ascii_hexdigit()), + "{id}" + ), + None => eprintln!("no GNU build-id note in the test binary on this host"), + } +} diff --git a/big-code-analysis-cli/src/build_info/digest.rs b/big-code-analysis-cli/src/build_info/digest.rs new file mode 100644 index 000000000..1a9ee9269 --- /dev/null +++ b/big-code-analysis-cli/src/build_info/digest.rs @@ -0,0 +1,224 @@ +//! The build-inputs digest: one SHA-256 over every file compiled into +//! `bca`, keyed on content alone. +//! +//! Included twice by `#[path]` — from `build.rs`, which bakes the +//! digest into the binary as `BCA_BUILD_INPUTS`, and from the crate +//! under `#[cfg(test)]`, which recomputes it to pin the two in +//! agreement — so it may use only `std` and `sha2`, the one dependency +//! both compilation graphs carry. `utils/self-scan-bca.py` reproduces +//! the same algorithm; the shared fixture in `digest_tests.rs` and +//! `self-scan-bca-test.py` is what holds the three implementations to +//! one answer. +//! +//! The algorithm, stated once so a reimplementation has nothing to +//! guess at: +//! +//! 1. Walk each root under the workspace. A root that is a file +//! contributes itself; a directory contributes every regular file +//! beneath it whose extension is in [`INPUT_EXTENSIONS`], except +//! under a top-level artifact directory named in +//! [`SKIPPED_TOP_LEVEL`]. Symlinks are refused rather than skipped: +//! the compiler follows them, so a digest that ignored one would +//! certify bytes it never saw. +//! 2. Encode each path relative to the workspace as bytes with `/` +//! separators. Non-UTF-8 names are refused for the same reason. +//! 3. Sort those byte strings. +//! 4. For each file, in that order, feed the hasher +//! `path ‖ 0x00 ‖ len(content) as u64 little-endian ‖ content`. +//! 5. The digest is the lowercase hex of the SHA-256 state. +//! +//! Content only — never an mtime, mode or owner — so two checkouts +//! with the same bytes agree regardless of when or where they were +//! written, and a `cargo install` from a checkout matches that +//! checkout until something compiled into it changes. CRLF +//! normalisation is deliberately absent: a checkout materialised with +//! other line endings holds other bytes, and the safe answer for a +//! binary built from it is a mismatch. + +use std::path::{Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +/// The workspace-relative roots whose contents reach the compiler. +/// +/// Whole crate directories rather than their `src/`, so each crate's +/// `Cargo.toml` and build script are in; the root `Cargo.toml` for the +/// workspace pins and profiles. `Cargo.lock` is not listed — cargo +/// already treats it as a fingerprint input, and a lockfile that moves +/// without any source moving changes no metric. Runtime inputs +/// (`bca.toml`, `.bcaignore`, the baseline) are not here either: a +/// prebuilt binary reads the live copy of each. +pub(crate) const INPUT_ROOTS: &[&str] = &[ + "Cargo.toml", + "src", + "big-code-analysis-ast", + "big-code-analysis-cli", + "tree-sitter-ccomment", + "tree-sitter-mozcpp", + "tree-sitter-mozjs", + "tree-sitter-preproc", + "tree-sitter-tcl", +]; + +/// Extensions that are compile-time inputs. `src/` carries over a +/// thousand tracked `.snap` files, and an `insta` accept would +/// otherwise read as a code change; `.snap.new` is untracked but not +/// ignored, so a forced corpus run would too. +pub(crate) const INPUT_EXTENSIONS: &[&str] = &["rs", "c", "cc", "h", "toml", "json"]; + +/// Build output a vendored grammar crate accumulates beside its +/// sources. Matched only as a *direct* child of a `tree-sitter-*` root, +/// never as a path component anywhere, so a tracked +/// `src/build/generated.rs` under any other root is hashed. +pub(crate) const SKIPPED_TOP_LEVEL: &[&str] = &["target", "build", "node_modules"]; + +/// Why a digest could not be taken. Every variant is a reason to report +/// the inputs as unavailable rather than to certify a partial tree. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum DigestError { + /// A root in [`INPUT_ROOTS`] does not exist under the workspace — + /// the crate is being built from a registry tarball, not a checkout. + MissingRoot(PathBuf), + /// A symlink under a root. See the module docs for why it is + /// refused rather than followed or skipped. + Symlink(PathBuf), + /// A path that is not UTF-8, which the shared encoding cannot spell. + NonUtf8Path(PathBuf), + /// Any I/O failure during the walk or the read. + Io(PathBuf, String), +} + +impl std::fmt::Display for DigestError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::MissingRoot(p) => write!(f, "input root is absent: {}", p.display()), + Self::Symlink(p) => write!(f, "symlink under an input root: {}", p.display()), + Self::NonUtf8Path(p) => { + write!(f, "non-UTF-8 path under an input root: {}", p.display()) + } + Self::Io(p, e) => write!(f, "{}: {e}", p.display()), + } + } +} + +/// The sorted, workspace-relative, `/`-separated paths of every input +/// file under `workspace`. Exposed separately from [`digest`] so a test +/// can check *which* files are hashed without re-deriving the hash. +pub(crate) fn input_files(workspace: &Path) -> Result, DigestError> { + let mut files = Vec::new(); + for root in INPUT_ROOTS { + let path = workspace.join(root); + let meta = std::fs::symlink_metadata(&path) + .map_err(|_| DigestError::MissingRoot(PathBuf::from(root)))?; + if meta.is_symlink() { + return Err(DigestError::Symlink(PathBuf::from(root))); + } + if meta.is_file() { + files.push((*root).to_owned()); + } else { + let grammar = root.starts_with("tree-sitter-"); + collect_dir(workspace, &path, grammar, &mut files)?; + } + } + files.sort_unstable_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + Ok(files) +} + +/// What the walk does with one directory entry. +enum Entry { + Descend(PathBuf), + Input(String), + Ignore, +} + +fn collect_dir( + workspace: &Path, + dir: &Path, + grammar_top: bool, + out: &mut Vec, +) -> Result<(), DigestError> { + let io = |e: std::io::Error| DigestError::Io(dir.to_path_buf(), e.to_string()); + let mut entries: Vec<_> = std::fs::read_dir(dir) + .map_err(io)? + .collect::>() + .map_err(io)?; + entries.sort_by_key(std::fs::DirEntry::file_name); + for entry in entries { + match classify(workspace, &entry.path(), grammar_top)? { + Entry::Descend(path) => collect_dir(workspace, &path, false, out)?, + Entry::Input(rel) => out.push(rel), + Entry::Ignore => {} + } + } + Ok(()) +} + +fn classify(workspace: &Path, path: &Path, grammar_top: bool) -> Result { + let meta = std::fs::symlink_metadata(path) + .map_err(|e| DigestError::Io(path.to_path_buf(), e.to_string()))?; + let rel = relative_posix(workspace, path)?; + if meta.is_symlink() { + return Err(DigestError::Symlink(PathBuf::from(rel))); + } + let skipped_artifact_dir = grammar_top + && path + .file_name() + .is_some_and(|n| SKIPPED_TOP_LEVEL.iter().any(|s| n == *s)); + Ok(if meta.is_dir() && !skipped_artifact_dir { + Entry::Descend(path.to_path_buf()) + } else if meta.is_file() && has_input_extension(path) { + Entry::Input(rel) + } else { + Entry::Ignore + }) +} + +fn has_input_extension(path: &Path) -> bool { + path.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| INPUT_EXTENSIONS.contains(&e)) +} + +fn relative_posix(workspace: &Path, path: &Path) -> Result { + let rel = path.strip_prefix(workspace).unwrap_or(path); + let mut out = String::new(); + for component in rel.components() { + let piece = component + .as_os_str() + .to_str() + .ok_or_else(|| DigestError::NonUtf8Path(rel.to_path_buf()))?; + if !out.is_empty() { + out.push('/'); + } + out.push_str(piece); + } + Ok(out) +} + +/// The build-inputs digest of `workspace` as 64 lowercase hex digits. +pub(crate) fn digest(workspace: &Path) -> Result { + let mut hasher = Sha256::new(); + for rel in input_files(workspace)? { + let path = workspace.join(&rel); + let content = + std::fs::read(&path).map_err(|e| DigestError::Io(path.clone(), e.to_string()))?; + hasher.update(rel.as_bytes()); + hasher.update([0u8]); + hasher.update((content.len() as u64).to_le_bytes()); + hasher.update(&content); + } + Ok(hex_lower(&hasher.finalize())) +} + +/// Lowercase hex, two digits per byte. The same shape as the Code +/// Climate writer's `hex_lower_bytes`, repeated here because this file +/// may import nothing from either crate. +pub(crate) fn hex_lower(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(bytes.len() * 2); + for b in bytes { + out.push(DIGITS[usize::from(b >> 4)] as char); + out.push(DIGITS[usize::from(b & 0x0f)] as char); + } + out +} diff --git a/big-code-analysis-cli/src/build_info/elf.rs b/big-code-analysis-cli/src/build_info/elf.rs new file mode 100644 index 000000000..307f2eac1 --- /dev/null +++ b/big-code-analysis-cli/src/build_info/elf.rs @@ -0,0 +1,151 @@ +//! The GNU build-id note of the running executable (#1773). +//! +//! The linker writes a hash of the final object into a `PT_NOTE` +//! segment as `NT_GNU_BUILD_ID`; debuggers, `perf` and symbol servers +//! key on it. It is the one provenance field that cannot be baked in by +//! `build.rs`, because it does not exist until the link has finished, +//! so it is read back from the binary at run time. +//! +//! Support is deliberately narrow: ELF64 in the host's byte order, +//! which is every Linux target the gate runs on. Anything else — ELF32, +//! a Mach-O or PE executable, a truncated or hand-edited file, an +//! executable that has been deleted since it started — yields `None` +//! and renders as `unavailable`. Nothing is decided on this field, so +//! every failure is informational. +//! +//! All offsets come from the file and are bounds-checked against the +//! bytes actually read; arithmetic is `checked_*` throughout, so a +//! malformed header cannot panic. + +const ELF_MAGIC: &[u8; 4] = b"\x7fELF"; +const ELFCLASS64: u8 = 2; +const ELFDATA2LSB: u8 = 1; +const PT_NOTE: u32 = 4; +const NT_GNU_BUILD_ID: u32 = 3; +const GNU_NOTE_NAME: &[u8] = b"GNU\0"; + +/// Lowercase hex of the running executable's GNU build-id, or `None`. +#[cfg(target_os = "linux")] +pub(crate) fn current_build_id() -> Option { + let exe = std::env::current_exe().ok()?; + let bytes = std::fs::read(exe).ok()?; + build_id(&bytes).map(hex_lower) +} + +/// Lowercase hex, two digits per byte. +pub(crate) fn hex_lower(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(bytes.len() * 2); + for b in bytes { + out.push(DIGITS[usize::from(b >> 4)] as char); + out.push(DIGITS[usize::from(b & 0x0f)] as char); + } + out +} + +#[cfg(not(target_os = "linux"))] +pub(crate) fn current_build_id() -> Option { + None +} + +/// The raw `NT_GNU_BUILD_ID` descriptor in `elf`, or `None` when the +/// bytes are not a little-endian ELF64 image carrying one. +pub(crate) fn build_id(elf: &[u8]) -> Option<&[u8]> { + let header = Header::parse(elf)?; + (0..header.phnum) + .filter_map(|i| header.program_header(elf, i)) + .filter(|ph| ph.kind == PT_NOTE) + .find_map(|ph| find_gnu_build_id(elf.get(ph.offset..ph.offset.checked_add(ph.size)?)?)) +} + +struct Header { + phoff: usize, + phentsize: usize, + phnum: usize, +} + +struct ProgramHeader { + kind: u32, + offset: usize, + size: usize, +} + +impl Header { + fn parse(elf: &[u8]) -> Option { + // bca: suppress(nexits) — every exit is a `?` on a bounds-checked + // read; a binary-format reader that fails closed is clearest as + // one straight line of them, not as nested `if let`s. + if elf.get(..4)? != ELF_MAGIC || *elf.get(4)? != ELFCLASS64 || *elf.get(5)? != ELFDATA2LSB { + return None; + } + Some(Self { + phoff: usize::try_from(u64_at(elf, 0x20)?).ok()?, + phentsize: usize::from(u16_at(elf, 0x36)?), + phnum: usize::from(u16_at(elf, 0x38)?), + }) + } + + fn program_header(&self, elf: &[u8], index: usize) -> Option { + // bca: suppress(nexits) — same shape as `parse`: `?` on checked + // arithmetic and bounded reads. + let at = self.phoff.checked_add(index.checked_mul(self.phentsize)?)?; + Some(ProgramHeader { + kind: u32_at(elf, at)?, + offset: usize::try_from(u64_at(elf, at.checked_add(0x08)?)?).ok()?, + size: usize::try_from(u64_at(elf, at.checked_add(0x20)?)?).ok()?, + }) + } +} + +/// Walk the notes in one `PT_NOTE` segment. Each is a 12-byte header +/// (`namesz`, `descsz`, `type`) followed by the name and the +/// descriptor, each padded to four bytes. +fn find_gnu_build_id(segment: &[u8]) -> Option<&[u8]> { + // bca: suppress(nexits) — the note walk fails closed through `?` on + // every read and every `checked_add`; that is the whole safety + // argument of the module, and it reads best uninterrupted. + let mut at = 0usize; + while let Some(namesz) = u32_at(segment, at) { + let descsz = usize::try_from(u32_at(segment, at + 4)?).ok()?; + let kind = u32_at(segment, at + 8)?; + let namesz = usize::try_from(namesz).ok()?; + let name_at = at.checked_add(12)?; + let desc_at = name_at.checked_add(align4(namesz)?)?; + let next = desc_at.checked_add(align4(descsz)?)?; + if kind == NT_GNU_BUILD_ID + && segment.get(name_at..name_at.checked_add(namesz)?)? == GNU_NOTE_NAME + { + return segment.get(desc_at..desc_at.checked_add(descsz)?); + } + at = next; + } + None +} + +fn align4(n: usize) -> Option { + n.checked_add(3).map(|v| v & !3) +} + +fn u16_at(bytes: &[u8], at: usize) -> Option { + bytes + .get(at..at.checked_add(2)?)? + .try_into() + .ok() + .map(u16::from_le_bytes) +} + +fn u32_at(bytes: &[u8], at: usize) -> Option { + bytes + .get(at..at.checked_add(4)?)? + .try_into() + .ok() + .map(u32::from_le_bytes) +} + +fn u64_at(bytes: &[u8], at: usize) -> Option { + bytes + .get(at..at.checked_add(8)?)? + .try_into() + .ok() + .map(u64::from_le_bytes) +} diff --git a/big-code-analysis-cli/src/build_info/mod.rs b/big-code-analysis-cli/src/build_info/mod.rs new file mode 100644 index 000000000..2520df47f --- /dev/null +++ b/big-code-analysis-cli/src/build_info/mod.rs @@ -0,0 +1,55 @@ +//! Build provenance for `bca --version` and the report footers (#1773). +//! +//! `build.rs` bakes the fields in as `BCA_BUILD_*` environment +//! variables; this module reads them with `env!` and renders the long +//! version block. One field is read at run time rather than build time: +//! the linker's GNU build-id note, which does not exist until the +//! binary has been linked ([`elf`]). +//! +//! Of the fields, only `inputs` ever decides anything — the self-scan +//! resolver compares it with the live tree. The others are evidence +//! for a human reading a log or a report later. + +pub(crate) mod elf; + +#[cfg(test)] +#[path = "digest.rs"] +pub(crate) mod digest; + +#[cfg(test)] +#[path = "build_info_tests.rs"] +mod tests; + +/// The content digest of everything compiled into this binary, or +/// `unavailable` for a build from a registry tarball, where the +/// workspace roots do not exist beside the crate. +pub(crate) const BUILD_INPUTS: &str = env!("BCA_BUILD_INPUTS"); + +/// `` or `-dirty` for the checkout the binary was built from, +/// or `unavailable`. +pub(crate) const BUILD_GIT: &str = env!("BCA_BUILD_GIT"); + +/// RFC 3339 UTC; `SOURCE_DATE_EPOCH` when it was set at build time. +pub(crate) const BUILD_TIME: &str = env!("BCA_BUILD_TIME"); + +const BUILD_RUSTC: &str = env!("BCA_BUILD_RUSTC"); +const BUILD_TARGET: &str = env!("BCA_BUILD_TARGET"); +const BUILD_PROFILE: &str = env!("BCA_BUILD_PROFILE"); + +/// The lines clap prints after `bca ` for `--version`. The +/// first line stays clap's own, so `-V` and the first line of +/// `--version` are the one-line form every existing consumer parses. +/// +/// `debug-assertions` is read from this crate's own `cfg`, not from +/// cargo's `DEBUG` variable, which reports debug *info* and is `true` +/// for this workspace's release profile. +pub(crate) fn long_version() -> String { + let assertions = if cfg!(debug_assertions) { "on" } else { "off" }; + let binary_id = elf::current_build_id().unwrap_or_else(|| "unavailable".to_owned()); + format!( + "{}\nbuild inputs: {BUILD_INPUTS}\ngit: {BUILD_GIT}\nbuilt: {BUILD_TIME} \ + (profile {BUILD_PROFILE}, {BUILD_RUSTC}, {BUILD_TARGET}, debug-assertions \ + {assertions})\nbinary id: {binary_id}", + env!("CARGO_PKG_VERSION"), + ) +} diff --git a/big-code-analysis-cli/src/check_format.rs b/big-code-analysis-cli/src/check_format.rs index eec719adb..9d67e3bed 100644 --- a/big-code-analysis-cli/src/check_format.rs +++ b/big-code-analysis-cli/src/check_format.rs @@ -28,8 +28,8 @@ use std::path::Path; use clap::ValueEnum; use big_code_analysis::{ - OffenderRecord, write_checkstyle, write_clang_warning, write_code_climate, write_msvc_warning, - write_sarif, write_sarif_with_suppressed, + OffenderRecord, SarifProvenance, write_checkstyle, write_clang_warning, write_code_climate, + write_msvc_warning, write_sarif_with_provenance, }; use crate::baseline::Coverage; @@ -93,7 +93,9 @@ impl AggregatedFormat { ) -> std::io::Result<()> { match self { Self::Checkstyle => write_buffered(output_path, |w| write_checkstyle(offenders, w)), - Self::Sarif => write_buffered(output_path, |w| write_sarif(offenders, w)), + Self::Sarif => write_buffered(output_path, |w| { + write_sarif_with_provenance(offenders, &[], &[], &sarif_provenance(), w) + }), Self::ClangWarning => { write_buffered(output_path, |w| write_clang_warning(offenders, w)) } @@ -127,10 +129,22 @@ pub(crate) fn dump_sarif_with_suppressed( } } write_buffered(output_path, |w| { - write_sarif_with_suppressed(active, &in_source, &baseline, w) + write_sarif_with_provenance(active, &in_source, &baseline, &sarif_provenance(), w) }) } +/// What this binary stamps into `tool.driver.properties` (#1773): the +/// digest of everything compiled into it and the revision it was built +/// from, so a SARIF upload traces to a build rather than to a version +/// that 92 unreleased commits can share. A registry build carries +/// `unavailable` for both, which is itself the information. +fn sarif_provenance() -> SarifProvenance { + SarifProvenance::new( + Some(crate::build_info::BUILD_INPUTS.to_owned()), + Some(crate::build_info::BUILD_GIT.to_owned()), + ) +} + /// Default annotation cap per metric. GitHub Actions surfaces at most /// 10 errors / 10 warnings / 10 notices per step in the UI, so a /// 400-violation run would exhaust the quota and silently drop diff --git a/big-code-analysis-cli/src/commands.rs b/big-code-analysis-cli/src/commands.rs index 5551831ed..33e227007 100644 --- a/big-code-analysis-cli/src/commands.rs +++ b/big-code-analysis-cli/src/commands.rs @@ -233,7 +233,13 @@ fn load_preproc(globals: &GlobalOpts) -> Option> { /// inferred from the parsed value alone — the manifest merge needs the /// `ArgMatches` value source to know whether to override it. fn parse_cli_with_legacy_hint() -> (Cli, bool) { - let matches = match Cli::command().try_get_matches() { + // The provenance block behind `--version` is attached here, to the + // `Command` that actually parses, and not in the derive: `xtask` + // renders man pages from a bare `Cli::command()`, and a derive-level + // `long_version` would stamp this build's digest into `man/bca.1` + // (#1773). `-V` keeps clap's one-line `version`. + let command = Cli::command().long_version(crate::build_info::long_version()); + let matches = match command.try_get_matches() { Ok(matches) => matches, Err(err) => { if matches!( diff --git a/big-code-analysis-cli/src/commands/report.rs b/big-code-analysis-cli/src/commands/report.rs index 98994b51b..24dfbf897 100644 --- a/big-code-analysis-cli/src/commands/report.rs +++ b/big-code-analysis-cli/src/commands/report.rs @@ -66,6 +66,7 @@ pub(crate) fn run_command_report( let date = crate::provenance::resolved_date(); let prov = crate::provenance::Provenance { version: env!("CARGO_PKG_VERSION"), + build: Some(crate::build_info::BUILD_INPUTS), date: &date, paths: &prov_paths, top, diff --git a/big-code-analysis-cli/src/html_report.rs b/big-code-analysis-cli/src/html_report.rs index 439aa46d1..3f7d9c919 100644 --- a/big-code-analysis-cli/src/html_report.rs +++ b/big-code-analysis-cli/src/html_report.rs @@ -663,6 +663,7 @@ mod tests { let s = two_lang_fixture(); let prov = crate::provenance::Provenance { version: "9.9.9", + build: None, date: "2026-06-11", paths: "src/", top: 0, diff --git a/big-code-analysis-cli/src/lib.rs b/big-code-analysis-cli/src/lib.rs index dca769844..f0247cf55 100644 --- a/big-code-analysis-cli/src/lib.rs +++ b/big-code-analysis-cli/src/lib.rs @@ -41,6 +41,7 @@ #![cfg_attr(not(test), warn(clippy::unwrap_used))] mod baseline; mod baseline_diff; +mod build_info; mod check_flags; mod check_format; mod cli_args; diff --git a/big-code-analysis-cli/src/markdown_report.rs b/big-code-analysis-cli/src/markdown_report.rs index 4860c0498..4e455bc7f 100644 --- a/big-code-analysis-cli/src/markdown_report.rs +++ b/big-code-analysis-cli/src/markdown_report.rs @@ -1891,6 +1891,7 @@ mod tests { ]; let prov = crate::provenance::Provenance { version: "9.9.9", + build: None, date: "2026-06-11", paths: "src/", top: 10, diff --git a/big-code-analysis-cli/src/provenance.rs b/big-code-analysis-cli/src/provenance.rs index f9d30bce7..67a45c00e 100644 --- a/big-code-analysis-cli/src/provenance.rs +++ b/big-code-analysis-cli/src/provenance.rs @@ -39,6 +39,10 @@ use crate::markdown_report::hotspot::cap; pub(crate) struct Provenance<'a> { /// `bca` package version (`CARGO_PKG_VERSION`). pub(crate) version: &'a str, + /// The build-inputs digest of the `bca` that wrote the report + /// (`build_info::BUILD_INPUTS`, #1773), or `None` to omit it. Hex or + /// the word `unavailable`, so it needs no per-format escaping. + pub(crate) build: Option<&'a str>, /// `YYYY-MM-DD` generation date (UTC), already resolved (see /// [`resolved_date`]). pub(crate) date: &'a str, @@ -77,8 +81,12 @@ impl Provenance<'_> { /// phrasing) is format-safe — semver, digits, and fixed words — so only /// `paths` needs per-format treatment. fn sentence(&self, paths_render: impl Fn(&str) -> String) -> String { + let build = self + .build + .map(|b| format!(" (build {})", b.get(..12).unwrap_or(b))) + .unwrap_or_default(); format!( - "Generated by bca {} on {} over {} \u{2014} {}, suppression markers {}.", + "Generated by bca {}{build} on {} over {} \u{2014} {}, suppression markers {}.", self.version, self.date, paths_render(self.paths), @@ -170,6 +178,7 @@ mod tests { fn prov<'a>(top: usize, policy: SuppressionPolicy) -> Provenance<'a> { Provenance { version: "9.9.9", + build: None, date: "2026-06-11", paths: "src/", top, @@ -177,6 +186,35 @@ mod tests { } } + #[test] + fn build_digest_is_abbreviated_after_the_version_and_absent_when_none() { + let mut out = String::new(); + let p = Provenance { + build: Some("0123456789abcdef0123456789abcdef"), + ..prov(20, SuppressionPolicy::Honor) + }; + push_markdown_footer(&mut out, &p); + assert!( + out.contains("Generated by bca 9.9.9 (build 0123456789ab) on 2026-06-11"), + "{out}" + ); + let mut plain = String::new(); + push_markdown_footer(&mut plain, &prov(20, SuppressionPolicy::Honor)); + assert!( + plain.contains("Generated by bca 9.9.9 on 2026-06-11"), + "{plain}" + ); + let mut short = String::new(); + push_markdown_footer( + &mut short, + &Provenance { + build: Some("unavailable"), + ..prov(20, SuppressionPolicy::Honor) + }, + ); + assert!(short.contains("(build unavailable)"), "{short}"); + } + #[test] fn markdown_footer_states_every_field() { let mut out = String::new(); diff --git a/big-code-analysis-cli/tests/check/check_exit_codes.rs b/big-code-analysis-cli/tests/check/check_exit_codes.rs index efa7a5594..7af65342d 100644 --- a/big-code-analysis-cli/tests/check/check_exit_codes.rs +++ b/big-code-analysis-cli/tests/check/check_exit_codes.rs @@ -564,6 +564,61 @@ fn version_exits_zero() { .stdout(predicate::str::contains("bca ")); } +/// `-V` stays the one-line `bca ` every release script, the +/// Homebrew formula and the role-coverage observer parse; `--version` +/// opens with that same line and then the provenance block (#1773). +#[test] +fn short_version_is_one_line_and_long_version_starts_with_it() { + let (dir, mut short) = common::cli_hermetic(); + let short_out = short + .arg("-V") + .assert() + .success() + .get_output() + .stdout + .clone(); + let short_text = String::from_utf8(short_out).expect("utf-8"); + assert_eq!(short_text.lines().count(), 1, "{short_text}"); + assert_eq!( + short_text.trim_end(), + format!("bca {}", env!("CARGO_PKG_VERSION")) + ); + + let (_dir2, mut long) = common::cli_hermetic(); + let _ = &dir; + let long_out = long + .arg("--version") + .assert() + .success() + .get_output() + .stdout + .clone(); + let long_text = String::from_utf8(long_out).expect("utf-8"); + let lines: Vec<&str> = long_text.lines().collect(); + assert_eq!( + lines.first().copied(), + Some(short_text.trim_end()), + "{long_text}" + ); + assert_eq!(lines.len(), 5, "{long_text}"); + for (line, prefix) in + lines[1..] + .iter() + .zip(["build inputs: ", "git: ", "built: ", "binary id: "]) + { + assert!( + line.starts_with(prefix), + "{line:?} should start with {prefix:?}" + ); + } + let inputs = lines[1].trim_start_matches("build inputs: "); + assert!( + inputs == "unavailable" + || (inputs.len() == 64 && inputs.bytes().all(|b| b.is_ascii_hexdigit())), + "{inputs}" + ); +} + // -- Manifest opt-in ------------------------------------------------------ /// Create a fixture repo with a `.git` marker so manifest discovery diff --git a/big-code-analysis-cli/tests/output/format_smoke.rs b/big-code-analysis-cli/tests/output/format_smoke.rs index 40e8bf82c..5ad545e38 100644 --- a/big-code-analysis-cli/tests/output/format_smoke.rs +++ b/big-code-analysis-cli/tests/output/format_smoke.rs @@ -157,6 +157,21 @@ fn cli_check_sarif_output_validates_against_schema() { !results.is_empty(), "expected at least one SARIF result for branchy fixture; doc was:\n{out}", ); + // The CLI stamps its build provenance into the driver's property + // bag (#1773) — the only place `toolComponent` admits a producer + // key, which the schema validation above has just confirmed. The + // digest is 64 hex digits from a checkout build and the literal + // `unavailable` from a registry build; nothing else is valid. + let props = &doc["runs"][0]["tool"]["driver"]["properties"]; + let inputs = props["bca.buildInputs"] + .as_str() + .expect("bca.buildInputs is a string"); + assert!( + inputs == "unavailable" + || (inputs.len() == 64 && inputs.bytes().all(|b| b.is_ascii_hexdigit())), + "{inputs}" + ); + assert!(props["bca.buildGit"].is_string(), "{out}"); } #[test] diff --git a/src/lib.rs b/src/lib.rs index 07f803a21..af419742b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -292,10 +292,11 @@ pub use crate::slash_path::slash_path; /// re-exported at the crate root. pub mod output; pub use crate::output::{ - CSV_EXTENSION, CSV_HEADER, ColorMode, OffenderRecord, Severity, TOOL_ID, defang_formula, - dump_node, dump_node_with_color, dump_ops, dump_ops_with_color, dump_root, + CSV_EXTENSION, CSV_HEADER, ColorMode, OffenderRecord, SarifProvenance, Severity, TOOL_ID, + defang_formula, dump_node, dump_node_with_color, dump_ops, dump_ops_with_color, dump_root, dump_root_with_color, write_checkstyle, write_clang_warning, write_code_climate, write_csv, - write_csv_aggregate, write_msvc_warning, write_sarif, write_sarif_with_suppressed, + write_csv_aggregate, write_msvc_warning, write_sarif, write_sarif_with_provenance, + write_sarif_with_suppressed, }; // --- AST plumbing (Node) --- diff --git a/src/output/mod.rs b/src/output/mod.rs index c5acf4d1c..828ede71f 100644 --- a/src/output/mod.rs +++ b/src/output/mod.rs @@ -27,7 +27,9 @@ pub mod csv; pub use csv::{CSV_EXTENSION, CSV_HEADER, defang_formula, write_csv, write_csv_aggregate}; pub mod sarif; -pub use sarif::{write_sarif, write_sarif_with_suppressed}; +pub use sarif::{ + SarifProvenance, write_sarif, write_sarif_with_provenance, write_sarif_with_suppressed, +}; pub mod code_climate; pub use code_climate::write_code_climate; diff --git a/src/output/sarif.rs b/src/output/sarif.rs index 8d32ab32b..085846164 100644 --- a/src/output/sarif.rs +++ b/src/output/sarif.rs @@ -169,6 +169,67 @@ pub fn write_sarif_with_suppressed( active: &[OffenderRecord], in_source: &[OffenderRecord], baseline: &[OffenderRecord], + writer: W, +) -> io::Result<()> { + write_sarif_with_provenance( + active, + in_source, + baseline, + &SarifProvenance::default(), + writer, + ) +} + +/// Build provenance a caller can stamp into the SARIF `tool.driver` +/// block, under `properties` (the SARIF 2.1.0 extension point — +/// `toolComponent` admits no other unknown key). +/// +/// The library itself knows only its own package version. A binary that +/// embeds it, such as `bca`, can record what *it* was built from so a +/// detached report traces to a build: `bca` sets `build_inputs` to the +/// content digest of everything compiled into it and `build_git` to the +/// checkout revision (#1773). `Default` carries nothing, and a default +/// provenance leaves the document byte-identical to [`write_sarif`]'s. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct SarifProvenance { + /// A content digest of the inputs compiled into the reporting + /// binary; rendered as the `bca.buildInputs` property. + pub build_inputs: Option, + /// The revision the reporting binary was built from; rendered as + /// the `bca.buildGit` property. + pub build_git: Option, +} + +impl SarifProvenance { + /// Provenance carrying the two fields `bca` stamps. + #[must_use] + pub fn new(build_inputs: Option, build_git: Option) -> Self { + Self { + build_inputs, + build_git, + } + } + + fn is_empty(&self) -> bool { + self.build_inputs.is_none() && self.build_git.is_none() + } +} + +/// [`write_sarif_with_suppressed`] with a [`SarifProvenance`] stamped +/// into `tool.driver.properties`. An empty provenance emits no +/// `properties` key at all, so the two older writers forward here with +/// their output unchanged. +/// +/// # Errors +/// +/// Same contract as [`write_sarif`]: any [`io::Error`] from `writer`, or a +/// serialisation failure mapped to `io::Error`. +pub fn write_sarif_with_provenance( + active: &[OffenderRecord], + in_source: &[OffenderRecord], + baseline: &[OffenderRecord], + provenance: &SarifProvenance, mut writer: W, ) -> io::Result<()> { let mut results: Vec> = @@ -203,6 +264,10 @@ pub fn write_sarif_with_suppressed( name: TOOL_ID, version: env!("CARGO_PKG_VERSION"), rules, + properties: (!provenance.is_empty()).then_some(DriverProperties { + build_inputs: provenance.build_inputs.as_deref(), + build_git: provenance.build_git.as_deref(), + }), }, }, results, @@ -327,6 +392,20 @@ struct Driver<'a> { name: &'a str, version: &'a str, rules: Vec>, + /// Present only when a [`SarifProvenance`] carried something, so the + /// provenance-free writers' output never gains a key. + #[serde(skip_serializing_if = "Option::is_none")] + properties: Option>, +} + +/// The `tool.driver.properties` bag. Keys are namespaced with `bca.` as +/// SARIF recommends for producer-specific properties. +#[derive(Serialize)] +struct DriverProperties<'a> { + #[serde(rename = "bca.buildInputs", skip_serializing_if = "Option::is_none")] + build_inputs: Option<&'a str>, + #[serde(rename = "bca.buildGit", skip_serializing_if = "Option::is_none")] + build_git: Option<&'a str>, } #[derive(Serialize)] @@ -478,6 +557,54 @@ mod tests { assert!(rule["shortDescription"]["text"].is_string()); } + #[test] + fn provenance_lands_under_driver_properties_and_an_empty_one_adds_no_key() { + let offenders = vec![rec("src/foo.rs", "cyclomatic", 17.0, 15.0)]; + let stamped = SarifProvenance::new(Some("ab".repeat(32)), Some("deadbeef-dirty".into())); + let mut buf = Vec::new(); + write_sarif_with_provenance(&offenders, &[], &[], &stamped, &mut buf) + .expect("writing to Vec is infallible"); + let v: serde_json::Value = serde_json::from_slice(&buf).expect("valid JSON"); + let props = &v["runs"][0]["tool"]["driver"]["properties"]; + assert_eq!(props["bca.buildInputs"], "ab".repeat(32)); + assert_eq!(props["bca.buildGit"], "deadbeef-dirty"); + // `toolComponent` admits no unknown direct keys, so the digest + // must live in the bag and nowhere else. + assert!( + v["runs"][0]["tool"]["driver"] + .get("bca.buildInputs") + .is_none() + ); + + // Every older writer forwards with an empty provenance, so its + // document gains no `properties` key — byte-identical output. + let mut plain = Vec::new(); + write_sarif_with_provenance( + &offenders, + &[], + &[], + &SarifProvenance::default(), + &mut plain, + ) + .expect("writing to Vec is infallible"); + assert_eq!(plain, render(&offenders).into_bytes()); + assert!( + !String::from_utf8(plain) + .expect("utf-8") + .contains("properties") + ); + + // Half-populated: only the present field is written. + let mut half = Vec::new(); + let git_only = SarifProvenance::new(None, Some("deadbeef".into())); + write_sarif_with_provenance(&offenders, &[], &[], &git_only, &mut half) + .expect("writing to Vec is infallible"); + let v: serde_json::Value = serde_json::from_slice(&half).expect("valid JSON"); + let props = &v["runs"][0]["tool"]["driver"]["properties"]; + assert_eq!(props["bca.buildGit"], "deadbeef"); + assert!(props.get("bca.buildInputs").is_none()); + } + #[test] fn write_sarif_omits_suppressions_for_active_results() { // The active-only `write_sarif` path must never emit a diff --git a/utils/check-role-coverage-test.py b/utils/check-role-coverage-test.py index 45652df8a..6769b1083 100644 --- a/utils/check-role-coverage-test.py +++ b/utils/check-role-coverage-test.py @@ -174,6 +174,33 @@ class CoverageTests(unittest.TestCase): def setUp(self) -> None: self.t = Tree() + def test_observer_header_keeps_one_line_and_round_trips_through_the_reader(self) -> None: + # Since #1773 `bca --version` is a multi-line provenance block; the + # writer reads `-V` and keeps its one line, so the file it writes is + # one its own reader accepts. Verified by perturbation: the old + # `.strip()` of the whole block makes `load_observed` raise on the + # `build inputs:` line. + self.assertEqual(cov.observer_line("bca 2.4.0\n"), "bca 2.4.0") + self.assertEqual( + cov.observer_line("bca 2.4.0\nbuild inputs: abc\ngit: def\n"), "bca 2.4.0" + ) + with self.assertRaises(rt.RoleTableError): + cov.observer_line("build inputs: abc\n") + with self.assertRaises(rt.RoleTableError): + cov.observer_line("") + with tempfile.TemporaryDirectory() as tmp: + path = pathlib.Path(tmp, "observed.txt") + path.write_text( + f"{cov.OBS_HEADER}observer {cov.observer_line('bca 2.4.0\nbuild inputs: abc\n')}\n", + encoding="utf-8", + ) + cov.load_observed(path) + path.write_text( + f"{cov.OBS_HEADER}observer bca 2.4.0\nbuild inputs: abc\n", encoding="utf-8" + ) + with self.assertRaises(rt.RoleTableError): + cov.load_observed(path) + def test_claimed_kinds_leave_the_residue_and_end_is_synthetic(self) -> None: self.t.table(FULL) code, out = self.t.run("--bootstrap") diff --git a/utils/check-role-coverage.py b/utils/check-role-coverage.py index 9c89330c2..b8170fb20 100755 --- a/utils/check-role-coverage.py +++ b/utils/check-role-coverage.py @@ -316,8 +316,7 @@ def observe( print("error: the observer did not build") return 2 bca = REPO_ROOT / "target" / "release" / "bca" - # `bca --version` prints `bca X.Y.Z`; keep the whole line. - version = subprocess.run([str(bca), "--version"], check=True, **RUN).stdout.strip() + version = observer_line(subprocess.run([str(bca), "-V"], check=True, **RUN).stdout) pins = rt.grammar_pins(cargo_toml) exts = extensions_from_langs(langs_rs) # Provenance is the inputs — observer version, corpus commits, pins — @@ -366,6 +365,24 @@ class Observation: seen: dict[str, set[int]] +def observer_line(version_stdout: str) -> str: + """The one-line `bca X.Y.Z` for the `observer` header, from `bca -V` output. + + `-V` rather than `--version`: since #1773 the long form is a multi-line + provenance block, and `load_observed` reads any line after the first as + an observation and rejects it. Only the first line is kept, and it must + have the short shape, so a build that changes `-V` fails here rather + than writing a file its own reader refuses. + """ + first = version_stdout.strip().splitlines()[0] if version_stdout.strip() else "" + if not OBSERVER_LINE_RE.fullmatch(first): + raise rt.RoleTableError(f"expected `bca ` from `bca -V`, got `{first}`") + return first + + +OBSERVER_LINE_RE = re.compile(r"bca \S+") + + def load_observed(path: pathlib.Path) -> Observation: obs = Observation({}, {}, {}, {}, {}) lang = None diff --git a/utils/self_scan_digest.py b/utils/self_scan_digest.py new file mode 100644 index 000000000..2980a2583 --- /dev/null +++ b/utils/self_scan_digest.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""The build-inputs digest, as `big-code-analysis-cli/src/build_info/digest.rs` defines it. + +`utils/self-scan-bca.py` recomputes the digest over the live tree and +compares it with the `build inputs:` line of an installed `bca --version` +to decide whether that binary implements the checkout (#1773). The two +implementations must therefore agree byte-for-byte; the Rust module's +docs state the algorithm once, and `self-scan-bca-test.py` and the Rust +tests hash one shared fixture to one pinned hex. + +A rule drift here cannot certify a wrong binary — it makes the resolver +fall back to building from source — but it silently gives the fast path +up, so the pinned fixture is the thing that keeps this file honest. +""" + +from __future__ import annotations + +import hashlib +import os +from pathlib import Path + +# Mirrors `INPUT_ROOTS`, `INPUT_EXTENSIONS` and `SKIPPED_TOP_LEVEL` in +# `digest.rs`; the shared fixture test fails if either side moves alone. +INPUT_ROOTS = ( + "Cargo.toml", + "src", + "big-code-analysis-ast", + "big-code-analysis-cli", + "tree-sitter-ccomment", + "tree-sitter-mozcpp", + "tree-sitter-mozjs", + "tree-sitter-preproc", + "tree-sitter-tcl", +) +INPUT_EXTENSIONS = frozenset({"rs", "c", "cc", "h", "toml", "json"}) +SKIPPED_TOP_LEVEL = frozenset({"target", "build", "node_modules"}) + + +class DigestError(Exception): + """The tree cannot be digested: a missing root, a symlink, or a non-UTF-8 name.""" + + +def input_files(workspace: Path) -> list[str]: + """Sorted, `/`-separated, workspace-relative paths of every input file.""" + files: list[str] = [] + for root in INPUT_ROOTS: + path = workspace / root + if path.is_symlink(): + raise DigestError(f"symlink under an input root: {root}") + if path.is_file(): + files.append(root) + elif path.is_dir(): + _collect_dir(workspace, path, root.startswith("tree-sitter-"), files) + else: + raise DigestError(f"input root is absent: {root}") + files.sort(key=lambda s: s.encode("utf-8")) + return files + + +def _collect_dir(workspace: Path, directory: Path, grammar_top: bool, out: list[str]) -> None: + for entry in sorted(os.scandir(directory), key=lambda e: e.name): + path = Path(entry.path) + rel = _relative_posix(workspace, path) + if entry.is_symlink(): + raise DigestError(f"symlink under an input root: {rel}") + if entry.is_dir(follow_symlinks=False): + if grammar_top and entry.name in SKIPPED_TOP_LEVEL: + continue + _collect_dir(workspace, path, False, out) + elif entry.is_file(follow_symlinks=False) and _has_input_extension(entry.name): + out.append(rel) + + +def _has_input_extension(name: str) -> bool: + _, dot, ext = name.rpartition(".") + return bool(dot) and ext in INPUT_EXTENSIONS + + +def _relative_posix(workspace: Path, path: Path) -> str: + rel = path.relative_to(workspace) + try: + return "/".join(part.encode("utf-8", "strict").decode("utf-8") for part in rel.parts) + except UnicodeError as e: + raise DigestError(f"non-UTF-8 path under an input root: {rel!r}") from e + + +def digest(workspace: Path) -> str: + """The build-inputs digest of `workspace` as 64 lowercase hex digits.""" + h = hashlib.sha256() + for rel in input_files(workspace): + content = (workspace / rel).read_bytes() + h.update(rel.encode("utf-8")) + h.update(b"\0") + h.update(len(content).to_bytes(8, "little")) + h.update(content) + return h.hexdigest() From 2d1901b27e8ae244e6cf4fa54e3373ec758bf5b7 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:53:38 -0800 Subject: [PATCH 3/8] perf(self-scan): resolve the gate binary through a digest-checked wrapper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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= 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 --- .github/workflows/ci.yml | 2 + .pre-commit-config.yaml | 6 + AGENTS.md | 33 ++- CHANGELOG.md | 10 +- Makefile | 100 ++++---- bca.toml | 4 +- big-code-analysis-book/src/recipes/ci.md | 6 +- utils/self-scan-bca-test.py | 288 +++++++++++++++++++++++ utils/self-scan-bca.py | 155 ++++++++++++ 9 files changed, 542 insertions(+), 62 deletions(-) create mode 100644 utils/self-scan-bca-test.py create mode 100755 utils/self-scan-bca.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0f99f36ec..a126d1db7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -856,6 +856,8 @@ jobs: run: python3 -B -m unittest -q utils/perturb-test.py - name: coverage-diff self-tests (explicit) run: python3 -B -m unittest -q utils/coverage-diff-test.py + - name: self-scan-bca self-tests (explicit) + run: python3 -B -m unittest -q utils/self-scan-bca-test.py # Defensive twin to the snapshot-anchors gate above: `make lint` # already invokes check-versions, but pinning it here guarantees # the lockstep version invariant is enforced even if a future diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 595d6bbfe..eee1ad296 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -194,6 +194,12 @@ repos: files: '^utils/coverage-diff(-test)?\.py$' entry: python3 -B -m unittest -q utils/coverage-diff-test.py pass_filenames: false + - id: self-scan-bca-test + name: self-scan-bca-test + language: system + files: '^utils/(self-scan-bca(-test)?|self_scan_digest)\.py$' + entry: python3 -B -m unittest -q utils/self-scan-bca-test.py + pass_filenames: false - id: role-coverage name: role-coverage language: system diff --git a/AGENTS.md b/AGENTS.md index 53d930b90..f84e1ed2e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -115,7 +115,15 @@ and `cargo run -p big-code-analysis-web --`. the enum owns. Each has a `*-test.py` in `make pre-commit` that stubs the binaries it drives (`coverage-diff-test.py` runs real `git` on a scratch repository), which is the only thing that lints - them (#1477). + them (#1477). `self-scan-bca.py` is what every `make self-scan*` + recipe runs instead of `cargo run`: it picks the `bca` to execute — + an explicit `BCA_SELF_SCAN_BINARY`, a PATH `bca` whose `--version` + reports a `build inputs:` digest equal to the one + `self_scan_digest.py` recomputes over the checkout, or a dev-profile + `cargo run` — and `exec`s it (#1773). The digest module mirrors + `big-code-analysis-cli/src/build_info/digest.rs`; one fixture and one + pinned hex in `self-scan-bca-test.py` and the Rust tests hold the two + together. - Other helper scripts: `recreate-grammars.sh`, `generate-grammars/`. (The grammar-bump diff step now uses the native `bca diff`; the former `split-minimal-tests.py` + external `json-minimal-tests` chain was @@ -532,13 +540,22 @@ self-scan-profile-parity` is the per-PR check that the two profiles write a byte-identical baseline, and the reason the default is safe. `BCA_SELF_SCAN_BINARY=` skips the build and runs a prebuilt binary, trusted as given: sound for a batch no commit of which touches -those compiled-in roots or `Cargo.toml` / `Cargo.lock` (the manifest, -`.bcaignore` and the baseline are read at run time, so any binary sees -the live copies), and wrong without a warning otherwise. CI sets it to -the release binary it has just installed from HEAD. `make -self-scan-baseline-fresh` answers the question the quarterly job asks -— does the committed file still describe the tree — in a few seconds -locally. +those compiled-in roots or `Cargo.toml` (the manifest, `.bcaignore` +and the baseline are read at run time, so any binary sees the live +copies), and wrong without a warning otherwise. CI sets it to the +release binary it has just installed from HEAD. A `bca` on PATH needs +no such care: `utils/self-scan-bca.py` uses it only when the `build +inputs:` digest its `--version` reports equals the digest of the +checkout's compiled-in sources, recomputed each run — which is to say +only when it was built from these exact bytes — and otherwise builds. +That proof is what an mtime cannot give (a binary installed from a +newer `main` reads as fresh in an older worktree), and it costs ~0.2 s. +It also bounds what the route can save: a tree whose inputs match an +installed binary is one cargo already finds fresh in ~0.1 s, so the +PATH route matters for the forensic trail and for CI's one-build +guarantee more than for the clock. `make self-scan-baseline-fresh` +answers the question the quarterly job asks — does the committed file +still describe the tree — in a few seconds locally. **Price a candidate limit at both tiers before calling it free.** Converging a limit onto a cluster of existing values is never free while diff --git a/CHANGELOG.md b/CHANGELOG.md index 99761af05..74ce857f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -198,7 +198,15 @@ for historical reference. (dev and release regenerations `cmp` equal; `pages.yml` runs it per PR, which is what makes the dev default safe). `.bcaignore` joins `pages.yml`'s path filters, so an edit to the walk deny-set re-runs - the gate. Repository tooling only; no published API moves. + the gate. The recipes run `utils/self-scan-bca.py`, which also + picks up a `bca` on PATH on its own — but only after comparing the + `build inputs:` digest that binary's `--version` reports with a + fresh digest of the checkout, so a binary installed from another + commit can never measure this tree by mistake; a `bca` from before + the field existed, or from crates.io, simply falls through to the + build. `BCA_SELF_SCAN_FROM_SOURCE=1` forces the build whatever else + is set, which is how the parity target keeps its two legs honest. + Repository tooling only; no published API moves. - **The `loc` declaration gates, the JS-family binding gate and the Python cognitive boolean-operator questions no longer climb to the root from every node** (#1767). Each asks a node's ancestors a diff --git a/Makefile b/Makefile index 7c10f9328..44a1e6b7b 100644 --- a/Makefile +++ b/Makefile @@ -88,7 +88,7 @@ find-by-ext = $(if $(FD),$(FD) --extension $(1) $(FD_EXCLUDE) $(2),find . -name NEXTEST := $(shell command -v cargo-nextest 2>/dev/null) TEST_CMD = $(if $(NEXTEST),$(NEXTEST) nextest run --workspace --all-features,cargo test --workspace --all-features --lib --bins --tests) -.PHONY: role-census role-census-test role-coverage role-coverage-test role-coverage-observe role-bypass role-bypass-test mutation-report-test mutation-workflow-test drift-common-test drift-oracle-test drift-compare-test recovery-oracle-test perturb-test coverage-diff-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test help check-tools worktree-setup worktree-setup-test build build-release check test test-doc chain-audit fmt fmt-check markdown-fmt markdown-lint shellcheck sh-fmt sh-fmt-check toml-fmt toml-fmt-check toml-lint makefile-check actionlint snapshot-anchors snapshot-anchors-test rustfmt-bail rustfmt-bail-test grammar-marker-sync grammar-marker-sync-test check-versions check-excluded-manifests check-excluded-manifests-test check-ruff-lockstep check-ruff-lockstep-test check-publish-metadata check-publish-metadata-test check-manpage-assets check-manpage-drift-test check-diagnostic-prefix check-diagnostic-prefix-test check-feature-gates check-feature-gates-test check-test-lang-gates check-test-lang-gates-compare check-test-lang-gates-test check-safety-doc-pin check-safety-doc-pin-test gate-status-test check-tools-test enums-check enums-codegen-drift enums-codegen-drift-test self-scan self-scan-headroom self-scan-write-baseline self-scan-write-baseline-headroom self-scan-baseline-fresh self-scan-profile-parity vcs lint clippy udeps insta-review insta-accept clean distclean install install-cli install-web doc doc-open doc-check doc-check-docsrs book book-serve book-pot book-po-update book-ja book-deploy all pre-commit ci release-check verify-changelog pkg-deb-local pkg-rpm-local dev-env-build dev-env-run dev-env-shell dev-env-rm py-bootstrap py-sync py-relock py-clean py-fmt py-fmt-check py-lint py-typecheck py-test py-stubtest smoke smoke-cli smoke-lib bench bench-scaling bench-walk fuzz-check fuzz-smoke fuzz-replay fuzz-run fuzz-tmin _check-find _pc-all _pc-fmt _pc-clippy _pc-test _pc-doc-check _pc-udeps _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test _pc-self-scan _pc-self-scan-headroom _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest _ci-all _ci-fmt-check _ci-clippy _ci-test _ci-doc-check _ci-build _ci-udeps _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test _ci-enums-codegen-drift-test _ci-self-scan _ci-self-scan-headroom _ci-cargo-pipeline _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest +.PHONY: role-census role-census-test role-coverage role-coverage-test role-coverage-observe role-bypass role-bypass-test mutation-report-test mutation-workflow-test drift-common-test drift-oracle-test drift-compare-test recovery-oracle-test perturb-test coverage-diff-test self-scan-bca-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test help check-tools worktree-setup worktree-setup-test build build-release check test test-doc chain-audit fmt fmt-check markdown-fmt markdown-lint shellcheck sh-fmt sh-fmt-check toml-fmt toml-fmt-check toml-lint makefile-check actionlint snapshot-anchors snapshot-anchors-test rustfmt-bail rustfmt-bail-test grammar-marker-sync grammar-marker-sync-test check-versions check-excluded-manifests check-excluded-manifests-test check-ruff-lockstep check-ruff-lockstep-test check-publish-metadata check-publish-metadata-test check-manpage-assets check-manpage-drift-test check-diagnostic-prefix check-diagnostic-prefix-test check-feature-gates check-feature-gates-test check-test-lang-gates check-test-lang-gates-compare check-test-lang-gates-test check-safety-doc-pin check-safety-doc-pin-test gate-status-test check-tools-test enums-check enums-codegen-drift enums-codegen-drift-test self-scan self-scan-headroom self-scan-write-baseline self-scan-write-baseline-headroom self-scan-baseline-fresh self-scan-profile-parity vcs lint clippy udeps insta-review insta-accept clean distclean install install-cli install-web doc doc-open doc-check doc-check-docsrs book book-serve book-pot book-po-update book-ja book-deploy all pre-commit ci release-check verify-changelog pkg-deb-local pkg-rpm-local dev-env-build dev-env-run dev-env-shell dev-env-rm py-bootstrap py-sync py-relock py-clean py-fmt py-fmt-check py-lint py-typecheck py-test py-stubtest smoke smoke-cli smoke-lib bench bench-scaling bench-walk fuzz-check fuzz-smoke fuzz-replay fuzz-run fuzz-tmin _check-find _pc-all _pc-fmt _pc-clippy _pc-test _pc-doc-check _pc-udeps _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test _pc-self-scan _pc-self-scan-headroom _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest _ci-all _ci-fmt-check _ci-clippy _ci-test _ci-doc-check _ci-build _ci-udeps _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test _ci-enums-codegen-drift-test _ci-self-scan _ci-self-scan-headroom _ci-cargo-pipeline _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest .PHONY: plugin-test _pc-plugin-test _ci-plugin-test @@ -144,6 +144,7 @@ help: @echo " recovery-oracle-test Self-tests for the recovery-tree drift sweep (utils/recovery-oracle.py)" @echo " perturb-test Self-tests for the perturbation sweep driver (utils/perturb.py)" @echo " coverage-diff-test Self-tests for the two-report patch-coverage driver (utils/coverage-diff.py)" + @echo " self-scan-bca-test Self-tests for the self-scan binary resolver (utils/self-scan-bca.py)" @echo " role-coverage Every runtime kind id claimed, excluded or baselined (#1692)" @echo " role-coverage-test Self-tests for the role-coverage gate" @echo " role-coverage-observe Record which kinds the integration corpus emits (slow; builds bca)" @@ -551,6 +552,10 @@ coverage-diff-test: @echo "Running coverage-diff self-tests..." @(cd $(BASE_DIR) && python3 -B -m unittest -q utils/coverage-diff-test.py) +self-scan-bca-test: + @echo "Running self-scan-bca self-tests..." + @(cd $(BASE_DIR) && python3 -B -m unittest -q utils/self-scan-bca-test.py) + role-coverage: @echo "Checking role kind coverage..." @python3 $(BASE_DIR)utils/check-role-coverage.py --require-observations @@ -890,30 +895,28 @@ enums-check: # any in-progress change to metric computation is reflected in the # values we gate on. # -# Which binary runs is decided by two knobs (#1773): -# -# BCA_SELF_SCAN_BINARY An explicit, trusted `bca` executable. Set, -# nothing is built: CI sets it to the release -# binary it has just `cargo install`ed from -# HEAD, so the gate and the published reports -# come from one build. Locally it is sound only -# when no commit in the work at hand touches -# `src/`, `big-code-analysis-ast/`, -# `big-code-analysis-cli/`, `tree-sitter-*/`, -# `Cargo.toml` or `Cargo.lock` — the inputs -# compiled into the binary; everything else -# (`bca.toml`, `.bcaignore`, the baseline) is -# read at run time, so a prebuilt binary sees -# the live copy. -# BCA_SELF_SCAN_PROFILE `dev` (default) or `release`. The profile -# `cargo run` builds under when no binary is -# given. `release` is what CI installs, but its -# `lto = true` / `codegen-units = 1` relink -# costs ~100 s after any `src/` edit; the dev -# profile is ~5 s for the same edit and 0.1 s -# when nothing changed, and both profiles write -# a byte-identical baseline — which -# `self-scan-profile-parity` below keeps true. +# Which binary runs is `utils/self-scan-bca.py`'s decision (#1773). In +# order: `BCA_SELF_SCAN_FROM_SOURCE=1` builds from the tree whatever +# else is set; `BCA_SELF_SCAN_BINARY=` runs that executable, +# trusted as given (CI sets it to the release binary it has just +# `cargo install`ed from HEAD, so the gate and the published reports +# come from one build); a `bca` on PATH is used when the `build inputs:` +# digest its `--version` reports equals the digest of this checkout's +# compiled-in sources, recomputed by the wrapper — equal means it was +# built from these exact bytes, whatever its mtime or branch; otherwise +# `cargo run` under `BCA_SELF_SCAN_PROFILE` (`dev` by default, or +# `release`). `release` is what CI installs, but its `lto = true` / +# `codegen-units = 1` relink costs ~100 s after any `src/` edit; the +# dev profile is ~5 s for the same edit and 0.1 s when nothing changed, +# and both profiles write a byte-identical baseline — which +# `self-scan-profile-parity` below keeps true. +# +# A trusted `BCA_SELF_SCAN_BINARY` is sound only when nothing compiled +# into it has changed: `src/`, `big-code-analysis-ast/`, +# `big-code-analysis-cli/`, `tree-sitter-*/`, `Cargo.toml`. Everything +# else (`bca.toml`, `.bcaignore`, the baseline) is read at run time, so +# any binary sees the live copy. The PATH route needs no such care; it +# proves the match before it uses the binary. # # Path selection (`paths = ["."]`), the ignore file # (`exclude_from = ".bcaignore"`), the baseline @@ -956,20 +959,11 @@ enums-check: # above; ~100 s because of the release # build. pages.yml runs it per PR. # --------------------------------------------------------------------------- -# Default to empty so `$(if …)` below does not trip -# `--warn-undefined-variables`; `?=` lets the environment override. -BCA_SELF_SCAN_BINARY ?= -BCA_SELF_SCAN_PROFILE ?= dev -ifneq ($(filter-out dev release,$(BCA_SELF_SCAN_PROFILE)),) -$(error BCA_SELF_SCAN_PROFILE must be `dev` or `release`, not `$(BCA_SELF_SCAN_PROFILE)`) -endif -SELF_SCAN_PROFILE_FLAG := $(if $(filter release,$(BCA_SELF_SCAN_PROFILE)),--release ,) -# Quoted so a binary path with spaces survives the recipe shell; the -# `cargo run` form is deliberately unquoted so bash splits it into words. -SELF_SCAN_BCA := $(if $(BCA_SELF_SCAN_BINARY),"$(BCA_SELF_SCAN_BINARY)",cargo run --quiet $(SELF_SCAN_PROFILE_FLAG)-p big-code-analysis-cli --) -# One line on stderr per recipe naming the binary, so a captured gate -# log says what measured the tree. -SELF_SCAN_NOTE := $(if $(BCA_SELF_SCAN_BINARY),bca self-scan via $(BCA_SELF_SCAN_BINARY),bca self-scan via cargo run ($(BCA_SELF_SCAN_PROFILE) profile)) +# The wrapper reads the `BCA_SELF_SCAN_*` knobs from the environment +# itself, prints one `bca: self-scan via …` line on stderr naming what +# it chose and why — so a captured gate log says what measured the tree +# — and `exec`s the choice, so a recipe's exit status is bca's own. +SELF_SCAN_BCA := $(BASE_DIR)utils/self-scan-bca.py # `--jobs` defaults to `auto` (effective CPU count, cgroup-/cpuset- # aware on Linux via Rust's std lib), so no `$(nproc)` plumbing is # needed for the self-scan recipes (issue #383). @@ -1007,18 +1001,15 @@ SELF_SCAN_SINCE_ARGS := $(if $(BCA_SINCE),--since $(BCA_SINCE),) self-scan: @echo "bca self-scan (hard gate)..." - @echo "$(SELF_SCAN_NOTE)" >&2 @$(SELF_SCAN_BCA) check $(SELF_SCAN_SINCE_ARGS) self-scan-headroom: @echo "bca self-scan (soft gate, BCA_HEADROOM=$${BCA_HEADROOM:-0.95})..." - @echo "$(SELF_SCAN_NOTE)" >&2 @$(SELF_SCAN_BCA) check $(SELF_SCAN_SINCE_ARGS) \ --tier=soft=$${BCA_HEADROOM:-0.95} self-scan-write-baseline: @echo "Refreshing .bca-baseline.toml from current offenders..." - @echo "$(SELF_SCAN_NOTE)" >&2 @$(SELF_SCAN_BCA) check --write-baseline # Refresh `.bca-baseline.toml` against the SOFT thresholds @@ -1029,7 +1020,6 @@ self-scan-write-baseline: # the new headroom band rather than firing on every commit. self-scan-write-baseline-headroom: @echo "Refreshing .bca-baseline.toml from current soft-tier offenders (BCA_HEADROOM=$${BCA_HEADROOM:-0.95})..." - @echo "$(SELF_SCAN_NOTE)" >&2 @$(SELF_SCAN_BCA) check \ --tier=soft=$${BCA_HEADROOM:-0.95} \ --write-baseline @@ -1047,7 +1037,6 @@ self-scan-write-baseline-headroom: # one line per shell here (no `.ONESHELL`). self-scan-baseline-fresh: @echo "bca self-scan baseline freshness (BCA_HEADROOM=$${BCA_HEADROOM:-0.95})..." - @echo "$(SELF_SCAN_NOTE)" >&2 @cd "$(BASE_DIR)" && t=$$(mktemp ".bca-baseline.XXXXXX.toml") && trap 'rm -f "$$t"' EXIT \ && $(SELF_SCAN_BCA) check --tier=soft=$${BCA_HEADROOM:-0.95} --write-baseline "$$t" \ && $(SELF_SCAN_BCA) diff-baseline .bca-baseline.toml "$$t" --exit-code @@ -1057,13 +1046,15 @@ self-scan-baseline-fresh: # `overflow-checks` are the only semantic differences between the # profiles, and either firing would be a bug the release gate hides. # On a mismatch both files are kept and named so they can be diffed. -# `BCA_SELF_SCAN_BINARY` is ignored here on purpose — the point is to -# compare two from-source builds, not whatever is installed. +# Both legs force a from-source build through the wrapper +# (`BCA_SELF_SCAN_FROM_SOURCE=1` outranks every other knob), so an +# inherited `BCA_SELF_SCAN_BINARY` or a matching PATH `bca` cannot turn +# this into a comparison of one binary with itself. self-scan-profile-parity: @echo "bca self-scan profile parity (dev vs release, BCA_HEADROOM=$${BCA_HEADROOM:-0.95})..." @cd "$(BASE_DIR)" && d=$$(mktemp ".bca-baseline.dev.XXXXXX.toml") && r=$$(mktemp ".bca-baseline.release.XXXXXX.toml") \ - && cargo run --quiet -p big-code-analysis-cli -- check --tier=soft=$${BCA_HEADROOM:-0.95} --write-baseline "$$d" \ - && cargo run --quiet --release -p big-code-analysis-cli -- check --tier=soft=$${BCA_HEADROOM:-0.95} --write-baseline "$$r" \ + && BCA_SELF_SCAN_FROM_SOURCE=1 BCA_SELF_SCAN_PROFILE=dev $(SELF_SCAN_BCA) check --tier=soft=$${BCA_HEADROOM:-0.95} --write-baseline "$$d" \ + && BCA_SELF_SCAN_FROM_SOURCE=1 BCA_SELF_SCAN_PROFILE=release $(SELF_SCAN_BCA) check --tier=soft=$${BCA_HEADROOM:-0.95} --write-baseline "$$r" \ && if cmp -s "$$d" "$$r"; then rm -f "$$d" "$$r"; echo "profile parity: dev and release baselines are byte-identical"; \ else echo "profile parity: dev and release baselines differ; kept $$d and $$r" >&2; exit 1; fi @@ -1642,7 +1633,7 @@ lint: $(MAKE) -j --output-sync=target \ _ci-clippy _ci-plugin-test \ _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check \ - _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test + _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test # --------------------------------------------------------------------------- # Maintenance @@ -1829,7 +1820,7 @@ _pc-all: $(MAKE) -j --output-sync=target \ _pc-test _pc-plugin-test \ _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check \ - _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test \ + _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test \ _pc-manpages \ _pc-self-scan _pc-self-scan-headroom \ _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest @@ -1839,7 +1830,7 @@ _ci-all: $(MAKE) -j --output-sync=target \ _ci-cargo-pipeline _ci-plugin-test \ _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check \ - _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test \ + _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test \ _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest # --------------------------------------------------------------------------- @@ -1881,6 +1872,7 @@ _ci-all: # ├── _pc-recovery-oracle-test # ├── _pc-perturb-test # ├── _pc-coverage-diff-test +# ├── _pc-self-scan-bca-test # ├── _pc-role-coverage # ├── _pc-role-coverage-test # ├── _pc-role-bypass @@ -2015,6 +2007,9 @@ _pc-perturb-test: _pc-fmt _pc-coverage-diff-test: _pc-fmt $(MAKE) coverage-diff-test +_pc-self-scan-bca-test: _pc-fmt + $(MAKE) self-scan-bca-test + _pc-role-coverage: _pc-fmt $(MAKE) role-coverage @@ -2274,6 +2269,9 @@ _ci-perturb-test: _ci-coverage-diff-test: $(MAKE) coverage-diff-test +_ci-self-scan-bca-test: + $(MAKE) self-scan-bca-test + _ci-role-coverage: $(MAKE) role-coverage diff --git a/bca.toml b/bca.toml index bff2ac10e..28ad9d60a 100644 --- a/bca.toml +++ b/bca.toml @@ -12,7 +12,9 @@ # under the dev profile by default, since the release relink costs # ~100 s per edit and both profiles write the same baseline (#1773); # CI hands the recipes its freshly installed release binary instead. -# The knobs are documented at `SELF_SCAN_BCA` in the Makefile. +# A `bca` on PATH is used instead when its `--version` reports a +# build-inputs digest equal to this checkout's. The knobs are documented +# at `SELF_SCAN_BCA` in the Makefile and in `utils/self-scan-bca.py`. # Scan the whole repo, honouring the ignore file. The walker re-anchors # the resolved seed to the `./`-prefixed form (#488), so the diff --git a/big-code-analysis-book/src/recipes/ci.md b/big-code-analysis-book/src/recipes/ci.md index 032926ee3..afdc180e9 100644 --- a/big-code-analysis-book/src/recipes/ci.md +++ b/big-code-analysis-book/src/recipes/ci.md @@ -661,7 +661,11 @@ wanted; `make self-scan-profile-parity` checks per PR that the two profiles write a byte-identical baseline. `BCA_SELF_SCAN_BINARY=` runs a prebuilt binary instead of building at all — what CI does with the release binary it installs from the checkout — and is sound only -when nothing compiled into that binary has changed since. +when nothing compiled into that binary has changed since. A `bca` on +PATH is used without being told to, but only after the recipe's +wrapper (`utils/self-scan-bca.py`) has compared the `build inputs:` +digest its `--version` reports with a fresh digest of the checkout's +compiled-in sources: equal means it was built from these bytes. Both tiers consume the same `bca.toml` thresholds and the same `.bca-baseline.toml`; the soft tier runs the hard recipe with every diff --git a/utils/self-scan-bca-test.py b/utils/self-scan-bca-test.py new file mode 100644 index 000000000..c32a39b08 --- /dev/null +++ b/utils/self-scan-bca-test.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +"""Self-tests for `utils/self-scan-bca.py` and `utils/self_scan_digest.py` (#1773). + +Run with `python3 -B -m unittest -q utils/self-scan-bca-test.py`. + +Two subjects. The digest module is held to the Rust implementation by +one shared fixture and one pinned hex, repeated byte-for-byte from +`big-code-analysis-cli/src/build_info/build_info_tests.rs`; change the +walker on either side and exactly that pair fails. The resolver is +exercised two ways: in dry-run for the *selection* (which command, and +why), and launched for real — with a fake `bca` on a controlled PATH that +records its argv and pid — for the claims dry-run cannot make: that the +user's arguments reach the binary, that its exit status is the wrapper's, +and that on POSIX the wrapper `exec`s rather than forks. + +Every selection case was verified by perturbation while being written +(the driver is recorded on #1773): a resolver that skips the digest +comparison, or trusts any digest, fails `..._falls_back_on_a_mismatch`; +one that reads the variables in the other order fails +`..._from_source_wins_over_an_explicit_binary`; one that forks instead +of `exec`ing fails the pid assertion in `..._launched_binary_...`; and +one that drops the user's arguments fails eight of eleven. +""" + +from __future__ import annotations + +import pathlib +import shutil +import subprocess +import sys +import tempfile +import unittest + +UTILS_DIR = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(UTILS_DIR)) + +import self_scan_digest as digest # noqa: E402 + +WRAPPER = UTILS_DIR / "self-scan-bca.py" + +# Byte-for-byte the fixture `build_info_tests.rs::shared_fixture` writes, +# and the hex it pins as `SHARED_FIXTURE_DIGEST`. +SHARED_FIXTURE = { + "Cargo.toml": b"[workspace]\n", + "src/lib.rs": b"fn a() {}\n", + "src/nested/b.rs": b"fn b() {\0}\n", + "src/empty.rs": b"", + "src/snapshots/x.snap": b"ignored\n", + "src/build/generated.rs": b"// nested build dir is hashed\n", + "big-code-analysis-ast/Cargo.toml": b"[package]\n", + "big-code-analysis-cli/Cargo.toml": b"[package]\n", + "big-code-analysis-cli/build.rs": b"fn main() {}\n", + "tree-sitter-ccomment/src/parser.c": b"int p;\n", + "tree-sitter-ccomment/target/junk.rs": b"skipped\n", + "tree-sitter-mozcpp/src/tree_sitter/parser.h": b"#define X\n", + "tree-sitter-mozjs/src/scanner.c": b"int s;\n", + "tree-sitter-preproc/src/node-types.json": b"[]\n", + "tree-sitter-tcl/src/grammar.json": b"{}\n", +} +SHARED_FIXTURE_DIGEST = "564b792dc7b3e4fca571038d165a8d89ca9069bccc956ea4af0413c572345299" +SHARED_FIXTURE_FILES = [ + "Cargo.toml", + "big-code-analysis-ast/Cargo.toml", + "big-code-analysis-cli/Cargo.toml", + "big-code-analysis-cli/build.rs", + "src/build/generated.rs", + "src/empty.rs", + "src/lib.rs", + "src/nested/b.rs", + "tree-sitter-ccomment/src/parser.c", + "tree-sitter-mozcpp/src/tree_sitter/parser.h", + "tree-sitter-mozjs/src/scanner.c", + "tree-sitter-preproc/src/node-types.json", + "tree-sitter-tcl/src/grammar.json", +] + + +def write_fixture(root: pathlib.Path, files: dict[str, bytes] = SHARED_FIXTURE) -> None: + for rel, content in files.items(): + path = root / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + + +class DigestTests(unittest.TestCase): + def test_shared_fixture_hashes_to_the_pinned_digest(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + write_fixture(root) + self.assertEqual(digest.input_files(root), SHARED_FIXTURE_FILES) + self.assertEqual(digest.digest(root), SHARED_FIXTURE_DIGEST) + + def test_digest_moves_on_content_add_and_rename_but_not_on_snapshots_or_artifacts(self) -> None: + def with_extra(rel: str, content: bytes) -> str: + with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + write_fixture(root) + write_fixture(root, {rel: content}) + return digest.digest(root) + + self.assertNotEqual(with_extra("src/lib.rs", b"fn a() { }\n"), SHARED_FIXTURE_DIGEST) + self.assertNotEqual(with_extra("src/added.rs", b""), SHARED_FIXTURE_DIGEST) + self.assertNotEqual(with_extra("src/lib2.rs", b"fn a() {}\n"), SHARED_FIXTURE_DIGEST) + self.assertEqual(with_extra("src/snapshots/y.snap", b"more"), SHARED_FIXTURE_DIGEST) + self.assertEqual(with_extra("tree-sitter-tcl/target/out.rs", b"x"), SHARED_FIXTURE_DIGEST) + + def test_a_missing_root_or_a_symlink_refuses_the_tree(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + write_fixture(root) + (root / "src/link.rs").symlink_to("lib.rs") + with self.assertRaises(digest.DigestError): + digest.digest(root) + (root / "src/link.rs").unlink() + shutil.rmtree(root / "tree-sitter-tcl") + with self.assertRaises(digest.DigestError): + digest.digest(root) + + +class ResolverHarness(unittest.TestCase): + """A scratch workspace, a controlled PATH, and a fake `bca`.""" + + def setUp(self) -> None: + self.tmp = tempfile.TemporaryDirectory() + self.root = pathlib.Path(self.tmp.name) + self.workspace = self.root / "ws" + self.workspace.mkdir() + write_fixture(self.workspace) + self.bin = self.root / "bin" + self.bin.mkdir() + self.record = self.root / "record.txt" + + def tearDown(self) -> None: + self.tmp.cleanup() + + def fake_bca(self, inputs: str | None, exit_code: int = 0, name: str = "bca") -> pathlib.Path: + """A `bca` whose `--version` reports `inputs` and which records its argv and pid.""" + version = ( + "bca 9.9.9\n" + ("" if inputs is None else f"build inputs: {inputs}\n") + "git: x\n" + ) + script = ( + "#!/bin/sh\n" + 'if [ "$1" = "--version" ]; then\n' + f" printf '%s' '{version}'\n" + " exit 0\n" + "fi\n" + f'printf "%s\\n" "$$" "$@" > "{self.record}"\n' + f"exit {exit_code}\n" + ) + path = self.bin / name + path.write_text(script) + path.chmod(0o755) + return path + + def run_wrapper( + self, *args: str, env: dict[str, str] | None = None, dry_run: bool = True + ) -> subprocess.CompletedProcess[str]: + full_env = { + "PATH": str(self.bin), + "HOME": self.tmp.name, + "BCA_SELF_SCAN_WORKSPACE": str(self.workspace), + } + if dry_run: + full_env["BCA_SELF_SCAN_DRY_RUN"] = "1" + full_env.update(env or {}) + return subprocess.run( + [sys.executable, "-B", str(WRAPPER), *args], + capture_output=True, + text=True, + env=full_env, + check=False, + cwd=self.root, + ) + + def chosen(self, result: subprocess.CompletedProcess[str]) -> list[str]: + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout.splitlines() + + +@unittest.skipIf(sys.platform == "win32", "the fake bca is a POSIX shell script") +class ResolverTests(ResolverHarness): + CARGO_DEV = ["cargo", "run", "--quiet", "-p", "big-code-analysis-cli", "--"] + CARGO_RELEASE = ["cargo", "run", "--quiet", "--release", "-p", "big-code-analysis-cli", "--"] + + def test_no_bca_on_path_builds_from_source_under_the_dev_profile(self) -> None: + result = self.run_wrapper("check", "--tier=soft=0.95") + self.assertEqual(self.chosen(result), [*self.CARGO_DEV, "check", "--tier=soft=0.95"]) + self.assertIn("no bca on PATH", result.stderr) + + def test_release_profile_adds_the_flag_and_a_typo_is_an_error(self) -> None: + result = self.run_wrapper("check", env={"BCA_SELF_SCAN_PROFILE": "release"}) + self.assertEqual(self.chosen(result), [*self.CARGO_RELEASE, "check"]) + bad = self.run_wrapper("check", env={"BCA_SELF_SCAN_PROFILE": "relese"}) + self.assertNotEqual(bad.returncode, 0) + self.assertIn("BCA_SELF_SCAN_PROFILE", bad.stderr) + # An empty value reads as unset, not as a bad profile. + empty = self.run_wrapper("check", env={"BCA_SELF_SCAN_PROFILE": ""}) + self.assertEqual(self.chosen(empty), [*self.CARGO_DEV, "check"]) + + def test_path_bca_is_used_when_its_digest_matches(self) -> None: + bca = self.fake_bca(SHARED_FIXTURE_DIGEST) + result = self.run_wrapper("check") + self.assertEqual(self.chosen(result), [str(bca), "check"]) + self.assertIn("build inputs match this tree", result.stderr) + + def test_path_bca_falls_back_on_a_mismatch_a_missing_line_or_a_registry_build(self) -> None: + self.fake_bca("0" * 64) + result = self.run_wrapper("check") + self.assertEqual(self.chosen(result), [*self.CARGO_DEV, "check"]) + self.assertIn("built from other inputs", result.stderr) + + self.fake_bca(None) + result = self.run_wrapper("check") + self.assertEqual(self.chosen(result), [*self.CARGO_DEV, "check"]) + self.assertIn("reports no build-inputs digest", result.stderr) + + self.fake_bca("unavailable") + result = self.run_wrapper("check") + self.assertEqual(self.chosen(result), [*self.CARGO_DEV, "check"]) + + # A matching binary stops matching the moment an input moves. + self.fake_bca(SHARED_FIXTURE_DIGEST) + (self.workspace / "src/lib.rs").write_bytes(b"fn a() { }\n") + result = self.run_wrapper("check") + self.assertEqual(self.chosen(result), [*self.CARGO_DEV, "check"]) + + def test_explicit_binary_is_trusted_and_a_relative_path_is_anchored_to_the_caller(self) -> None: + other = self.fake_bca("0" * 64, name="other-bca") + result = self.run_wrapper("check", env={"BCA_SELF_SCAN_BINARY": str(other)}) + self.assertEqual(self.chosen(result), [str(other), "check"]) + relative = self.run_wrapper("check", env={"BCA_SELF_SCAN_BINARY": "bin/other-bca"}) + self.assertEqual(self.chosen(relative), [str(other.resolve()), "check"]) + bare = self.run_wrapper("check", env={"BCA_SELF_SCAN_BINARY": "other-bca"}) + self.assertEqual(self.chosen(bare), ["other-bca", "check"]) + empty = self.run_wrapper("check", env={"BCA_SELF_SCAN_BINARY": ""}) + self.assertEqual(self.chosen(empty), [*self.CARGO_DEV, "check"]) + + def test_from_source_wins_over_an_explicit_binary_and_a_matching_path_bca(self) -> None: + bca = self.fake_bca(SHARED_FIXTURE_DIGEST) + result = self.run_wrapper( + "check", env={"BCA_SELF_SCAN_FROM_SOURCE": "1", "BCA_SELF_SCAN_BINARY": str(bca)} + ) + self.assertEqual(self.chosen(result), [*self.CARGO_DEV, "check"]) + self.assertIn("BCA_SELF_SCAN_FROM_SOURCE", result.stderr) + + def test_a_tree_that_cannot_be_digested_falls_back(self) -> None: + self.fake_bca(SHARED_FIXTURE_DIGEST) + (self.workspace / "src/link.rs").symlink_to("lib.rs") + result = self.run_wrapper("check") + self.assertEqual(self.chosen(result), [*self.CARGO_DEV, "check"]) + self.assertIn("cannot be digested", result.stderr) + + def test_launched_binary_receives_the_arguments_and_its_status_and_pid_are_the_wrappers( + self, + ) -> None: + self.fake_bca(SHARED_FIXTURE_DIGEST, exit_code=3) + proc = subprocess.Popen( + [ + sys.executable, + "-B", + str(WRAPPER), + "check", + "--tier=soft=0.95", + "--write-baseline", + "x y.toml", + ], + env={ + "PATH": str(self.bin), + "HOME": self.tmp.name, + "BCA_SELF_SCAN_WORKSPACE": str(self.workspace), + }, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + cwd=self.root, + ) + _, stderr = proc.communicate(timeout=60) + self.assertEqual(proc.returncode, 3, stderr) + recorded = self.record.read_text().splitlines() + # `exec` keeps the pid: the fake's `$$` is the process we spawned. + self.assertEqual(int(recorded[0]), proc.pid) + self.assertEqual( + recorded[1:], ["check", "--tier=soft=0.95", "--write-baseline", "x y.toml"] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/self-scan-bca.py b/utils/self-scan-bca.py new file mode 100755 index 000000000..461940b48 --- /dev/null +++ b/utils/self-scan-bca.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Run `bca` for the self-scan recipes, choosing which one (#1773). + + utils/self-scan-bca.py check --tier=soft=0.95 --write-baseline + +Resolution, first match wins: + +1. `BCA_SELF_SCAN_FROM_SOURCE=1` — build from the tree (step 3), whatever + else is set. The override for a parity check that must compare two + from-source builds. +2. `BCA_SELF_SCAN_BINARY=` — run that executable, trusted as given. + CI sets it to the release binary it has just installed from HEAD. +3. A `bca` on PATH whose `--version` reports a `build inputs:` digest + equal to the digest of this checkout's inputs, recomputed here with + `self_scan_digest.py`. Equal means the binary was compiled from these + exact bytes — committed or not, whatever its mtime or branch — so it + is used in place of a build. A missing line (a `bca` from before the + field existed), `unavailable` (a crates.io build), a mismatch or a + failing `--version` all fall through. +4. `cargo run --quiet [--release] -p big-code-analysis-cli --`, under the + profile `BCA_SELF_SCAN_PROFILE` names (`dev` by default; anything + other than `dev` or `release` is an error). + +One line on stderr names what was chosen and why; a captured gate log +then says what measured the tree. On POSIX the chosen command replaces +this process (`os.execvp`), so signals, exit status and stdin — for a +`--paths-from -` — are the child's own; on Windows it runs as a child +and its status is relayed, a signal death mapped to `128 + N`. + +What this does not do: hash the executable, or verify its self-report. +A binary that prints a digest it was not built from is trusted exactly +as the `cargo install`ed one in CI is. And a disagreement between the +two digest implementations only ever costs the fast path — the resolver +falls back to building — never a wrong binary. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +from pathlib import Path + +UTILS_DIR = Path(__file__).resolve().parent +REPO_ROOT = UTILS_DIR.parent +sys.path.insert(0, str(UTILS_DIR)) + +import self_scan_digest # noqa: E402 + +PROFILES = ("dev", "release") +CARGO_RUN = ("cargo", "run", "--quiet") +INPUTS_PREFIX = "build inputs: " + + +def env(name: str) -> str | None: + """The variable's value, with an empty string reading as unset.""" + value = os.environ.get(name, "") + return value if value != "" else None + + +def truthy(name: str) -> bool: + return (env(name) or "").lower() in {"1", "true", "yes"} + + +def note(message: str) -> None: + print(f"bca: self-scan {message}", file=sys.stderr, flush=True) + + +def build_inputs_of(binary: str) -> str | None: + """The `build inputs:` digest `binary --version` reports, or `None`.""" + try: + out = subprocess.run( + [binary, "--version"], capture_output=True, text=True, check=False, timeout=30 + ) + except (OSError, subprocess.TimeoutExpired): + return None + if out.returncode != 0: + return None + for line in out.stdout.splitlines(): + if line.startswith(INPUTS_PREFIX): + value = line[len(INPUTS_PREFIX) :].strip() + return value if value and value != "unavailable" else None + return None + + +def cargo_command(profile: str) -> list[str]: + flag = ["--release"] if profile == "release" else [] + return [*CARGO_RUN, *flag, "-p", "big-code-analysis-cli", "--"] + + +def resolve(workspace: Path) -> tuple[list[str], str]: + """The command to run — without the user's arguments — and the reason.""" + profile = env("BCA_SELF_SCAN_PROFILE") or "dev" + if profile not in PROFILES: + raise SystemExit( + f"bca: self-scan: BCA_SELF_SCAN_PROFILE must be one of {PROFILES}, not {profile!r}" + ) + + if truthy("BCA_SELF_SCAN_FROM_SOURCE"): + return cargo_command( + profile + ), f"via cargo run ({profile} profile): BCA_SELF_SCAN_FROM_SOURCE is set" + + explicit = env("BCA_SELF_SCAN_BINARY") + if explicit is not None: + # A relative path with a directory part is anchored to the + # invoking directory now, before `main` changes to the repo root, + # so it means what the caller's shell meant; a bare name is left + # for PATH lookup. + path = Path(explicit) + resolved = ( + str(path.resolve()) if path.parent != Path() and not path.is_absolute() else explicit + ) + return [resolved], f"via {resolved}: BCA_SELF_SCAN_BINARY is set" + + on_path = shutil.which("bca") + if on_path is not None: + reported = build_inputs_of(on_path) + if reported is None: + reason = f"{on_path} reports no build-inputs digest" + else: + try: + live = self_scan_digest.digest(workspace) + except self_scan_digest.DigestError as e: + live, reason = None, f"the tree cannot be digested ({e})" + else: + reason = f"{on_path} was built from other inputs ({reported[:12]} vs {live[:12]})" + if live is not None and live == reported: + return [on_path], f"via {on_path}: its build inputs match this tree ({live[:12]})" + return cargo_command(profile), f"via cargo run ({profile} profile): {reason}" + + return cargo_command(profile), f"via cargo run ({profile} profile): no bca on PATH" + + +def main(argv: list[str]) -> int: + # `BCA_SELF_SCAN_WORKSPACE` is the self-test's seam: it points the + # digest and the `chdir` at a scratch tree. Nothing else sets it. + workspace = Path(env("BCA_SELF_SCAN_WORKSPACE") or REPO_ROOT) + command, reason = resolve(workspace) + note(reason) + full = [*command, *argv] + if env("BCA_SELF_SCAN_DRY_RUN") is not None: + print("\n".join(full)) + return 0 + os.chdir(workspace) + if os.name == "posix": + os.execvp(full[0], full) + completed = subprocess.run(full, check=False) + code = completed.returncode + return 128 - code if code < 0 else code + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) From ce23169e7ad13322ef653f23d14e668cba74492b Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:02:13 -0800 Subject: [PATCH 4/8] refactor(cli): tighten the build-info reader and its tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- big-code-analysis-cli/build.rs | 69 ++++++++++--------- .../src/build_info/build_info_tests.rs | 17 +++-- .../src/build_info/digest.rs | 15 ++-- big-code-analysis-cli/src/build_info/elf.rs | 44 +++++++----- .../tests/check/check_exit_codes.rs | 10 +-- .../tests/output/format_smoke.rs | 27 +++++--- utils/self_scan_digest.py | 4 ++ 7 files changed, 107 insertions(+), 79 deletions(-) diff --git a/big-code-analysis-cli/build.rs b/big-code-analysis-cli/build.rs index c8c909cd8..dffaabd61 100644 --- a/big-code-analysis-cli/build.rs +++ b/big-code-analysis-cli/build.rs @@ -78,31 +78,32 @@ fn emit_inputs_digest(workspace: &Path) -> Option { digest::digest(workspace).ok() } +/// Run `git` with the repository-selecting variables scrubbed and +/// discovery fenced at `workspace`, so a packaged copy under +/// `target/package/` on a developer host cannot stamp the parent +/// checkout's revision, and a `pre-commit` hook's temporary +/// `GIT_INDEX_FILE` cannot leak in. `None` on any failure. +fn git(workspace: &Path, args: &[&str]) -> Option { + let out = Command::new("git") + .args(args) + .current_dir(workspace) + .env_remove("GIT_DIR") + .env_remove("GIT_WORK_TREE") + .env_remove("GIT_INDEX_FILE") + .env_remove("GIT_COMMON_DIR") + .env("GIT_CEILING_DIRECTORIES", workspace) + .output() + .ok()?; + out.status + .success() + .then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned()) +} + /// `` or `-dirty` for the checkout `workspace` lies in, or /// `None` outside one. The dirtiness pathspec is the digest's own /// roots, so the two fields cannot disagree about what "dirty" means. -/// -/// Git's repository-selecting variables are scrubbed and discovery is -/// fenced at the workspace, so a packaged copy under `target/package/` -/// on a developer host cannot stamp the parent checkout's revision, and -/// a `pre-commit` hook's temporary `GIT_INDEX_FILE` cannot leak in. fn git_revision(workspace: &Path) -> Option { - let git = |args: &[&str]| { - let out = Command::new("git") - .args(args) - .current_dir(workspace) - .env_remove("GIT_DIR") - .env_remove("GIT_WORK_TREE") - .env_remove("GIT_INDEX_FILE") - .env_remove("GIT_COMMON_DIR") - .env("GIT_CEILING_DIRECTORIES", workspace) - .output() - .ok()?; - out.status - .success() - .then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned()) - }; - let sha = git(&["rev-parse", "HEAD"])?; + let sha = git(workspace, &["rev-parse", "HEAD"])?; let mut status = vec![ "status", "--porcelain", @@ -111,7 +112,7 @@ fn git_revision(workspace: &Path) -> Option { "--", ]; status.extend(digest::INPUT_ROOTS); - let dirty = git(&status).is_some_and(|s| !s.is_empty()); + let dirty = git(workspace, &status).is_some_and(|s| !s.is_empty()); for watched in git_state_files(workspace) { println!("cargo:rerun-if-changed={}", watched.display()); } @@ -119,24 +120,24 @@ fn git_revision(workspace: &Path) -> Option { } /// The files whose change means `HEAD` may have moved: `HEAD` itself, -/// the ref it names when symbolic, `packed-refs`, and the index. A -/// worktree's `.git` is a file naming its private directory, which -/// `rev-parse --git-dir` and `--git-common-dir` resolve. +/// the ref it names when symbolic, and `packed-refs`. A worktree's +/// `.git` is a file naming its private directory, which `rev-parse +/// --git-dir` and `--git-common-dir` resolve. +/// +/// The index is deliberately not watched. It would keep the `-dirty` +/// suffix exact across a bare `git add`, but git rewrites it on every +/// `status` and on the refresh any hook performs, and each rewrite +/// would cost a rebuild of this crate — the relink #1773 exists to +/// avoid. `-dirty` therefore describes the tree as of the last build +/// that saw a source or ref change; the digest, which is what decides +/// anything, is exact regardless. fn git_state_files(workspace: &Path) -> Vec { let resolve = |flag: &str| { - Command::new("git") - .args(["rev-parse", "--path-format=absolute", flag]) - .current_dir(workspace) - .env("GIT_CEILING_DIRECTORIES", workspace) - .output() - .ok() - .filter(|o| o.status.success()) - .map(|o| PathBuf::from(String::from_utf8_lossy(&o.stdout).trim())) + git(workspace, &["rev-parse", "--path-format=absolute", flag]).map(PathBuf::from) }; let mut files = Vec::new(); if let Some(git_dir) = resolve("--git-dir") { files.push(git_dir.join("HEAD")); - files.push(git_dir.join("index")); if let Ok(head) = std::fs::read_to_string(git_dir.join("HEAD")) && let Some(reference) = head.trim().strip_prefix("ref: ") { diff --git a/big-code-analysis-cli/src/build_info/build_info_tests.rs b/big-code-analysis-cli/src/build_info/build_info_tests.rs index 27b893f68..be6ab6d32 100644 --- a/big-code-analysis-cli/src/build_info/build_info_tests.rs +++ b/big-code-analysis-cli/src/build_info/build_info_tests.rs @@ -164,17 +164,20 @@ fn long_version_starts_with_the_bare_version_and_carries_every_field() { assert_eq!(rest.len(), 4, "{text}"); assert!(rest[0].starts_with("build inputs: "), "{text}"); assert!(rest[1].starts_with("git: "), "{text}"); + // The state is read from this crate's own `cfg`, so the test binary + // knows the right answer; `DEBUG`, the obvious build-script source, + // reports debug *info* and is `true` for the release profile here. + // A hardcoded `off` passed every other assertion in this module. + let expected = if cfg!(debug_assertions) { "on" } else { "off" }; assert!( - rest[2].starts_with("built: ") && rest[2].contains("debug-assertions "), + rest[2].starts_with("built: ") + && rest[2].ends_with(&format!("debug-assertions {expected})")), "{text}" ); assert!(rest[3].starts_with("binary id: "), "{text}"); - let inputs = rest[0].trim_start_matches("build inputs: "); - assert!( - inputs == "unavailable" - || (inputs.len() == 64 && inputs.bytes().all(|b| b.is_ascii_hexdigit())), - "{inputs}" - ); + // The exact baked value, not a shape: the render could print any + // 64-hex string and a shape check would never know. + assert_eq!(rest[0], format!("build inputs: {}", super::BUILD_INPUTS)); } #[test] diff --git a/big-code-analysis-cli/src/build_info/digest.rs b/big-code-analysis-cli/src/build_info/digest.rs index 1a9ee9269..15aee182a 100644 --- a/big-code-analysis-cli/src/build_info/digest.rs +++ b/big-code-analysis-cli/src/build_info/digest.rs @@ -142,6 +142,8 @@ fn collect_dir( .map_err(io)? .collect::>() .map_err(io)?; + // `input_files` re-sorts the whole list by bytes; this sort only makes + // the first error a deterministic one when two entries are bad. entries.sort_by_key(std::fs::DirEntry::file_name); for entry in entries { match classify(workspace, &entry.path(), grammar_top)? { @@ -156,9 +158,10 @@ fn collect_dir( fn classify(workspace: &Path, path: &Path, grammar_top: bool) -> Result { let meta = std::fs::symlink_metadata(path) .map_err(|e| DigestError::Io(path.to_path_buf(), e.to_string()))?; - let rel = relative_posix(workspace, path)?; if meta.is_symlink() { - return Err(DigestError::Symlink(PathBuf::from(rel))); + return Err(DigestError::Symlink(PathBuf::from(relative_posix( + workspace, path, + )?))); } let skipped_artifact_dir = grammar_top && path @@ -167,7 +170,7 @@ fn classify(workspace: &Path, path: &Path, grammar_top: bool) -> Result Result { } /// Lowercase hex, two digits per byte. The same shape as the Code -/// Climate writer's `hex_lower_bytes`, repeated here because this file -/// may import nothing from either crate. +/// Climate writer's `hex_lower_bytes` and `elf::hex_lower`, repeated +/// because this file is `#[path]`-included by `build.rs`, which can +/// import nothing from the crate — and the crate includes this file +/// only under `cfg(test)`, so `elf.rs` cannot borrow it back. pub(crate) fn hex_lower(bytes: &[u8]) -> String { const DIGITS: &[u8; 16] = b"0123456789abcdef"; let mut out = String::with_capacity(bytes.len() * 2); diff --git a/big-code-analysis-cli/src/build_info/elf.rs b/big-code-analysis-cli/src/build_info/elf.rs index 307f2eac1..dcad57023 100644 --- a/big-code-analysis-cli/src/build_info/elf.rs +++ b/big-code-analysis-cli/src/build_info/elf.rs @@ -24,12 +24,28 @@ const PT_NOTE: u32 = 4; const NT_GNU_BUILD_ID: u32 = 3; const GNU_NOTE_NAME: &[u8] = b"GNU\0"; +/// How much of the executable to read looking for the note. The +/// program headers and every `PT_NOTE` segment the linker emits sit in +/// the first page or so of a GNU-linked image (`PT_PHDR`, `PT_INTERP` +/// and the notes precede the first `PT_LOAD` of code); 64 KiB covers +/// that with a wide margin and keeps this off the path of reading a +/// 140 MB binary into memory to answer `--version`. A note past the +/// bound reads as absent, the documented answer for every shape the +/// reader does not handle. +const HEAD_BYTES: u64 = 64 * 1024; + /// Lowercase hex of the running executable's GNU build-id, or `None`. #[cfg(target_os = "linux")] pub(crate) fn current_build_id() -> Option { + use std::io::Read as _; let exe = std::env::current_exe().ok()?; - let bytes = std::fs::read(exe).ok()?; - build_id(&bytes).map(hex_lower) + let mut head = Vec::new(); + std::fs::File::open(exe) + .ok()? + .take(HEAD_BYTES) + .read_to_end(&mut head) + .ok()?; + build_id(&head).map(hex_lower) } /// Lowercase hex, two digits per byte. @@ -126,26 +142,20 @@ fn align4(n: usize) -> Option { n.checked_add(3).map(|v| v & !3) } +/// `N` little-endian bytes at `at`, or `None` past the end or on an +/// overflowing offset. One reader for the three widths below. +fn le_at(bytes: &[u8], at: usize) -> Option<&[u8; N]> { + bytes.get(at..at.checked_add(N)?)?.as_array() +} + fn u16_at(bytes: &[u8], at: usize) -> Option { - bytes - .get(at..at.checked_add(2)?)? - .try_into() - .ok() - .map(u16::from_le_bytes) + le_at(bytes, at).copied().map(u16::from_le_bytes) } fn u32_at(bytes: &[u8], at: usize) -> Option { - bytes - .get(at..at.checked_add(4)?)? - .try_into() - .ok() - .map(u32::from_le_bytes) + le_at(bytes, at).copied().map(u32::from_le_bytes) } fn u64_at(bytes: &[u8], at: usize) -> Option { - bytes - .get(at..at.checked_add(8)?)? - .try_into() - .ok() - .map(u64::from_le_bytes) + le_at(bytes, at).copied().map(u64::from_le_bytes) } diff --git a/big-code-analysis-cli/tests/check/check_exit_codes.rs b/big-code-analysis-cli/tests/check/check_exit_codes.rs index 7af65342d..166054938 100644 --- a/big-code-analysis-cli/tests/check/check_exit_codes.rs +++ b/big-code-analysis-cli/tests/check/check_exit_codes.rs @@ -611,12 +611,12 @@ fn short_version_is_one_line_and_long_version_starts_with_it() { "{line:?} should start with {prefix:?}" ); } + // 64 hex digits from this checkout; `unavailable` only outside a + // workspace, where this integration test does not run (it needs the + // workspace's `tests/` beside the crate to exist at all). let inputs = lines[1].trim_start_matches("build inputs: "); - assert!( - inputs == "unavailable" - || (inputs.len() == 64 && inputs.bytes().all(|b| b.is_ascii_hexdigit())), - "{inputs}" - ); + assert_eq!(inputs.len(), 64, "{inputs}"); + assert!(inputs.bytes().all(|b| b.is_ascii_hexdigit()), "{inputs}"); } // -- Manifest opt-in ------------------------------------------------------ diff --git a/big-code-analysis-cli/tests/output/format_smoke.rs b/big-code-analysis-cli/tests/output/format_smoke.rs index 5ad545e38..b4e78cc82 100644 --- a/big-code-analysis-cli/tests/output/format_smoke.rs +++ b/big-code-analysis-cli/tests/output/format_smoke.rs @@ -160,18 +160,23 @@ fn cli_check_sarif_output_validates_against_schema() { // The CLI stamps its build provenance into the driver's property // bag (#1773) — the only place `toolComponent` admits a producer // key, which the schema validation above has just confirmed. The - // digest is 64 hex digits from a checkout build and the literal - // `unavailable` from a registry build; nothing else is valid. + // values are the same two fields `--version` prints, so compare them + // against that output rather than against a shape. + let version = std::process::Command::new(env!("CARGO_BIN_EXE_bca")) + .arg("--version") + .output() + .expect("bca --version runs"); + let version = String::from_utf8(version.stdout).expect("utf-8"); + let field = |prefix: &str| { + version + .lines() + .find_map(|l| l.strip_prefix(prefix)) + .unwrap_or_else(|| panic!("{prefix} missing from --version:\n{version}")) + .to_owned() + }; let props = &doc["runs"][0]["tool"]["driver"]["properties"]; - let inputs = props["bca.buildInputs"] - .as_str() - .expect("bca.buildInputs is a string"); - assert!( - inputs == "unavailable" - || (inputs.len() == 64 && inputs.bytes().all(|b| b.is_ascii_hexdigit())), - "{inputs}" - ); - assert!(props["bca.buildGit"].is_string(), "{out}"); + assert_eq!(props["bca.buildInputs"], field("build inputs: ")); + assert_eq!(props["bca.buildGit"], field("git: ")); } #[test] diff --git a/utils/self_scan_digest.py b/utils/self_scan_digest.py index 2980a2583..319ef6880 100644 --- a/utils/self_scan_digest.py +++ b/utils/self_scan_digest.py @@ -53,6 +53,10 @@ def input_files(workspace: Path) -> list[str]: _collect_dir(workspace, path, root.startswith("tree-sitter-"), files) else: raise DigestError(f"input root is absent: {root}") + # Bytes rather than code points to match the Rust side literally; + # UTF-8 preserves code-point order, so the two never differ for a + # name both sides accept — this spelling only makes the agreement + # visible. files.sort(key=lambda s: s.encode("utf-8")) return files From 78ef466482b8bb009700963586927bdc6e328a72 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:44:25 -0800 Subject: [PATCH 5/8] fix(cli,self-scan): apply the six-agent review of the provenance work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .bca-baseline.toml | 2 +- .checkmake.ini | 3 +- .github/workflows/pages.yml | 43 +++- .gitignore | 4 + AGENTS.md | 15 +- CHANGELOG.md | 6 +- Cargo.toml | 12 +- Makefile | 55 ++--- STABILITY.md | 28 ++- bca.toml | 8 +- big-code-analysis-book/src/commands/report.md | 7 +- big-code-analysis-book/src/recipes/ci.md | 19 +- big-code-analysis-cli/Cargo.toml | 9 +- big-code-analysis-cli/build.rs | 83 ++++--- .../src/build_info/build_info_tests.rs | 78 ++++++- .../src/build_info/digest.rs | 92 +++++--- big-code-analysis-cli/src/build_info/elf.rs | 220 ++++++++++-------- big-code-analysis-cli/src/build_info/mod.rs | 38 ++- big-code-analysis-cli/src/check_format.rs | 17 +- big-code-analysis-cli/src/commands.rs | 9 +- big-code-analysis-cli/src/commands/report.rs | 2 +- big-code-analysis-cli/src/provenance.rs | 8 +- .../tests/check/check_exit_codes.rs | 5 +- .../tests/output/format_smoke.rs | 15 +- docs/development/baseline_freshness.md | 10 +- src/output/sarif.rs | 42 ++-- tree-sitter-ccomment/bindings/rust/build.rs | 4 +- tree-sitter-mozcpp/bindings/rust/build.rs | 4 +- tree-sitter-mozjs/bindings/rust/build.rs | 4 +- tree-sitter-preproc/bindings/rust/build.rs | 4 +- tree-sitter-tcl/bindings/rust/build.rs | 4 +- utils/check-role-coverage.py | 6 +- utils/self-scan-bca-test.py | 67 +++++- utils/self-scan-bca.py | 56 +++-- utils/self_scan_digest.py | 35 ++- 35 files changed, 655 insertions(+), 359 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 2143c6845..da0694009 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -515,7 +515,7 @@ value = 39.93745109543172 path = "big-code-analysis-cli/src/commands/report.rs" qualified = "run_command_report" metric = "halstead.effort" -value = 65001.24036761245 +value = 64495.18935578189 [[entry]] path = "big-code-analysis-cli/src/diff.rs" diff --git a/.checkmake.ini b/.checkmake.ini index 1e528b9b9..29974fcb3 100644 --- a/.checkmake.ini +++ b/.checkmake.ini @@ -30,7 +30,8 @@ ; ; Raised from 165 to 170 in #1773: the two baseline-check targets ; (`self-scan-baseline-fresh`, `self-scan-profile-parity`) took the -; `help` body from 149 to 151, leaving 14 of the promised 15. +; `help` body from 149 to 152 (with `self-scan-bca-test`), leaving 13 +; of the promised 15. [maxbodylength] maxBodyLength = 170 diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 4b82d6411..a7585cdf9 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -37,6 +37,13 @@ on: # The walk deny-set. An edit here changes which files the gate # measures, so it must re-run the gate (#1773). - '.bcaignore' + # The gate's own runner. `make self-scan` is the Makefile recipe + # plus the wrapper it execs, and CI's route through the wrapper + # (an explicit `BCA_SELF_SCAN_BINARY`) is one the self-test only + # dry-runs. + - 'Makefile' + - 'utils/self-scan-bca.py' + - 'utils/self_scan_digest.py' - '.github/workflows/pages.yml' pull_request: paths: @@ -57,6 +64,13 @@ on: - 'bca.toml' - '.bca-baseline.toml' - '.bcaignore' + # The gate's own runner. `make self-scan` is the Makefile recipe + # plus the wrapper it execs, and CI's route through the wrapper + # (an explicit `BCA_SELF_SCAN_BINARY`) is one the self-test only + # dry-runs. + - 'Makefile' + - 'utils/self-scan-bca.py' + - 'utils/self_scan_digest.py' - '.github/workflows/pages.yml' workflow_dispatch: @@ -236,8 +250,11 @@ jobs: # bca workspace (many tree-sitter grammar C crates plus the Rust # workspace itself). Warm-cache runs finish in 3-5 min; the # ceiling absorbs the worst-case "Cargo.lock churned + Swatinem - # cache evicted" combo without killing useful runs. - timeout-minutes: 30 + # cache evicted" combo without killing useful runs. Raised from 30 + # for the profile-parity step (#1773), which on that same cold + # cache adds a full dev build and a release relink after the + # install. + timeout-minutes: 45 # security-events:write lets the upload-sarif step publish bca's own # self-scan offenders to GitHub code scanning (Security tab + PR # annotations) — dogfooding the SARIF path we document for adopters @@ -416,13 +433,23 @@ jobs: # The dev-profile default behind `make self-scan` locally (#1773) # rests on both profiles writing the same baseline. This builds - # the dev binary too — several minutes cold, since the cache above - # is release-only — and `cmp`s the two regenerations. Per PR - # rather than quarterly so a divergence is attributed to the - # change that caused it. Not `BCA_SELF_SCAN_BINARY`-driven: the - # recipe builds both sides from source on purpose. + # the dev binary — several minutes cold, since the cache above is + # release-only — and the release one again, since `cargo install` + # builds in its own temporary target directory and leaves nothing + # for `cargo run --release` to reuse, then `cmp`s the two + # regenerations. Per PR rather than quarterly so a divergence is + # attributed to the change that caused it. Not + # `BCA_SELF_SCAN_BINARY`-driven: the recipe builds both sides from + # source on purpose. The release leg is the ~100 s LTO link, warm + # only through the restored cache; the dev artifacts left behind + # grow the `pages-scan-release` entry; split the key if it starts + # evicting, and raise the job timeout if a cold run nears it. + # `success()` rather than the gate's `!cancelled()`: a red gate or + # a failed report step already has the job's answer, and this step + # is the costliest in the job on a cold cache, so it is not spent + # on a run that has already failed. - name: Profile parity (dev vs release baseline) - if: ${{ !cancelled() }} + if: ${{ success() }} run: make self-scan-profile-parity # Dogfood bca's own SARIF writer: re-run the gate as a pure diff --git a/.gitignore b/.gitignore index 401601c12..6d2c456e3 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,7 @@ big-code-analysis-cli/dist/ big-code-analysis-cli/LICENSE big-code-analysis-cli/THIRD-PARTY-LICENSES-bca.md big-code-analysis-cli/man/ +# Temporary siblings `make self-scan-baseline-fresh` / `-profile-parity` +# write beside the committed baseline (#1773); removed on exit, but a +# Ctrl-C that kills make first can leave one. +.bca-baseline.*.toml diff --git a/AGENTS.md b/AGENTS.md index f84e1ed2e..467bc0656 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -529,9 +529,18 @@ because the file is `-merge`: regenerate, stage, and `git rebase **What a refresh costs, and why.** The scan itself is ~0.2 s for the whole tree; what you wait for is the build. The self-scan recipes build `bca` under the **dev** profile (#1773): ~5 s for a step that -touched Rust under `src/`, `big-code-analysis-ast/`, -`big-code-analysis-cli/` or a grammar crate, and ~0.1 s for one that -did not, because cargo finds every artifact fresh. They used to build +touched something compiled into it — Rust under `src/`, +`big-code-analysis-ast/src/`, `big-code-analysis-cli/src/`, a grammar +crate's sources, a manifest or `Cargo.lock` — and ~0.1 s for one that +did not, because cargo finds every artifact fresh. A commit that +touches nothing compiled is in the second class even though it moves +`HEAD`: the `git:` field of `bca --version` is deliberately *not* +refreshed on a bare commit, because refreshing it would cost the +rebuild on every step of the rebase loop this paragraph is about (it +is exact as of the last build whose inputs changed; the `build +inputs:` digest, the field the resolver decides on, is exact always). +Integration tests under a crate's `tests/`, `.snap` files and grammar +`node-types.json` are not inputs either. They used to build release, whose `lto = true` / `codegen-units = 1` relink is ~100 s after *any* such edit — which made the nine-conflict rebase that motivated #1773 a ten-minute job. `BCA_SELF_SCAN_PROFILE=release` diff --git a/CHANGELOG.md b/CHANGELOG.md index 74ce857f3..94b3aaf77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,10 +31,12 @@ for historical reference. `build inputs:` (a SHA-256 content digest of every source compiled into the binary — the workspace's Rust, manifests and the five vendored grammars — or `unavailable` for a crates.io build), - `git:` (``, `-dirty` when those inputs had uncommitted edits), + `git:` (``, `-dirty` when those inputs had uncommitted edits; + exact as of the last build whose inputs changed, since refreshing it + on a bare commit would cost the rebuild #1773 removes), `built:` (RFC 3339 UTC, honouring `SOURCE_DATE_EPOCH`, with the profile, `rustc`, target and debug-assertions state) and - `binary id:` (the linker's GNU build-id on Linux). Two builds of one + `build id:` (the linker's GNU build-id on Linux). Two builds of one tree share a digest whatever their mtimes or branch, and two binaries that both print `2.4.0` from different commits do not — which is the question "is this installed `bca` the one this checkout diff --git a/Cargo.toml b/Cargo.toml index 13d7df809..a3545fed6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,6 +66,12 @@ serde-saphyr = { version = "^2.0", default-features = false, features = [ "serialize", "deserialize", ] } +# Exact-pinned: the Code Climate writer's per-violation fingerprints and +# the CLI's build-inputs digest (#1773) are both frozen contracts over +# this hash, so the implementation only ever moves deliberately. Here +# rather than in the root `[dependencies]` because the CLI needs the +# same pin twice over (its build script and its tests). +sha2 = "=0.11.1" tree-sitter = "=0.26.13" tree-sitter-bash = "=0.25.1" tree-sitter-c-sharp = "=0.23.5" @@ -233,9 +239,9 @@ serde.workspace = true # which is deterministic and gives the uniform field set #674 requires. serde_json = { workspace = true, features = ["float_roundtrip"] } # Used by the GitLab Code Climate writer to compute stable -# per-violation fingerprints. Exact-pinned so the hash implementation -# behind a frozen output contract only ever moves deliberately. -sha2 = "=0.11.1" +# per-violation fingerprints; the pin and its rationale are the +# workspace's. +sha2.workspace = true # HMAC-SHA256 for the opt-in keyed author-identity hashing # (`--author-hash-key`, #956). Kept in lockstep with `sha2`: both sit on # the RustCrypto `digest` 0.11 trait family, which `actix-http` already diff --git a/Makefile b/Makefile index 44a1e6b7b..3cf1b5589 100644 --- a/Makefile +++ b/Makefile @@ -895,28 +895,19 @@ enums-check: # any in-progress change to metric computation is reflected in the # values we gate on. # -# Which binary runs is `utils/self-scan-bca.py`'s decision (#1773). In -# order: `BCA_SELF_SCAN_FROM_SOURCE=1` builds from the tree whatever -# else is set; `BCA_SELF_SCAN_BINARY=` runs that executable, -# trusted as given (CI sets it to the release binary it has just -# `cargo install`ed from HEAD, so the gate and the published reports -# come from one build); a `bca` on PATH is used when the `build inputs:` -# digest its `--version` reports equals the digest of this checkout's -# compiled-in sources, recomputed by the wrapper — equal means it was -# built from these exact bytes, whatever its mtime or branch; otherwise -# `cargo run` under `BCA_SELF_SCAN_PROFILE` (`dev` by default, or -# `release`). `release` is what CI installs, but its `lto = true` / -# `codegen-units = 1` relink costs ~100 s after any `src/` edit; the -# dev profile is ~5 s for the same edit and 0.1 s when nothing changed, -# and both profiles write a byte-identical baseline — which -# `self-scan-profile-parity` below keeps true. -# -# A trusted `BCA_SELF_SCAN_BINARY` is sound only when nothing compiled -# into it has changed: `src/`, `big-code-analysis-ast/`, -# `big-code-analysis-cli/`, `tree-sitter-*/`, `Cargo.toml`. Everything -# else (`bca.toml`, `.bcaignore`, the baseline) is read at run time, so -# any binary sees the live copy. The PATH route needs no such care; it -# proves the match before it uses the binary. +# Which binary runs is `utils/self-scan-bca.py`'s decision (#1773); +# its docstring is the one full statement of the order and the +# `BCA_SELF_SCAN_*` knobs, and its self-test exercises every branch. +# In short: a forced from-source build, else an explicit binary, else +# a `bca` on PATH whose `--version` digest proves it was built from +# this checkout's compiled-in sources, else `cargo run` under +# `BCA_SELF_SCAN_PROFILE` — `dev` by default, since the release +# profile's `lto = true` / `codegen-units = 1` relink costs ~100 s +# after any `src/` edit against ~5 s for dev, and both profiles write a +# byte-identical baseline, which `self-scan-profile-parity` below keeps +# true. CI sets `BCA_SELF_SCAN_BINARY` to the release binary it has +# just `cargo install`ed from HEAD, so the gate and the published +# reports come from one build. # # Path selection (`paths = ["."]`), the ignore file # (`exclude_from = ".bcaignore"`), the baseline @@ -1032,12 +1023,14 @@ self-scan-write-baseline-headroom: # or from another working directory, keys the same functions # differently and every entry reads as removed-and-added. The walker # never analyses the temp file itself — `.toml` is no language it -# knows — and `trap` removes it on every exit, so nothing is left for -# `git status` to show. One `&&`-joined command because recipes run -# one line per shell here (no `.ONESHELL`). +# knows — and `trap` removes it on exit and on a signal. A Ctrl-C that +# kills `make` before the shell runs its trap can still leave one; +# `.gitignore` carries `.bca-baseline.*.toml` so a leak cannot be +# staged. One `&&`-joined command because recipes run one line per +# shell here (no `.ONESHELL`). self-scan-baseline-fresh: @echo "bca self-scan baseline freshness (BCA_HEADROOM=$${BCA_HEADROOM:-0.95})..." - @cd "$(BASE_DIR)" && t=$$(mktemp ".bca-baseline.XXXXXX.toml") && trap 'rm -f "$$t"' EXIT \ + @cd "$(BASE_DIR)" && t=$$(mktemp ".bca-baseline.XXXXXX.toml") && trap 'rm -f "$$t"' EXIT INT TERM \ && $(SELF_SCAN_BCA) check --tier=soft=$${BCA_HEADROOM:-0.95} --write-baseline "$$t" \ && $(SELF_SCAN_BCA) diff-baseline .bca-baseline.toml "$$t" --exit-code @@ -1045,18 +1038,20 @@ self-scan-baseline-fresh: # The dev-profile default rests on it: `debug-assertions` and # `overflow-checks` are the only semantic differences between the # profiles, and either firing would be a bug the release gate hides. -# On a mismatch both files are kept and named so they can be diffed. -# Both legs force a from-source build through the wrapper +# On a mismatch — and only then — both files are kept and named so +# they can be diffed; every other exit, a failed build included, +# removes them. Both legs force a from-source build through the wrapper # (`BCA_SELF_SCAN_FROM_SOURCE=1` outranks every other knob), so an # inherited `BCA_SELF_SCAN_BINARY` or a matching PATH `bca` cannot turn # this into a comparison of one binary with itself. self-scan-profile-parity: @echo "bca self-scan profile parity (dev vs release, BCA_HEADROOM=$${BCA_HEADROOM:-0.95})..." @cd "$(BASE_DIR)" && d=$$(mktemp ".bca-baseline.dev.XXXXXX.toml") && r=$$(mktemp ".bca-baseline.release.XXXXXX.toml") \ + && trap 'rm -f "$$d" "$$r"' EXIT INT TERM \ && BCA_SELF_SCAN_FROM_SOURCE=1 BCA_SELF_SCAN_PROFILE=dev $(SELF_SCAN_BCA) check --tier=soft=$${BCA_HEADROOM:-0.95} --write-baseline "$$d" \ && BCA_SELF_SCAN_FROM_SOURCE=1 BCA_SELF_SCAN_PROFILE=release $(SELF_SCAN_BCA) check --tier=soft=$${BCA_HEADROOM:-0.95} --write-baseline "$$r" \ - && if cmp -s "$$d" "$$r"; then rm -f "$$d" "$$r"; echo "profile parity: dev and release baselines are byte-identical"; \ - else echo "profile parity: dev and release baselines differ; kept $$d and $$r" >&2; exit 1; fi + && if cmp -s "$$d" "$$r"; then echo "profile parity: dev and release baselines are byte-identical"; \ + else trap - EXIT INT TERM; echo "profile parity: dev and release baselines differ; kept $$d and $$r" >&2; exit 1; fi # --------------------------------------------------------------------------- # Change-history (VCS) risk report (issue #328). Dogfoods `bca vcs` on diff --git a/STABILITY.md b/STABILITY.md index 0b99fb6c5..c28aa70a8 100644 --- a/STABILITY.md +++ b/STABILITY.md @@ -691,17 +691,24 @@ compiled into the binary, or `unavailable` for a build from the crates.io tarball, where the workspace is not beside the crate), `git:`, `built:` (RFC 3339 UTC, `SOURCE_DATE_EPOCH` when it was set at build time, with the profile, `rustc` version, target and -debug-assertions state) and `binary id:` (the linker's GNU build-id +debug-assertions state) and `build id:` (the linker's GNU build-id note on Linux; `unavailable` elsewhere). The first line is the stable -contract; the fields after it are informational, their wording may -change in a minor release, and a consumer that needs the version alone -should read `-V` or the first line. The same digest is stamped into a -`bca check` SARIF document under `tool.driver.properties` as -`bca.buildInputs` / `bca.buildGit`, and abbreviated in the `bca report` -provenance footer. The library's own `write_sarif` and -`write_sarif_with_suppressed` are unchanged; `write_sarif_with_provenance` -and `SarifProvenance` are the additive surface a host uses to stamp its -own build. +contract, and so is one thing about the second: a line beginning +`build inputs:` followed by a space and either 64 lowercase hex digits +or the word `unavailable`, which is what `utils/self-scan-bca.py` — +and any CI that wants the same trick — keys on. The remaining fields are +informational, their wording may change in a minor release, and a +consumer that needs the version alone should read `-V` or the first +line. The same digest is stamped into a `bca check` SARIF document +under `tool.driver.properties` as `bca.buildInputs` / `bca.buildGit` +(each *omitted*, not spelled `unavailable`, when unknown), and +abbreviated in the `bca report` provenance footer. The library's own +`write_sarif` and `write_sarif_with_suppressed` are unchanged; +`write_sarif_with_provenance` and `SarifProvenance` are the additive +surface a host uses to stamp its own build. `SarifProvenance` follows +`MetricsOptions`'s shape — `#[non_exhaustive]`, private fields, +`Default` plus `with_*` setters — and is the extension point for any +run-level metadata added later; the writer's parameter list is not. The next major re-baseline at `3.0` (whenever it happens) is the point at which the value drifts accumulated across `2.x` will be @@ -924,6 +931,7 @@ at the crate root from `src/output/`: | `write_csv_aggregate` | `(spaces: impl IntoIterator, writer: W) -> io::Result<()>`; one shared header, then every tree's rows | | `write_sarif` | `(offenders: &[OffenderRecord], writer: W) -> io::Result<()>` | | `write_sarif_with_suppressed` | `(active, in_source, baseline: &[OffenderRecord], writer: W) -> io::Result<()>`. The two suppressed slices stay separate because they render different `suppressions[].kind` values: `in_source` gives `"inSource"`, `baseline` gives `"external"` | +| `write_sarif_with_provenance` | `(active, in_source, baseline: &[OffenderRecord], provenance: &SarifProvenance, writer: W) -> io::Result<()>`. The suppressed writer with a `tool.driver.properties` stamp; an empty `SarifProvenance::default()` yields `write_sarif_with_suppressed`'s bytes exactly (#1773) | | `write_checkstyle` | `(offenders: &[OffenderRecord], writer: W) -> io::Result<()>` | | `write_clang_warning` | `(offenders: &[OffenderRecord], writer: W) -> io::Result<()>` | | `write_msvc_warning` | `(offenders: &[OffenderRecord], writer: W) -> io::Result<()>` | diff --git a/bca.toml b/bca.toml index 28ad9d60a..436e2063b 100644 --- a/bca.toml +++ b/bca.toml @@ -10,11 +10,9 @@ # We build the bca binary from source on purpose so any in-progress # change to metric computation is reflected in the values we gate on — # under the dev profile by default, since the release relink costs -# ~100 s per edit and both profiles write the same baseline (#1773); -# CI hands the recipes its freshly installed release binary instead. -# A `bca` on PATH is used instead when its `--version` reports a -# build-inputs digest equal to this checkout's. The knobs are documented -# at `SELF_SCAN_BCA` in the Makefile and in `utils/self-scan-bca.py`. +# ~100 s per edit and both profiles write the same baseline (#1773). +# Which binary actually runs is `utils/self-scan-bca.py`'s decision; +# see `SELF_SCAN_BCA` in the Makefile. # Scan the whole repo, honouring the ignore file. The walker re-anchors # the resolved seed to the `./`-prefixed form (#488), so the diff --git a/big-code-analysis-book/src/commands/report.md b/big-code-analysis-book/src/commands/report.md index 1eefe2f4f..0219c40c7 100644 --- a/big-code-analysis-book/src/commands/report.md +++ b/big-code-analysis-book/src/commands/report.md @@ -195,8 +195,11 @@ same shared column specs the tooltips use, so the two formats cannot drift. Both formats close with a **provenance footer** stating the `bca` -version, generation date, the seed paths scanned, the per-table `--top` -value, and whether suppression markers were honored, so a detached +version — followed, for a `bca` built from a source checkout, by the +first twelve digits of its build-inputs digest in parentheses, the +same digest `bca --version` prints in full — the generation date, the +seed paths scanned, the per-table `--top` value, and whether +suppression markers were honored, so a detached artifact (a PR comment, a Pages deployment, a file on a ticket) records what it was generated from. The date honors [`SOURCE_DATE_EPOCH`](https://reproducible-builds.org/docs/source-date-epoch/) diff --git a/big-code-analysis-book/src/recipes/ci.md b/big-code-analysis-book/src/recipes/ci.md index afdc180e9..ab5337f4d 100644 --- a/big-code-analysis-book/src/recipes/ci.md +++ b/big-code-analysis-book/src/recipes/ci.md @@ -654,18 +654,13 @@ the manifest supplies them: cargo run --quiet -p big-code-analysis-cli -- check ``` -That is the dev profile. The release relink costs ~100 s after any -edit under `src/`, so the recipes build dev by default and leave the -profile to `BCA_SELF_SCAN_PROFILE=release` when CI's exact binary is -wanted; `make self-scan-profile-parity` checks per PR that the two -profiles write a byte-identical baseline. `BCA_SELF_SCAN_BINARY=` -runs a prebuilt binary instead of building at all — what CI does with -the release binary it installs from the checkout — and is sound only -when nothing compiled into that binary has changed since. A `bca` on -PATH is used without being told to, but only after the recipe's -wrapper (`utils/self-scan-bca.py`) has compared the `build inputs:` -digest its `--version` reports with a fresh digest of the checkout's -compiled-in sources: equal means it was built from these bytes. +That is the dev profile: the release relink costs ~100 s after any +edit under `src/`, and both profiles write a byte-identical baseline, +which `make self-scan-profile-parity` checks per PR. The recipes go +through a small wrapper that can also run an already-installed `bca` +when it proves it was built from the checkout; that mechanism and its +knobs are repository tooling, documented in the Makefile, not part of +the gate an adopter copies. Both tiers consume the same `bca.toml` thresholds and the same `.bca-baseline.toml`; the soft tier runs the hard recipe with every diff --git a/big-code-analysis-cli/Cargo.toml b/big-code-analysis-cli/Cargo.toml index b1a64793b..0a157a8ba 100644 --- a/big-code-analysis-cli/Cargo.toml +++ b/big-code-analysis-cli/Cargo.toml @@ -53,15 +53,14 @@ workspace = true # `build.rs` hashes every compiled-in source into the `--version` # provenance block (#1773). `src/build_info/digest.rs` is shared with -# the crate's tests by `#[path]`, so the pin appears under both tables; -# it is the root crate's exact pin repeated, since `sha2` is a package -# dependency there rather than a `[workspace.dependencies]` entry. +# the crate's tests by `#[path]`, so the workspace pin appears under +# both tables. [build-dependencies] -sha2 = "=0.11.1" +sha2.workspace = true [dev-dependencies] assert_cmd = "^2.0" -sha2 = "=0.11.1" +sha2.workspace = true csv.workspace = true insta = "1.49.0" jsonschema = "^0.59" diff --git a/big-code-analysis-cli/build.rs b/big-code-analysis-cli/build.rs index dffaabd61..d7b10acba 100644 --- a/big-code-analysis-cli/build.rs +++ b/big-code-analysis-cli/build.rs @@ -71,19 +71,38 @@ fn env_or_empty(key: &str) -> String { /// `None` when the layout is not a workspace checkout; nothing is /// registered then except `build.rs` itself. fn emit_inputs_digest(workspace: &Path) -> Option { - let files = digest::input_files(workspace).ok()?; - for rel in &files { - println!("cargo:rerun-if-changed={}", workspace.join(rel).display()); + let walked = digest::input_files(workspace).and_then(|files| { + for rel in &files { + println!("cargo:rerun-if-changed={}", workspace.join(rel).display()); + } + digest::digest_of(workspace, &files) + }); + match walked { + Ok(digest) => Some(digest), + // The one silent case: no workspace beside the crate, which is + // what a crates.io build looks like and not a defect. + Err(digest::DigestError::MissingRoot(_)) => None, + // Anything else is a real checkout the digest cannot describe — + // a symlink, a non-UTF-8 name, an unreadable file. The binary + // still builds, reporting `unavailable`, but the cause is said + // at the build that produced it rather than at the next test. + Err(e) => { + println!("cargo:warning=build-inputs digest unavailable: {e}"); + None + } } - digest::digest(workspace).ok() } /// Run `git` with the repository-selecting variables scrubbed and -/// discovery fenced at `workspace`, so a packaged copy under -/// `target/package/` on a developer host cannot stamp the parent -/// checkout's revision, and a `pre-commit` hook's temporary -/// `GIT_INDEX_FILE` cannot leak in. `None` on any failure. +/// discovery fenced so that only a `.git` *in* `workspace` is found: +/// a packaged copy under `target/package/`, or a tree exported into +/// another checkout, then reports `unavailable` rather than stamping +/// the enclosing repository's revision, and a `pre-commit` hook's +/// temporary `GIT_INDEX_FILE` cannot leak in. The ceiling is the +/// workspace's *parent* — git never excludes the directory it starts +/// in, only the ones it would climb into. `None` on any failure. fn git(workspace: &Path, args: &[&str]) -> Option { + let ceiling = workspace.parent().unwrap_or(workspace); let out = Command::new("git") .args(args) .current_dir(workspace) @@ -91,7 +110,7 @@ fn git(workspace: &Path, args: &[&str]) -> Option { .env_remove("GIT_WORK_TREE") .env_remove("GIT_INDEX_FILE") .env_remove("GIT_COMMON_DIR") - .env("GIT_CEILING_DIRECTORIES", workspace) + .env("GIT_CEILING_DIRECTORIES", ceiling) .output() .ok()?; out.status @@ -101,7 +120,18 @@ fn git(workspace: &Path, args: &[&str]) -> Option { /// `` or `-dirty` for the checkout `workspace` lies in, or /// `None` outside one. The dirtiness pathspec is the digest's own -/// roots, so the two fields cannot disagree about what "dirty" means. +/// roots — not its extension filter, so an untracked `.snap.new` reads +/// `-dirty` while the digest stands; the field is informational and +/// that over-approximation is the cheaper side to err on. +/// +/// Nothing under `.git/` is watched, on purpose. `BCA_BUILD_GIT` is an +/// `env!` the library reads, so a changed value invalidates the +/// library's fingerprint and costs a recompile plus the `bca` relink — +/// ~4 s dev, ~100 s release. Watching `HEAD` would charge that on +/// every commit, and on every step of the `git rebase --exec` loop +/// #1773 was opened to make cheap, for a step that compiled nothing. +/// So the field is exact as of the last build whose *inputs* changed; +/// `build inputs`, the one field anything decides on, is exact always. fn git_revision(workspace: &Path) -> Option { let sha = git(workspace, &["rev-parse", "HEAD"])?; let mut status = vec![ @@ -113,42 +143,9 @@ fn git_revision(workspace: &Path) -> Option { ]; status.extend(digest::INPUT_ROOTS); let dirty = git(workspace, &status).is_some_and(|s| !s.is_empty()); - for watched in git_state_files(workspace) { - println!("cargo:rerun-if-changed={}", watched.display()); - } Some(if dirty { format!("{sha}-dirty") } else { sha }) } -/// The files whose change means `HEAD` may have moved: `HEAD` itself, -/// the ref it names when symbolic, and `packed-refs`. A worktree's -/// `.git` is a file naming its private directory, which `rev-parse -/// --git-dir` and `--git-common-dir` resolve. -/// -/// The index is deliberately not watched. It would keep the `-dirty` -/// suffix exact across a bare `git add`, but git rewrites it on every -/// `status` and on the refresh any hook performs, and each rewrite -/// would cost a rebuild of this crate — the relink #1773 exists to -/// avoid. `-dirty` therefore describes the tree as of the last build -/// that saw a source or ref change; the digest, which is what decides -/// anything, is exact regardless. -fn git_state_files(workspace: &Path) -> Vec { - let resolve = |flag: &str| { - git(workspace, &["rev-parse", "--path-format=absolute", flag]).map(PathBuf::from) - }; - let mut files = Vec::new(); - if let Some(git_dir) = resolve("--git-dir") { - files.push(git_dir.join("HEAD")); - if let Ok(head) = std::fs::read_to_string(git_dir.join("HEAD")) - && let Some(reference) = head.trim().strip_prefix("ref: ") - { - let common = resolve("--git-common-dir").unwrap_or(git_dir); - files.push(common.join(reference)); - files.push(common.join("packed-refs")); - } - } - files.into_iter().filter(|p| p.exists()).collect() -} - /// RFC 3339 UTC, from `SOURCE_DATE_EPOCH` when set (the /// reproducible-builds convention the report footer already honours) /// and the wall clock otherwise. diff --git a/big-code-analysis-cli/src/build_info/build_info_tests.rs b/big-code-analysis-cli/src/build_info/build_info_tests.rs index be6ab6d32..9de50310f 100644 --- a/big-code-analysis-cli/src/build_info/build_info_tests.rs +++ b/big-code-analysis-cli/src/build_info/build_info_tests.rs @@ -9,7 +9,7 @@ use super::elf::{build_id, hex_lower}; /// file, a `.snap` that must be ignored, a top-level `target/` that /// must be skipped, and a nested `build/` that must *not* be. const SHARED_FIXTURE_DIGEST: &str = - "564b792dc7b3e4fca571038d165a8d89ca9069bccc956ea4af0413c572345299"; + "2d6dfcc20156bfc6bcd2bc38ab2cdff68cc864b1a4b6951b891cffc40508a17e"; fn shared_fixture(dir: &Path) { let write = |rel: &str, bytes: &[u8]| { @@ -18,6 +18,7 @@ fn shared_fixture(dir: &Path) { std::fs::write(p, bytes).expect("write"); }; write("Cargo.toml", b"[workspace]\n"); + write("Cargo.lock", b"version = 4\n"); write("src/lib.rs", b"fn a() {}\n"); write("src/nested/b.rs", b"fn b() {\0}\n"); write("src/empty.rs", b""); @@ -26,6 +27,16 @@ fn shared_fixture(dir: &Path) { write("big-code-analysis-ast/Cargo.toml", b"[package]\n"); write("big-code-analysis-cli/Cargo.toml", b"[package]\n"); write("big-code-analysis-cli/build.rs", b"fn main() {}\n"); + write( + "big-code-analysis-cli/tests/smoke.rs", + b"// integration test, not compiled in\n", + ); + write("big-code-analysis-cli/pyproject.toml", b"[tool]\n"); + write( + "src/tests/mod.rs", + b"// a module named tests under src/ is source\n", + ); + write("src/.rs", b"// a pure dotfile has no extension\n"); write("tree-sitter-ccomment/src/parser.c", b"int p;\n"); write("tree-sitter-ccomment/target/junk.rs", b"skipped\n"); write( @@ -35,6 +46,7 @@ fn shared_fixture(dir: &Path) { write("tree-sitter-mozjs/src/scanner.c", b"int s;\n"); write("tree-sitter-preproc/src/node-types.json", b"[]\n"); write("tree-sitter-tcl/src/grammar.json", b"{}\n"); + write("tree-sitter-tcl/examples/x.c", b"int e;\n"); } #[test] @@ -44,19 +56,20 @@ fn shared_fixture_hashes_to_the_pinned_digest() { assert_eq!( input_files(dir.path()).expect("walk"), [ + "Cargo.lock", "Cargo.toml", "big-code-analysis-ast/Cargo.toml", "big-code-analysis-cli/Cargo.toml", "big-code-analysis-cli/build.rs", + "big-code-analysis-cli/pyproject.toml", "src/build/generated.rs", "src/empty.rs", "src/lib.rs", "src/nested/b.rs", + "src/tests/mod.rs", "tree-sitter-ccomment/src/parser.c", "tree-sitter-mozcpp/src/tree_sitter/parser.h", "tree-sitter-mozjs/src/scanner.c", - "tree-sitter-preproc/src/node-types.json", - "tree-sitter-tcl/src/grammar.json", ] ); assert_eq!(digest(dir.path()).expect("digest"), SHARED_FIXTURE_DIGEST); @@ -104,6 +117,21 @@ fn digest_is_independent_of_creation_order_and_moves_on_every_input_kind() { base, "a grammar's top-level target/ is not an input" ); + assert_eq!( + perturb("big-code-analysis-cli/tests/other.rs", b"x"), + base, + "a crate's integration tests are not compiled into bca" + ); + assert_eq!( + perturb("tree-sitter-tcl/src/node-types.json", b"[1]"), + base, + "grammar metadata is not compiled; the generated enum under src/ is" + ); + assert_ne!( + perturb("src/tests/other.rs", b"x"), + base, + "src/tests/ is a module of the root crate, not a test target" + ); } #[test] @@ -131,10 +159,11 @@ fn walk_refuses_a_symlinked_input() { #[test] fn input_roots_name_what_the_build_script_and_the_resolver_agree_on() { - // `Cargo.lock` is deliberately absent (cargo fingerprints it) and so - // is every runtime input; the resolver's copy of this list is - // checked against the same fixture, so this pins the Rust side. - assert!(!INPUT_ROOTS.contains(&"Cargo.lock")); + // The lockfile is in — the resolver bypasses cargo's fingerprint, so + // a dependency bump must move the digest — and every runtime input + // is out; the resolver's copy of this list is checked against the + // same fixture, so this pins the Rust side. + assert!(INPUT_ROOTS.contains(&"Cargo.lock")); assert!(!INPUT_ROOTS.contains(&"bca.toml")); assert!(INPUT_ROOTS.contains(&"big-code-analysis-cli")); } @@ -155,6 +184,39 @@ fn baked_digest_matches_a_fresh_walk_of_the_checkout() { } } +/// The shared fixture pins the two walkers to the rules it exercises; +/// this pins them to the rules the live tree exercises — a dotfile, an +/// extension neither fixture thought of, whatever lands next. A +/// disagreement is silent in production (the resolver just stops +/// taking the fast path), so it has to be loud here. Same shape as +/// `python_reader_agrees_with_the_compiled_tables` in the ast crate: +/// a missing `python3` is a failure, not a skip. +#[cfg(not(windows))] +#[test] +fn python_digest_agrees_with_the_rust_digest_over_this_checkout() { + let workspace = Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("the CLI crate sits one below the workspace root"); + let rust = match digest(workspace) { + Ok(digest) => digest, + Err(DigestError::MissingRoot(_)) => return, + Err(e) => panic!("walk failed: {e}"), + }; + let out = std::process::Command::new("python3") + .args(["-B", "utils/self_scan_digest.py"]) + .arg(workspace) + .current_dir(workspace) + .output() + .expect("python3 is on PATH: the self-scan resolver needs it, so this test does too"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let python = String::from_utf8(out.stdout).expect("digest is UTF-8"); + assert_eq!(python.trim(), rust); +} + #[test] fn long_version_starts_with_the_bare_version_and_carries_every_field() { let text = super::long_version(); @@ -174,7 +236,7 @@ fn long_version_starts_with_the_bare_version_and_carries_every_field() { && rest[2].ends_with(&format!("debug-assertions {expected})")), "{text}" ); - assert!(rest[3].starts_with("binary id: "), "{text}"); + assert!(rest[3].starts_with("build id: "), "{text}"); // The exact baked value, not a shape: the render could print any // 64-hex string and a shape check would never know. assert_eq!(rest[0], format!("build inputs: {}", super::BUILD_INPUTS)); diff --git a/big-code-analysis-cli/src/build_info/digest.rs b/big-code-analysis-cli/src/build_info/digest.rs index 15aee182a..48e993ec1 100644 --- a/big-code-analysis-cli/src/build_info/digest.rs +++ b/big-code-analysis-cli/src/build_info/digest.rs @@ -43,13 +43,15 @@ use sha2::{Digest, Sha256}; /// /// Whole crate directories rather than their `src/`, so each crate's /// `Cargo.toml` and build script are in; the root `Cargo.toml` for the -/// workspace pins and profiles. `Cargo.lock` is not listed — cargo -/// already treats it as a fingerprint input, and a lockfile that moves -/// without any source moving changes no metric. Runtime inputs -/// (`bca.toml`, `.bcaignore`, the baseline) are not here either: a +/// workspace pins and profiles; `Cargo.lock` because the resolver +/// compares digests *instead of* letting cargo fingerprint, and the +/// manifests carry ranged dependencies (`ignore`, `globset`, `regex`) +/// whose resolved version decides which files a walk sees. Runtime +/// inputs (`bca.toml`, `.bcaignore`, the baseline) are not here: a /// prebuilt binary reads the live copy of each. pub(crate) const INPUT_ROOTS: &[&str] = &[ "Cargo.toml", + "Cargo.lock", "src", "big-code-analysis-ast", "big-code-analysis-cli", @@ -63,14 +65,29 @@ pub(crate) const INPUT_ROOTS: &[&str] = &[ /// Extensions that are compile-time inputs. `src/` carries over a /// thousand tracked `.snap` files, and an `insta` accept would /// otherwise read as a code change; `.snap.new` is untracked but not -/// ignored, so a forced corpus run would too. -pub(crate) const INPUT_EXTENSIONS: &[&str] = &["rs", "c", "cc", "h", "toml", "json"]; +/// ignored, so a forced corpus run would too. A grammar's +/// `node-types.json` is `include_str!`ed into a constant nothing in +/// `bca` reaches — the `enums/` generator reads it, and the generated +/// enum under `src/` is what the metrics compile against — so `.json` +/// is out as well: its bytes cannot move a metric. +pub(crate) const INPUT_EXTENSIONS: &[&str] = &["rs", "c", "cc", "h", "toml"]; -/// Build output a vendored grammar crate accumulates beside its -/// sources. Matched only as a *direct* child of a `tree-sitter-*` root, -/// never as a path component anywhere, so a tracked -/// `src/build/generated.rs` under any other root is hashed. -pub(crate) const SKIPPED_TOP_LEVEL: &[&str] = &["target", "build", "node_modules"]; +/// Directories under a crate root that hold nothing the library or +/// the `bca` binary compiles: cargo's integration-test, benchmark and +/// example targets, and the build output a vendored grammar +/// accumulates beside its sources. Matched only as a *direct* child of +/// a root, never as a path component anywhere, so a tracked +/// `src/build/generated.rs` is hashed. Inline `#[cfg(test)]` modules +/// stay in — telling one apart needs the attribute, and they live +/// under `src/` beside the code they test. +pub(crate) const SKIPPED_TOP_LEVEL: &[&str] = &[ + "tests", + "benches", + "examples", + "target", + "build", + "node_modules", +]; /// Why a digest could not be taken. Every variant is a reason to report /// the inputs as unavailable rather than to certify a partial tree. @@ -116,8 +133,10 @@ pub(crate) fn input_files(workspace: &Path) -> Result, DigestError> if meta.is_file() { files.push((*root).to_owned()); } else { - let grammar = root.starts_with("tree-sitter-"); - collect_dir(workspace, &path, grammar, &mut files)?; + // `src/` is the workspace root crate's source directory, not a + // crate root: a `src/tests/` there would be a module. + let crate_root = root != &"src"; + collect_dir(workspace, &path, crate_root, &mut files)?; } } files.sort_unstable_by(|a, b| a.as_bytes().cmp(b.as_bytes())); @@ -134,7 +153,7 @@ enum Entry { fn collect_dir( workspace: &Path, dir: &Path, - grammar_top: bool, + crate_root: bool, out: &mut Vec, ) -> Result<(), DigestError> { let io = |e: std::io::Error| DigestError::Io(dir.to_path_buf(), e.to_string()); @@ -146,7 +165,7 @@ fn collect_dir( // the first error a deterministic one when two entries are bad. entries.sort_by_key(std::fs::DirEntry::file_name); for entry in entries { - match classify(workspace, &entry.path(), grammar_top)? { + match classify(workspace, &entry, crate_root)? { Entry::Descend(path) => collect_dir(workspace, &path, false, out)?, Entry::Input(rel) => out.push(rel), Entry::Ignore => {} @@ -155,22 +174,29 @@ fn collect_dir( Ok(()) } -fn classify(workspace: &Path, path: &Path, grammar_top: bool) -> Result { - let meta = std::fs::symlink_metadata(path) - .map_err(|e| DigestError::Io(path.to_path_buf(), e.to_string()))?; - if meta.is_symlink() { +/// `DirEntry::file_type` is the type `read_dir` already learned from +/// the directory itself — `d_type`, no second `stat` — and it never +/// follows a symlink, which is exactly the question asked here. +fn classify( + workspace: &Path, + entry: &std::fs::DirEntry, + crate_root: bool, +) -> Result { + let path = entry.path(); + let kind = entry + .file_type() + .map_err(|e| DigestError::Io(path.clone(), e.to_string()))?; + if kind.is_symlink() { return Err(DigestError::Symlink(PathBuf::from(relative_posix( - workspace, path, + workspace, &path, )?))); } - let skipped_artifact_dir = grammar_top - && path - .file_name() - .is_some_and(|n| SKIPPED_TOP_LEVEL.iter().any(|s| n == *s)); - Ok(if meta.is_dir() && !skipped_artifact_dir { - Entry::Descend(path.to_path_buf()) - } else if meta.is_file() && has_input_extension(path) { - Entry::Input(relative_posix(workspace, path)?) + let skipped_artifact_dir = + crate_root && SKIPPED_TOP_LEVEL.iter().any(|s| entry.file_name() == *s); + Ok(if kind.is_dir() && !skipped_artifact_dir { + Entry::Descend(path) + } else if kind.is_file() && has_input_extension(&path) { + Entry::Input(relative_posix(workspace, &path)?) } else { Entry::Ignore }) @@ -200,9 +226,15 @@ fn relative_posix(workspace: &Path, path: &Path) -> Result /// The build-inputs digest of `workspace` as 64 lowercase hex digits. pub(crate) fn digest(workspace: &Path) -> Result { + digest_of(workspace, &input_files(workspace)?) +} + +/// [`digest`] over an already-walked file list, for a caller that has +/// just registered that list with cargo and need not walk it twice. +pub(crate) fn digest_of(workspace: &Path, files: &[String]) -> Result { let mut hasher = Sha256::new(); - for rel in input_files(workspace)? { - let path = workspace.join(&rel); + for rel in files { + let path = workspace.join(rel); let content = std::fs::read(&path).map_err(|e| DigestError::Io(path.clone(), e.to_string()))?; hasher.update(rel.as_bytes()); diff --git a/big-code-analysis-cli/src/build_info/elf.rs b/big-code-analysis-cli/src/build_info/elf.rs index dcad57023..1870aa7fd 100644 --- a/big-code-analysis-cli/src/build_info/elf.rs +++ b/big-code-analysis-cli/src/build_info/elf.rs @@ -17,13 +17,6 @@ //! bytes actually read; arithmetic is `checked_*` throughout, so a //! malformed header cannot panic. -const ELF_MAGIC: &[u8; 4] = b"\x7fELF"; -const ELFCLASS64: u8 = 2; -const ELFDATA2LSB: u8 = 1; -const PT_NOTE: u32 = 4; -const NT_GNU_BUILD_ID: u32 = 3; -const GNU_NOTE_NAME: &[u8] = b"GNU\0"; - /// How much of the executable to read looking for the note. The /// program headers and every `PT_NOTE` segment the linker emits sit in /// the first page or so of a GNU-linked image (`PT_PHDR`, `PT_INTERP` @@ -32,130 +25,153 @@ const GNU_NOTE_NAME: &[u8] = b"GNU\0"; /// 140 MB binary into memory to answer `--version`. A note past the /// bound reads as absent, the documented answer for every shape the /// reader does not handle. +#[cfg(target_os = "linux")] const HEAD_BYTES: u64 = 64 * 1024; - -/// Lowercase hex of the running executable's GNU build-id, or `None`. #[cfg(target_os = "linux")] pub(crate) fn current_build_id() -> Option { use std::io::Read as _; let exe = std::env::current_exe().ok()?; - let mut head = Vec::new(); + let mut head = Vec::with_capacity(usize::try_from(HEAD_BYTES).unwrap_or(0)); std::fs::File::open(exe) .ok()? .take(HEAD_BYTES) .read_to_end(&mut head) .ok()?; - build_id(&head).map(hex_lower) -} - -/// Lowercase hex, two digits per byte. -pub(crate) fn hex_lower(bytes: &[u8]) -> String { - const DIGITS: &[u8; 16] = b"0123456789abcdef"; - let mut out = String::with_capacity(bytes.len() * 2); - for b in bytes { - out.push(DIGITS[usize::from(b >> 4)] as char); - out.push(DIGITS[usize::from(b & 0x0f)] as char); - } - out + reader::build_id(&head).map(reader::hex_lower) } +/// Lowercase hex of the running executable's GNU build-id, or `None` — +/// always `None` off Linux, where the executable is not ELF. #[cfg(not(target_os = "linux"))] pub(crate) fn current_build_id() -> Option { None } -/// The raw `NT_GNU_BUILD_ID` descriptor in `elf`, or `None` when the -/// bytes are not a little-endian ELF64 image carrying one. -pub(crate) fn build_id(elf: &[u8]) -> Option<&[u8]> { - let header = Header::parse(elf)?; - (0..header.phnum) - .filter_map(|i| header.program_header(elf, i)) - .filter(|ph| ph.kind == PT_NOTE) - .find_map(|ph| find_gnu_build_id(elf.get(ph.offset..ph.offset.checked_add(ph.size)?)?)) -} +#[cfg(test)] +pub(crate) use reader::{build_id, hex_lower}; + +/// The parser itself. Compiled only where it has a caller — Linux, and +/// the test build on every platform, where the synthetic fixtures +/// exercise it — so a macOS or Windows release build under +/// `-D warnings` carries no dead code. +#[cfg(any(target_os = "linux", test))] +mod reader { + /// Lowercase hex, two digits per byte. + pub(crate) fn hex_lower(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(bytes.len() * 2); + for b in bytes { + out.push(DIGITS[usize::from(b >> 4)] as char); + out.push(DIGITS[usize::from(b & 0x0f)] as char); + } + out + } -struct Header { - phoff: usize, - phentsize: usize, - phnum: usize, -} + const ELF_MAGIC: &[u8; 4] = b"\x7fELF"; + const ELFCLASS64: u8 = 2; + const ELFDATA2LSB: u8 = 1; + const PT_NOTE: u32 = 4; + const NT_GNU_BUILD_ID: u32 = 3; + const GNU_NOTE_NAME: &[u8] = b"GNU\0"; + + /// The raw `NT_GNU_BUILD_ID` descriptor in `elf`, or `None` when the + /// bytes are not a little-endian ELF64 image carrying one. + pub(crate) fn build_id(elf: &[u8]) -> Option<&[u8]> { + let header = Header::parse(elf)?; + (0..header.phnum) + .filter_map(|i| header.program_header(elf, i)) + .filter(|ph| ph.kind == PT_NOTE) + .find_map(|ph| find_gnu_build_id(elf.get(ph.offset..ph.offset.checked_add(ph.size)?)?)) + } -struct ProgramHeader { - kind: u32, - offset: usize, - size: usize, -} + struct Header { + phoff: usize, + phentsize: usize, + phnum: usize, + } -impl Header { - fn parse(elf: &[u8]) -> Option { - // bca: suppress(nexits) — every exit is a `?` on a bounds-checked - // read; a binary-format reader that fails closed is clearest as - // one straight line of them, not as nested `if let`s. - if elf.get(..4)? != ELF_MAGIC || *elf.get(4)? != ELFCLASS64 || *elf.get(5)? != ELFDATA2LSB { - return None; - } - Some(Self { - phoff: usize::try_from(u64_at(elf, 0x20)?).ok()?, - phentsize: usize::from(u16_at(elf, 0x36)?), - phnum: usize::from(u16_at(elf, 0x38)?), - }) + struct ProgramHeader { + kind: u32, + offset: usize, + size: usize, } - fn program_header(&self, elf: &[u8], index: usize) -> Option { - // bca: suppress(nexits) — same shape as `parse`: `?` on checked - // arithmetic and bounded reads. - let at = self.phoff.checked_add(index.checked_mul(self.phentsize)?)?; - Some(ProgramHeader { - kind: u32_at(elf, at)?, - offset: usize::try_from(u64_at(elf, at.checked_add(0x08)?)?).ok()?, - size: usize::try_from(u64_at(elf, at.checked_add(0x20)?)?).ok()?, - }) + impl Header { + fn parse(elf: &[u8]) -> Option { + // bca: suppress(nexits) — every exit is a `?` on a bounds-checked + // read; a binary-format reader that fails closed is clearest as + // one straight line of them, not as nested `if let`s. + if elf.get(..4)? != ELF_MAGIC + || *elf.get(4)? != ELFCLASS64 + || *elf.get(5)? != ELFDATA2LSB + { + return None; + } + Some(Self { + phoff: usize::try_from(u64_at(elf, 0x20)?).ok()?, + phentsize: usize::from(u16_at(elf, 0x36)?), + phnum: usize::from(u16_at(elf, 0x38)?), + }) + } + + fn program_header(&self, elf: &[u8], index: usize) -> Option { + // bca: suppress(nexits) — same shape as `parse`: `?` on checked + // arithmetic and bounded reads. + let at = self.phoff.checked_add(index.checked_mul(self.phentsize)?)?; + Some(ProgramHeader { + kind: u32_at(elf, at)?, + offset: usize::try_from(u64_at(elf, at.checked_add(0x08)?)?).ok()?, + size: usize::try_from(u64_at(elf, at.checked_add(0x20)?)?).ok()?, + }) + } } -} -/// Walk the notes in one `PT_NOTE` segment. Each is a 12-byte header -/// (`namesz`, `descsz`, `type`) followed by the name and the -/// descriptor, each padded to four bytes. -fn find_gnu_build_id(segment: &[u8]) -> Option<&[u8]> { - // bca: suppress(nexits) — the note walk fails closed through `?` on - // every read and every `checked_add`; that is the whole safety - // argument of the module, and it reads best uninterrupted. - let mut at = 0usize; - while let Some(namesz) = u32_at(segment, at) { - let descsz = usize::try_from(u32_at(segment, at + 4)?).ok()?; - let kind = u32_at(segment, at + 8)?; - let namesz = usize::try_from(namesz).ok()?; - let name_at = at.checked_add(12)?; - let desc_at = name_at.checked_add(align4(namesz)?)?; - let next = desc_at.checked_add(align4(descsz)?)?; - if kind == NT_GNU_BUILD_ID - && segment.get(name_at..name_at.checked_add(namesz)?)? == GNU_NOTE_NAME - { - return segment.get(desc_at..desc_at.checked_add(descsz)?); + /// Walk the notes in one `PT_NOTE` segment. Each is a 12-byte header + /// (`namesz`, `descsz`, `type`) followed by the name and the + /// descriptor, each padded to four bytes. + fn find_gnu_build_id(segment: &[u8]) -> Option<&[u8]> { + // bca: suppress(nexits) — the note walk fails closed through `?` on + // every read and every `checked_add`; that is the whole safety + // argument of the module, and it reads best uninterrupted. + let mut at = 0usize; + while let Some(namesz) = u32_at(segment, at) { + // `u32_at(segment, at)` succeeded, so `at + 8 <= len`: these + // two plain additions cannot overflow. + let descsz = usize::try_from(u32_at(segment, at + 4)?).ok()?; + let kind = u32_at(segment, at + 8)?; + let namesz = usize::try_from(namesz).ok()?; + let name_at = at.checked_add(12)?; + let desc_at = name_at.checked_add(align4(namesz)?)?; + let next = desc_at.checked_add(align4(descsz)?)?; + if kind == NT_GNU_BUILD_ID + && segment.get(name_at..name_at.checked_add(namesz)?)? == GNU_NOTE_NAME + { + return segment.get(desc_at..desc_at.checked_add(descsz)?); + } + at = next; } - at = next; + None } - None -} -fn align4(n: usize) -> Option { - n.checked_add(3).map(|v| v & !3) -} + fn align4(n: usize) -> Option { + n.checked_add(3).map(|v| v & !3) + } -/// `N` little-endian bytes at `at`, or `None` past the end or on an -/// overflowing offset. One reader for the three widths below. -fn le_at(bytes: &[u8], at: usize) -> Option<&[u8; N]> { - bytes.get(at..at.checked_add(N)?)?.as_array() -} + /// `N` little-endian bytes at `at`, or `None` past the end or on an + /// overflowing offset. One reader for the three widths below. + fn le_at(bytes: &[u8], at: usize) -> Option<&[u8; N]> { + bytes.get(at..at.checked_add(N)?)?.as_array() + } -fn u16_at(bytes: &[u8], at: usize) -> Option { - le_at(bytes, at).copied().map(u16::from_le_bytes) -} + fn u16_at(bytes: &[u8], at: usize) -> Option { + le_at(bytes, at).copied().map(u16::from_le_bytes) + } -fn u32_at(bytes: &[u8], at: usize) -> Option { - le_at(bytes, at).copied().map(u32::from_le_bytes) -} + fn u32_at(bytes: &[u8], at: usize) -> Option { + le_at(bytes, at).copied().map(u32::from_le_bytes) + } -fn u64_at(bytes: &[u8], at: usize) -> Option { - le_at(bytes, at).copied().map(u64::from_le_bytes) + fn u64_at(bytes: &[u8], at: usize) -> Option { + le_at(bytes, at).copied().map(u64::from_le_bytes) + } } diff --git a/big-code-analysis-cli/src/build_info/mod.rs b/big-code-analysis-cli/src/build_info/mod.rs index 2520df47f..ff5130617 100644 --- a/big-code-analysis-cli/src/build_info/mod.rs +++ b/big-code-analysis-cli/src/build_info/mod.rs @@ -13,29 +13,49 @@ pub(crate) mod elf; #[cfg(test)] -#[path = "digest.rs"] pub(crate) mod digest; #[cfg(test)] #[path = "build_info_tests.rs"] mod tests; +/// What `build.rs` writes for a field it could not determine. The +/// `--version` text prints the word; every machine-readable consumer +/// reads the field through [`build_inputs`] / [`build_git`], which map +/// it to `None` once, so a crates.io `bca` stamps no digest into SARIF +/// and prints no `(build …)` in a footer rather than the literal word. +const UNAVAILABLE: &str = "unavailable"; + /// The content digest of everything compiled into this binary, or -/// `unavailable` for a build from a registry tarball, where the -/// workspace roots do not exist beside the crate. +/// [`UNAVAILABLE`] for a build from a registry tarball, where the +/// workspace roots do not exist beside the crate. The `--version` +/// spelling; see [`build_inputs`] for the value. pub(crate) const BUILD_INPUTS: &str = env!("BCA_BUILD_INPUTS"); /// `` or `-dirty` for the checkout the binary was built from, -/// or `unavailable`. -pub(crate) const BUILD_GIT: &str = env!("BCA_BUILD_GIT"); - -/// RFC 3339 UTC; `SOURCE_DATE_EPOCH` when it was set at build time. -pub(crate) const BUILD_TIME: &str = env!("BCA_BUILD_TIME"); +/// or [`UNAVAILABLE`]. The `--version` spelling; see [`build_git`]. +const BUILD_GIT: &str = env!("BCA_BUILD_GIT"); +const BUILD_TIME: &str = env!("BCA_BUILD_TIME"); const BUILD_RUSTC: &str = env!("BCA_BUILD_RUSTC"); const BUILD_TARGET: &str = env!("BCA_BUILD_TARGET"); const BUILD_PROFILE: &str = env!("BCA_BUILD_PROFILE"); +fn known(field: &'static str) -> Option<&'static str> { + (field != UNAVAILABLE).then_some(field) +} + +/// The build-inputs digest, or `None` when the binary was not built +/// from a workspace checkout. +pub(crate) fn build_inputs() -> Option<&'static str> { + known(BUILD_INPUTS) +} + +/// The build revision, or `None` outside a git checkout. +pub(crate) fn build_git() -> Option<&'static str> { + known(BUILD_GIT) +} + /// The lines clap prints after `bca ` for `--version`. The /// first line stays clap's own, so `-V` and the first line of /// `--version` are the one-line form every existing consumer parses. @@ -49,7 +69,7 @@ pub(crate) fn long_version() -> String { format!( "{}\nbuild inputs: {BUILD_INPUTS}\ngit: {BUILD_GIT}\nbuilt: {BUILD_TIME} \ (profile {BUILD_PROFILE}, {BUILD_RUSTC}, {BUILD_TARGET}, debug-assertions \ - {assertions})\nbinary id: {binary_id}", + {assertions})\nbuild id: {binary_id}", env!("CARGO_PKG_VERSION"), ) } diff --git a/big-code-analysis-cli/src/check_format.rs b/big-code-analysis-cli/src/check_format.rs index 9d67e3bed..f0130076b 100644 --- a/big-code-analysis-cli/src/check_format.rs +++ b/big-code-analysis-cli/src/check_format.rs @@ -136,13 +136,18 @@ pub(crate) fn dump_sarif_with_suppressed( /// What this binary stamps into `tool.driver.properties` (#1773): the /// digest of everything compiled into it and the revision it was built /// from, so a SARIF upload traces to a build rather than to a version -/// that 92 unreleased commits can share. A registry build carries -/// `unavailable` for both, which is itself the information. +/// that 92 unreleased commits can share. A registry build knows +/// neither and stamps nothing — an absent property, not a sentinel a +/// consumer comparing digests would read as a value. fn sarif_provenance() -> SarifProvenance { - SarifProvenance::new( - Some(crate::build_info::BUILD_INPUTS.to_owned()), - Some(crate::build_info::BUILD_GIT.to_owned()), - ) + let mut provenance = SarifProvenance::default(); + if let Some(digest) = crate::build_info::build_inputs() { + provenance = provenance.with_build_inputs(digest); + } + if let Some(revision) = crate::build_info::build_git() { + provenance = provenance.with_build_git(revision); + } + provenance } /// Default annotation cap per metric. GitHub Actions surfaces at most diff --git a/big-code-analysis-cli/src/commands.rs b/big-code-analysis-cli/src/commands.rs index 33e227007..587469822 100644 --- a/big-code-analysis-cli/src/commands.rs +++ b/big-code-analysis-cli/src/commands.rs @@ -237,8 +237,13 @@ fn parse_cli_with_legacy_hint() -> (Cli, bool) { // `Command` that actually parses, and not in the derive: `xtask` // renders man pages from a bare `Cli::command()`, and a derive-level // `long_version` would stamp this build's digest into `man/bca.1` - // (#1773). `-V` keeps clap's one-line `version`. - let command = Cli::command().long_version(crate::build_info::long_version()); + // (#1773). `-V` keeps clap's one-line `version`. Rendering reads the + // executable's own header for the build-id, so it is done only when + // `--version` is on the command line rather than on every run. + let mut command = Cli::command(); + if std::env::args_os().any(|arg| arg == "--version") { + command = command.long_version(crate::build_info::long_version()); + } let matches = match command.try_get_matches() { Ok(matches) => matches, Err(err) => { diff --git a/big-code-analysis-cli/src/commands/report.rs b/big-code-analysis-cli/src/commands/report.rs index 24dfbf897..fdf1ab041 100644 --- a/big-code-analysis-cli/src/commands/report.rs +++ b/big-code-analysis-cli/src/commands/report.rs @@ -66,7 +66,7 @@ pub(crate) fn run_command_report( let date = crate::provenance::resolved_date(); let prov = crate::provenance::Provenance { version: env!("CARGO_PKG_VERSION"), - build: Some(crate::build_info::BUILD_INPUTS), + build: crate::build_info::build_inputs(), date: &date, paths: &prov_paths, top, diff --git a/big-code-analysis-cli/src/provenance.rs b/big-code-analysis-cli/src/provenance.rs index 67a45c00e..9700db037 100644 --- a/big-code-analysis-cli/src/provenance.rs +++ b/big-code-analysis-cli/src/provenance.rs @@ -40,8 +40,8 @@ pub(crate) struct Provenance<'a> { /// `bca` package version (`CARGO_PKG_VERSION`). pub(crate) version: &'a str, /// The build-inputs digest of the `bca` that wrote the report - /// (`build_info::BUILD_INPUTS`, #1773), or `None` to omit it. Hex or - /// the word `unavailable`, so it needs no per-format escaping. + /// (`build_info::build_inputs`, #1773), or `None` to omit it — which + /// a crates.io build does. Hex, so it needs no per-format escaping. pub(crate) build: Option<&'a str>, /// `YYYY-MM-DD` generation date (UTC), already resolved (see /// [`resolved_date`]). @@ -208,11 +208,11 @@ mod tests { push_markdown_footer( &mut short, &Provenance { - build: Some("unavailable"), + build: Some("abc"), ..prov(20, SuppressionPolicy::Honor) }, ); - assert!(short.contains("(build unavailable)"), "{short}"); + assert!(short.contains("(build abc)"), "{short}"); } #[test] diff --git a/big-code-analysis-cli/tests/check/check_exit_codes.rs b/big-code-analysis-cli/tests/check/check_exit_codes.rs index 166054938..bf175457a 100644 --- a/big-code-analysis-cli/tests/check/check_exit_codes.rs +++ b/big-code-analysis-cli/tests/check/check_exit_codes.rs @@ -569,7 +569,7 @@ fn version_exits_zero() { /// opens with that same line and then the provenance block (#1773). #[test] fn short_version_is_one_line_and_long_version_starts_with_it() { - let (dir, mut short) = common::cli_hermetic(); + let (_dir, mut short) = common::cli_hermetic(); let short_out = short .arg("-V") .assert() @@ -585,7 +585,6 @@ fn short_version_is_one_line_and_long_version_starts_with_it() { ); let (_dir2, mut long) = common::cli_hermetic(); - let _ = &dir; let long_out = long .arg("--version") .assert() @@ -604,7 +603,7 @@ fn short_version_is_one_line_and_long_version_starts_with_it() { for (line, prefix) in lines[1..] .iter() - .zip(["build inputs: ", "git: ", "built: ", "binary id: "]) + .zip(["build inputs: ", "git: ", "built: ", "build id: "]) { assert!( line.starts_with(prefix), diff --git a/big-code-analysis-cli/tests/output/format_smoke.rs b/big-code-analysis-cli/tests/output/format_smoke.rs index b4e78cc82..026f52a54 100644 --- a/big-code-analysis-cli/tests/output/format_smoke.rs +++ b/big-code-analysis-cli/tests/output/format_smoke.rs @@ -174,9 +174,20 @@ fn cli_check_sarif_output_validates_against_schema() { .unwrap_or_else(|| panic!("{prefix} missing from --version:\n{version}")) .to_owned() }; + // `--version` spells an unknown field `unavailable`; the property + // bag omits it instead, so a consumer never reads the word as a + // digest. An integration test runs from a checkout, so both are + // present here, and the branch below is the registry build's. let props = &doc["runs"][0]["tool"]["driver"]["properties"]; - assert_eq!(props["bca.buildInputs"], field("build inputs: ")); - assert_eq!(props["bca.buildGit"], field("git: ")); + for (key, line) in [ + ("bca.buildInputs", "build inputs: "), + ("bca.buildGit", "git: "), + ] { + match field(line).as_str() { + "unavailable" => assert!(props.get(key).is_none(), "{out}"), + value => assert_eq!(props[key], value, "{out}"), + } + } } #[test] diff --git a/docs/development/baseline_freshness.md b/docs/development/baseline_freshness.md index e50058e7e..7e802bdae 100644 --- a/docs/development/baseline_freshness.md +++ b/docs/development/baseline_freshness.md @@ -102,16 +102,18 @@ table, the recipe's two commands are simple to run by hand: ```bash t=$(mktemp .bca-baseline.XXXXXX.toml) +trap 'rm -f "$t"' EXIT cargo run --quiet -p big-code-analysis-cli -- \ check --tier=soft=0.95 --write-baseline "$t" cargo run --quiet -p big-code-analysis-cli -- \ diff-baseline .bca-baseline.toml "$t" --format markdown -rm -f "$t" ``` -Both build the dev-profile binary, a few seconds warm; the job itself -installs a release binary and hands it to the recipe through -`BCA_SELF_SCAN_BINARY`, which the target honours too. +Those two bare `cargo run` lines always build the dev-profile binary, +a few seconds warm. The `make` target goes through the self-scan +wrapper instead, so it honours `BCA_SELF_SCAN_BINARY` — which is how +the job itself runs it, against the release binary it has just +installed. Always the `-headroom` target, never the bare `self-scan-write-baseline`. The committed file carries diff --git a/src/output/sarif.rs b/src/output/sarif.rs index 085846164..5d6dee59a 100644 --- a/src/output/sarif.rs +++ b/src/output/sarif.rs @@ -190,25 +190,37 @@ pub fn write_sarif_with_suppressed( /// content digest of everything compiled into it and `build_git` to the /// checkout revision (#1773). `Default` carries nothing, and a default /// provenance leaves the document byte-identical to [`write_sarif`]'s. +/// +/// The shape is `MetricsOptions`'s: `#[non_exhaustive]`, private fields, +/// `Default` plus `with_*` setters, so a later field is additive. These +/// are facts about the *tool's* build, not about the scanned repository +/// — which is why they sit here and not in SARIF's +/// `run.versionControlProvenance`, even though in a self-scan the two +/// revisions coincide. Run-level metadata a host wants to add later +/// (invocation, timestamps) belongs on this struct, never as a further +/// writer parameter. #[derive(Debug, Default, Clone, PartialEq, Eq)] #[non_exhaustive] pub struct SarifProvenance { - /// A content digest of the inputs compiled into the reporting - /// binary; rendered as the `bca.buildInputs` property. - pub build_inputs: Option, - /// The revision the reporting binary was built from; rendered as - /// the `bca.buildGit` property. - pub build_git: Option, + build_inputs: Option, + build_git: Option, } impl SarifProvenance { - /// Provenance carrying the two fields `bca` stamps. + /// Record a content digest of the inputs compiled into the reporting + /// binary; rendered as the `bca.buildInputs` property. #[must_use] - pub fn new(build_inputs: Option, build_git: Option) -> Self { - Self { - build_inputs, - build_git, - } + pub fn with_build_inputs(mut self, digest: impl Into) -> Self { + self.build_inputs = Some(digest.into()); + self + } + + /// Record the revision the reporting binary was built from; rendered + /// as the `bca.buildGit` property. + #[must_use] + pub fn with_build_git(mut self, revision: impl Into) -> Self { + self.build_git = Some(revision.into()); + self } fn is_empty(&self) -> bool { @@ -560,7 +572,9 @@ mod tests { #[test] fn provenance_lands_under_driver_properties_and_an_empty_one_adds_no_key() { let offenders = vec![rec("src/foo.rs", "cyclomatic", 17.0, 15.0)]; - let stamped = SarifProvenance::new(Some("ab".repeat(32)), Some("deadbeef-dirty".into())); + let stamped = SarifProvenance::default() + .with_build_inputs("ab".repeat(32)) + .with_build_git("deadbeef-dirty"); let mut buf = Vec::new(); write_sarif_with_provenance(&offenders, &[], &[], &stamped, &mut buf) .expect("writing to Vec is infallible"); @@ -596,7 +610,7 @@ mod tests { // Half-populated: only the present field is written. let mut half = Vec::new(); - let git_only = SarifProvenance::new(None, Some("deadbeef".into())); + let git_only = SarifProvenance::default().with_build_git("deadbeef"); write_sarif_with_provenance(&offenders, &[], &[], &git_only, &mut half) .expect("writing to Vec is infallible"); let v: serde_json::Value = serde_json::from_slice(&half).expect("valid JSON"); diff --git a/tree-sitter-ccomment/bindings/rust/build.rs b/tree-sitter-ccomment/bindings/rust/build.rs index 1fc5d882a..153c8bd3c 100644 --- a/tree-sitter-ccomment/bindings/rust/build.rs +++ b/tree-sitter-ccomment/bindings/rust/build.rs @@ -12,9 +12,7 @@ fn main() { // binary advertising a tree it did not compile. if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { for entry in entries.flatten() { - if let Some(path) = entry.path().to_str() { - println!("cargo:rerun-if-changed={path}"); - } + println!("cargo:rerun-if-changed={}", entry.path().display()); } } diff --git a/tree-sitter-mozcpp/bindings/rust/build.rs b/tree-sitter-mozcpp/bindings/rust/build.rs index f07447cfd..5386cbb12 100644 --- a/tree-sitter-mozcpp/bindings/rust/build.rs +++ b/tree-sitter-mozcpp/bindings/rust/build.rs @@ -8,9 +8,7 @@ fn main() { // binary advertising a tree it did not compile. if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { for entry in entries.flatten() { - if let Some(path) = entry.path().to_str() { - println!("cargo:rerun-if-changed={path}"); - } + println!("cargo:rerun-if-changed={}", entry.path().display()); } } diff --git a/tree-sitter-mozjs/bindings/rust/build.rs b/tree-sitter-mozjs/bindings/rust/build.rs index bc0ed2af8..e09881fa1 100644 --- a/tree-sitter-mozjs/bindings/rust/build.rs +++ b/tree-sitter-mozjs/bindings/rust/build.rs @@ -8,9 +8,7 @@ fn main() { // binary advertising a tree it did not compile. if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { for entry in entries.flatten() { - if let Some(path) = entry.path().to_str() { - println!("cargo:rerun-if-changed={path}"); - } + println!("cargo:rerun-if-changed={}", entry.path().display()); } } diff --git a/tree-sitter-preproc/bindings/rust/build.rs b/tree-sitter-preproc/bindings/rust/build.rs index 1fc5d882a..153c8bd3c 100644 --- a/tree-sitter-preproc/bindings/rust/build.rs +++ b/tree-sitter-preproc/bindings/rust/build.rs @@ -12,9 +12,7 @@ fn main() { // binary advertising a tree it did not compile. if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { for entry in entries.flatten() { - if let Some(path) = entry.path().to_str() { - println!("cargo:rerun-if-changed={path}"); - } + println!("cargo:rerun-if-changed={}", entry.path().display()); } } diff --git a/tree-sitter-tcl/bindings/rust/build.rs b/tree-sitter-tcl/bindings/rust/build.rs index 9deab1bc7..e6e32ab08 100644 --- a/tree-sitter-tcl/bindings/rust/build.rs +++ b/tree-sitter-tcl/bindings/rust/build.rs @@ -8,9 +8,7 @@ fn main() { // binary advertising a tree it did not compile. if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { for entry in entries.flatten() { - if let Some(path) = entry.path().to_str() { - println!("cargo:rerun-if-changed={path}"); - } + println!("cargo:rerun-if-changed={}", entry.path().display()); } } diff --git a/utils/check-role-coverage.py b/utils/check-role-coverage.py index b8170fb20..48f600cdb 100755 --- a/utils/check-role-coverage.py +++ b/utils/check-role-coverage.py @@ -365,6 +365,9 @@ class Observation: seen: dict[str, set[int]] +OBSERVER_LINE_RE = re.compile(r"bca \S+") + + def observer_line(version_stdout: str) -> str: """The one-line `bca X.Y.Z` for the `observer` header, from `bca -V` output. @@ -380,9 +383,6 @@ def observer_line(version_stdout: str) -> str: return first -OBSERVER_LINE_RE = re.compile(r"bca \S+") - - def load_observed(path: pathlib.Path) -> Observation: obs = Observation({}, {}, {}, {}, {}) lang = None diff --git a/utils/self-scan-bca-test.py b/utils/self-scan-bca-test.py index c32a39b08..b45f0e7b9 100644 --- a/utils/self-scan-bca-test.py +++ b/utils/self-scan-bca-test.py @@ -24,6 +24,7 @@ from __future__ import annotations +import os import pathlib import shutil import subprocess @@ -42,6 +43,7 @@ # and the hex it pins as `SHARED_FIXTURE_DIGEST`. SHARED_FIXTURE = { "Cargo.toml": b"[workspace]\n", + "Cargo.lock": b"version = 4\n", "src/lib.rs": b"fn a() {}\n", "src/nested/b.rs": b"fn b() {\0}\n", "src/empty.rs": b"", @@ -50,28 +52,34 @@ "big-code-analysis-ast/Cargo.toml": b"[package]\n", "big-code-analysis-cli/Cargo.toml": b"[package]\n", "big-code-analysis-cli/build.rs": b"fn main() {}\n", + "big-code-analysis-cli/tests/smoke.rs": b"// integration test, not compiled in\n", + "big-code-analysis-cli/pyproject.toml": b"[tool]\n", + "src/tests/mod.rs": b"// a module named tests under src/ is source\n", + "src/.rs": b"// a pure dotfile has no extension\n", "tree-sitter-ccomment/src/parser.c": b"int p;\n", "tree-sitter-ccomment/target/junk.rs": b"skipped\n", "tree-sitter-mozcpp/src/tree_sitter/parser.h": b"#define X\n", "tree-sitter-mozjs/src/scanner.c": b"int s;\n", "tree-sitter-preproc/src/node-types.json": b"[]\n", "tree-sitter-tcl/src/grammar.json": b"{}\n", + "tree-sitter-tcl/examples/x.c": b"int e;\n", } -SHARED_FIXTURE_DIGEST = "564b792dc7b3e4fca571038d165a8d89ca9069bccc956ea4af0413c572345299" +SHARED_FIXTURE_DIGEST = "2d6dfcc20156bfc6bcd2bc38ab2cdff68cc864b1a4b6951b891cffc40508a17e" SHARED_FIXTURE_FILES = [ + "Cargo.lock", "Cargo.toml", "big-code-analysis-ast/Cargo.toml", "big-code-analysis-cli/Cargo.toml", "big-code-analysis-cli/build.rs", + "big-code-analysis-cli/pyproject.toml", "src/build/generated.rs", "src/empty.rs", "src/lib.rs", "src/nested/b.rs", + "src/tests/mod.rs", "tree-sitter-ccomment/src/parser.c", "tree-sitter-mozcpp/src/tree_sitter/parser.h", "tree-sitter-mozjs/src/scanner.c", - "tree-sitter-preproc/src/node-types.json", - "tree-sitter-tcl/src/grammar.json", ] @@ -103,6 +111,13 @@ def with_extra(rel: str, content: bytes) -> str: self.assertNotEqual(with_extra("src/lib2.rs", b"fn a() {}\n"), SHARED_FIXTURE_DIGEST) self.assertEqual(with_extra("src/snapshots/y.snap", b"more"), SHARED_FIXTURE_DIGEST) self.assertEqual(with_extra("tree-sitter-tcl/target/out.rs", b"x"), SHARED_FIXTURE_DIGEST) + self.assertEqual( + with_extra("big-code-analysis-cli/tests/o.rs", b"x"), SHARED_FIXTURE_DIGEST + ) + self.assertEqual( + with_extra("tree-sitter-tcl/src/node-types.json", b"1"), SHARED_FIXTURE_DIGEST + ) + self.assertNotEqual(with_extra("src/tests/other.rs", b"x"), SHARED_FIXTURE_DIGEST) def test_a_missing_root_or_a_symlink_refuses_the_tree(self) -> None: with tempfile.TemporaryDirectory() as tmp: @@ -230,6 +245,13 @@ def test_explicit_binary_is_trusted_and_a_relative_path_is_anchored_to_the_calle self.assertEqual(self.chosen(result), [str(other), "check"]) relative = self.run_wrapper("check", env={"BCA_SELF_SCAN_BINARY": "bin/other-bca"}) self.assertEqual(self.chosen(relative), [str(other.resolve()), "check"]) + # `./x` has a separator but `Path("./x").parent == Path()`; the + # anchoring keys on the separator, so this resolves too. The + # fake sits in the invoking directory for exactly this case. + here = self.fake_bca("0" * 64, name="here-bca") + here = here.rename(self.root / "here-bca") + dot = self.run_wrapper("check", env={"BCA_SELF_SCAN_BINARY": "./here-bca"}) + self.assertEqual(self.chosen(dot), [str(here.resolve()), "check"]) bare = self.run_wrapper("check", env={"BCA_SELF_SCAN_BINARY": "other-bca"}) self.assertEqual(self.chosen(bare), ["other-bca", "check"]) empty = self.run_wrapper("check", env={"BCA_SELF_SCAN_BINARY": ""}) @@ -250,6 +272,45 @@ def test_a_tree_that_cannot_be_digested_falls_back(self) -> None: self.assertEqual(self.chosen(result), [*self.CARGO_DEV, "check"]) self.assertIn("cannot be digested", result.stderr) + def test_relative_paths_still_resolve_after_the_wrapper_changes_directory(self) -> None: + # Both `which` on a relative PATH entry and an explicit `./bca` + # name the binary relative to the *invoking* directory, and + # `main` chdirs to the workspace before exec. Launched for real: + # a dry run cannot see the chdir. + self.fake_bca(SHARED_FIXTURE_DIGEST, exit_code=7) + shutil.copy(self.bin / "bca", self.root / "bca") + for env in ( + {"PATH": "bin"}, + {"PATH": str(self.bin), "BCA_SELF_SCAN_BINARY": "./bca"}, + ): + result = self.run_wrapper("check", env=env, dry_run=False) + self.assertEqual(result.returncode, 7, result.stderr) + self.assertEqual(self.record.read_text().splitlines()[1:], ["check"]) + + def test_a_lockfile_only_change_rejects_the_installed_binary(self) -> None: + # The resolver compares digests instead of letting cargo + # fingerprint, so a dependency bump with no source edit must + # still move the digest: ranged dependencies decide which files + # a walk sees. + self.fake_bca(SHARED_FIXTURE_DIGEST) + self.assertEqual(self.chosen(self.run_wrapper("check"))[0], str(self.bin / "bca")) + (self.workspace / "Cargo.lock").write_bytes(b"version = 4\n[[package]]\n") + result = self.run_wrapper("check") + self.assertEqual(self.chosen(result), [*self.CARGO_DEV, "check"]) + self.assertIn("built from other inputs", result.stderr) + + @unittest.skipIf(getattr(os, "geteuid", lambda: -1)() == 0, "root reads unreadable files") + def test_an_unreadable_input_falls_back_instead_of_crashing(self) -> None: + self.fake_bca(SHARED_FIXTURE_DIGEST) + locked = self.workspace / "src/lib.rs" + locked.chmod(0o000) + try: + result = self.run_wrapper("check") + finally: + locked.chmod(0o644) + self.assertEqual(self.chosen(result), [*self.CARGO_DEV, "check"]) + self.assertIn("cannot be digested", result.stderr) + def test_launched_binary_receives_the_arguments_and_its_status_and_pid_are_the_wrappers( self, ) -> None: diff --git a/utils/self-scan-bca.py b/utils/self-scan-bca.py index 461940b48..b6c851b73 100755 --- a/utils/self-scan-bca.py +++ b/utils/self-scan-bca.py @@ -27,11 +27,17 @@ `--paths-from -` — are the child's own; on Windows it runs as a child and its status is relayed, a signal death mapped to `128 + N`. -What this does not do: hash the executable, or verify its self-report. -A binary that prints a digest it was not built from is trusted exactly -as the `cargo install`ed one in CI is. And a disagreement between the -two digest implementations only ever costs the fast path — the resolver -falls back to building — never a wrong binary. +The digest is recomputed here, in Python, rather than asked of a `bca`: +the verifier has to be independent of the thing verified. A candidate +with a walker bug — a root it is blind to — would bake and recompute +the same wrong answer and certify itself after an edit it cannot see; +cargo's own fingerprint is out of reach by construction, since +bypassing `cargo run` is the point. What this does not do: hash the +executable, or verify its self-report. A binary that prints a digest +it was not built from is trusted exactly as the `cargo install`ed one +in CI is. And a disagreement between the two digest implementations +only ever costs the fast path — the resolver falls back to building — +never a wrong binary. """ from __future__ import annotations @@ -89,13 +95,24 @@ def cargo_command(profile: str) -> list[str]: return [*CARGO_RUN, *flag, "-p", "big-code-analysis-cli", "--"] +def anchor_to_caller(explicit: str) -> str: + """An explicit binary as `exec` must see it after `main`'s `chdir`. + + A value spelling a directory — `./bca`, `bin/bca`, `../x/bca` — is + anchored to the invoking directory now, so it means what the + caller's shell meant; a bare name is left for PATH lookup. Detected + on the separator, not on `Path.parent`, which reads `./bca` as bare. + """ + if os.sep in explicit or (os.altsep is not None and os.altsep in explicit): + return str(Path(explicit).resolve()) + return explicit + + def resolve(workspace: Path) -> tuple[list[str], str]: """The command to run — without the user's arguments — and the reason.""" profile = env("BCA_SELF_SCAN_PROFILE") or "dev" if profile not in PROFILES: - raise SystemExit( - f"bca: self-scan: BCA_SELF_SCAN_PROFILE must be one of {PROFILES}, not {profile!r}" - ) + raise SystemExit(f"error: BCA_SELF_SCAN_PROFILE must be one of {PROFILES}, not {profile!r}") if truthy("BCA_SELF_SCAN_FROM_SOURCE"): return cargo_command( @@ -104,25 +121,21 @@ def resolve(workspace: Path) -> tuple[list[str], str]: explicit = env("BCA_SELF_SCAN_BINARY") if explicit is not None: - # A relative path with a directory part is anchored to the - # invoking directory now, before `main` changes to the repo root, - # so it means what the caller's shell meant; a bare name is left - # for PATH lookup. - path = Path(explicit) - resolved = ( - str(path.resolve()) if path.parent != Path() and not path.is_absolute() else explicit - ) + resolved = anchor_to_caller(explicit) return [resolved], f"via {resolved}: BCA_SELF_SCAN_BINARY is set" on_path = shutil.which("bca") if on_path is not None: + # `which` returns a relative path for a relative PATH entry, and + # `main` changes directory before the exec. + on_path = str(Path(on_path).resolve()) reported = build_inputs_of(on_path) if reported is None: reason = f"{on_path} reports no build-inputs digest" else: try: live = self_scan_digest.digest(workspace) - except self_scan_digest.DigestError as e: + except (self_scan_digest.DigestError, OSError) as e: live, reason = None, f"the tree cannot be digested ({e})" else: reason = f"{on_path} was built from other inputs ({reported[:12]} vs {live[:12]})" @@ -144,9 +157,12 @@ def main(argv: list[str]) -> int: print("\n".join(full)) return 0 os.chdir(workspace) - if os.name == "posix": - os.execvp(full[0], full) - completed = subprocess.run(full, check=False) + try: + if os.name == "posix": + os.execvp(full[0], full) + completed = subprocess.run(full, check=False) + except OSError as e: + raise SystemExit(f"error: cannot run {full[0]}: {e}") from e code = completed.returncode return 128 - code if code < 0 else code diff --git a/utils/self_scan_digest.py b/utils/self_scan_digest.py index 319ef6880..2a42b71d1 100644 --- a/utils/self_scan_digest.py +++ b/utils/self_scan_digest.py @@ -23,6 +23,7 @@ # `digest.rs`; the shared fixture test fails if either side moves alone. INPUT_ROOTS = ( "Cargo.toml", + "Cargo.lock", "src", "big-code-analysis-ast", "big-code-analysis-cli", @@ -32,8 +33,8 @@ "tree-sitter-preproc", "tree-sitter-tcl", ) -INPUT_EXTENSIONS = frozenset({"rs", "c", "cc", "h", "toml", "json"}) -SKIPPED_TOP_LEVEL = frozenset({"target", "build", "node_modules"}) +INPUT_EXTENSIONS = frozenset({"rs", "c", "cc", "h", "toml"}) +SKIPPED_TOP_LEVEL = frozenset({"tests", "benches", "examples", "target", "build", "node_modules"}) class DigestError(Exception): @@ -50,7 +51,8 @@ def input_files(workspace: Path) -> list[str]: if path.is_file(): files.append(root) elif path.is_dir(): - _collect_dir(workspace, path, root.startswith("tree-sitter-"), files) + # `src/` is the root crate's source directory, not a crate root. + _collect_dir(workspace, path, root != "src", files) else: raise DigestError(f"input root is absent: {root}") # Bytes rather than code points to match the Rust side literally; @@ -61,14 +63,16 @@ def input_files(workspace: Path) -> list[str]: return files -def _collect_dir(workspace: Path, directory: Path, grammar_top: bool, out: list[str]) -> None: - for entry in sorted(os.scandir(directory), key=lambda e: e.name): +def _collect_dir(workspace: Path, directory: Path, crate_root: bool, out: list[str]) -> None: + with os.scandir(directory) as it: + entries = sorted(it, key=lambda e: e.name) + for entry in entries: path = Path(entry.path) rel = _relative_posix(workspace, path) if entry.is_symlink(): raise DigestError(f"symlink under an input root: {rel}") if entry.is_dir(follow_symlinks=False): - if grammar_top and entry.name in SKIPPED_TOP_LEVEL: + if crate_root and entry.name in SKIPPED_TOP_LEVEL: continue _collect_dir(workspace, path, False, out) elif entry.is_file(follow_symlinks=False) and _has_input_extension(entry.name): @@ -76,8 +80,10 @@ def _collect_dir(workspace: Path, directory: Path, grammar_top: bool, out: list[ def _has_input_extension(name: str) -> bool: - _, dot, ext = name.rpartition(".") - return bool(dot) and ext in INPUT_EXTENSIONS + # A pure dotfile (`.toml`) has no extension to Rust's `Path::extension`; + # the empty stem check keeps this side from hashing what that side skips. + stem, dot, ext = name.rpartition(".") + return bool(dot) and bool(stem) and ext in INPUT_EXTENSIONS def _relative_posix(workspace: Path, path: Path) -> str: @@ -98,3 +104,16 @@ def digest(workspace: Path) -> str: h.update(len(content).to_bytes(8, "little")) h.update(content) return h.hexdigest() + + +if __name__ == "__main__": + # `python3 utils/self_scan_digest.py ` prints the digest; + # the Rust test `python_digest_agrees_with_the_rust_digest_over_this_checkout` + # compares it with its own walk of the live tree. + import sys + + try: + print(digest(Path(sys.argv[1]) if len(sys.argv) > 1 else Path.cwd())) + except (DigestError, OSError) as e: + print(f"error: {e}", file=sys.stderr) + sys.exit(1) From a938b74adb87eb04aea62d652ce5f270ff74cf5b Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:50:52 -0800 Subject: [PATCH 6/8] fix(cli,self-scan): close the three gaps astra found in the review fix-up MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .../src/build_info/build_info_tests.rs | 34 +++++++++++++++++++ .../src/build_info/digest.rs | 30 ++++++++++++---- tree-sitter-ccomment/bindings/rust/build.rs | 10 ++++-- tree-sitter-mozcpp/bindings/rust/build.rs | 10 ++++-- tree-sitter-mozjs/bindings/rust/build.rs | 10 ++++-- tree-sitter-preproc/bindings/rust/build.rs | 10 ++++-- tree-sitter-tcl/bindings/rust/build.rs | 10 ++++-- utils/self-scan-bca-test.py | 16 ++++++++- 8 files changed, 113 insertions(+), 17 deletions(-) diff --git a/big-code-analysis-cli/src/build_info/build_info_tests.rs b/big-code-analysis-cli/src/build_info/build_info_tests.rs index 9de50310f..34edea3fe 100644 --- a/big-code-analysis-cli/src/build_info/build_info_tests.rs +++ b/big-code-analysis-cli/src/build_info/build_info_tests.rs @@ -145,6 +145,40 @@ fn walk_refuses_a_partial_tree_rather_than_hashing_it() { ); } +/// Only an absent root is the registry layout; a root whose lookup +/// fails any other way is a defect in a real checkout and must say so, +/// or `build.rs` reports `unavailable` without the warning it owes. +/// Permissions do not reach `symlink_metadata` on the entry itself — +/// they gate reading the parent, which is the workspace here — so the +/// failure that can is a symlink loop: `ELOOP`, not `NotFound`. +#[cfg(unix)] +#[test] +fn a_root_whose_lookup_fails_is_an_io_error_not_a_missing_one() { + let dir = tempfile::tempdir().expect("tempdir"); + shared_fixture(dir.path()); + let root = dir.path().join("tree-sitter-tcl"); + std::fs::remove_dir_all(&root).expect("rm"); + std::os::unix::fs::symlink("tree-sitter-tcl", &root).expect("self-referential symlink"); + // `symlink_metadata` reads the link itself, so a loop is only hit + // one level down; make the parent the loop instead. + std::fs::remove_file(&root).expect("rm link"); + let hidden = dir.path().join("loop"); + std::os::unix::fs::symlink("loop", &hidden).expect("symlink loop"); + let result = input_files_under_root(dir.path(), "loop/tree-sitter-tcl"); + assert!( + matches!(result, Err(DigestError::Io(_, ref msg)) if !msg.is_empty()), + "{result:?}" + ); +} + +/// `input_files`' root lookup, pointed at an arbitrary relative root +/// so a test can hand it a path whose `symlink_metadata` fails with +/// something other than `NotFound`. +#[cfg(unix)] +fn input_files_under_root(workspace: &Path, root: &str) -> Result<(), DigestError> { + super::digest::lookup_root(workspace, root).map(|_| ()) +} + #[cfg(unix)] #[test] fn walk_refuses_a_symlinked_input() { diff --git a/big-code-analysis-cli/src/build_info/digest.rs b/big-code-analysis-cli/src/build_info/digest.rs index 48e993ec1..bfb558bbd 100644 --- a/big-code-analysis-cli/src/build_info/digest.rs +++ b/big-code-analysis-cli/src/build_info/digest.rs @@ -124,12 +124,7 @@ impl std::fmt::Display for DigestError { pub(crate) fn input_files(workspace: &Path) -> Result, DigestError> { let mut files = Vec::new(); for root in INPUT_ROOTS { - let path = workspace.join(root); - let meta = std::fs::symlink_metadata(&path) - .map_err(|_| DigestError::MissingRoot(PathBuf::from(root)))?; - if meta.is_symlink() { - return Err(DigestError::Symlink(PathBuf::from(root))); - } + let (path, meta) = lookup_root(workspace, root)?; if meta.is_file() { files.push((*root).to_owned()); } else { @@ -143,6 +138,29 @@ pub(crate) fn input_files(workspace: &Path) -> Result, DigestError> Ok(files) } +/// Resolve one root under `workspace`. Absent is the registry layout +/// and reads as [`DigestError::MissingRoot`]; any other lookup failure +/// — a symlink loop, an unsearchable parent — is a defect in a real +/// checkout and keeps its own message, so `build.rs` can warn about it +/// rather than file it under "not a workspace". +pub(crate) fn lookup_root( + workspace: &Path, + root: &str, +) -> Result<(PathBuf, std::fs::Metadata), DigestError> { + let path = workspace.join(root); + let meta = std::fs::symlink_metadata(&path).map_err(|e| { + if e.kind() == std::io::ErrorKind::NotFound { + DigestError::MissingRoot(PathBuf::from(root)) + } else { + DigestError::Io(path.clone(), e.to_string()) + } + })?; + if meta.is_symlink() { + return Err(DigestError::Symlink(PathBuf::from(root))); + } + Ok((path, meta)) +} + /// What the walk does with one directory entry. enum Entry { Descend(PathBuf), diff --git a/tree-sitter-ccomment/bindings/rust/build.rs b/tree-sitter-ccomment/bindings/rust/build.rs index 153c8bd3c..390c8ec5e 100644 --- a/tree-sitter-ccomment/bindings/rust/build.rs +++ b/tree-sitter-ccomment/bindings/rust/build.rs @@ -10,9 +10,15 @@ fn main() { // the two translation units below left a header-only edit with a stale // object while the CLI's build-inputs digest (#1773) moved on — a // binary advertising a tree it did not compile. - if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { + let headers = src_dir.join("tree_sitter"); + if let Ok(entries) = std::fs::read_dir(&headers) { for entry in entries.flatten() { - println!("cargo:rerun-if-changed={}", entry.path().display()); + match entry.path().to_str() { + Some(path) => println!("cargo:rerun-if-changed={path}"), + // A name cargo cannot be told exactly: watch the directory + // instead, which changes whenever that file is replaced. + None => println!("cargo:rerun-if-changed={}", headers.display()), + } } } diff --git a/tree-sitter-mozcpp/bindings/rust/build.rs b/tree-sitter-mozcpp/bindings/rust/build.rs index 5386cbb12..f8ae226f3 100644 --- a/tree-sitter-mozcpp/bindings/rust/build.rs +++ b/tree-sitter-mozcpp/bindings/rust/build.rs @@ -6,9 +6,15 @@ fn main() { // the two translation units below left a header-only edit with a stale // object while the CLI's build-inputs digest (#1773) moved on — a // binary advertising a tree it did not compile. - if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { + let headers = src_dir.join("tree_sitter"); + if let Ok(entries) = std::fs::read_dir(&headers) { for entry in entries.flatten() { - println!("cargo:rerun-if-changed={}", entry.path().display()); + match entry.path().to_str() { + Some(path) => println!("cargo:rerun-if-changed={path}"), + // A name cargo cannot be told exactly: watch the directory + // instead, which changes whenever that file is replaced. + None => println!("cargo:rerun-if-changed={}", headers.display()), + } } } diff --git a/tree-sitter-mozjs/bindings/rust/build.rs b/tree-sitter-mozjs/bindings/rust/build.rs index e09881fa1..cd9890e12 100644 --- a/tree-sitter-mozjs/bindings/rust/build.rs +++ b/tree-sitter-mozjs/bindings/rust/build.rs @@ -6,9 +6,15 @@ fn main() { // the two translation units below left a header-only edit with a stale // object while the CLI's build-inputs digest (#1773) moved on — a // binary advertising a tree it did not compile. - if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { + let headers = src_dir.join("tree_sitter"); + if let Ok(entries) = std::fs::read_dir(&headers) { for entry in entries.flatten() { - println!("cargo:rerun-if-changed={}", entry.path().display()); + match entry.path().to_str() { + Some(path) => println!("cargo:rerun-if-changed={path}"), + // A name cargo cannot be told exactly: watch the directory + // instead, which changes whenever that file is replaced. + None => println!("cargo:rerun-if-changed={}", headers.display()), + } } } diff --git a/tree-sitter-preproc/bindings/rust/build.rs b/tree-sitter-preproc/bindings/rust/build.rs index 153c8bd3c..390c8ec5e 100644 --- a/tree-sitter-preproc/bindings/rust/build.rs +++ b/tree-sitter-preproc/bindings/rust/build.rs @@ -10,9 +10,15 @@ fn main() { // the two translation units below left a header-only edit with a stale // object while the CLI's build-inputs digest (#1773) moved on — a // binary advertising a tree it did not compile. - if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { + let headers = src_dir.join("tree_sitter"); + if let Ok(entries) = std::fs::read_dir(&headers) { for entry in entries.flatten() { - println!("cargo:rerun-if-changed={}", entry.path().display()); + match entry.path().to_str() { + Some(path) => println!("cargo:rerun-if-changed={path}"), + // A name cargo cannot be told exactly: watch the directory + // instead, which changes whenever that file is replaced. + None => println!("cargo:rerun-if-changed={}", headers.display()), + } } } diff --git a/tree-sitter-tcl/bindings/rust/build.rs b/tree-sitter-tcl/bindings/rust/build.rs index e6e32ab08..9e0d80b23 100644 --- a/tree-sitter-tcl/bindings/rust/build.rs +++ b/tree-sitter-tcl/bindings/rust/build.rs @@ -6,9 +6,15 @@ fn main() { // the two translation units below left a header-only edit with a stale // object while the CLI's build-inputs digest (#1773) moved on — a // binary advertising a tree it did not compile. - if let Ok(entries) = std::fs::read_dir(src_dir.join("tree_sitter")) { + let headers = src_dir.join("tree_sitter"); + if let Ok(entries) = std::fs::read_dir(&headers) { for entry in entries.flatten() { - println!("cargo:rerun-if-changed={}", entry.path().display()); + match entry.path().to_str() { + Some(path) => println!("cargo:rerun-if-changed={path}"), + // A name cargo cannot be told exactly: watch the directory + // instead, which changes whenever that file is replaced. + None => println!("cargo:rerun-if-changed={}", headers.display()), + } } } diff --git a/utils/self-scan-bca-test.py b/utils/self-scan-bca-test.py index b45f0e7b9..9fd46effc 100644 --- a/utils/self-scan-bca-test.py +++ b/utils/self-scan-bca-test.py @@ -207,7 +207,8 @@ def test_release_profile_adds_the_flag_and_a_typo_is_an_error(self) -> None: self.assertEqual(self.chosen(result), [*self.CARGO_RELEASE, "check"]) bad = self.run_wrapper("check", env={"BCA_SELF_SCAN_PROFILE": "relese"}) self.assertNotEqual(bad.returncode, 0) - self.assertIn("BCA_SELF_SCAN_PROFILE", bad.stderr) + self.assertIn("error: BCA_SELF_SCAN_PROFILE", bad.stderr) + self.assertNotIn("Traceback", bad.stderr) # An empty value reads as unset, not as a bad profile. empty = self.run_wrapper("check", env={"BCA_SELF_SCAN_PROFILE": ""}) self.assertEqual(self.chosen(empty), [*self.CARGO_DEV, "check"]) @@ -287,6 +288,19 @@ def test_relative_paths_still_resolve_after_the_wrapper_changes_directory(self) self.assertEqual(result.returncode, 7, result.stderr) self.assertEqual(self.record.read_text().splitlines()[1:], ["check"]) + def test_an_explicit_binary_that_cannot_run_is_one_error_line(self) -> None: + # Launched for real: the exec is what fails. A missing path and a + # present but non-executable file both end in `error:`, not a + # Python traceback, and with a non-zero status. + unrunnable = self.root / "not-executable" + unrunnable.write_text("#!/bin/sh\nexit 0\n") + unrunnable.chmod(0o644) + for path in (str(self.root / "no-such-bca"), str(unrunnable)): + result = self.run_wrapper("check", env={"BCA_SELF_SCAN_BINARY": path}, dry_run=False) + self.assertNotEqual(result.returncode, 0, path) + self.assertIn(f"error: cannot run {path}", result.stderr) + self.assertNotIn("Traceback", result.stderr) + def test_a_lockfile_only_change_rejects_the_installed_binary(self) -> None: # The resolver compares digests instead of letting cargo # fingerprint, so a dependency bump with no source edit must From 126adf725ec53c60b8d0f4fa240d381d99264739 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:34:46 -0800 Subject: [PATCH 7/8] test(cli): cover the provenance error paths codecov reported MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../src/build_info/build_info_tests.rs | 218 +++++++++++++++++- big-code-analysis-cli/src/check_format.rs | 43 +++- 2 files changed, 257 insertions(+), 4 deletions(-) diff --git a/big-code-analysis-cli/src/build_info/build_info_tests.rs b/big-code-analysis-cli/src/build_info/build_info_tests.rs index 34edea3fe..90a387ea8 100644 --- a/big-code-analysis-cli/src/build_info/build_info_tests.rs +++ b/big-code-analysis-cli/src/build_info/build_info_tests.rs @@ -1,4 +1,4 @@ -use std::path::Path; +use std::path::{Path, PathBuf}; use super::digest::{DigestError, INPUT_ROOTS, digest, input_files}; use super::elf::{build_id, hex_lower}; @@ -179,6 +179,152 @@ fn input_files_under_root(workspace: &Path, root: &str) -> Result<(), DigestErro super::digest::lookup_root(workspace, root).map(|_| ()) } +/// Every `DigestError` renders its path and its kind; `build.rs` prints +/// the rendering as a `cargo:warning`, so each arm is a line a reader +/// has to be able to act on. +#[test] +fn every_digest_error_names_its_path_and_its_kind() { + let cases = [ + ( + DigestError::MissingRoot("src".into()), + "input root is absent: src", + ), + ( + DigestError::Symlink("src/link.rs".into()), + "symlink under an input root: src/link.rs", + ), + ( + DigestError::NonUtf8Path("src/x".into()), + "non-UTF-8 path under an input root: src/x", + ), + ( + DigestError::Io("src/lib.rs".into(), "boom".into()), + "src/lib.rs: boom", + ), + ]; + for (error, rendered) in cases { + assert_eq!(error.to_string(), rendered); + } +} + +/// A root that is itself a symlink is refused before anything beneath +/// it is read — the compiler would follow it to bytes the digest never +/// saw. +#[cfg(unix)] +#[test] +fn walk_refuses_a_symlinked_root() { + let dir = tempfile::tempdir().expect("tempdir"); + shared_fixture(dir.path()); + std::fs::remove_dir_all(dir.path().join("big-code-analysis-ast")).expect("rm"); + std::os::unix::fs::symlink( + "big-code-analysis-cli", + dir.path().join("big-code-analysis-ast"), + ) + .expect("symlink"); + assert_eq!( + digest(dir.path()), + Err(DigestError::Symlink("big-code-analysis-ast".into())) + ); +} + +/// A name the shared encoding cannot spell is refused rather than +/// hashed under a lossy spelling the Python side would not reproduce. +#[cfg(unix)] +#[test] +fn walk_refuses_a_non_utf8_path() { + use std::os::unix::ffi::OsStrExt as _; + let dir = tempfile::tempdir().expect("tempdir"); + shared_fixture(dir.path()); + let name = std::ffi::OsStr::from_bytes(b"bad\xff.rs"); + std::fs::write(dir.path().join("src").join(name), b"fn x() {}\n").expect("write"); + assert!( + matches!(digest(dir.path()), Err(DigestError::NonUtf8Path(_))), + "{:?}", + digest(dir.path()) + ); +} + +/// `input_files` lists the file, then the read fails: the error carries +/// the file's path, not the directory's, so the warning names what to +/// fix. Skipped for root, who reads anything. +#[cfg(unix)] +#[test] +fn an_unreadable_file_is_an_io_error_naming_the_file() { + if effective_root() { + return; + } + let dir = tempfile::tempdir().expect("tempdir"); + shared_fixture(dir.path()); + let _unreadable = Unreadable::new(dir.path().join("src/lib.rs"), 0o644); + let result = digest(dir.path()); + assert!( + matches!(result, Err(DigestError::Io(ref p, _)) if p.ends_with("src/lib.rs")), + "{result:?}" + ); +} + +/// A directory the walk cannot list is an `Io` error naming that +/// directory, from `read_dir` rather than from a later read. +#[cfg(unix)] +#[test] +fn an_unlistable_directory_is_an_io_error_naming_the_directory() { + if effective_root() { + return; + } + let dir = tempfile::tempdir().expect("tempdir"); + shared_fixture(dir.path()); + let _unlistable = Unreadable::new(dir.path().join("src/nested"), 0o755); + let result = digest(dir.path()); + assert!( + matches!(result, Err(DigestError::Io(ref p, _)) if p.ends_with("src/nested")), + "{result:?}" + ); +} + +/// A path held at mode `0o000` for the guard's lifetime and restored on +/// drop — on an assertion failure too, which matters for a directory: +/// `TempDir::drop` ignores the `remove_dir_all` error a `0o000` +/// subdirectory produces and leaves the tree behind. Declared before +/// the `TempDir` in each test so it drops first. +#[cfg(unix)] +struct Unreadable { + path: PathBuf, + restore: u32, +} + +#[cfg(unix)] +impl Unreadable { + fn new(path: PathBuf, restore: u32) -> Self { + use std::os::unix::fs::PermissionsExt as _; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).expect("chmod"); + Self { path, restore } + } +} + +#[cfg(unix)] +impl Drop for Unreadable { + fn drop(&mut self) { + use std::os::unix::fs::PermissionsExt as _; + let _ = std::fs::set_permissions(&self.path, std::fs::Permissions::from_mode(self.restore)); + } +} + +/// Whether this process reads past permission bits. The *effective* +/// uid, from `id -u`, which every Unix has — `/proc` does not exist on +/// macOS, and the `Uid:` line there is the real uid anyway. An answer +/// that cannot be read is not evidence of an unprivileged run, so it +/// counts as root and skips. +#[cfg(unix)] +fn effective_root() -> bool { + std::process::Command::new("id") + .arg("-u") + .output() + .ok() + .filter(|o| o.status.success()) + .and_then(|o| String::from_utf8(o.stdout).ok()) + .is_none_or(|uid| uid.trim() == "0") +} + #[cfg(unix)] #[test] fn walk_refuses_a_symlinked_input() { @@ -251,6 +397,21 @@ fn python_digest_agrees_with_the_rust_digest_over_this_checkout() { assert_eq!(python.trim(), rust); } +/// The sentinel `build.rs` writes for a field it could not determine +/// is a word in the `--version` text and nothing anywhere else: the +/// accessors map it to `None` so SARIF omits the property and the +/// footer its suffix. A checkout build never produces it, so the +/// mapping is pinned on the function rather than on the baked consts. +#[test] +fn the_unavailable_sentinel_reads_as_none_and_anything_else_as_itself() { + assert_eq!(super::known("unavailable"), None); + assert_eq!(super::known("deadbeef"), Some("deadbeef")); + assert_eq!(super::known(""), Some("")); + // Whatever this build baked, the accessors agree with the consts. + assert_eq!(super::build_inputs(), super::known(super::BUILD_INPUTS)); + assert_eq!(super::build_git(), super::known(super::BUILD_GIT)); +} + #[test] fn long_version_starts_with_the_bare_version_and_carries_every_field() { let text = super::long_version(); @@ -368,12 +529,65 @@ fn build_id_is_none_for_every_shape_the_reader_does_not_support() { "not NT_GNU_BUILD_ID" ); + // Every prefix of a valid image must read as absent, not panic and + // not misparse. This walks each `?` in the header and program-header + // readers; it never reaches the note reader, because the shortened + // image keeps the program header's declared segment size and the + // segment slice fails first. + for cut in 0..good.len() { + assert_eq!(build_id(&good[..cut]), None, "truncated at byte {cut}"); + } + // The note reader's own short reads need a segment whose *declared* + // size is honest: 4 bytes reach `descsz`'s read, 8 reach `kind`'s, + // 12 reach the name's. These execute each read's `None` arm; they + // cannot tell a failed read from an infallible one, because the + // next read fails the same way and no id can come out of a note + // that short — the outcome, not the mechanism, is what is pinned. + for short in [&[0u8; 4][..], &[0u8; 8], &[0u8; 12]] { + assert_eq!( + build_id(&elf64(4, short)), + None, + "{}-byte note segment", + short.len() + ); + } + let mut overflow = good.clone(); overflow[0x40 + 0x20..0x40 + 0x28].copy_from_slice(&u64::MAX.to_le_bytes()); assert_eq!(build_id(&overflow), None, "segment size past the end"); - let mut far_offset = good; + let mut far_offset = good.clone(); far_offset[0x40 + 0x08..0x40 + 0x10].copy_from_slice(&u64::MAX.to_le_bytes()); assert_eq!(build_id(&far_offset), None, "segment offset past the end"); + + let mut more_headers_than_exist = good.clone(); + more_headers_than_exist[0x38..0x3a].copy_from_slice(&7u16.to_le_bytes()); + assert_eq!( + build_id(&more_headers_than_exist), + Some(&id[..]), + "a phnum past the table still finds the note in the headers present" + ); + + let mut huge_phoff = good.clone(); + huge_phoff[0x20..0x28].copy_from_slice(&u64::MAX.to_le_bytes()); + assert_eq!( + build_id(&huge_phoff), + None, + "program-header offset past the end" + ); + + // A name length that overruns the segment: the note walk fails + // closed. (A clamped slice would fail closed too — the name would + // not compare equal — so this pins the outcome, not the mechanism; + // the bounded-read spelling is the module's safety argument.) + let mut lying_namesz = good; + let note_at = 0x40 + 0x38; + lying_namesz[note_at..note_at + 4].copy_from_slice(&0xffff_fff0u32.to_le_bytes()); + assert_eq!(build_id(&lying_namesz), None, "namesz past the segment"); + + // A descriptor length that overruns: same, on the other field. + let mut lying_descsz = elf64(4, ¬e(b"GNU\0", 3, &id)); + lying_descsz[note_at + 4..note_at + 8].copy_from_slice(&0xffff_fff0u32.to_le_bytes()); + assert_eq!(build_id(&lying_descsz), None, "descsz past the segment"); } /// A capability probe, not a contract: the linker on this host is what diff --git a/big-code-analysis-cli/src/check_format.rs b/big-code-analysis-cli/src/check_format.rs index f0130076b..fb80932ee 100644 --- a/big-code-analysis-cli/src/check_format.rs +++ b/big-code-analysis-cli/src/check_format.rs @@ -140,11 +140,20 @@ pub(crate) fn dump_sarif_with_suppressed( /// neither and stamps nothing — an absent property, not a sentinel a /// consumer comparing digests would read as a value. fn sarif_provenance() -> SarifProvenance { + provenance_from( + crate::build_info::build_inputs(), + crate::build_info::build_git(), + ) +} + +/// [`sarif_provenance`] over explicit fields, so the registry build's +/// shape — neither known — can be pinned from a checkout build. +fn provenance_from(build_inputs: Option<&str>, build_git: Option<&str>) -> SarifProvenance { let mut provenance = SarifProvenance::default(); - if let Some(digest) = crate::build_info::build_inputs() { + if let Some(digest) = build_inputs { provenance = provenance.with_build_inputs(digest); } - if let Some(revision) = crate::build_info::build_git() { + if let Some(revision) = build_git { provenance = provenance.with_build_git(revision); } provenance @@ -624,6 +633,36 @@ mod tests { use super::*; use crate::thresholds::test_threshold; + /// Each field is stamped iff known: the registry build (neither) + /// yields the empty provenance whose document is byte-identical to + /// `write_sarif`'s, and a half-known pair stamps only its half. + #[test] + fn provenance_stamps_exactly_the_fields_that_are_known() { + assert_eq!(provenance_from(None, None), SarifProvenance::default()); + assert_eq!( + provenance_from(Some("ab"), None), + SarifProvenance::default().with_build_inputs("ab") + ); + assert_eq!( + provenance_from(None, Some("cd")), + SarifProvenance::default().with_build_git("cd") + ); + assert_eq!( + provenance_from(Some("ab"), Some("cd")), + SarifProvenance::default() + .with_build_inputs("ab") + .with_build_git("cd") + ); + // What this binary stamps is exactly what its own fields say. + assert_eq!( + sarif_provenance(), + provenance_from( + crate::build_info::build_inputs(), + crate::build_info::build_git() + ) + ); + } + fn violation(function: &str) -> Violation { Violation { path: std::path::PathBuf::from("fixture.rs"), From 7daa6079a9ae6ab1444b13a1b780da1eb2c371a9 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:45:19 -0800 Subject: [PATCH 8/8] test(cli): gate the non-UTF-8 name test to Linux and drop an import Windows flags MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two CI legs red on 126adf72, 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 --- .../src/build_info/build_info_tests.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/big-code-analysis-cli/src/build_info/build_info_tests.rs b/big-code-analysis-cli/src/build_info/build_info_tests.rs index 90a387ea8..a0824396d 100644 --- a/big-code-analysis-cli/src/build_info/build_info_tests.rs +++ b/big-code-analysis-cli/src/build_info/build_info_tests.rs @@ -1,4 +1,4 @@ -use std::path::{Path, PathBuf}; +use std::path::Path; use super::digest::{DigestError, INPUT_ROOTS, digest, input_files}; use super::elf::{build_id, hex_lower}; @@ -229,7 +229,10 @@ fn walk_refuses_a_symlinked_root() { /// A name the shared encoding cannot spell is refused rather than /// hashed under a lossy spelling the Python side would not reproduce. -#[cfg(unix)] +/// Linux only: APFS refuses to create such a name (`EILSEQ`), and +/// Windows file names are UTF-16, where the analogous case is an +/// unpaired surrogate this fixture cannot write portably. +#[cfg(target_os = "linux")] #[test] fn walk_refuses_a_non_utf8_path() { use std::os::unix::ffi::OsStrExt as _; @@ -288,13 +291,13 @@ fn an_unlistable_directory_is_an_io_error_naming_the_directory() { /// the `TempDir` in each test so it drops first. #[cfg(unix)] struct Unreadable { - path: PathBuf, + path: std::path::PathBuf, restore: u32, } #[cfg(unix)] impl Unreadable { - fn new(path: PathBuf, restore: u32) -> Self { + fn new(path: std::path::PathBuf, restore: u32) -> Self { use std::os::unix::fs::PermissionsExt as _; std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).expect("chmod"); Self { path, restore }