diff --git a/.bca-baseline.toml b/.bca-baseline.toml index b820d4cd4..da0694009 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 = 64495.18935578189 [[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/.checkmake.ini b/.checkmake.ini index 2109a05ad..29974fcb3 100644 --- a/.checkmake.ini +++ b/.checkmake.ini @@ -27,6 +27,11 @@ ; `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 152 (with `self-scan-bca-test`), leaving 13 +; 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/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/.github/workflows/pages.yml b/.github/workflows/pages.yml index f33922635..a7585cdf9 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -34,6 +34,16 @@ 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' + # 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: @@ -53,6 +63,14 @@ on: - 'tree-sitter-tcl/**' - '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: @@ -232,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 @@ -302,6 +323,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 +431,27 @@ 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 — 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: ${{ success() }} + 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/.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/.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 2c946725a..467bc0656 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 @@ -518,6 +526,46 @@ 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 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` +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` (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 a proportional soft tier is active — the soft tier measures *distance to diff --git a/CHANGELOG.md b/CHANGELOG.md index 899e1e2f0..94b3aaf77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,30 @@ 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; + 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 + `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 + 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 @@ -157,6 +181,34 @@ 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. 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/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/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 aaab76e31..3cf1b5589 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 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)" @@ -181,6 +182,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" @@ -549,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 @@ -886,8 +893,21 @@ 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 `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 @@ -915,8 +935,26 @@ 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 -- +# 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). @@ -977,6 +1015,44 @@ self-scan-write-baseline-headroom: --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 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 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 + +# 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 — 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 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 # this repo: ranks tracked files by composite change-history risk (churn, @@ -1552,7 +1628,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 @@ -1739,7 +1815,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 @@ -1749,7 +1825,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 # --------------------------------------------------------------------------- @@ -1791,6 +1867,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 @@ -1815,12 +1892,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 @@ -1918,6 +2002,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 @@ -2030,11 +2117,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 @@ -2176,6 +2264,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 @@ -2279,9 +2370,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/STABILITY.md b/STABILITY.md index 8f2588682..c28aa70a8 100644 --- a/STABILITY.md +++ b/STABILITY.md @@ -680,10 +680,35 @@ 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 `build id:` (the linker's GNU build-id +note on Linux; `unavailable` elsewhere). The first line is the stable +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 @@ -906,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 6ef37ce29..436e2063b 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). +# 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 775936306..ab5337f4d 100644 --- a/big-code-analysis-book/src/recipes/ci.md +++ b/big-code-analysis-book/src/recipes/ci.md @@ -651,9 +651,17 @@ 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/`, 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 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/big-code-analysis-cli/Cargo.toml b/big-code-analysis-cli/Cargo.toml index 440a72eb1..0a157a8ba 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,16 @@ 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 workspace pin appears under +# both tables. +[build-dependencies] +sha2.workspace = true + [dev-dependencies] assert_cmd = "^2.0" +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 new file mode 100644 index 000000000..d7b10acba --- /dev/null +++ b/big-code-analysis-cli/build.rs @@ -0,0 +1,200 @@ +//! 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 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 + } + } +} + +/// Run `git` with the repository-selecting variables scrubbed and +/// 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) + .env_remove("GIT_DIR") + .env_remove("GIT_WORK_TREE") + .env_remove("GIT_INDEX_FILE") + .env_remove("GIT_COMMON_DIR") + .env("GIT_CEILING_DIRECTORIES", ceiling) + .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 — 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![ + "status", + "--porcelain", + "--untracked-files=all", + "--ignore-submodules=all", + "--", + ]; + status.extend(digest::INPUT_ROOTS); + let dirty = git(workspace, &status).is_some_and(|s| !s.is_empty()); + Some(if dirty { format!("{sha}-dirty") } else { sha }) +} + +/// 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..a0824396d --- /dev/null +++ b/big-code-analysis-cli/src/build_info/build_info_tests.rs @@ -0,0 +1,610 @@ +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 = + "2d6dfcc20156bfc6bcd2bc38ab2cdff68cc864b1a4b6951b891cffc40508a17e"; + +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("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""); + 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( + "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( + "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"); + write("tree-sitter-tcl/examples/x.c", b"int e;\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.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", + ] + ); + 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" + ); + 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] +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())) + ); +} + +/// 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(|_| ()) +} + +/// 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. +/// 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 _; + 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: std::path::PathBuf, + restore: u32, +} + +#[cfg(unix)] +impl Unreadable { + 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 } + } +} + +#[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() { + 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() { + // 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")); +} + +/// 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}"), + } +} + +/// 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); +} + +/// 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(); + 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}"); + // 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].ends_with(&format!("debug-assertions {expected})")), + "{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)); +} + +#[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" + ); + + // 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.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 +/// 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..bfb558bbd --- /dev/null +++ b/big-code-analysis-cli/src/build_info/digest.rs @@ -0,0 +1,279 @@ +//! 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` 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", + "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. 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"]; + +/// 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. +#[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, meta) = lookup_root(workspace, root)?; + if meta.is_file() { + files.push((*root).to_owned()); + } else { + // `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())); + 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), + Input(String), + Ignore, +} + +fn collect_dir( + workspace: &Path, + dir: &Path, + crate_root: 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)?; + // `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, crate_root)? { + Entry::Descend(path) => collect_dir(workspace, &path, false, out)?, + Entry::Input(rel) => out.push(rel), + Entry::Ignore => {} + } + } + Ok(()) +} + +/// `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, + )?))); + } + 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 + }) +} + +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 { + 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 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()); + 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` 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); + 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..1870aa7fd --- /dev/null +++ b/big-code-analysis-cli/src/build_info/elf.rs @@ -0,0 +1,177 @@ +//! 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. + +/// 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. +#[cfg(target_os = "linux")] +const HEAD_BYTES: u64 = 64 * 1024; +#[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::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()?; + 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 +} + +#[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 + } + + 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 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) { + // `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; + } + None + } + + 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 { + 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 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 new file mode 100644 index 000000000..ff5130617 --- /dev/null +++ b/big-code-analysis-cli/src/build_info/mod.rs @@ -0,0 +1,75 @@ +//! 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)] +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. 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`]. 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. +/// +/// `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})\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 eec719adb..fb80932ee 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,36 @@ 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 knows +/// 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) = build_inputs { + provenance = provenance.with_build_inputs(digest); + } + if let Some(revision) = build_git { + provenance = provenance.with_build_git(revision); + } + provenance +} + /// 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 @@ -605,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"), diff --git a/big-code-analysis-cli/src/commands.rs b/big-code-analysis-cli/src/commands.rs index 5551831ed..587469822 100644 --- a/big-code-analysis-cli/src/commands.rs +++ b/big-code-analysis-cli/src/commands.rs @@ -233,7 +233,18 @@ 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`. 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) => { if matches!( diff --git a/big-code-analysis-cli/src/commands/report.rs b/big-code-analysis-cli/src/commands/report.rs index 98994b51b..fdf1ab041 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: 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..9700db037 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 — 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`]). 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("abc"), + ..prov(20, SuppressionPolicy::Honor) + }, + ); + assert!(short.contains("(build abc)"), "{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..bf175457a 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,60 @@ 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 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: ", "build id: "]) + { + assert!( + line.starts_with(prefix), + "{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_eq!(inputs.len(), 64, "{inputs}"); + assert!(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..026f52a54 100644 --- a/big-code-analysis-cli/tests/output/format_smoke.rs +++ b/big-code-analysis-cli/tests/output/format_smoke.rs @@ -157,6 +157,37 @@ 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 + // 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() + }; + // `--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"]; + 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 0f3437031..7e802bdae 100644 --- a/docs/development/baseline_freshness.md +++ b/docs/development/baseline_freshness.md @@ -85,18 +85,35 @@ 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) +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 ``` -Drop `--exit-code`; as above it is informational. With the flag a -non-empty diff exits 2 and a tool error exits 1. +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/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..5d6dee59a 100644 --- a/src/output/sarif.rs +++ b/src/output/sarif.rs @@ -169,6 +169,79 @@ 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. +/// +/// 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 { + build_inputs: Option, + build_git: Option, +} + +impl SarifProvenance { + /// Record a content digest of the inputs compiled into the reporting + /// binary; rendered as the `bca.buildInputs` property. + #[must_use] + 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 { + 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 +276,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 +404,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 +569,56 @@ 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::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"); + 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::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"); + 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/tree-sitter-ccomment/bindings/rust/build.rs b/tree-sitter-ccomment/bindings/rust/build.rs index 9f7afc0b8..390c8ec5e 100644 --- a/tree-sitter-ccomment/bindings/rust/build.rs +++ b/tree-sitter-ccomment/bindings/rust/build.rs @@ -5,6 +5,23 @@ 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. + let headers = src_dir.join("tree_sitter"); + if let Ok(entries) = std::fs::read_dir(&headers) { + for entry in entries.flatten() { + 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()), + } + } + } + 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..f8ae226f3 100644 --- a/tree-sitter-mozcpp/bindings/rust/build.rs +++ b/tree-sitter-mozcpp/bindings/rust/build.rs @@ -1,6 +1,23 @@ 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. + let headers = src_dir.join("tree_sitter"); + if let Ok(entries) = std::fs::read_dir(&headers) { + for entry in entries.flatten() { + 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()), + } + } + } + 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..cd9890e12 100644 --- a/tree-sitter-mozjs/bindings/rust/build.rs +++ b/tree-sitter-mozjs/bindings/rust/build.rs @@ -1,6 +1,23 @@ 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. + let headers = src_dir.join("tree_sitter"); + if let Ok(entries) = std::fs::read_dir(&headers) { + for entry in entries.flatten() { + 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()), + } + } + } + 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..390c8ec5e 100644 --- a/tree-sitter-preproc/bindings/rust/build.rs +++ b/tree-sitter-preproc/bindings/rust/build.rs @@ -5,6 +5,23 @@ 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. + let headers = src_dir.join("tree_sitter"); + if let Ok(entries) = std::fs::read_dir(&headers) { + for entry in entries.flatten() { + 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()), + } + } + } + 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..9e0d80b23 100644 --- a/tree-sitter-tcl/bindings/rust/build.rs +++ b/tree-sitter-tcl/bindings/rust/build.rs @@ -1,6 +1,23 @@ 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. + let headers = src_dir.join("tree_sitter"); + if let Ok(entries) = std::fs::read_dir(&headers) { + for entry in entries.flatten() { + 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()), + } + } + } + let mut c_config = cc::Build::new(); c_config.include(src_dir); c_config 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..48f600cdb 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]] +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. + + `-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 + + 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 new file mode 100644 index 000000000..9fd46effc --- /dev/null +++ b/utils/self-scan-bca-test.py @@ -0,0 +1,363 @@ +#!/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 os +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", + "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"", + "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", + "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 = "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", +] + + +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) + 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: + 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("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"]) + + 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"]) + # `./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": ""}) + 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_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_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 + # 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: + 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..b6c851b73 --- /dev/null +++ b/utils/self-scan-bca.py @@ -0,0 +1,171 @@ +#!/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`. + +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 + +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 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"error: 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: + 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, 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]})" + 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) + 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 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/utils/self_scan_digest.py b/utils/self_scan_digest.py new file mode 100644 index 000000000..2a42b71d1 --- /dev/null +++ b/utils/self_scan_digest.py @@ -0,0 +1,119 @@ +#!/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", + "Cargo.lock", + "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"}) +SKIPPED_TOP_LEVEL = frozenset({"tests", "benches", "examples", "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(): + # `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; + # 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 + + +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 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): + out.append(rel) + + +def _has_input_extension(name: str) -> bool: + # 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: + 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() + + +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)