From df6c739ef7c37e02687c38029df2d4d407e80b11 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 21 Oct 2026 21:26:50 -0400 Subject: [PATCH 01/10] Run CI's checks before proposing results; allowlist propose's commands The results bot verified seals, regenerated the replay namespaces and built the database twice, but never ran the suite or the format check, so #195, #204 and #206 opened ready and failed CI. The build job now runs ci.yml's own ruff and pytest lines (pinned word for word) and its no-drift check on the assembled tree, with no token and no step command files in reach. A failure no longer means a red ready PR: the PR opens as a draft whose body names the failing tests, files or paths, and a failing rebuild turns an open PR back into a draft. Nothing marks a PR ready. runs_pipeline_code matched shell names before quote removal, so b''ash and b\ash ran bash past it. It now lists every command bash would run from propose (substitutions, groups, compound commands, function bodies) and requires each command word, as written, to be one propose uses; what the parser does not model is flagged. Both bypasses are test cases. Review of 24434729, findings 2 and 3. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/uk_replay_results_pr.sh | 55 +- .github/workflows/uk-replay-results.yml | 23 +- docs/uk_replay/RELEASE_REPLAY.md | 42 +- pipeline/uk_replay_results_pr.py | 196 ++++- tests/test_uk_replay_results_pr.py | 1042 ++++++++++++++++++++++- 5 files changed, 1305 insertions(+), 53 deletions(-) diff --git a/.github/scripts/uk_replay_results_pr.sh b/.github/scripts/uk_replay_results_pr.sh index 95a7941fd..47f75778d 100644 --- a/.github/scripts/uk_replay_results_pr.sh +++ b/.github/scripts/uk_replay_results_pr.sh @@ -155,18 +155,44 @@ build() { echo "::error::scorecard_db.build_db is nondeterministic on the results branch" >&2 exit 1 fi + preflight # The verified commit, for the job that holds the token to reproduce. output base "$base_commit" output state "$state_commit" output tree "$(git -C "$TREE" rev-parse 'HEAD^{tree}')" output sealed "$(cat "$WORK/verify-sealed.txt")" output content_hash "$(content_hash "$WORK/build1.json")" + output preflight "$(cat "$WORK/preflight.json")" output action build echo "verified tree $(git -C "$TREE" rev-parse 'HEAD^{tree}') for $(plan branch)" } +# CI's format check and suite on the commit, as ci.yml's python job runs them +# (tests check the lines are its lines), then its no-drift check. A failure +# is reported, not fatal: the pull request opens as a draft that names it +# (review of 24434729, 3). This runs in the build job, which holds no write +# credential, and in a subshell without the step's command files, so nothing +# the checks run can set this job's outputs or a later step's environment. +preflight() ( + local RUFF=(uvx ruff format --check be nz scorecard_db tests pipeline) + local SUITE=(uv run --with pytest --with hypothesis --with pypdf --with pyyaml --with numpy --with psutil --with rfc8785==0.1.4 --with jsonschema pytest tests/ -q) + if [ -n "${GH_TOKEN:-}${GITHUB_TOKEN:-}" ]; then + echo "::error::CI's checks run with no GitHub token in the environment" >&2 + exit 1 + fi + unset GITHUB_ENV GITHUB_OUTPUT GITHUB_PATH GITHUB_STATE GITHUB_STEP_SUMMARY + local ruff=0 suite=0 + (cd "$TREE" && "${RUFF[@]}") 2>&1 | tee "$WORK/ruff.log" || ruff=$? + (cd "$TREE" && PYTHONPATH=. "${SUITE[@]}") 2>&1 | tee "$WORK/suite.log" || suite=$? + git -C "$TREE" status --porcelain > "$WORK/porcelain.txt" + builder preflight --ruff-exit "$ruff" --ruff-log "$WORK/ruff.log" \ + --suite-exit "$suite" --suite-log "$WORK/suite.log" \ + --porcelain "$WORK/porcelain.txt" --output "$WORK/preflight.json" +) + rebuild() { - : "${BUILT_TREE:?}" "${BUILT_BASE:?}" "${BUILT_STATE:?}" "${BUILT_SEALED:?}" "${BUILT_CONTENT_HASH:?}" + : "${BUILT_TREE:?}" "${BUILT_BASE:?}" "${BUILT_STATE:?}" "${BUILT_SEALED:?}" "${BUILT_CONTENT_HASH:?}" \ + "${BUILT_PREFLIGHT:?}" # The standard library alone: no site-packages, nothing installed. check # skips the schema and digest checks the build job made; the rest of the # builder needs no package in either job. @@ -218,31 +244,37 @@ rebuild() { exit 0 fi fi - python3 -I - "$WORK/validation.json" "$IDENTICAL" "$BUILT_SEALED" "$BUILT_CONTENT_HASH" <<'PY' + python3 -I - "$WORK/validation.json" "$IDENTICAL" "$BUILT_SEALED" "$BUILT_CONTENT_HASH" \ + "$BUILT_PREFLIGHT" <<'PY' import json import sys -path, identical, sealed, content_hash = sys.argv[1:] +path, identical, sealed, content_hash, preflight = sys.argv[1:] with open(path, "w") as handle: json.dump( { "identical_files": int(identical), "verify_sealed": sealed, "content_hash": content_hash, + "preflight": preflight, }, handle, ) PY - python3 -I -S "$HERE/pipeline/uk_replay_results_pr.py" body --request-dir "$STAGE/$REQUEST" \ - --plan "$WORK/plan.json" --validation "$WORK/validation.json" --output "$WORK/BODY.md" + # body refuses a malformed preflight report, and says whether the pull + # request is a draft: integrity is not complete, or one of CI's checks fails. + local draft + draft=$(python3 -I -S "$HERE/pipeline/uk_replay_results_pr.py" body --request-dir "$STAGE/$REQUEST" \ + --plan "$WORK/plan.json" --validation "$WORK/validation.json" --output "$WORK/BODY.md") output commit "$(git -C "$TREE" rev-parse HEAD)" output branch "$(plan branch)" + output draft "$draft" output action build echo "rebuilt $(plan branch) at $(git -C "$TREE" rev-parse HEAD), tree $BUILT_TREE" } propose() { - : "${BUILT_COMMIT:?}" "${BUILT_BRANCH:?}" "${GH_TOKEN:?}" + : "${BUILT_COMMIT:?}" "${BUILT_BRANCH:?}" "${BUILT_DRAFT:?}" "${GH_TOKEN:?}" local branch=$BUILT_BRANCH head # Push exactly the commit this job assembled, on the main it assembled it on. head=$(git -C "$TREE" rev-parse HEAD) @@ -250,6 +282,10 @@ propose() { echo "::error::the results commit changed after it was assembled" >&2 exit 1 fi + if [ "$BUILT_DRAFT" != true ] && [ "$BUILT_DRAFT" != false ]; then + echo "::error::BUILT_DRAFT must be true or false" >&2 + exit 1 + fi # The token reaches git only through gh, for these commands alone. pushgit() { git -C "$TREE" -c credential.helper= -c 'credential.helper=!gh auth git-credential' "$@"; } @@ -301,13 +337,18 @@ propose() { if [ -z "$number" ]; then local create=(--repo "$GITHUB_REPOSITORY" --base "$BASE" --head "$branch" --title "$title" --body-file "$WORK/BODY.md") - if [ "$(plan draft)" = True ]; then + if [ "$BUILT_DRAFT" = true ]; then create+=(--draft) fi gh pr create "${create[@]}" elif [ "$pushed" = true ]; then gh pr edit "$number" --repo "$GITHUB_REPOSITORY" --title "$title" \ --body-file "$WORK/BODY.md" + # A rebuild that should be a draft turns a ready pull request back into + # one. Nothing here marks one ready: a person does, once CI passes. + if [ "$BUILT_DRAFT" = true ]; then + gh pr ready "$number" --repo "$GITHUB_REPOSITORY" --undo + fi fi echo "::notice::Results pull request for $REQUEST_ID on $branch at $head" if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then diff --git a/.github/workflows/uk-replay-results.yml b/.github/workflows/uk-replay-results.yml index e82e97e1b..2e67913cc 100644 --- a/.github/workflows/uk-replay-results.yml +++ b/.github/workflows/uk-replay-results.yml @@ -15,15 +15,17 @@ name: UK replay results PR # code. It holds no dataset token. # # Two jobs, two runners. `build` assembles the commit and runs every check, -# with PyPI packages and no write credential. `propose` runs on a fresh -# runner, so nothing those packages did can reach it: with git and the -# standard library alone it assembles the same commit from the same main and -# replay-state history, refuses unless its tree is the one `build` verified -# (`build`'s other outputs are its word, checked for shape; CI on the pull -# request reruns the checks), decides again against main's tip from the -# request it guarded, and only then mints a short-lived token for the -# organisation's policyengine GitHub App, scoped to this repository, with -# contents and pull-requests to push its own uk-replay-results/ +# with PyPI packages and no write credential: main's results checks, then +# CI's own format check, suite and no-drift check, whose failure makes the +# pull request a draft that names it rather than stopping the run. `propose` +# runs on a fresh runner, so nothing those packages did can reach it: with +# git and the standard library alone it assembles the same commit from the +# same main and replay-state history, refuses unless its tree is the one +# `build` verified (`build`'s other outputs are its word, checked for shape; +# CI on the pull request reruns the checks), decides again against main's +# tip from the request it guarded, and only then mints a short-lived token +# for the organisation's policyengine GitHub App, scoped to this repository, +# with contents and pull-requests to push its own uk-replay-results/ # branch and open the pull request. A pull request opened with GITHUB_TOKEN # would start no pull_request run, so it would never carry checks; the # App's does. The token has no workflows permission: the commit touches @@ -64,6 +66,7 @@ jobs: tree: ${{ steps.build.outputs.tree }} sealed: ${{ steps.build.outputs.sealed }} content_hash: ${{ steps.build.outputs.content_hash }} + preflight: ${{ steps.build.outputs.preflight }} steps: - uses: actions/checkout@v4 with: @@ -104,6 +107,7 @@ jobs: BUILT_STATE: ${{ needs.build.outputs.state }} BUILT_SEALED: ${{ needs.build.outputs.sealed }} BUILT_CONTENT_HASH: ${{ needs.build.outputs.content_hash }} + BUILT_PREFLIGHT: ${{ needs.build.outputs.preflight }} run: bash .github/scripts/uk_replay_results_pr.sh rebuild - name: Mint a repository-scoped token to push the branch and open the PR id: token @@ -122,5 +126,6 @@ jobs: BASE_BRANCH: ${{ github.event.repository.default_branch }} BUILT_COMMIT: ${{ steps.rebuild.outputs.commit }} BUILT_BRANCH: ${{ steps.rebuild.outputs.branch }} + BUILT_DRAFT: ${{ steps.rebuild.outputs.draft }} GH_TOKEN: ${{ steps.token.outputs.token }} run: bash .github/scripts/uk_replay_results_pr.sh propose diff --git a/docs/uk_replay/RELEASE_REPLAY.md b/docs/uk_replay/RELEASE_REPLAY.md index 15c844c91..8453e042c 100644 --- a/docs/uk_replay/RELEASE_REPLAY.md +++ b/docs/uk_replay/RELEASE_REPLAY.md @@ -829,7 +829,7 @@ runs only the default branch's code. | Job | Authority and inputs | |---|---| -| `build` | `GITHUB_TOKEN` `contents: read`, checkout credentials not persisted, no secret. Assembles the commit and runs every check, with the PyPI packages the checks need. Outputs the verified tree, the main and `replay-state` commits it used, and two check results. | +| `build` | `GITHUB_TOKEN` `contents: read`, checkout credentials not persisted, no secret. Assembles the commit and runs every check, with the PyPI packages the checks need, CI's own format check and suite among them. Outputs the verified tree, the main and `replay-state` commits it used, two check results and its report of CI's checks. | | `propose` | On a fresh runner. `GITHUB_TOKEN` `contents: read`; actions pinned to commits; no uv and no installed package. Assembles the same commit again with git and the standard library (the builder under `python3 -I -S`, small helpers under `python3 -I`) on the commits `build` used: `replay-state` history, and main history no older than the workflow's own commit. It refuses unless its tree is `build`'s, then decides again against main's current tip, reading only the request it extracted and guarded. Only then is a short-lived token for the organisation's `policyengine` GitHub App minted, scoped to this repository with `contents: write` and `pull-requests: write`, to push that commit and open the pull request. | Neither job holds a dataset token, and neither installs, imports or runs @@ -840,9 +840,10 @@ runner: whatever the checks' packages did there (a `$GITHUB_PATH` or the token. Job 2 receives only job 1's outputs, as strings it validates, and pushes only what this code builds from main's and `replay-state`'s history. The tree comparison catches an honest build job whose commit diverges; the -`verify-sealed` and content-hash lines in the pull request body are the build -job's word, checked only for shape. CI on the pull request runs the -regeneration, both database builds and the drift check again. +`verify-sealed` and content-hash lines and the report of CI's checks in the +pull request body are the build job's word, checked only for shape. CI on the +pull request runs the regeneration, both database builds, the format check, +the suite and the drift checks again. The App token, not `GITHUB_TOKEN`, writes because a pull request opened with `GITHUB_TOKEN` starts no `pull_request` workflow @@ -911,7 +912,25 @@ which CI now reads from the index: 4. **Checks.** `uk_replay_qualify verify-sealed` (the new namespace, then every one), CI's `.github/scripts/uk_replay_regenerate.sh`, and two `scorecard_db.build_db` runs, which must agree on the content hash and - leave no tracked-file drift. + leave no tracked-file drift. A failure of any of these stops the run. + Then CI's own checks on the same tree, as `ci.yml`'s `python` job runs + them on every pull request: `uvx ruff format --check be nz scorecard_db + tests pipeline`, the suite (`uv run --with pytest … pytest tests/ -q`, + with `PYTHONPATH=.`), and its no-drift check, `git status --porcelain` + after the suite. A test checks that these are `ci.yml`'s lines word for + word. They run in the `build` job, which holds no write credential: the + script refuses to start them if `GH_TOKEN` or `GITHUB_TOKEN` is set, and + runs them without the step's command files (`$GITHUB_OUTPUT`, + `$GITHUB_ENV`, `$GITHUB_PATH`, `$GITHUB_STATE`, `$GITHUB_STEP_SUMMARY`), + so nothing the suite runs can set the job's outputs. Their failure does + not stop the run. The job reports each check's exit status, how many + files, tests or paths failed (the node ids of pytest's last short test + summary, the files ruff names, the paths `git status` lists) and the + first 100 that are printable ASCII without a backtick, as one line of + JSON. `propose` refuses a report of any other shape. Results pull + requests #195, #204 and #206 opened ready and failed CI's `pytest` job; + with these checks such a pull request opens as a draft that names the + failures. 5. **Pull request.** In the `propose` job, steps 1 to 3 run again with the standard library, skipping only the JSON Schema and RFC 8785 checks `build` made. Only when the tree matches is the App token minted. The @@ -919,13 +938,24 @@ which CI now reads from the index: bot identity) with a `Replay-Request:` trailer and pushed with the App's token, goes to `uk-replay-results/`, and a pull request against main follows; CI runs on it as on any pull request, without the - dataset token. It is a draft when integrity is not `complete`. + dataset token. It is a draft when integrity is not `complete`, or when + one of CI's checks in step 4 fails; its body then lists what failed, + under "Validation in the results run", in a fenced block, with the + count of any it could not list. Fix those on main and run the workflow + again for the same request: it rebuilds the branch on the new main. + The builder never marks a pull request ready; a person does, once CI + passes. Running the workflow again for the same request is safe. An identical tree pushes nothing. A branch built on an older main is rebuilt and force-pushed, with a lease on the commit it read, only when it holds exactly one commit, authored and committed by the bot with this request's trailer; an added or amended commit is a person's, and the run fails and leaves the branch alone. +A rebuild that pushes edits the open pull request's title and body, and a +rebuild whose checks fail also turns a ready pull request back into a draft +(`gh pr ready --undo`); one whose checks pass leaves it as it is. A rerun on +an unchanged main pushes nothing, so it leaves the body as it was, even when +the earlier run's suite failed only by chance. A rebuilt branch also carries main's commits since the branch was built. GitHub does not document whether it counts that as editing a workflow when one of those commits changed `.github/workflows`, even a change main later diff --git a/pipeline/uk_replay_results_pr.py b/pipeline/uk_replay_results_pr.py index 0f35da352..4ffa3e49c 100644 --- a/pipeline/uk_replay_results_pr.py +++ b/pipeline/uk_replay_results_pr.py @@ -21,8 +21,11 @@ ``check`` reads the request directory and a checkout of main and decides whether to build; ``apply`` makes edits 2 to 4 after the extraction; -``scope`` refuses a commit that touches anything else; ``body`` renders the -pull request. ``.github/scripts/uk_replay_results_pr.sh`` does the git work, +``scope`` refuses a commit that touches anything else; ``preflight`` reports +CI's format check, suite and no-drift check, which the build job runs on the +commit; ``body`` renders the pull request, a draft when integrity is not +complete or one of those checks fails, and prints whether it is one. +``.github/scripts/uk_replay_results_pr.sh`` does the git work, the verification, the push and the pull request. Nothing here installs, imports or runs candidate or release code, and nothing here merges. @@ -607,10 +610,163 @@ def scope(plan: dict, changed: list[str]) -> None: need(not missing, f"the commit lacks edits to {missing}") +# --- CI's own checks on the commit ------------------------------------------------ + +# The build job runs ci.yml's format check and suite on the results commit, +# then its no-drift check (review of 24434729, 3). Each is reported as its +# exit status (drift's is 1 when the tree is not clean), how many distinct +# things failed and the first LISTED of them the pull request can show. A +# failure opens the pull request as a draft that names them, where #195, #204 +# and #206 opened ready and failed CI. +PREFLIGHT = { + "ruff": ( + "CI's format check, `uvx ruff format --check be nz scorecard_db tests pipeline`", + "file", + ), + "suite": ( + "CI's suite, `pytest tests/ -q` with CI's packages", + "failed or erroring test", + ), + "drift": ( + "CI's no-drift check after the suite, `git status --porcelain`", + "changed or untracked path", + ), +} +LISTED = 100 +# A name the pull request shows sits in a fenced block: printable ASCII, no +# backtick (which could close the fence), no space at either end. +LISTABLE = re.compile(r"[!-_a-~](?:[ -_a-~]{0,298}[!-_a-~])?") +SUMMARY = re.compile(r"^=+ short test summary info =+$", re.M) +# ruff format --check names a file "Would reformat: PATH" before ruff 0.16 +# and in a diagnostic's "--> PATH:LINE:COLUMN" after it; CI's uvx ruff is +# whichever is newest. +UNFORMATTED = re.compile(r"^(?:Would reformat: (.+)|\s*--> (.+?):[0-9]+:[0-9]+)$", re.M) + + +def node_id(text: str) -> str: + """A short-summary line's node id: the text before its " - " message, + outside any brackets (a parametrised id can hold " - ").""" + depth = 0 + for at, character in enumerate(text): + if depth == 0 and text.startswith(" - ", at): + return text[:at] + depth = max(0, depth + {"[": 1, "]": -1}.get(character, 0)) + return text + + +def suite_failures(log: str) -> list[str]: + """The node ids pytest's last short test summary in ``log`` names as + FAILED or ERROR (a collection error names its module).""" + starts = [match.end() for match in SUMMARY.finditer(log)] + if not starts: + return [] + return [ + node_id(line.split(" ", 1)[1]) + for line in log[starts[-1] :].splitlines() + if line.startswith(("FAILED ", "ERROR ")) + ] + + +def format_failures(log: str) -> list[str]: + """The files ``ruff format --check`` names in ``log``.""" + return [old or new for old, new in UNFORMATTED.findall(log)] + + +def drift_paths(porcelain: str) -> list[str]: + """The paths ``git status --porcelain`` lists, changed or untracked.""" + return [line[3:] for line in porcelain.splitlines() if line.strip()] + + +def report(status: int, names: list[str]) -> dict: + """One check: its exit status and, when it failed, how many distinct + names it gave and the first LISTED of those the pull request can show.""" + distinct = list(dict.fromkeys(names)) if status else [] + return { + "exit": status, + "count": len(distinct), + "names": [name for name in distinct if LISTABLE.fullmatch(name)][:LISTED], + } + + +def preflight( + ruff_exit: int, ruff_log: str, suite_exit: int, suite_log: str, porcelain: str +) -> dict: + """The build job's report of CI's checks on the results commit.""" + return { + "ruff": report(ruff_exit, format_failures(ruff_log)), + "suite": report(suite_exit, suite_failures(suite_log)), + "drift": report(1 if porcelain.strip() else 0, drift_paths(porcelain)), + } + + +def read_preflight(text: str) -> dict: + """The build job's report as the propose job receives it, a string: + refused unless it has exactly the shape ``preflight`` gives. The + counts and names are still the build job's word; CI on the pull request + runs the checks again.""" + try: + value = json.loads(text) + except ValueError: + value = None + + def shaped(condition: bool, what: str) -> None: + need(condition, f"the build job's outputs are malformed: preflight {what}") + + shaped(isinstance(value, dict) and set(value) == set(PREFLIGHT), "checks") + for key, check in value.items(): + shaped( + isinstance(check, dict) and set(check) == {"exit", "count", "names"}, + f"{key} fields", + ) + status, count, names = check["exit"], check["count"], check["names"] + shaped(type(status) is int and 0 <= status <= 255, f"{key} exit") + shaped(type(count) is int and 0 <= count <= 10**6, f"{key} count") + shaped(status != 0 or count == 0, f"{key} passes with failures") + shaped( + isinstance(names, list) + and len(names) <= min(count, LISTED) + and all(isinstance(n, str) and LISTABLE.fullmatch(n) for n in names) + and len(set(names)) == len(names), + f"{key} names", + ) + return value + + +def failed_checks(checks: dict) -> list[str]: + return [key for key in PREFLIGHT if checks[key]["exit"]] + + +def is_draft(plan: dict, checks: dict) -> bool: + """A draft when integrity is not complete or any of CI's checks fails.""" + return bool(plan["draft"] or failed_checks(checks)) + + +def check_line(key: str, check: dict) -> str: + """The check's line under "Validation in the results run": what failed, + in a fenced block.""" + what, noun = PREFLIGHT[key] + if not check["exit"]: + return f"- {what}: passes." + line = f"- {what}: **fails**" + ( + f" (exit {check['exit']})" if key != "drift" else "" + ) + count, names = check["count"], check["names"] + if not count: + return f"{line}, naming no {noun}; the build job's log has its output." + line += f", {tally(count, noun)}:" + if not names: + return f"{line} none can be shown here; the build job's log lists them." + listing = "\n".join(f" {name}" for name in names) + more = count - len(names) + rest = f"\n\n {more:,} more are in the build job's log." if more else "" + return f"{line}\n\n ```text\n{listing}\n ```{rest}" + + # --- the pull request ----------------------------------------------------------- def body(directory: Path, plan: dict, validation: dict) -> str: + reported = read_preflight(validation["preflight"]) record = json.loads((directory / "results" / "VARIANT.json").read_bytes()) receipt = json.loads((directory / variants.RECEIPT_NAME).read_bytes()) packages = record["identity"]["packages"] @@ -693,6 +849,7 @@ def body(directory: Path, plan: dict, validation: dict) -> str: "- CI's `.github/scripts/uk_replay_regenerate.sh` leaves the tree unchanged.", "- `scorecard_db.build_db`: two builds agree " f"(`{validation['content_hash'][:8]}…`), and there is no tracked-file drift.", + *(check_line(key, reported[key]) for key in PREFLIGHT), ] draft = ( "\n\nIntegrity is not `complete`, so this pull request is a draft: decide " @@ -700,6 +857,13 @@ def body(directory: Path, plan: dict, validation: dict) -> str: if plan["draft"] else "" ) + if failed_checks(reported): + draft += ( + "\n\nCI's own checks fail on this commit (see \"Validation in the " + 'results run"), so this pull request is a draft. Fix them on main and ' + "run the results workflow again for this request, which rebuilds this " + "branch on the new main; mark the pull request ready once CI passes." + ) return ( f"# {plan['title']}\n\n" f"This PR commits the receiver's sealed qualification of `{plan['variant_id']}`" @@ -746,6 +910,13 @@ def main(argv: list[str] | None = None) -> int: sub.add_argument("--output", type=Path, required=True) scoped = commands.add_parser("scope") scoped.add_argument("--plan", type=Path, required=True) + # The build job's report of CI's checks, one line of JSON for job 2. + reported = commands.add_parser("preflight") + for name in ("ruff", "suite"): + reported.add_argument(f"--{name}-exit", type=int, required=True) + reported.add_argument(f"--{name}-log", type=Path, required=True) + reported.add_argument("--porcelain", type=Path, required=True) + reported.add_argument("--output", type=Path, required=True) args = parser.parse_args(argv) try: if args.command == "check": @@ -768,10 +939,31 @@ def main(argv: list[str] | None = None) -> int: elif args.command == "scope": plan = json.loads(args.plan.read_bytes()) scope(plan, [line for line in sys.stdin.read().splitlines() if line]) + elif args.command == "preflight": + text = json.dumps( + preflight( + args.ruff_exit, + args.ruff_log.read_text(errors="replace"), + args.suite_exit, + args.suite_log.read_text(errors="replace"), + args.porcelain.read_text(errors="replace"), + ), + separators=(",", ":"), + sort_keys=True, + ) + # Never a report job 2 would refuse. + read_preflight(text) + args.output.write_text(text) else: plan = json.loads(args.plan.read_bytes()) validation = json.loads(args.validation.read_bytes()) args.output.write_text(body(args.request_dir, plan, validation)) + # The propose job opens a draft on this word. + print( + "true" + if is_draft(plan, read_preflight(validation["preflight"])) + else "false" + ) except (Refused, variants.VariantError) as problem: print(f"::error::{problem}", file=sys.stderr) return 1 diff --git a/tests/test_uk_replay_results_pr.py b/tests/test_uk_replay_results_pr.py index cc7fb1f66..77c71b812 100644 --- a/tests/test_uk_replay_results_pr.py +++ b/tests/test_uk_replay_results_pr.py @@ -24,6 +24,7 @@ import json import os import re +import shlex import shutil import subprocess import sys @@ -137,6 +138,7 @@ def test_the_results_workflow_is_dispatch_only_main_only_and_holds_no_dataset_to "tree", "sealed", "content_hash", + "preflight", } # Job 2, on a fresh runner: no uv, actions pinned to commits, and the @@ -155,6 +157,7 @@ def test_the_results_workflow_is_dispatch_only_main_only_and_holds_no_dataset_to "BUILT_STATE": "${{ needs.build.outputs.state }}", "BUILT_SEALED": "${{ needs.build.outputs.sealed }}", "BUILT_CONTENT_HASH": "${{ needs.build.outputs.content_hash }}", + "BUILT_PREFLIGHT": "${{ needs.build.outputs.preflight }}", } rebuilt = "steps.rebuild.outputs.action == 'build'" assert token["if"] == rebuilt and propose["if"] == rebuilt @@ -176,6 +179,7 @@ def test_the_results_workflow_is_dispatch_only_main_only_and_holds_no_dataset_to "BASE_BRANCH": "${{ github.event.repository.default_branch }}", "BUILT_COMMIT": "${{ steps.rebuild.outputs.commit }}", "BUILT_BRANCH": "${{ steps.rebuild.outputs.branch }}", + "BUILT_DRAFT": "${{ steps.rebuild.outputs.draft }}", "GH_TOKEN": "${{ steps.token.outputs.token }}", } for step in steps: @@ -185,9 +189,13 @@ def test_the_results_workflow_is_dispatch_only_main_only_and_holds_no_dataset_to def phase(script, name): - """The body of one function in the builder script.""" - start = script.index(f"\n{name}() {{\n") - return script[start : script.index("\n}\n", start)] + """The body of one function in the builder script, ``{ }`` or, run in + a subshell, ``( )``.""" + for opening, closing in (("{", "}"), ("(", ")")): + start = script.find(f"\n{name}() {opening}\n") + if start >= 0: + return script[start : script.index(f"\n{closing}\n", start)] + raise ValueError(f"no function {name}") class Unlexed(ValueError): @@ -292,32 +300,329 @@ def shell_residue(text): return "".join(out) -# A command that can run text as shell code, such as a block of echoed -# messages piped or written to it: a shell by name or as $BASH, $SHELL or -# $0, eval, exec, source, trap, or the . command, escaped or not. -SHELL = re.compile( - r"\b(?:(?:ba|da|z|k)?sh|eval|exec|source|trap)\b" - r"|\$\{?(?:BASH|SHELL|0)\b" - r"|(?:^|[\s;&|(){}!])\\?\.(?=\s|$)" +def function_body(script, name): + """phase() less its ``name() {`` line: the commands the function runs.""" + return phase(script, name).split("\n", 2)[2] + + +# Review of 24434729 (2): a pattern of shell names (bash, sh, eval, ...) +# matches text before bash removes quotes, so `b''ash` and `b\ash` passed it +# and ran bash. propose's commands are checked against what it may run +# instead: each command word, as written, must be one of these. Quoting, +# escaping or an expansion makes it another word, so it is flagged. The +# list is git and gh, the text tools propose pipes through, the builtins it +# uses, plan (the script's helper, pinned below) and pushgit (its own git +# wrapper, pinned below). +PROPOSE_RUNS = { + *("git", "gh", "grep", "cut", "cat", "printf", "echo"), + *(":", "[", "local", "exit"), + *("plan", "pushgit"), +} +GIT_RUNS = {"diff", "fetch", "log", "ls-remote", "rev-list", "rev-parse"} +PUSHGIT_RUNS = {"push"} +GH_RUNS = {("pr", "create"), ("pr", "edit"), ("pr", "list"), ("pr", "ready")} +# git -c may set only the credential helper pushgit hands the token through, +# and no git option may name a program for git to run. +GIT_CONFIG = {"credential.helper=", "'credential.helper=!gh auth git-credential'"} +GIT_RUNS_PROGRAM = re.compile( + r"""^['"]?(?:--upload-pack|--receive-pack|--exec\b|-u$)""" +) +PUSHGIT = ( + 'pushgit() { git -C "$TREE" -c credential.helper= ' + "-c 'credential.helper=!gh auth git-credential' \"$@\"; }" +) +# Where propose may write: the log and the step summary. A file it wrote +# elsewhere (a hook, $GITHUB_ENV) could run later. +PROPOSE_WRITES = {(">&", "2"), (">>", '"$GITHUB_STEP_SUMMARY"')} + +WORD_END = frozenset(" \t\n;&|()<>") +# &> and &>> are redirections, not & and a redirection. +OPERATOR = re.compile(r"&&|\|\||;;|\|&|[;|\n]|&(?!>)") +REDIRECT = re.compile(r"[0-9]*(?:&>>|&>|>>|>&|<&|<>|>\||<<<|>|<)") +ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(?:\[[^]]*\])?\+?=") +LOCAL_NAME = re.compile(r"[a-z_][a-z0-9_]*") +# A parameter expansion holding no quote, expansion or brace of its own. +PARAMETER = re.compile( + r"\$\{[#!]?(?:[A-Za-z_][A-Za-z0-9_]*|[0-9@*#?$!-])" + r"(?:\[[^]\s'\"$`\\]*\])?[^{}'\"$`\\]*\}" ) +class Commands: + """Every simple command bash would run from ``text`` (a shell_residue), + each with its words as written, its assignments and redirections, and + the function whose body holds it: the top level, the bodies of + if/while/until, ``{ }`` and ``( )``, and every ``$(...)``, ``<(...)``, + ``>(...)``, bash 5.3 ``${ ...; }`` and ``${|...;}``. A command word is + whatever starts a command, after an operator, a newline, ``!`` or a + reserved word, and after any assignments and redirections before it. + What it does not model (case, for, arithmetic, a parameter expansion + holding quotes or expansions, a word after a compound command) raises + Unlexed, so it is flagged rather than read past.""" + + def __init__(self, text): + self.text, self.commands, self.functions = text, [], [] + self.sequence(0, None, function=None) + + def blank(self, i): + while i < len(self.text): + if self.text[i] in " \t": + i += 1 + elif self.text.startswith("\\\n", i): + i += 2 + else: + break + return i + + def sequence(self, i, closer, function): + """The commands from i to ``closer`` (``)`` or ``}``; None for the + end of the text), returning the index past it.""" + t, open_, command = self.text, [], None + while True: + i = self.blank(i) + if i == len(t): + if closer or open_: + raise Unlexed(f"an unclosed {closer or open_[-1][0]}") + return i + if t[i] == "#": + # An inline comment, which the text rules flag. + i = t.find("\n", i) if "\n" in t[i:] else len(t) + continue + operator = OPERATOR.match(t, i) + if operator: + if operator.group() == ";;": + raise Unlexed("case") + command, i = None, operator.end() + continue + if t[i] == ")": + if closer != ")" or open_: + raise Unlexed("an unmatched )") + return i + 1 + if command is None and t[i] == "}": + if open_ and open_[-1][0] == "}": + _, name, start = open_.pop() + if name is not None: + self.functions.append( + { + "name": name, + "text": t[start : i + 1], + "top": not open_ and closer is None, + "at": start, + } + ) + function = None + command, i = self.record(i, function, closed=True), i + 1 + continue + if closer == "}": + return i + 1 + raise Unlexed("an unmatched }") + if t[i] == "(": + if command is not None: + raise Unlexed("( after a word") + i = self.sequence(i + 1, ")", function) + command = self.record(i, function, closed=True) + continue + if t.startswith(("<(", ">("), i): + start, i = i, self.sequence(i + 2, ")", function) + word = t[start:i] + elif REDIRECT.match(t, i): + redirect = REDIRECT.match(t, i) + target, i = self.word(self.blank(redirect.end()), function) + if command is None: + command = self.record(redirect.start(), function) + command["writes"].append((redirect.group(), target)) + continue + else: + start = i + word, i = self.word(i, function) + if command is not None and command["closed"]: + raise Unlexed(f"{word} after a compound command") + if command is None or command["name"] is None: + if command is None and word in ("if", "while", "until", "{"): + open_.append( + ({"if": "fi", "{": "}"}.get(word, "done"), None, start) + ) + continue + if command is None and word in ("then", "elif", "else", "do"): + if not open_ or open_[-1][0] != ("done" if word == "do" else "fi"): + raise Unlexed(f"{word} outside its compound command") + continue + if command is None and word in ("fi", "done"): + if not open_ or open_[-1][0] != word: + raise Unlexed(f"an unmatched {word}") + open_.pop() + command = self.record(i, function, closed=True) + continue + if command is None and word == "!": + continue + if ASSIGNMENT.match(word): + command = command or self.record(start, function) + command["assigns"].append(word) + continue + if command is None and t.startswith("()", self.blank(i)): + # name() { ...; }: its body runs where it is called. + i = self.blank(i) + 2 + while i < len(t) and t[i] in " \t\n": + i += 1 + if not t.startswith("{", i): + raise Unlexed(f"a function {word} without {{ }}") + open_.append(("}", word, start)) + function, i = word, i + 1 + continue + command = command or self.record(start, function) + command["name"] = word + continue + command["args"].append(word) + + def record(self, at, function, closed=False): + command = { + "name": None, + "args": [], + "assigns": [], + "writes": [], + "function": function, + "closed": closed, + "at": at, + } + self.commands.append(command) + return command + + def word(self, i, function): + """The word at i as written, and the index past it. Its + substitutions are read as commands.""" + t, start = self.text, i + while i < len(t) and t[i] not in WORD_END: + if t[i] == "\\": + i += 2 + elif t[i] == "'": + i = t.index("'", i + 1) + 1 + elif t[i] == '"': + i = self.quoted(i + 1, function) + elif t[i] == "$": + i = self.dollar(i, function) + else: + i += 1 + if t[i : i + 1] == "(" and ASSIGNMENT.fullmatch(t[start:i]): + i = self.array(i + 1, function) + if i == start: + raise Unlexed(f"no word at {t[i : i + 10]!r}") + return t[start:i], i + + def quoted(self, i, function): + t = self.text + while t[i] != '"': + if t[i] == "\\": + i += 2 + elif t[i] == "$": + i = self.dollar(i, function) + else: + i += 1 + return i + 1 + + def dollar(self, i, function): + t = self.text + if t.startswith("$((", i): + raise Unlexed("arithmetic") + if t.startswith("$(", i): + return self.sequence(i + 2, ")", function) + if t.startswith("${", i) and t[i + 2 : i + 3] in (" ", "\t", "\n", "|"): + return self.sequence(i + 3, "}", function) + if t.startswith("${", i): + parameter = PARAMETER.match(t, i) + if not parameter: + raise Unlexed(f"the expansion {t[i : i + 20]!r}") + return parameter.end() + if t.startswith('$"', i): + return self.quoted(i + 2, function) + return i + 1 + + def array(self, i, function): + """NAME=( WORD... ): the words, over lines, up to ``)``.""" + t = self.text + while True: + i = self.blank(i) + if i < len(t) and t[i] == "\n": + i += 1 + elif i < len(t) and t[i] == ")": + return i + 1 + else: + _, i = self.word(i, function) + + +def disallowed(commands): + """What in ``commands`` runs or writes beyond PROPOSE_RUNS and + PROPOSE_WRITES, as a list of findings. pushgit's body is PUSHGIT, at the + top level, before any call; nothing else may be defined.""" + found, wrapper = [], None + for function in commands.functions: + if function["text"] == PUSHGIT and function["top"] and wrapper is None: + wrapper = function["at"] + else: + found.append(f"defines {function['name']}") + for command in commands.commands: + name, args = command["name"], command["args"] + shown = " ".join([*command["assigns"], *filter(None, [name]), *args]) + if command["function"] == "pushgit" and wrapper is not None: + continue + for write in command["writes"]: + if write not in PROPOSE_WRITES: + found.append(f"{shown or 'a compound command'} writes {''.join(write)}") + if name is None: + for assign in command["assigns"]: + if not LOCAL_NAME.fullmatch( + ASSIGNMENT.match(assign).group().rstrip("+=") + ): + found.append(f"{assign} sets a variable that is not a local's") + continue + if command["assigns"]: + found.append(f"{shown} sets its command's environment") + if name not in PROPOSE_RUNS: + found.append(f"{shown} runs {name}") + elif name == "local": + for arg in args: + bound = ASSIGNMENT.match(arg) + if not LOCAL_NAME.fullmatch( + bound.group().rstrip("+=") if bound else arg + ): + found.append(f"{shown} declares {arg}") + elif name == "printf" and args[:1] and args[0].startswith("-v"): + found.append(f"{shown} sets a variable") + elif name == "gh" and tuple(args[:2]) not in GH_RUNS: + found.append(f"{shown} runs gh {' '.join(args[:2])}") + elif name in ("git", "pushgit"): + if name == "pushgit" and (wrapper is None or wrapper > command["at"]): + found.append(f"{shown} runs pushgit where it is not defined") + at = 0 + while name == "git" and args[at : at + 1] in (["-C"], ["-c"]): + value = args[at + 1 : at + 2] + if args[at] == "-c" and not (value and value[0] in GIT_CONFIG): + found.append(f"{shown} sets git config {' '.join(value)}") + at += 2 + runs = GIT_RUNS if name == "git" else PUSHGIT_RUNS + if args[at : at + 1] == [] or args[at] not in runs: + found.append(f"{shown} runs {name} {' '.join(args[at : at + 1])}") + found += [ + f"{shown} hands git a program: {arg}" + for arg in args[at:] + if GIT_RUNS_PROGRAM.match(arg) + ] + return found + + def runs_pipeline_code(text): - """The lines of ``text`` that may run the builder or a pipeline module, - hide a command in a comment or run text as code, once its messages are - set aside.""" + """What in ``text`` may run the builder or a pipeline module, hide a + command in a comment, or run or write anything beyond PROPOSE_RUNS and + PROPOSE_WRITES, once its messages are set aside.""" try: residue = shell_residue(text) + commands = Commands(residue) except Unlexed as problem: return [str(problem)] return [ line for line in residue.splitlines() - if "#" in line - or "pipeline" in line - or re.search(r"\bbuilder\b", line) - or SHELL.search(line) - ] + if "#" in line or "pipeline" in line or re.search(r"\bbuilder\b", line) + ] + disallowed(commands) def test_the_builder_runs_no_release_code_and_never_merges(): @@ -364,11 +669,11 @@ def test_the_builder_runs_no_release_code_and_never_merges(): if "python" in line and not line.lstrip().startswith("#"): assert "python3 -I" in line, line assert 'python3 -I -S "$HERE/pipeline/uk_replay_results_pr.py"' in rebuild - # propose runs neither the builder nor any pipeline module. Its messages - # may name them (review of 78e080c6, 3), so shell_residue sets aside - # each message that bash reads as a literal echoed to the log. Bash runs - # `builder check` in each of these (bash 5.3 in the ${ ...; } forms, - # bash 3.2 in the rest), and each is flagged. + # propose runs neither the builder nor any pipeline module, and nothing + # but PROPOSE_RUNS. Its messages may name them (review of 78e080c6, 3), + # so shell_residue sets aside each message that bash reads as a literal + # echoed to the log. Bash runs `builder check` in each of these (bash 5.3 + # in the ${ ...; } forms, bash 3.2 in the rest), and each is flagged. for runs in ( 'echo "::error::fine" >&2; builder check', 'echo "::notice::$(builder check)"', @@ -423,7 +728,8 @@ def test_the_builder_runs_no_release_code_and_never_merges(): 'x=(--a \'b\'\n "c")\necho "::warning::not this builder"', ): assert not runs_pipeline_code(inert), inert - assert not runs_pipeline_code(propose), runs_pipeline_code(propose) + body = function_body(script, "propose") + assert not runs_pipeline_code(body), runs_pipeline_code(body) tree = ast.parse((ROOT / "pipeline/uk_replay_results_pr.py").read_text()) for node in ast.walk(tree): if isinstance(node, ast.Import): @@ -444,6 +750,190 @@ def test_the_builder_runs_no_release_code_and_never_merges(): assert node.func.id not in {"eval", "exec", "__import__"} +GROUP = '{\necho "::error::; builder check"\n}' +# pushgit, defined with another program in git's place. +NOT_PUSHGIT = PUSHGIT.replace("git -C", "b''ash -C") + + +def test_propose_runs_only_the_commands_it_lists(): + script = SCRIPT.read_text() + body = function_body(script, "propose") + commands = Commands(shell_residue(body)) + # The list is what propose runs, no more: a command it gains is a + # reviewed edit to PROPOSE_RUNS, and one it drops leaves the list. + assert {c["name"] for c in commands.commands if c["name"]} == PROPOSE_RUNS + # Review of 24434729 (2): bash removes the quotes and runs bash. Every + # spelling or other route to a program, a variable or a file beyond + # PROPOSE_RUNS and PROPOSE_WRITES is flagged. + for runs in ( + f"{GROUP} | b''ash", + f"{GROUP} | b\\ash", + f'{GROUP} | "b"ash', + f"{GROUP} | $SHELL", + f"{GROUP} | env bash", + f"{GROUP} | command bash", + f"{GROUP} | xargs -0 sh -c", + f"{GROUP} | /bin/bash", + f"{GROUP} | python3 -c 'import os'", + f"if :; then\n {GROUP} | b''ash\nfi", + f"while :; do\n {GROUP} | b''ash\ndone", + # Substitutions and subshells, where no message is set aside. + "x=\"${ b''ash x; }\"", + "x=${|b''ash x;}", + "x=$(b''ash x)", + "cat <(b''ash x)", + "(\n b''ash x\n)", + # A command's environment, or a variable bash or a program reads. + "PATH=/tmp git rev-parse HEAD", + 'PATH="$WORK"', + "BASH_ENV=/tmp/x", + "local PATH=/tmp", + "local -n x=PATH", + "printf -v PATH %s /tmp", + # git and gh beyond what propose uses, or naming a program to run. + "git -c alias.x='!bash' x", + "git -c core.pager=bash log", + "git --exec-path=/tmp fetch origin", + "git ls-remote --upload-pack='bash -c x' .", + "git push --receive-pack=x origin HEAD", + "git -C x worktree add y", + "gh api /repos", + "gh extension exec x", + # A file it writes elsewhere may run later. + 'cat x > "$GITHUB_ENV"', + 'echo x >> "$GITHUB_PATH"', + f'{GROUP} > "$TMPDIR/x"', + # Its own functions: only pushgit, pinned, defined before it runs. + "git() { b''ash; }", + 'pushgit push -q origin "HEAD:refs/heads/$branch"', + f"{NOT_PUSHGIT}\npushgit push", + f"pushgit push\n{PUSHGIT}", + f"if :; then\n {PUSHGIT}\nfi\npushgit push", + f"{PUSHGIT}\npushgit fetch origin", + # What the parser does not model is flagged, not read past. + "for x in a; do :; done", + "case x in x) : ;; esac", + "[[ -n x ]]", + "echo $((1 + 2))", + "echo \"${x:-$(b''ash)}\"", + "{ :; } x", + ): + assert runs_pipeline_code(runs), runs + for inert in ( + f'{PUSHGIT}\npushgit push -q origin "HEAD:refs/heads/$branch"', + 'x=$(git -C "$TREE" rev-parse HEAD | cut -f1)', + 'if ! git log -1 --format=%B "$r" | grep -qxF "$t"; then\n exit 1\nfi', + 'local create=(--repo "$R"\n --title "$t")\ncreate+=(--draft)\ngh pr create "${create[@]}"', + 'if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then\n cat x >> "$GITHUB_STEP_SUMMARY"\nfi', + 'echo "$branch already holds this tree" >&2', + "n=$(gh pr list --head \"$b\" \\\n --json number --jq '.[0].number // empty')", + ): + assert not runs_pipeline_code(inert), (inert, runs_pipeline_code(inert)) + # A function shadows a program or builtin of the same name, so none in + # the script has one of those names but plan and pushgit, each defined + # once: pushgit as PUSHGIT, and plan as field on the plan. field, which + # plan runs, is the isolated runner's Python on a fixed program that + # imports json and sys alone. + defined = re.findall(r"^\s*([A-Za-z_][A-Za-z0-9_]*)\(\) \{", script, re.M) + assert set(defined) & PROPOSE_RUNS == {"plan", "pushgit"} + assert defined.count("plan") == defined.count("pushgit") == 1 + assert defined.count("field") == 1 + assert f" {PUSHGIT}\n" in body + assert '\nplan() { field "$WORK/plan.json" "$@"; }\n' in script + (field,) = Commands(shell_residue(function_body(script, "field"))).commands + assert field["name"] == "python3" and not field["assigns"] and not field["writes"] + flag, option, program, rest = field["args"] + assert (flag, option, rest) == ("-I", "-c", '"$@"') + assert program[0] == program[-1] == "'" + imported = { + alias.name + for node in ast.walk(ast.parse(program[1:-1])) + if isinstance(node, (ast.Import, ast.ImportFrom)) + for alias in node.names + } + assert imported == {"json", "sys"} + assert not [ + node + for node in ast.walk(ast.parse(program[1:-1])) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id in {"eval", "exec", "__import__", "compile"} + ] + + +# The names propose may run with any one argument (git, gh and pushgit +# take only some), and names it may not run at all. +PLAIN_RUNS = sorted(PROPOSE_RUNS - {"git", "gh", "pushgit"}) +NOT_RUNS = ["bash", "sh", "dash", "zsh", "ksh", "eval", "exec", "source", "."] +NOT_RUNS += ["trap", "env", "command", "builtin", "xargs", "python3", "tee", "time"] +CONTEXTS = [ + "{w} x", + ": | {w} x", + ": && {w} x", + ": || {w} x", + ": ; {w} x", + "! {w} x", + ">&2 {w} x", + "if :; then {w} x; fi", + "if :; then :; elif {w} x; then :; else {w} x; fi", + "while {w} x; do {w} x; done", + "until {w} x; do :; done", + "x=$({w} x)", + 'x="$({w} x)"', + "( {w} x )", + "{{ {w} x; }}", + 'x="${{ {w} x; }}"', + "x=${{|{w} x;}}", + "cat <({w} x)", + "local x=$({w} x)", + "x=(a $({w} x))", +] + + +@st.composite +def spellings(draw): + """A command name, written as is or with bash's quotes and escapes + around or inside it (quote removal gives the name back).""" + name = draw( + st.sampled_from(PLAIN_RUNS + NOT_RUNS) + | st.from_regex(r"[a-z][a-z0-9_-]{0,8}", fullmatch=True) + ) + pieces = [] + for character in name: + pieces.append( + draw( + st.sampled_from( + [ + character, + f"'{character}'", + f'"{character}"', + f"\\{character}", + f"''{character}", + f'{character}""', + ] + ) + ) + ) + return name, "".join(pieces) + + +@settings(max_examples=300, deadline=None) +@given(spelled=spellings(), context=st.sampled_from(CONTEXTS)) +def test_a_command_runs_only_as_a_listed_literal_word(spelled, context): + # Invariant: for any spelling of any name, in any command position the + # parser models, the command is flagged unless the word as written is a + # name PROPOSE_RUNS lists. Quote removal never turns a flagged word into + # an allowed one, and an allowed one is allowed wherever it runs. + name, written = spelled + text = context.format(w=written) + assert bool(runs_pipeline_code(text)) == (written not in PLAIN_RUNS), ( + text, + runs_pipeline_code(text), + ) + if name not in PLAIN_RUNS: + assert runs_pipeline_code(context.format(w=name)), name + + def test_every_guard_runs_before_the_commit_or_the_push_it_protects(): # Defense in depth that correct code never trips (scope) still has to be # wired in, in this order. @@ -478,9 +968,24 @@ def order(section, *fragments): 'verify-sealed "$(plan paths namespace)"', "uk_replay_regenerate.sh", "scorecard_db.build_db", + "the checks changed tracked files", + "nondeterministic", + "preflight", "output tree", + "output preflight", "output action build", ) + # Review of 24434729 (3): CI's checks run after every check that stops + # the run, with no token, and report before anything is output. + order( + phase(script, "preflight"), + "no GitHub token in the environment", + "unset GITHUB_ENV GITHUB_OUTPUT GITHUB_PATH GITHUB_STATE GITHUB_STEP_SUMMARY", + '"${RUFF[@]}"', + '"${SUITE[@]}"', + 'git -C "$TREE" status --porcelain', + "builder preflight ", + ) rebuild = phase(script, "rebuild") order( rebuild, @@ -492,6 +997,7 @@ def order(section, *fragments): 'builder check --request-dir "$STAGE/$REQUEST" --checkout "$WORK/tip"', "on main as it is now", " body ", + "output draft", "output action build", ) # Review of 78e080c6 (1): job 2 reads the request only as assemble @@ -788,6 +1294,31 @@ def control_line(): return words, [word for word, before in zip(words[1:], words) if before == "--with"] +def script_array(name): + """The words of the builder script's ``local NAME=(...)`` line.""" + (line,) = [ + line.strip() + for line in SCRIPT.read_text().splitlines() + if line.strip().startswith(f"local {name}=(") + ] + return shlex.split(line.removeprefix(f"local {name}=(").removesuffix(")")) + + +def test_the_build_job_runs_cis_format_check_and_suite_word_for_word(): + # Review of 24434729 (3): the results commit faces ci.yml's own python + # job before it is proposed, so the lines are its lines, as are their + # environments (PYTHONPATH=. for the suite, nothing for ruff). + ci = yaml.safe_load((ROOT / ".github/workflows/ci.yml").read_text()) + steps = ci["jobs"]["python"]["steps"] + (ruff,) = [s for s in steps if s.get("run", "").startswith("uvx ruff format")] + (suite,) = [s for s in steps if " pytest tests/" in s.get("run", "")] + assert script_array("RUFF") == shlex.split(ruff["run"]) + assert "env" not in ruff + assert script_array("SUITE") == shlex.split(suite["run"]) + assert suite["env"] == {"PYTHONPATH": "."} + assert 'PYTHONPATH=. "${SUITE[@]}"' in phase(SCRIPT.read_text(), "preflight") + + RELEASE = {"policyengine", "policyengine_uk", "policyengine_core", "huggingface_hub"} @@ -1484,6 +2015,248 @@ def test_a_commit_never_touches_github_even_inside_its_own_trees(path): # --- the whole builder on a local bare remote ---------------------------------- +# --- CI's checks on the commit ---------------------------------------------------- + +# pytest -q's tail as CI prints it (CI is set, so whole messages, over lines), +# with a failing test's captured output holding an earlier summary of its own. +SUMMARY_HEADER = "=" * 27 + " short test summary info " + "=" * 28 + "\n" +SUITE_LOG = ( + "....F.E\n" + + "=" * 35 + + " FAILURES " + + "=" * 35 + + "\n----- Captured stdout call -----\n" + + SUMMARY_HEADER + + "FAILED tests/inner.py::test_of_an_inner_run - AssertionError\n" + + SUMMARY_HEADER + + "FAILED tests/test_toy.py::test_bad - AssertionError: multi\n" + + " line - message\n" + + "assert 1 == 2\n" + + "FAILED tests/test_toy.py::test_p[a - b] - AssertionError: assert 'a - b' == 'z'\n" + + "ERROR tests/test_toy.py::test_err - RuntimeError: setup\n" + + "ERROR tests/test_broken.py\n" + + "3 failed, 1 passed, 2 errors in 0.01s\n" +) +# ruff format --check from ruff 0.16.7, and before 0.16. +RUFF_LOG = """unformatted: File would be reformatted + --> tests/fmt_me.py:1:2 + | + - x=1 +1 + x = 1 + | + +invalid-syntax: Expected a parameter or the end of the parameter list + --> tests/syntax.py:1:7 + | +1 | def f(: + | ^ + +unformatted: File would be reformatted + --> tests/test_toy.py:3:1 + | +2 | +3 + + +2 files would be reformatted +""" +OLD_RUFF_LOG = "Would reformat: tests/a.py\nWould reformat: pipeline/b.py\n2 files would be reformatted, 9 files already formatted\n" + + +def test_the_failures_are_what_the_last_summary_and_ruff_and_git_name(): + assert builder.suite_failures(SUITE_LOG) == [ + "tests/test_toy.py::test_bad", + "tests/test_toy.py::test_p[a - b]", + "tests/test_toy.py::test_err", + "tests/test_broken.py", + ] + assert builder.suite_failures("...\n3 passed in 0.01s\n") == [] + assert builder.suite_failures("INTERNALERROR> collection died\n") == [] + assert builder.format_failures(RUFF_LOG) == [ + "tests/fmt_me.py", + "tests/syntax.py", + "tests/test_toy.py", + ] + assert builder.format_failures(OLD_RUFF_LOG) == ["tests/a.py", "pipeline/b.py"] + assert builder.drift_paths(" M data/x.json\n?? stray.txt\n") == [ + "data/x.json", + "stray.txt", + ] + # A passing check reports nothing, whatever its log holds. + assert builder.report(0, ["tests/a.py"]) == {"exit": 0, "count": 0, "names": []} + + +PARAMETER_TEXT = st.text( + st.characters(min_codepoint=32, max_codepoint=126, exclude_characters="[]`"), + max_size=20, +) +NODE_IDS = st.builds( + lambda module, test, parameter: ( + f"tests/test_{module}.py" + + (f"::test_{test}" if test else "") + + (f"[{parameter}]" if test and parameter is not None else "") + ), + st.from_regex(r"[a-z][a-z0-9_]{0,10}", fullmatch=True), + st.none() | st.from_regex(r"[a-z][a-z0-9_]{0,10}", fullmatch=True), + st.none() | PARAMETER_TEXT, +) +MESSAGE_LINE = st.text( + st.characters(min_codepoint=32, max_codepoint=126), max_size=40 +).filter(lambda line: not line.startswith(("FAILED ", "ERROR "))) + + +@settings(max_examples=200, deadline=None) +@given( + names=st.lists(NODE_IDS, unique=True, max_size=20), + messages=st.lists(st.lists(MESSAGE_LINE, max_size=3), min_size=20, max_size=20), +) +def test_the_suites_failures_round_trip_through_its_summary(names, messages): + # Invariant: the node ids of pytest's short summary come back exactly, + # in order, whatever the messages hold (a " - ", more lines) and + # whatever a parametrised id holds (a " - " inside its brackets). + lines = [] + for name, message in zip(names, messages): + word = "ERROR" if "::" not in name else "FAILED" + lines.append(f"{word} {name}" + (f" - {message[0]}" if message else "")) + lines += message[1:] + log = "..F\n" + SUMMARY_HEADER + "".join(f"{line}\n" for line in lines) + assert builder.suite_failures(log) == names + + +ANY_LINE = st.text(st.characters(exclude_characters="\n\r"), max_size=400) + + +@settings(max_examples=200, deadline=None) +@given( + ruff_exit=st.integers(0, 255), + unformatted=st.lists(ANY_LINE, max_size=150), + suite_exit=st.integers(0, 255), + failed=st.lists(ANY_LINE, max_size=150), + drift=st.lists(ANY_LINE, max_size=150), +) +def test_the_build_job_never_reports_what_the_propose_job_refuses( + ruff_exit, unformatted, suite_exit, failed, drift +): + # Invariant (differential: job 1's writer against job 2's reader): for + # any exit statuses and any names the logs hold, the report job 1 + # outputs is one line job 2 accepts unchanged, small enough for a job + # output, listing at most LISTED names per check, each listable. + report = builder.preflight( + ruff_exit, + "".join(f"Would reformat: {name}\n" for name in unformatted), + suite_exit, + SUMMARY_HEADER + "".join(f"FAILED {name}\n" for name in failed), + "".join(f"?? {name}\n" for name in drift), + ) + text = json.dumps(report, separators=(",", ":"), sort_keys=True) + assert builder.read_preflight(text) == report + assert "\n" not in text and len(text) < 100_000 + for check in report.values(): + assert len(check["names"]) <= min(check["count"], builder.LISTED) + assert all(builder.LISTABLE.fullmatch(name) for name in check["names"]) + assert (report["suite"]["count"] > 0) <= (suite_exit != 0) + + +def passing(): + return json.loads(PASSING) + + +MALFORMED = { + "not JSON": "all fine", + "a list": "[]", + "null": "null", + "a check missing": lambda r: r.pop("drift"), + "a check added": lambda r: r.update(lint={"exit": 0, "count": 0, "names": []}), + "a field missing": lambda r: r["suite"].pop("names"), + "a field added": lambda r: r["suite"].update(note="x"), + "a check not an object": lambda r: r.update(suite=[]), + "a negative exit": lambda r: r["suite"].update(exit=-1), + "an exit over 255": lambda r: r["suite"].update(exit=256), + "a boolean exit": lambda r: r["suite"].update(exit=True), + "a string exit": lambda r: r["suite"].update(exit="1"), + "a float exit": lambda r: r["suite"].update(exit=1.0), + "a negative count": lambda r: r["suite"].update(exit=1, count=-1), + "a boolean count": lambda r: r["suite"].update(exit=1, count=True), + "a pass with failures": lambda r: r["ruff"].update(count=1, names=["a.py"]), + "more names than failures": lambda r: r["suite"].update( + exit=1, count=1, names=["a", "b"] + ), + "more names than LISTED": lambda r: r["suite"].update( + exit=1, count=500, names=[f"t{i}" for i in range(builder.LISTED + 1)] + ), + "a name twice": lambda r: r["suite"].update(exit=1, count=2, names=["a", "a"]), + "a backtick": lambda r: r["suite"].update(exit=1, count=1, names=["a```b"]), + "a newline": lambda r: r["suite"].update(exit=1, count=1, names=["a\nb"]), + "a leading space": lambda r: r["suite"].update(exit=1, count=1, names=[" a"]), + "non-ASCII": lambda r: r["suite"].update(exit=1, count=1, names=["tést"]), + "a long name": lambda r: r["suite"].update(exit=1, count=1, names=["a" * 301]), + "a number for a name": lambda r: r["suite"].update(exit=1, count=1, names=[1]), +} + + +@pytest.mark.parametrize("edit", MALFORMED.values(), ids=MALFORMED.keys()) +def test_the_propose_job_refuses_a_report_of_any_other_shape(edit): + if isinstance(edit, str): + text = edit + else: + report = passing() + edit(report) + text = json.dumps(report) + with pytest.raises(builder.Refused, match="outputs are malformed: preflight"): + builder.read_preflight(text) + + +@settings(max_examples=100, deadline=None) +@given( + incomplete=st.booleans(), + exits=st.fixed_dictionaries( + {key: st.integers(0, 255) for key in builder.PREFLIGHT} + ), +) +def test_a_pull_request_is_a_draft_exactly_when_integrity_or_a_check_fails( + incomplete, exits +): + checks = { + key: {"exit": status, "count": 0, "names": []} for key, status in exits.items() + } + checks = builder.read_preflight(json.dumps(checks)) + assert builder.is_draft({"draft": incomplete}, checks) == ( + incomplete or any(exits.values()) + ) + assert builder.failed_checks(checks) == [ + key for key in builder.PREFLIGHT if exits[key] + ] + + +@settings(max_examples=100, deadline=None) +@given( + key=st.sampled_from(sorted(builder.PREFLIGHT)), + names=st.lists( + st.from_regex(r"[!-_a-~][ -_a-~]{0,40}[!-_a-~]", fullmatch=True), + unique=True, + max_size=builder.LISTED, + ), + unlisted=st.integers(0, 5000), +) +def test_a_failing_checks_line_lists_its_names_in_one_fence(key, names, unlisted): + # Invariant: every listed name is a line of its own inside one fenced + # block, nothing else is, and a count beyond the list is stated. + count = len(names) + unlisted + if not count: + return + check = {"exit": 1, "count": count, "names": names} + line = builder.check_line( + key, builder.read_preflight(json.dumps({**passing(), key: check}))[key] + ) + assert line.count("```") == (2 if names else 0) + if names: + fenced = line.split("```text\n", 1)[1].split("\n ```", 1)[0] + assert fenced.splitlines() == [f" {name}" for name in names] + assert (f"{unlisted:,} more are in the build job's log" in line) == bool( + names and unlisted + ) + assert f"{count:,} " in line + + def next_minor(version): major, minor = (int(part) for part in version.split(".")[:2]) return f"{major}.{minor + 1}.0" @@ -1807,9 +2580,70 @@ def install_uv(tools): print(os.environ.get("GH_OPEN_PR", "")) elif args[:2] == ["pr", "create"]: print("https://github.com/PolicyEngine/policyengine-scorecard/pull/999") -elif args[:2] != ["pr", "edit"]: +elif args[:2] not in (["pr", "edit"], ["pr", "ready"]): sys.exit(97) """ +# CI's suite and format check in the build job, as stubs. Each logs the +# commit it ran on, its arguments and which GitHub token or command file its +# environment held, and fails as the test asks: SUITE_FAILS (node ids, +# comma-separated), SUITE_EXIT (no summary), SUITE_DRIFT (a changed tracked +# file and an untracked one), RUFF_UNFORMATTED (paths), RUFF_STYLE=old (the +# "Would reformat:" lines ruff printed before 0.16). +EXPOSED = ( + "GH_TOKEN", + "GITHUB_TOKEN", + "GITHUB_ENV", + "GITHUB_OUTPUT", + "GITHUB_PATH", + "GITHUB_STATE", + "GITHUB_STEP_SUMMARY", +) +CHECK_STUB = f"""import os, subprocess, sys +from pathlib import Path +check, args = sys.argv[1], sys.argv[2:] +head = subprocess.run( + ["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True +).stdout.strip() +exposed = ",".join(k for k in {EXPOSED!r} if k in os.environ) or "-" +with open(os.environ["CHECK_LOG"], "a") as log: + log.write( + f"{{check}} {{head}} {{os.environ.get('PYTHONPATH', '-')}} {{exposed}} " + + " ".join(args) + "\\n" + ) +if check == "ruff": + paths = [p for p in os.environ.get("RUFF_UNFORMATTED", "").split(",") if p] + for path in paths: + if os.environ.get("RUFF_STYLE") == "old": + print(f"Would reformat: {{path}}") + else: + print(f"unformatted: File would be reformatted\\n --> {{path}}:1:1") + print(f"{{len(paths)}} files would be reformatted, 9 files already formatted") + sys.exit(1 if paths else 0) +if os.environ.get("SUITE_DRIFT"): + Path("data/uk/replay_variants.json").write_text("{{}}") + Path("stray.txt").write_text("left behind") +names = [n for n in os.environ.get("SUITE_FAILS", "").split(",") if n] +print("..F" if names else "...") +if os.environ.get("SUITE_EXIT"): + print("INTERNALERROR> collection died") + sys.exit(int(os.environ["SUITE_EXIT"])) +if names: + print("=" * 27 + " short test summary info " + "=" * 28) + for name in names: + if name.endswith(".py"): + print(f"ERROR {{name}}") + else: + print(f"FAILED {{name}} - AssertionError: a - b\\nsecond line") + print(f"{{len(names)}} failed, 3 passed in 0.01s") + sys.exit(1) +print("3 passed in 0.01s") +""" +# What the build job outputs when all three of CI's checks pass. +PASSING = json.dumps( + {key: {"exit": 0, "count": 0, "names": []} for key in builder.PREFLIGHT}, + separators=(",", ":"), + sort_keys=True, +) class Remote: @@ -1868,8 +2702,30 @@ def __init__(self, tmp_path): ) self.tools = tmp_path / "bin" self.tools.mkdir() - # The build job's checks run with CONTROL's packages alone (UV_RUN). - install_uv(self.tools) + # The build job's checks run with CONTROL's packages alone (UV_RUN); + # `uv run` of anything but python is CI's suite, and uvx is ruff. + (self.tools / "control").mkdir() + control = install_uv(self.tools / "control") + stub = self.tools / "check_stub.py" + stub.write_text(CHECK_STUB) + for name, dispatch in ( + ( + "uv", + f"if 'python' in sys.argv:\n os.execv({str(control)!r}, sys.argv)\n" + f"os.execv(sys.executable, [sys.executable, {str(stub)!r}, 'suite'," + " *sys.argv[1:]])\n", + ), + ( + "uvx", + "assert sys.argv[1] == 'ruff', sys.argv\n" + f"os.execv(sys.executable, [sys.executable, {str(stub)!r}, 'ruff'," + " *sys.argv[2:]])\n", + ), + ): + (self.tools / name).write_text( + f"#!{sys.executable}\nimport os, sys\n{dispatch}" + ) + (self.tools / name).chmod(0o755) gh = self.tools / "gh" gh.write_text(f"#!{sys.executable}\n{GH_STUB}") gh.chmod(0o755) @@ -1972,6 +2828,7 @@ def rebuild_job(self, rid, received, sha, name, **overrides): BUILT_STATE=received["state"], BUILT_SEALED=received["sealed"], BUILT_CONTENT_HASH=received["content_hash"], + BUILT_PREFLIGHT=received["preflight"], ) return result, outputs, (fresh, env, temp) @@ -2003,6 +2860,7 @@ def run(self, rid, forge=None, dispatched=None, **overrides): env2, BUILT_COMMIT=self.rebuilt["commit"], BUILT_BRANCH=self.rebuilt["branch"], + BUILT_DRAFT=self.rebuilt["draft"], GH_TOKEN="app-installation-token", ) outs.append(proposed) @@ -2125,7 +2983,17 @@ def test_a_certified_request_becomes_one_bot_commit_and_a_pull_request(remote): assert git(remote.runner, "rev-parse", f"{verified}^{{tree}}") == git( remote.remote, "rev-parse", f"{head}^{{tree}}" ) - assert [line.split()[0] for line in checks[1:]] == ["build_db", "build_db"] + assert [line.split()[0] for line in checks[1:3]] == ["build_db", "build_db"] + # Review of 24434729 (3): then CI's format check and suite, its own + # lines, on that commit, with no token or command file in reach. + assert checks[3:] == [ + f"ruff {verified} - - {' '.join(script_array('RUFF')[2:])}", + f"suite {verified} . - {' '.join(script_array('SUITE')[1:])}", + ] + assert json.loads(remote.outputs["preflight"]) == { + key: {"exit": 0, "count": 0, "names": []} for key in builder.PREFLIGHT + } + assert remote.rebuilt["draft"] == "false" calls = remote.gh_calls() assert [call[:2] for call in calls] == [["pr", "list"], ["pr", "create"]] create = calls[1] @@ -2140,6 +3008,9 @@ def test_a_certified_request_becomes_one_bot_commit_and_a_pull_request(remote): assert "all 8 committed result files" in body assert "axiom: n/a" in body assert "Diff vs `" + PE650 + "`" in body + for key in builder.PREFLIGHT: + assert builder.check_line(key, {"exit": 0, "count": 0, "names": []}) in body + assert "this pull request is a draft" not in body # The builder never merged and never touched main. assert git(remote.remote, "rev-parse", "main") == main @@ -2658,6 +3529,12 @@ def test_a_variant_id_that_cannot_name_a_branch_is_refused(remote): ({"sealed": "all fine; rm -rf /"}, "outputs are malformed"), ({"content_hash": "not hex"}, "outputs are malformed"), ({"tree": "abc"}, "outputs are malformed"), + ({"preflight": "all fine"}, "outputs are malformed: preflight checks"), + ({"preflight": "{}"}, "outputs are malformed: preflight checks"), + ( + {"preflight": PASSING.replace('"names":[]', '"names":["```x"]', 1)}, + "outputs are malformed: preflight", + ), ], ) def test_job_2_pushes_only_what_it_rebuilt_and_job_1_verified(remote, forge, message): @@ -2827,16 +3704,18 @@ def test_propose_pushes_only_the_commit_rebuild_assembled(remote): env, BUILT_COMMIT=remote.rebuilt["commit"], BUILT_BRANCH=remote.rebuilt["branch"], + BUILT_DRAFT=remote.rebuilt["draft"], GH_TOKEN="app-installation-token", ) assert again.returncode == 1 assert "changed after it was assembled" in again.stderr assert remote.branch(record) == pushed # And propose needs rebuild's outputs and the token. - for missing in ("BUILT_COMMIT", "BUILT_BRANCH", "GH_TOKEN"): + for missing in ("BUILT_COMMIT", "BUILT_BRANCH", "BUILT_DRAFT", "GH_TOKEN"): extra = { "BUILT_COMMIT": remote.rebuilt["commit"], "BUILT_BRANCH": remote.rebuilt["branch"], + "BUILT_DRAFT": remote.rebuilt["draft"], "GH_TOKEN": "app-installation-token", } del extra[missing] @@ -2992,6 +3871,111 @@ def test_an_incomplete_integrity_opens_a_draft(remote): assert "this pull request is a draft" in remote.body() +CHECK_FAILURES = [ + ( + {"SUITE_FAILS": "tests/test_a.py::test_x[a - b],tests/test_b.py"}, + "suite", + 1, + ["tests/test_a.py::test_x[a - b]", "tests/test_b.py"], + ), + ( + {"RUFF_UNFORMATTED": "tests/test_a.py,pipeline/b.py"}, + "ruff", + 1, + ["tests/test_a.py", "pipeline/b.py"], + ), + ( + {"RUFF_UNFORMATTED": "tests/test_a.py", "RUFF_STYLE": "old"}, + "ruff", + 1, + ["tests/test_a.py"], + ), + ({"SUITE_EXIT": "2"}, "suite", 2, []), + ( + {"SUITE_DRIFT": "1"}, + "drift", + 1, + ["data/uk/replay_variants.json", "stray.txt"], + ), +] + + +@pytest.mark.parametrize(("override", "key", "status", "names"), CHECK_FAILURES) +def test_a_failing_ci_check_opens_a_draft_that_names_it( + remote, override, key, status, names +): + # Review of 24434729 (3): CI's own checks on the commit, failing, still + # propose it, as a draft whose body says what failed. + rid, record, _ = remote.certify() + result = remote.run(rid, **override) + assert result.returncode == 0, result.stdout + result.stderr + assert remote.branch(record) + reported = json.loads(remote.outputs["preflight"]) + assert reported[key] == {"exit": status, "count": len(names), "names": names} + assert all(reported[other]["exit"] == 0 for other in set(reported) - {key}) + assert remote.rebuilt["draft"] == "true" + create = next(call for call in remote.gh_calls() if call[:2] == ["pr", "create"]) + assert "--draft" in create + body = remote.body() + assert "CI's own checks fail on this commit" in body + assert "Integrity is not `complete`" not in body + assert builder.check_line(key, reported[key]) in body + for name in names: + assert f"\n {name}\n" in body + if not names: + assert "the build job's log has its output" in body + + +def test_incomplete_integrity_and_a_failing_check_say_both(remote): + rid, _, _ = remote.certify(integrity="incomplete") + result = remote.run(rid, SUITE_FAILS="tests/test_a.py::test_x") + assert result.returncode == 0, result.stdout + result.stderr + body = remote.body() + assert "Integrity is not `complete`" in body + assert "CI's own checks fail on this commit" in body + + +def test_a_failing_rebuild_turns_its_open_pull_request_back_into_a_draft(remote): + # A rerun after main moves edits the open pull request. One whose checks + # fail makes it a draft again; one whose checks pass leaves it as it is, + # since only a person marks a pull request ready. + rid, _, _ = remote.certify() + assert remote.run(rid).returncode == 0 + move_main(remote) + result = remote.run(rid, GH_OPEN_PR="999", SUITE_FAILS="tests/test_a.py::test_x") + assert result.returncode == 0, result.stdout + result.stderr + calls = remote.gh_calls() + assert [call[:2] for call in calls] == [ + ["pr", "list"], + ["pr", "edit"], + ["pr", "ready"], + ] + assert calls[2] == ["pr", "ready", "999", "--repo", REPOSITORY, "--undo"] + move_main(remote, "main moved again\n") + result = remote.run(rid, GH_OPEN_PR="999") + assert result.returncode == 0, result.stdout + result.stderr + assert [call[:2] for call in remote.gh_calls()] == [["pr", "list"], ["pr", "edit"]] + + +def test_the_checks_refuse_to_run_beside_a_github_token(remote): + # The build job holds no token; were one ever in its environment, CI's + # checks and their packages would not run beside it. + rid, _, _ = remote.certify() + sha = git(remote.remote, "rev-parse", "main") + remote.checkout(remote.runner, sha) + for name in ("GH_TOKEN", "GITHUB_TOKEN"): + temp = remote.tmp / f"token-{name}" + temp.mkdir() + env = remote.environment(temp, rid, GITHUB_SHA=sha) + result, outputs = remote.step( + remote.runner, "build", env, temp / "out.txt", **{name: "a-write-token"} + ) + assert result.returncode == 1, result.stdout + result.stderr + assert "no GitHub token in the environment" in result.stderr + assert "action" not in outputs + assert "suite " not in remote.check_log.read_text() + + def test_a_malformed_or_unknown_request_id_fails(remote): result = remote.run("../escape") assert result.returncode == 1 From 2fff5e1271c93eb152f2cf0887c4906ecff7b724 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 21 Oct 2026 21:35:24 -0400 Subject: [PATCH 02/10] Flag arithmetic, quoted options and abbreviations in the propose detector Bash evaluates an array subscript, a substring offset, ${!name}, $[...] and an array literal's [index] as arithmetic, and arithmetic runs a command substitution held in a value: with x='a[$(touch m)]', each of ${a[x]}, ${y:x}, ${!x}, a[x]=1, $[x] and a+=([x]=v) ran touch under bash 3.2, past the allowlist. Parameter expansions are now a name with at most a literal default, alternative or error word, subscripts are @, * or digits, and indices and $[...] are unmodelled, so flagged. printf's format must be a literal that is not an option (quoted -v or an expansion is still -v). git's options that run a program or write a file are matched after quote removal and as abbreviations, and --output joins them; gh may not open an editor or browser. The script-level shadowing check also finds `name () {` and `function name` definitions. Co-Authored-By: Claude Opus 5.5 --- tests/test_uk_replay_results_pr.py | 97 ++++++++++++++++++++++++------ 1 file changed, 77 insertions(+), 20 deletions(-) diff --git a/tests/test_uk_replay_results_pr.py b/tests/test_uk_replay_results_pr.py index 77c71b812..3ab1fbdb5 100644 --- a/tests/test_uk_replay_results_pr.py +++ b/tests/test_uk_replay_results_pr.py @@ -321,12 +321,13 @@ def function_body(script, name): GIT_RUNS = {"diff", "fetch", "log", "ls-remote", "rev-list", "rev-parse"} PUSHGIT_RUNS = {"push"} GH_RUNS = {("pr", "create"), ("pr", "edit"), ("pr", "list"), ("pr", "ready")} -# git -c may set only the credential helper pushgit hands the token through, -# and no git option may name a program for git to run. +# git -c may set only the credential helper pushgit hands the token through. +# No option of git's may name a program for it to run or a file for it to +# write, however it is quoted or abbreviated (git takes any unambiguous +# prefix of a long option), and none of gh's may open an editor or browser. GIT_CONFIG = {"credential.helper=", "'credential.helper=!gh auth git-credential'"} -GIT_RUNS_PROGRAM = re.compile( - r"""^['"]?(?:--upload-pack|--receive-pack|--exec\b|-u$)""" -) +GIT_OPTIONS_TO_AVOID = ("upload-pack", "receive-pack", "exec", "output") +GH_OPTIONS_TO_AVOID = {"--editor", "-e", "--web", "-w"} PUSHGIT = ( 'pushgit() { git -C "$TREE" -c credential.helper= ' "-c 'credential.helper=!gh auth git-credential' \"$@\"; }" @@ -339,15 +340,35 @@ def function_body(script, name): # &> and &>> are redirections, not & and a redirection. OPERATOR = re.compile(r"&&|\|\||;;|\|&|[;|\n]|&(?!>)") REDIRECT = re.compile(r"[0-9]*(?:&>>|&>|>>|>&|<&|<>|>\||<<<|>|<)") -ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(?:\[[^]]*\])?\+?=") +# Bash evaluates an array subscript, a substring offset and ${!name} as +# arithmetic, and arithmetic runs a command substitution held in a value +# (x='a[$(cmd)]'; ${a[x]}). So a subscript is @, * or digits, and a +# parameter expansion is a name with at most a default, alternative or error +# word holding no quote, expansion, brace or bracket. +ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(?:\[[0-9]+\])?\+?=") LOCAL_NAME = re.compile(r"[a-z_][a-z0-9_]*") -# A parameter expansion holding no quote, expansion or brace of its own. PARAMETER = re.compile( - r"\$\{[#!]?(?:[A-Za-z_][A-Za-z0-9_]*|[0-9@*#?$!-])" - r"(?:\[[^]\s'\"$`\\]*\])?[^{}'\"$`\\]*\}" + r"\$\{#?(?:[A-Za-z_][A-Za-z0-9_]*|[0-9]+|[@*#?$-])(?:\[(?:[@*]|[0-9]+)\])?" + r"(?::?[-+?][^{}\[\]'\"$`\\]*)?\}" ) +def unquoted(word): + """``word`` less its quotes and backslashes: what a literal word is to + the program that receives it.""" + return re.sub(r"[\\'\"]", "", word) + + +def avoided_git_option(word): + """An option, however quoted or abbreviated, that has git run a program + or write a file.""" + plain = unquoted(word) + name = plain[2:].split("=", 1)[0] if plain.startswith("--") else "" + return plain == "-u" or ( + bool(name) and any(option.startswith(name) for option in GIT_OPTIONS_TO_AVOID) + ) + + class Commands: """Every simple command bash would run from ``text`` (a shell_residue), each with its words as written, its assignments and redirections, and @@ -356,9 +377,9 @@ class Commands: ``>(...)``, bash 5.3 ``${ ...; }`` and ``${|...;}``. A command word is whatever starts a command, after an operator, a newline, ``!`` or a reserved word, and after any assignments and redirections before it. - What it does not model (case, for, arithmetic, a parameter expansion - holding quotes or expansions, a word after a compound command) raises - Unlexed, so it is flagged rather than read past.""" + What it does not model (case, for, arithmetic, an array element's + index, a parameter expansion beyond PARAMETER, a word after a compound + command) raises Unlexed, so it is flagged rather than read past.""" def __init__(self, text): self.text, self.commands, self.functions = text, [], [] @@ -521,7 +542,7 @@ def quoted(self, i, function): def dollar(self, i, function): t = self.text - if t.startswith("$((", i): + if t.startswith(("$((", "$["), i): raise Unlexed("arithmetic") if t.startswith("$(", i): return self.sequence(i + 2, ")", function) @@ -545,6 +566,9 @@ def array(self, i, function): i += 1 elif i < len(t) and t[i] == ")": return i + 1 + elif i < len(t) and t[i] == "[": + # ([expr]=value): the index is arithmetic. + raise Unlexed("an array element's index") else: _, i = self.word(i, function) @@ -585,10 +609,19 @@ def disallowed(commands): bound.group().rstrip("+=") if bound else arg ): found.append(f"{shown} declares {arg}") - elif name == "printf" and args[:1] and args[0].startswith("-v"): - found.append(f"{shown} sets a variable") - elif name == "gh" and tuple(args[:2]) not in GH_RUNS: - found.append(f"{shown} runs gh {' '.join(args[:2])}") + elif name == "printf" and ( + not args or "$" in args[0] or unquoted(args[0]).startswith("-") + ): + # printf -v sets a variable, and a format that expands may be -v. + found.append(f"{shown} has no literal format") + elif name == "gh": + if tuple(args[:2]) not in GH_RUNS: + found.append(f"{shown} runs gh {' '.join(args[:2])}") + found += [ + f"{shown} opens a program: {arg}" + for arg in args + if unquoted(arg).split("=", 1)[0] in GH_OPTIONS_TO_AVOID + ] elif name in ("git", "pushgit"): if name == "pushgit" and (wrapper is None or wrapper > command["at"]): found.append(f"{shown} runs pushgit where it is not defined") @@ -602,9 +635,9 @@ def disallowed(commands): if args[at : at + 1] == [] or args[at] not in runs: found.append(f"{shown} runs {name} {' '.join(args[at : at + 1])}") found += [ - f"{shown} hands git a program: {arg}" + f"{shown} has git run or write something: {arg}" for arg in args[at:] - if GIT_RUNS_PROGRAM.match(arg) + if avoided_git_option(arg) ] return found @@ -810,6 +843,23 @@ def test_propose_runs_only_the_commands_it_lists(): f"pushgit push\n{PUSHGIT}", f"if :; then\n {PUSHGIT}\nfi\npushgit push", f"{PUSHGIT}\npushgit fetch origin", + # Arithmetic runs a substitution held in a value (x='a[$(cmd)]'), + # wherever bash evaluates one: each of these ran `touch` under + # bash 3.2 with that x. + 'x=y\n: "${create[x]}"', + ': "${y:x}"', + ': "${!x}"', + "create[x]=1", + ": $[x]", + "create+=([x]=v)", + # Quoting or abbreviating an option, or a format that may expand to + # one, is the option. + 'printf "-v" PATH x', + 'printf "$f" x', + "git ls-remote --upl\\oad-pack=x .", + "git ls-remote --upl=x .", + "git log -1 --ou=/tmp/x", + "gh pr create --editor", # What the parser does not model is flagged, not read past. "for x in a; do :; done", "case x in x) : ;; esac", @@ -834,7 +884,14 @@ def test_propose_runs_only_the_commands_it_lists(): # once: pushgit as PUSHGIT, and plan as field on the plan. field, which # plan runs, is the isolated runner's Python on a fixed program that # imports json and sys alone. - defined = re.findall(r"^\s*([A-Za-z_][A-Za-z0-9_]*)\(\) \{", script, re.M) + defined = [ + keyword or plain + for keyword, plain in re.findall( + r"^\s*(?:function\s+([^\s(){}]+)|([^\s(){}=;&|<>\"'$`]+)\s*\(\s*\))", + script, + re.M, + ) + ] assert set(defined) & PROPOSE_RUNS == {"plan", "pushgit"} assert defined.count("plan") == defined.count("pushgit") == 1 assert defined.count("field") == 1 From 56ebf542b7410be66c25aa4dd7f32ed08e9ad4b9 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 21 Oct 2026 21:36:37 -0400 Subject: [PATCH 03/10] Keep a results PR body inside GitHub's limit with every list full Three checks listing 100 names of up to 300 characters could reach about 90,000 characters, past the 65,536 GitHub accepts for a pull request body, and the branch would already be pushed when gh pr create failed. Each check now lists at most 50 names of at most 200 characters (about 31,000 for all three), and an end-to-end test fails every check with 80 names of the longest listable length and checks the body still fits. Co-Authored-By: Claude Opus 5.5 --- docs/uk_replay/RELEASE_REPLAY.md | 5 +++-- pipeline/uk_replay_results_pr.py | 7 +++++-- tests/test_uk_replay_results_pr.py | 32 +++++++++++++++++++++++++++++- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/docs/uk_replay/RELEASE_REPLAY.md b/docs/uk_replay/RELEASE_REPLAY.md index 8453e042c..59891b1e6 100644 --- a/docs/uk_replay/RELEASE_REPLAY.md +++ b/docs/uk_replay/RELEASE_REPLAY.md @@ -926,8 +926,9 @@ which CI now reads from the index: not stop the run. The job reports each check's exit status, how many files, tests or paths failed (the node ids of pytest's last short test summary, the files ruff names, the paths `git status` lists) and the - first 100 that are printable ASCII without a backtick, as one line of - JSON. `propose` refuses a report of any other shape. Results pull + first 50 that are printable ASCII without a backtick and at most 200 + characters long, as one line of JSON (three full lists keep the body + inside GitHub's 65,536-character limit). `propose` refuses a report of any other shape. Results pull requests #195, #204 and #206 opened ready and failed CI's `pytest` job; with these checks such a pull request opens as a draft that names the failures. diff --git a/pipeline/uk_replay_results_pr.py b/pipeline/uk_replay_results_pr.py index 4ffa3e49c..1ccb782d8 100644 --- a/pipeline/uk_replay_results_pr.py +++ b/pipeline/uk_replay_results_pr.py @@ -632,10 +632,13 @@ def scope(plan: dict, changed: list[str]) -> None: "changed or untracked path", ), } -LISTED = 100 +# At most LISTED names of at most 200 characters per check: three full +# lists (about 31,000 characters) leave the rest of the body well inside +# GitHub's 65,536-character limit, and the job output inside its 1 MB. +LISTED = 50 # A name the pull request shows sits in a fenced block: printable ASCII, no # backtick (which could close the fence), no space at either end. -LISTABLE = re.compile(r"[!-_a-~](?:[ -_a-~]{0,298}[!-_a-~])?") +LISTABLE = re.compile(r"[!-_a-~](?:[ -_a-~]{0,198}[!-_a-~])?") SUMMARY = re.compile(r"^=+ short test summary info =+$", re.M) # ruff format --check names a file "Would reformat: PATH" before ruff 0.16 # and in a diagnostic's "--> PATH:LINE:COLUMN" after it; CI's uvx ruff is diff --git a/tests/test_uk_replay_results_pr.py b/tests/test_uk_replay_results_pr.py index 3ab1fbdb5..d9d0d7ffb 100644 --- a/tests/test_uk_replay_results_pr.py +++ b/tests/test_uk_replay_results_pr.py @@ -2245,7 +2245,7 @@ def passing(): "a newline": lambda r: r["suite"].update(exit=1, count=1, names=["a\nb"]), "a leading space": lambda r: r["suite"].update(exit=1, count=1, names=[" a"]), "non-ASCII": lambda r: r["suite"].update(exit=1, count=1, names=["tést"]), - "a long name": lambda r: r["suite"].update(exit=1, count=1, names=["a" * 301]), + "a long name": lambda r: r["suite"].update(exit=1, count=1, names=["a" * 201]), "a number for a name": lambda r: r["suite"].update(exit=1, count=1, names=[1]), } @@ -3983,6 +3983,36 @@ def test_a_failing_ci_check_opens_a_draft_that_names_it( assert "the build job's log has its output" in body +def test_the_body_fits_githubs_limit_when_every_list_is_full(remote): + # GitHub refuses a pull request body over 65,536 characters, and the + # branch would already be pushed. Every check failing with more names + # than LISTED, each of the longest listable length, still fits. + rid, _, _ = remote.certify() + longest = [f"tests/test_{i:03d}.py::test_" + "x" * 176 for i in range(80)] + assert all(len(name) == 200 for name in longest) + result = remote.run( + rid, + SUITE_FAILS=",".join(longest), + RUFF_UNFORMATTED=",".join(name.split("::")[0] + "x" * 172 for name in longest), + ) + assert result.returncode == 0, result.stdout + result.stderr + reported = json.loads(remote.outputs["preflight"]) + assert reported["suite"]["count"] == reported["ruff"]["count"] == 80 + body = remote.body() + assert f"\n {longest[builder.LISTED - 1]}\n" in body + assert longest[builder.LISTED] not in body + assert "30 more are in the build job's log" in body + full = { + "exit": 1, + "count": 10**6, + "names": [n[:200] for n in longest[: builder.LISTED]], + } + worst = sum(len(builder.check_line(key, full)) for key in builder.PREFLIGHT) + assert ( + len(body) - len(builder.check_line("drift", reported["drift"])) + worst < 65_536 + ) + + def test_incomplete_integrity_and_a_failing_check_say_both(remote): rid, _, _ = remote.certify(integrity="incomplete") result = remote.run(rid, SUITE_FAILS="tests/test_a.py::test_x") From 23d198b39e6fe802d2ed1f00cb7b3e3c80fb5355 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 21 Oct 2026 21:40:14 -0400 Subject: [PATCH 04/10] Reflow the preflight paragraph and say both draft reasons re-draft a PR Co-Authored-By: Claude Opus 5.5 --- docs/uk_replay/RELEASE_REPLAY.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/uk_replay/RELEASE_REPLAY.md b/docs/uk_replay/RELEASE_REPLAY.md index 59891b1e6..e3955608d 100644 --- a/docs/uk_replay/RELEASE_REPLAY.md +++ b/docs/uk_replay/RELEASE_REPLAY.md @@ -928,10 +928,10 @@ which CI now reads from the index: summary, the files ruff names, the paths `git status` lists) and the first 50 that are printable ASCII without a backtick and at most 200 characters long, as one line of JSON (three full lists keep the body - inside GitHub's 65,536-character limit). `propose` refuses a report of any other shape. Results pull - requests #195, #204 and #206 opened ready and failed CI's `pytest` job; - with these checks such a pull request opens as a draft that names the - failures. + inside GitHub's 65,536-character limit). `propose` refuses a report of + any other shape. Results pull requests #195, #204 and #206 opened ready + and failed CI's `pytest` job; with these checks such a pull request + opens as a draft that names the failures. 5. **Pull request.** In the `propose` job, steps 1 to 3 run again with the standard library, skipping only the JSON Schema and RFC 8785 checks `build` made. Only when the tree matches is the App token minted. The @@ -952,9 +952,10 @@ pushes nothing. A branch built on an older main is rebuilt and force-pushed, with a lease on the commit it read, only when it holds exactly one commit, authored and committed by the bot with this request's trailer; an added or amended commit is a person's, and the run fails and leaves the branch alone. -A rebuild that pushes edits the open pull request's title and body, and a -rebuild whose checks fail also turns a ready pull request back into a draft -(`gh pr ready --undo`); one whose checks pass leaves it as it is. A rerun on +A rebuild that pushes edits the open pull request's title and body, and one +that is a draft (integrity not `complete`, or one of CI's checks failing) +also turns a ready pull request back into a draft (`gh pr ready --undo`); +one that is not leaves it as it is. A rerun on an unchanged main pushes nothing, so it leaves the body as it was, even when the earlier run's suite failed only by chance. A rebuilt branch also carries main's commits since the branch was built. From cf8066bc8d106f8136159932ea50f8d8b5dff9a9 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 21 Oct 2026 22:50:36 -0400 Subject: [PATCH 05/10] Say what unsetting the command-file variables does and does not stop The suite runs with $GITHUB_OUTPUT and the other command-file variables unset, which stops a test that writes one by name. A process that finds the files on the runner's disk can still write them; job 2 already takes every build output as build's word, checked for shape. The script comment, the release doc and a test comment claimed more. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/uk_replay_results_pr.sh | 7 +++++-- docs/uk_replay/RELEASE_REPLAY.md | 9 ++++++--- tests/test_uk_replay_results_pr.py | 3 ++- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/.github/scripts/uk_replay_results_pr.sh b/.github/scripts/uk_replay_results_pr.sh index 47f75778d..6eae09c15 100644 --- a/.github/scripts/uk_replay_results_pr.sh +++ b/.github/scripts/uk_replay_results_pr.sh @@ -171,8 +171,11 @@ build() { # (tests check the lines are its lines), then its no-drift check. A failure # is reported, not fatal: the pull request opens as a draft that names it # (review of 24434729, 3). This runs in the build job, which holds no write -# credential, and in a subshell without the step's command files, so nothing -# the checks run can set this job's outputs or a later step's environment. +# credential. The variables that name the step's command files are unset for +# it, so a test or tool that writes $GITHUB_OUTPUT or $GITHUB_ENV by name +# writes nowhere. That is hygiene, not a sandbox: a process that finds the +# files on the runner's disk can still write them, which is why job 2 takes +# every output of this job as its word, checked for shape. preflight() ( local RUFF=(uvx ruff format --check be nz scorecard_db tests pipeline) local SUITE=(uv run --with pytest --with hypothesis --with pypdf --with pyyaml --with numpy --with psutil --with rfc8785==0.1.4 --with jsonschema pytest tests/ -q) diff --git a/docs/uk_replay/RELEASE_REPLAY.md b/docs/uk_replay/RELEASE_REPLAY.md index e3955608d..1e6cdad9a 100644 --- a/docs/uk_replay/RELEASE_REPLAY.md +++ b/docs/uk_replay/RELEASE_REPLAY.md @@ -920,9 +920,12 @@ which CI now reads from the index: after the suite. A test checks that these are `ci.yml`'s lines word for word. They run in the `build` job, which holds no write credential: the script refuses to start them if `GH_TOKEN` or `GITHUB_TOKEN` is set, and - runs them without the step's command files (`$GITHUB_OUTPUT`, - `$GITHUB_ENV`, `$GITHUB_PATH`, `$GITHUB_STATE`, `$GITHUB_STEP_SUMMARY`), - so nothing the suite runs can set the job's outputs. Their failure does + unsets the variables that name the step's command files + (`$GITHUB_OUTPUT`, `$GITHUB_ENV`, `$GITHUB_PATH`, `$GITHUB_STATE`, + `$GITHUB_STEP_SUMMARY`), so a test that writes one by name writes + nowhere. That is hygiene, not a sandbox: a process that finds the files + on the runner's disk can still write them, and `propose` takes every + output of `build` as its word, checked for shape. Their failure does not stop the run. The job reports each check's exit status, how many files, tests or paths failed (the node ids of pytest's last short test summary, the files ruff names, the paths `git status` lists) and the diff --git a/tests/test_uk_replay_results_pr.py b/tests/test_uk_replay_results_pr.py index d9d0d7ffb..d5e6f746f 100644 --- a/tests/test_uk_replay_results_pr.py +++ b/tests/test_uk_replay_results_pr.py @@ -3042,7 +3042,8 @@ def test_a_certified_request_becomes_one_bot_commit_and_a_pull_request(remote): ) assert [line.split()[0] for line in checks[1:3]] == ["build_db", "build_db"] # Review of 24434729 (3): then CI's format check and suite, its own - # lines, on that commit, with no token or command file in reach. + # lines, on that commit, with no token and no command file's variable + # in their environment. assert checks[3:] == [ f"ruff {verified} - - {' '.join(script_array('RUFF')[2:])}", f"suite {verified} . - {' '.join(script_array('SUITE')[1:])}", From f936b49c75c7d01859dcc81d7efdd8f5fabcdce1 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 22 Oct 2026 04:35:58 -0400 Subject: [PATCH 06/10] Close the review's detector gaps; re-draft before the push Review of cf8066bc (GPT-6.1 Sol, CHANGES REQUESTED on the test-side detector only) found 14 inputs bash runs that the detector passed, each executed under bash 3.2, 5.2.37 and 5.3: [ -v 'a[$(cmd)]' ], an array redeclared from a quoted value, process substitution inside ${...}, brace-expanded printf -v, and git or gh options passed through variables, arrays, braces, backslash line breaks or short-option bundles. Its patch is applied as written: options are checked in every word, after a backslash line break is removed, and brace expansion, [ -v ] and a local declared twice are flagged. The claim is narrowed to options written as words; one assembled at run time is beyond any rule on words. git's -u is dropped from the rule: in git 2.55 it is --set-upstream. Function definitions now count wherever they start, and the script holds no eval, source or . to build one. A node id's brackets end at the first ] its message follows, so an unbalanced [ no longer glues the message on; the report's count bound is 10^9; a duplicate failure counts once. The build job reads what it outputs about the commit before the suite runs in its tree, and pauses workflow commands (::stop-commands:: with a token only it holds) around the checks' output. A rebuild that should be a draft turns its open pull request back into one before the push, not after, and every gh pr ready carries --undo. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/uk_replay_results_pr.sh | 45 ++++-- docs/uk_replay/RELEASE_REPLAY.md | 30 ++-- pipeline/uk_replay_results_pr.py | 23 +-- tests/test_uk_replay_results_pr.py | 187 ++++++++++++++++-------- 4 files changed, 190 insertions(+), 95 deletions(-) diff --git a/.github/scripts/uk_replay_results_pr.sh b/.github/scripts/uk_replay_results_pr.sh index 6eae09c15..f9d6d18f5 100644 --- a/.github/scripts/uk_replay_results_pr.sh +++ b/.github/scripts/uk_replay_results_pr.sh @@ -155,16 +155,22 @@ build() { echo "::error::scorecard_db.build_db is nondeterministic on the results branch" >&2 exit 1 fi + # What this job verified, read before CI's checks run in its tree. + local verified sealed hash branch + verified=$(git -C "$TREE" rev-parse 'HEAD^{tree}') + sealed=$(cat "$WORK/verify-sealed.txt") + hash=$(content_hash "$WORK/build1.json") + branch=$(plan branch) preflight # The verified commit, for the job that holds the token to reproduce. output base "$base_commit" output state "$state_commit" - output tree "$(git -C "$TREE" rev-parse 'HEAD^{tree}')" - output sealed "$(cat "$WORK/verify-sealed.txt")" - output content_hash "$(content_hash "$WORK/build1.json")" + output tree "$verified" + output sealed "$sealed" + output content_hash "$hash" output preflight "$(cat "$WORK/preflight.json")" output action build - echo "verified tree $(git -C "$TREE" rev-parse 'HEAD^{tree}') for $(plan branch)" + echo "verified tree $verified for $branch" } # CI's format check and suite on the commit, as ci.yml's python job runs them @@ -184,9 +190,15 @@ preflight() ( exit 1 fi unset GITHUB_ENV GITHUB_OUTPUT GITHUB_PATH GITHUB_STATE GITHUB_STEP_SUMMARY - local ruff=0 suite=0 + # Their output goes to the log, where GitHub would act on a line that is a + # workflow command (::set-output, ::add-mask:: ...): a token only this + # shell holds pauses those until the checks are done. + local ruff=0 suite=0 resume + resume=$(python3 -I -c 'import os; print(os.urandom(16).hex())') + echo "::stop-commands::$resume" (cd "$TREE" && "${RUFF[@]}") 2>&1 | tee "$WORK/ruff.log" || ruff=$? (cd "$TREE" && PYTHONPATH=. "${SUITE[@]}") 2>&1 | tee "$WORK/suite.log" || suite=$? + echo "::$resume::" git -C "$TREE" status --porcelain > "$WORK/porcelain.txt" builder preflight --ruff-exit "$ruff" --ruff-log "$WORK/ruff.log" \ --suite-exit "$suite" --suite-log "$WORK/suite.log" \ @@ -292,6 +304,12 @@ propose() { # The token reaches git only through gh, for these commands alone. pushgit() { git -C "$TREE" -c credential.helper= -c 'credential.helper=!gh auth git-credential' "$@"; } + # The open pull request on this branch, if any. Nothing here merges it. + local title number + title=$(plan title) + number=$(gh pr list --repo "$GITHUB_REPOSITORY" --head "$branch" --base "$BASE" \ + --state open --json number --jq '.[0].number // empty') + # Push: a new branch, or a rebuild over the one commit this builder wrote. local remote pushed=false remote=$(git ls-remote --heads origin "refs/heads/$branch" | cut -f1) @@ -315,6 +333,13 @@ propose() { echo "::error::$branch holds work this builder did not write; update the branch by hand" >&2 exit 1 fi + # A rebuild that should be a draft turns its open pull request back + # into one before the push, so it is never ready on a commit whose + # checks failed. Nothing here marks one ready: a person does, once CI + # passes. + if [ -n "$number" ] && [ "$BUILT_DRAFT" = true ]; then + gh pr ready "$number" --repo "$GITHUB_REPOSITORY" --undo + fi # The token has no workflows permission. This commit changes no # workflow, but the rebuilt branch also carries main's commits since # $remote; if one changed .github/workflows (even one main later @@ -332,11 +357,6 @@ propose() { fi # The pull request: opening it, or the push to its branch, starts CI on it. - # Nothing here merges it. - local title number - title=$(plan title) - number=$(gh pr list --repo "$GITHUB_REPOSITORY" --head "$branch" --base "$BASE" \ - --state open --json number --jq '.[0].number // empty') if [ -z "$number" ]; then local create=(--repo "$GITHUB_REPOSITORY" --base "$BASE" --head "$branch" --title "$title" --body-file "$WORK/BODY.md") @@ -347,11 +367,6 @@ propose() { elif [ "$pushed" = true ]; then gh pr edit "$number" --repo "$GITHUB_REPOSITORY" --title "$title" \ --body-file "$WORK/BODY.md" - # A rebuild that should be a draft turns a ready pull request back into - # one. Nothing here marks one ready: a person does, once CI passes. - if [ "$BUILT_DRAFT" = true ]; then - gh pr ready "$number" --repo "$GITHUB_REPOSITORY" --undo - fi fi echo "::notice::Results pull request for $REQUEST_ID on $branch at $head" if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then diff --git a/docs/uk_replay/RELEASE_REPLAY.md b/docs/uk_replay/RELEASE_REPLAY.md index 1e6cdad9a..9a717488a 100644 --- a/docs/uk_replay/RELEASE_REPLAY.md +++ b/docs/uk_replay/RELEASE_REPLAY.md @@ -925,14 +925,19 @@ which CI now reads from the index: `$GITHUB_STEP_SUMMARY`), so a test that writes one by name writes nowhere. That is hygiene, not a sandbox: a process that finds the files on the runner's disk can still write them, and `propose` takes every - output of `build` as its word, checked for shape. Their failure does - not stop the run. The job reports each check's exit status, how many - files, tests or paths failed (the node ids of pytest's last short test - summary, the files ruff names, the paths `git status` lists) and the - first 50 that are printable ASCII without a backtick and at most 200 - characters long, as one line of JSON (three full lists keep the body - inside GitHub's 65,536-character limit). `propose` refuses a report of - any other shape. Results pull requests #195, #204 and #206 opened ready + output of `build` as its word, checked for shape. Their output goes to + the step log with workflow commands paused (`::stop-commands::`, by a + token only the script holds), so a line the suite prints is not acted + on as one, and what `build` outputs about the commit is read before they + run. Their failure does not stop the run. The job reports each check's + exit status, how many files, tests or paths failed (the node ids of + pytest's last short test summary, the files ruff names, the paths + `git status` lists) and the first 50 that are printable ASCII without a + backtick, with no space at either end and at most 200 characters long, + as one line of JSON (three full lists keep the body inside GitHub's + 65,536-character limit). On CI pytest prints whole messages over lines; + a message line that itself starts with `FAILED` or `ERROR` is read as + another node id. `propose` refuses a report of any other shape. Results pull requests #195, #204 and #206 opened ready and failed CI's `pytest` job; with these checks such a pull request opens as a draft that names the failures. 5. **Pull request.** In the `propose` job, steps 1 to 3 run again with the @@ -955,10 +960,11 @@ pushes nothing. A branch built on an older main is rebuilt and force-pushed, with a lease on the commit it read, only when it holds exactly one commit, authored and committed by the bot with this request's trailer; an added or amended commit is a person's, and the run fails and leaves the branch alone. -A rebuild that pushes edits the open pull request's title and body, and one -that is a draft (integrity not `complete`, or one of CI's checks failing) -also turns a ready pull request back into a draft (`gh pr ready --undo`); -one that is not leaves it as it is. A rerun on +A rebuild that pushes edits the open pull request's title and body. One that +is a draft (integrity not `complete`, or one of CI's checks failing) first +turns a ready pull request back into a draft (`gh pr ready --undo`), before +the push, so it is never ready on a commit whose checks failed; one that is +not leaves it as it is. A rerun on an unchanged main pushes nothing, so it leaves the body as it was, even when the earlier run's suite failed only by chance. A rebuilt branch also carries main's commits since the branch was built. diff --git a/pipeline/uk_replay_results_pr.py b/pipeline/uk_replay_results_pr.py index 1ccb782d8..8f83a3005 100644 --- a/pipeline/uk_replay_results_pr.py +++ b/pipeline/uk_replay_results_pr.py @@ -646,20 +646,23 @@ def scope(plan: dict, changed: list[str]) -> None: UNFORMATTED = re.compile(r"^(?:Would reformat: (.+)|\s*--> (.+?):[0-9]+:[0-9]+)$", re.M) +# A node id: a path and names, which hold no space or "[", then, when it is +# parametrised, its brackets up to the first "]" its " - " message (or the +# line's end) follows. A parameter may hold " - " or an unmatched "[". +NODE_ID = re.compile(r"[^\s\[]+(?:\[.*?\])?(?= - |$)") + + def node_id(text: str) -> str: - """A short-summary line's node id: the text before its " - " message, - outside any brackets (a parametrised id can hold " - ").""" - depth = 0 - for at, character in enumerate(text): - if depth == 0 and text.startswith(" - ", at): - return text[:at] - depth = max(0, depth + {"[": 1, "]": -1}.get(character, 0)) - return text + """A short-summary line's node id, less its " - " message.""" + match = NODE_ID.match(text) + return match.group() if match else text.split(" - ", 1)[0] def suite_failures(log: str) -> list[str]: """The node ids pytest's last short test summary in ``log`` names as - FAILED or ERROR (a collection error names its module).""" + FAILED or ERROR (a collection error names its module). On CI pytest + prints whole messages, over lines; a message line that itself starts + with FAILED or ERROR is read as another id.""" starts = [match.end() for match in SUMMARY.finditer(log)] if not starts: return [] @@ -723,7 +726,7 @@ def shaped(condition: bool, what: str) -> None: ) status, count, names = check["exit"], check["count"], check["names"] shaped(type(status) is int and 0 <= status <= 255, f"{key} exit") - shaped(type(count) is int and 0 <= count <= 10**6, f"{key} count") + shaped(type(count) is int and 0 <= count < 10**9, f"{key} count") shaped(status != 0 or count == 0, f"{key} passes with failures") shaped( isinstance(names, list) diff --git a/tests/test_uk_replay_results_pr.py b/tests/test_uk_replay_results_pr.py index d5e6f746f..c82b58b7e 100644 --- a/tests/test_uk_replay_results_pr.py +++ b/tests/test_uk_replay_results_pr.py @@ -322,9 +322,12 @@ def function_body(script, name): PUSHGIT_RUNS = {"push"} GH_RUNS = {("pr", "create"), ("pr", "edit"), ("pr", "list"), ("pr", "ready")} # git -c may set only the credential helper pushgit hands the token through. -# No option of git's may name a program for it to run or a file for it to -# write, however it is quoted or abbreviated (git takes any unambiguous -# prefix of a long option), and none of gh's may open an editor or browser. +# No word propose writes, as an argument, a variable's value or an array's +# element, may be an option that has git run a program or write a file, or +# gh open an editor or a browser, however it is quoted, escaped, abbreviated +# (git takes any unambiguous prefix of a long option) or bundled (gh -dw). +# An option assembled at run time (u=--w; u+=eb) is beyond any rule on +# words, so these rules cover options written as words. GIT_CONFIG = {"credential.helper=", "'credential.helper=!gh auth git-credential'"} GIT_OPTIONS_TO_AVOID = ("upload-pack", "receive-pack", "exec", "output") GH_OPTIONS_TO_AVOID = {"--editor", "-e", "--web", "-w"} @@ -349,23 +352,28 @@ def function_body(script, name): LOCAL_NAME = re.compile(r"[a-z_][a-z0-9_]*") PARAMETER = re.compile( r"\$\{#?(?:[A-Za-z_][A-Za-z0-9_]*|[0-9]+|[@*#?$-])(?:\[(?:[@*]|[0-9]+)\])?" - r"(?::?[-+?][^{}\[\]'\"$`\\]*)?\}" + r"(?::?[-+?][^{}\[\]'\"$`\\<>()]*)?\}" ) def unquoted(word): """``word`` less its quotes and backslashes: what a literal word is to the program that receives it.""" - return re.sub(r"[\\'\"]", "", word) + return re.sub(r"\\\n|[\\'\"]", "", word) -def avoided_git_option(word): - """An option, however quoted or abbreviated, that has git run a program - or write a file.""" +def avoided_option(word): + """``word``, unquoted, as an option that has git run a program or write + a file (any prefix of one of GIT_OPTIONS_TO_AVOID), or one of gh's that + opens a program, alone or in a bundle of short options.""" plain = unquoted(word) - name = plain[2:].split("=", 1)[0] if plain.startswith("--") else "" - return plain == "-u" or ( - bool(name) and any(option.startswith(name) for option in GIT_OPTIONS_TO_AVOID) + option = plain.split("=", 1)[0] + name = option[2:] if option.startswith("--") else "" + return ( + bool(name) and any(avoided.startswith(name) for avoided in GIT_OPTIONS_TO_AVOID) + ) or ( + option in GH_OPTIONS_TO_AVOID + or bool(re.fullmatch(r"-[A-Za-z]*[ew][A-Za-z]*", option)) ) @@ -382,7 +390,7 @@ class Commands: command) raises Unlexed, so it is flagged rather than read past.""" def __init__(self, text): - self.text, self.commands, self.functions = text, [], [] + self.text, self.commands, self.functions, self.words = text, [], [], [] self.sequence(0, None, function=None) def blank(self, i): @@ -521,12 +529,15 @@ def word(self, i, function): i = self.quoted(i + 1, function) elif t[i] == "$": i = self.dollar(i, function) + elif t[i] == "{" and t[i + 1 : i + 2] not in ("", *WORD_END): + raise Unlexed(f"a brace expansion at {t[i : i + 20]!r}") else: i += 1 if t[i : i + 1] == "(" and ASSIGNMENT.fullmatch(t[start:i]): i = self.array(i + 1, function) if i == start: raise Unlexed(f"no word at {t[i : i + 10]!r}") + self.words.append(t[start:i]) return t[start:i], i def quoted(self, i, function): @@ -578,6 +589,13 @@ def disallowed(commands): PROPOSE_WRITES, as a list of findings. pushgit's body is PUSHGIT, at the top level, before any call; nothing else may be defined.""" found, wrapper = [], None + # An option reaches git or gh from any word: an argument, a variable's + # value or an array's element. + for word in commands.words: + bound = ASSIGNMENT.match(word) + if avoided_option(word) or bound and avoided_option(word[bound.end() :]): + found.append(f"{word} is an option that runs or writes something") + declared = [] for function in commands.functions: if function["text"] == PUSHGIT and function["top"] and wrapper is None: wrapper = function["at"] @@ -602,9 +620,17 @@ def disallowed(commands): found.append(f"{shown} sets its command's environment") if name not in PROPOSE_RUNS: found.append(f"{shown} runs {name}") + elif name == "[" and any(unquoted(arg) == "-v" for arg in args): + found.append(f"{shown} evaluates a subscript") elif name == "local": for arg in args: bound = ASSIGNMENT.match(arg) + local = (bound.group().rstrip("+=") if bound else arg).split("[")[0] + if local in declared: + # A second local of an array reads a quoted value as + # a compound assignment: local a='($(cmd))'. + found.append(f"{shown} declares {local} again") + declared.append(local) if not LOCAL_NAME.fullmatch( bound.group().rstrip("+=") if bound else arg ): @@ -614,14 +640,8 @@ def disallowed(commands): ): # printf -v sets a variable, and a format that expands may be -v. found.append(f"{shown} has no literal format") - elif name == "gh": - if tuple(args[:2]) not in GH_RUNS: - found.append(f"{shown} runs gh {' '.join(args[:2])}") - found += [ - f"{shown} opens a program: {arg}" - for arg in args - if unquoted(arg).split("=", 1)[0] in GH_OPTIONS_TO_AVOID - ] + elif name == "gh" and tuple(args[:2]) not in GH_RUNS: + found.append(f"{shown} runs gh {' '.join(args[:2])}") elif name in ("git", "pushgit"): if name == "pushgit" and (wrapper is None or wrapper > command["at"]): found.append(f"{shown} runs pushgit where it is not defined") @@ -634,11 +654,6 @@ def disallowed(commands): runs = GIT_RUNS if name == "git" else PUSHGIT_RUNS if args[at : at + 1] == [] or args[at] not in runs: found.append(f"{shown} runs {name} {' '.join(args[at : at + 1])}") - found += [ - f"{shown} has git run or write something: {arg}" - for arg in args[at:] - if avoided_git_option(arg) - ] return found @@ -784,6 +799,18 @@ def test_the_builder_runs_no_release_code_and_never_merges(): GROUP = '{\necho "::error::; builder check"\n}' +# A function definition, wherever in a line it starts. +DEFINITION = re.compile( + r"(?:^|[\s;&|(){}'\"])" + r"(?:function\s+([^\s(){}]+)|([^\s(){}=;&|<>\"'$`]+)\s*\(\s*\))", + re.M, +) + + +def definitions(text): + return [keyword or plain for keyword, plain in DEFINITION.findall(text)] + + # pushgit, defined with another program in git's place. NOT_PUSHGIT = PUSHGIT.replace("git -C", "b''ash -C") @@ -797,25 +824,13 @@ def test_propose_runs_only_the_commands_it_lists(): assert {c["name"] for c in commands.commands if c["name"]} == PROPOSE_RUNS # Review of 24434729 (2): bash removes the quotes and runs bash. Every # spelling or other route to a program, a variable or a file beyond - # PROPOSE_RUNS and PROPOSE_WRITES is flagged. + # PROPOSE_RUNS and PROPOSE_WRITES is flagged. The property test below + # covers other names and spellings in every command position. for runs in ( f"{GROUP} | b''ash", f"{GROUP} | b\\ash", - f'{GROUP} | "b"ash', f"{GROUP} | $SHELL", - f"{GROUP} | env bash", - f"{GROUP} | command bash", - f"{GROUP} | xargs -0 sh -c", f"{GROUP} | /bin/bash", - f"{GROUP} | python3 -c 'import os'", - f"if :; then\n {GROUP} | b''ash\nfi", - f"while :; do\n {GROUP} | b''ash\ndone", - # Substitutions and subshells, where no message is set aside. - "x=\"${ b''ash x; }\"", - "x=${|b''ash x;}", - "x=$(b''ash x)", - "cat <(b''ash x)", - "(\n b''ash x\n)", # A command's environment, or a variable bash or a program reads. "PATH=/tmp git rev-parse HEAD", 'PATH="$WORK"', @@ -867,6 +882,21 @@ def test_propose_runs_only_the_commands_it_lists(): "echo $((1 + 2))", "echo \"${x:-$(b''ash)}\"", "{ :; } x", + # Review of cf8066bc: each ran touch under bash 5.2 (test -v, 4.2+) + # or 3.2 to 5.3 (the rest). + "[ -v 'a[$(touch m)]' ]", + "local create=(p)\nlocal create='($(touch m))'", + ": ${x:-<(touch m)}", + ": ${x:->(touch m)}", + "printf {-v,PATH} %s x", + "local u='--upload-pack=x'\ngit ls-remote \"$u\" .", + 'local o=(--upload-pack=x)\ngit ls-remote "${o[@]}" .', + "git ls-remote --{upload-pack=x,quiet} .", + "git ls-remote --upl\\\noad-pack=x .", + "gh pr list -dw", + 'local c=(--web)\ngh pr list "${c[@]}"', + "gh pr list --{web,draft}", + "gh pr list --we\\\nb", ): assert runs_pipeline_code(runs), runs for inert in ( @@ -881,17 +911,22 @@ def test_propose_runs_only_the_commands_it_lists(): assert not runs_pipeline_code(inert), (inert, runs_pipeline_code(inert)) # A function shadows a program or builtin of the same name, so none in # the script has one of those names but plan and pushgit, each defined - # once: pushgit as PUSHGIT, and plan as field on the plan. field, which - # plan runs, is the isolated runner's Python on a fixed program that - # imports json and sys alone. - defined = [ - keyword or plain - for keyword, plain in re.findall( - r"^\s*(?:function\s+([^\s(){}]+)|([^\s(){}=;&|<>\"'$`]+)\s*\(\s*\))", - script, - re.M, - ) - ] + # once: pushgit as PUSHGIT, and plan as field on the plan. A definition + # counts wherever it starts (after ;, &&, a quote...), and the script + # holds no eval, source or . that could define one from text it builds + # (review of cf8066bc, 2). field, which plan runs, is the isolated + # runner's Python on a fixed program that imports json and sys alone. + code = "\n".join( + line for line in script.splitlines() if not line.lstrip().startswith("#") + ) + assert not re.findall(r"(?:^|[\s;&|({])(?:eval|source|\.)\s", code, re.M) + for elsewhere in ( + ": ; cat() { :; }", + "true && cat() { :; }", + "eval 'cat() { :; }'", + ): + assert definitions(elsewhere) == ["cat"], elsewhere + defined = definitions(script) assert set(defined) & PROPOSE_RUNS == {"plan", "pushgit"} assert defined.count("plan") == defined.count("pushgit") == 1 assert defined.count("field") == 1 @@ -1027,8 +1062,14 @@ def order(section, *fragments): "scorecard_db.build_db", "the checks changed tracked files", "nondeterministic", + # Review of cf8066bc (6): what it verified is read before the suite + # runs in the tree, so the suite cannot change it. + "verified=$(git", + 'sealed=$(cat "$WORK/verify-sealed.txt")', + 'hash=$(content_hash "$WORK/build1.json")', + "branch=$(plan branch)", "preflight", - "output tree", + 'output tree "$verified"', "output preflight", "output action build", ) @@ -1038,8 +1079,10 @@ def order(section, *fragments): phase(script, "preflight"), "no GitHub token in the environment", "unset GITHUB_ENV GITHUB_OUTPUT GITHUB_PATH GITHUB_STATE GITHUB_STEP_SUMMARY", + 'echo "::stop-commands::$resume"', '"${RUFF[@]}"', '"${SUITE[@]}"', + 'echo "::$resume::"', 'git -C "$TREE" status --porcelain', "builder preflight ", ) @@ -1069,11 +1112,16 @@ def order(section, *fragments): order( phase(script, "propose"), "the results commit changed after it was assembled", + "gh pr list", "pushgit push -q origin", "holds work this builder did not write", + "gh pr ready", "pushgit push -q --force-with-lease", "gh pr create", ) + # It only ever turns a pull request into a draft, never marks one ready. + ready = [line for line in script.splitlines() if "gh pr ready" in line] + assert ready and all(line.rstrip().endswith("--undo") for line in ready) class ImportScan: @@ -2090,6 +2138,7 @@ def test_a_commit_never_touches_github_even_inside_its_own_trees(path): + " line - message\n" + "assert 1 == 2\n" + "FAILED tests/test_toy.py::test_p[a - b] - AssertionError: assert 'a - b' == 'z'\n" + + "FAILED tests/test_toy.py::test_q[a[b] - AssertionError: [1] - [2]\n" + "ERROR tests/test_toy.py::test_err - RuntimeError: setup\n" + "ERROR tests/test_broken.py\n" + "3 failed, 1 passed, 2 errors in 0.01s\n" @@ -2123,6 +2172,7 @@ def test_the_failures_are_what_the_last_summary_and_ruff_and_git_name(): assert builder.suite_failures(SUITE_LOG) == [ "tests/test_toy.py::test_bad", "tests/test_toy.py::test_p[a - b]", + "tests/test_toy.py::test_q[a[b]", "tests/test_toy.py::test_err", "tests/test_broken.py", ] @@ -2140,10 +2190,17 @@ def test_the_failures_are_what_the_last_summary_and_ruff_and_git_name(): ] # A passing check reports nothing, whatever its log holds. assert builder.report(0, ["tests/a.py"]) == {"exit": 0, "count": 0, "names": []} + # A test that fails and then errors in teardown is one failure. + assert builder.report(1, ["t::a", "t::a", "t::b"]) == { + "exit": 1, + "count": 2, + "names": ["t::a", "t::b"], + } +# A parameter may hold " - " and an unmatched "[", but no "]". PARAMETER_TEXT = st.text( - st.characters(min_codepoint=32, max_codepoint=126, exclude_characters="[]`"), + st.characters(min_codepoint=32, max_codepoint=126, exclude_characters="]`"), max_size=20, ) NODE_IDS = st.builds( @@ -2168,8 +2225,10 @@ def test_the_failures_are_what_the_last_summary_and_ruff_and_git_name(): ) def test_the_suites_failures_round_trip_through_its_summary(names, messages): # Invariant: the node ids of pytest's short summary come back exactly, - # in order, whatever the messages hold (a " - ", more lines) and - # whatever a parametrised id holds (a " - " inside its brackets). + # in order, whatever the messages hold (" - ", "]", more lines) and + # whatever a parametrised id holds (" - " or an unmatched "[" inside its + # brackets). A message line that starts FAILED or ERROR is the stated + # limit, so the messages here hold none. lines = [] for name, message in zip(names, messages): word = "ERROR" if "::" not in name else "FAILED" @@ -2864,7 +2923,9 @@ def build_job(self, rid, sha, temp, **overrides): temp.mkdir() self.gh_log, self.check_log = temp / "gh.jsonl", temp / "checks.log" self.checkout(self.runner, sha) - env = self.environment(temp, rid, **{"GITHUB_SHA": sha, **overrides}) + # Every command file a step has, as the runner sets them. + files = {name: str(temp / name.lower()) for name in EXPOSED[2:]} + env = self.environment(temp, rid, **{"GITHUB_SHA": sha, **files, **overrides}) return self.step(self.runner, "build", env, temp / "build-output.txt") def rebuild_job(self, rid, received, sha, name, **overrides): @@ -3051,6 +3112,13 @@ def test_a_certified_request_becomes_one_bot_commit_and_a_pull_request(remote): assert json.loads(remote.outputs["preflight"]) == { key: {"exit": 0, "count": 0, "names": []} for key in builder.PREFLIGHT } + # Their output sits between a pause of workflow commands and its resume, + # by a token the checks never see (review of cf8066bc, 8). + paused = re.search(r"^::stop-commands::([0-9a-f]{32})$", result.stdout, re.M) + assert paused + resumed = result.stdout.index(f"\n::{paused.group(1)}::\n") + assert paused.end() < result.stdout.index("3 passed in 0.01s") < resumed + assert paused.group(1) not in remote.check_log.read_text() assert remote.rebuilt["draft"] == "false" calls = remote.gh_calls() assert [call[:2] for call in calls] == [["pr", "list"], ["pr", "create"]] @@ -3256,7 +3324,8 @@ def test_without_workflows_a_rebuild_over_mains_workflow_change_says_what_to_do( result.stderr ) assert remote.branch(record) == rebuilt - assert remote.gh_calls() == [] + # It only read which pull request is open. + assert [call[:2] for call in remote.gh_calls()] == [["pr", "list"]] # The way out: with the branch deleted, the run pushes a new one, which # holds only the bot's commit on the new main. branch = f"refs/heads/{builder.BRANCH_PREFIX}{record['variant_id']}" @@ -4032,13 +4101,15 @@ def test_a_failing_rebuild_turns_its_open_pull_request_back_into_a_draft(remote) move_main(remote) result = remote.run(rid, GH_OPEN_PR="999", SUITE_FAILS="tests/test_a.py::test_x") assert result.returncode == 0, result.stdout + result.stderr + # Back to a draft before the push that makes it fail (review of + # cf8066bc, 7), then the body that says why. calls = remote.gh_calls() assert [call[:2] for call in calls] == [ ["pr", "list"], - ["pr", "edit"], ["pr", "ready"], + ["pr", "edit"], ] - assert calls[2] == ["pr", "ready", "999", "--repo", REPOSITORY, "--undo"] + assert calls[1] == ["pr", "ready", "999", "--repo", REPOSITORY, "--undo"] move_main(remote, "main moved again\n") result = remote.run(rid, GH_OPEN_PR="999") assert result.returncode == 0, result.stdout + result.stderr From 9078c44981d436dcd7778ff436e06daf2d559375 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 30 Oct 2026 10:48:53 -0400 Subject: [PATCH 07/10] Resume workflow commands on their own line; close the detector's split words Sol's re-review of f936b49c asked for changes. The one production finding: the runner reads a workflow command only at the start of a line, so a suite that stopped mid-line left `::::` on that line and later commands paused. The pause and the resume now each start a line of their own. The rest is the test-side detector, where it now refuses what it could not see, rather than listing more spellings: - `[` runs only as -n or -z and a word, or two words around = or !=. An operator held in a value or array ([ "$op" "$x" ]) ran test -v. - An argument with an expansion or a glob outside double quotes is flagged: bash turns it into words the text does not show (--web from a value, a default or a file name). A default now counts as a word. - Loops leave the model, so `while` and `until` are commands PROPOSE_RUNS does not list, and each declaration runs at most once. propose has none. - The script-wide pins read text after quote removal, so `c\at()`, e''val, 'source' and \. no longer pass them. Tests add the count's boundary, the nonce's generation and exposure, and a suite that stops mid-line, which close the review's surviving mutants. The docs state the summary-header limit beside the FAILED/ERROR one. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/uk_replay_results_pr.sh | 8 +- docs/uk_replay/RELEASE_REPLAY.md | 13 +- pipeline/uk_replay_results_pr.py | 10 +- tests/test_uk_replay_results_pr.py | 192 ++++++++++++++++++------ 4 files changed, 167 insertions(+), 56 deletions(-) diff --git a/.github/scripts/uk_replay_results_pr.sh b/.github/scripts/uk_replay_results_pr.sh index f9d6d18f5..5b4b80f00 100644 --- a/.github/scripts/uk_replay_results_pr.sh +++ b/.github/scripts/uk_replay_results_pr.sh @@ -192,13 +192,15 @@ preflight() ( unset GITHUB_ENV GITHUB_OUTPUT GITHUB_PATH GITHUB_STATE GITHUB_STEP_SUMMARY # Their output goes to the log, where GitHub would act on a line that is a # workflow command (::set-output, ::add-mask:: ...): a token only this - # shell holds pauses those until the checks are done. + # shell holds pauses those until the checks are done. The runner reads a + # command only at the start of a line, so each of these starts its own: a + # suite that stops mid-line would otherwise leave commands paused. local ruff=0 suite=0 resume resume=$(python3 -I -c 'import os; print(os.urandom(16).hex())') - echo "::stop-commands::$resume" + printf '\n::stop-commands::%s\n' "$resume" (cd "$TREE" && "${RUFF[@]}") 2>&1 | tee "$WORK/ruff.log" || ruff=$? (cd "$TREE" && PYTHONPATH=. "${SUITE[@]}") 2>&1 | tee "$WORK/suite.log" || suite=$? - echo "::$resume::" + printf '\n::%s::\n' "$resume" git -C "$TREE" status --porcelain > "$WORK/porcelain.txt" builder preflight --ruff-exit "$ruff" --ruff-log "$WORK/ruff.log" \ --suite-exit "$suite" --suite-log "$WORK/suite.log" \ diff --git a/docs/uk_replay/RELEASE_REPLAY.md b/docs/uk_replay/RELEASE_REPLAY.md index 767ecbf6a..bc0a7c4f2 100644 --- a/docs/uk_replay/RELEASE_REPLAY.md +++ b/docs/uk_replay/RELEASE_REPLAY.md @@ -981,11 +981,14 @@ which CI now reads from the index: `git status` lists) and the first 50 that are printable ASCII without a backtick, with no space at either end and at most 200 characters long, as one line of JSON (three full lists keep the body inside GitHub's - 65,536-character limit). On CI pytest prints whole messages over lines; - a message line that itself starts with `FAILED` or `ERROR` is read as - another node id. `propose` refuses a report of any other shape. Results pull requests #195, #204 and #206 opened ready - and failed CI's `pytest` job; with these checks such a pull request - opens as a draft that names the failures. + 65,536-character limit). On CI pytest prints whole messages over lines: + the job reads a message line that itself starts with `FAILED` or `ERROR` + as another node id, and one that is itself a summary header drops the + ids before it. Only the list changes: a check's exit status, not its + list, says whether it failed. `propose` refuses a report of any other + shape, a count of a billion or more among them. Results pull requests + #195, #204 and #206 opened ready and failed CI's `pytest` job; with these + checks such a pull request opens as a draft that names the failures. 5. **Pull request.** In the `propose` job, steps 1 to 3 run again with the standard library, skipping only the JSON Schema and RFC 8785 checks `build` made. Only when the tree matches is the App token minted. The diff --git a/pipeline/uk_replay_results_pr.py b/pipeline/uk_replay_results_pr.py index 8f83a3005..e88d1edb3 100644 --- a/pipeline/uk_replay_results_pr.py +++ b/pipeline/uk_replay_results_pr.py @@ -661,8 +661,10 @@ def node_id(text: str) -> str: def suite_failures(log: str) -> list[str]: """The node ids pytest's last short test summary in ``log`` names as FAILED or ERROR (a collection error names its module). On CI pytest - prints whole messages, over lines; a message line that itself starts - with FAILED or ERROR is read as another id.""" + prints whole messages, over lines. This reads a message line that + itself starts with FAILED or ERROR as another id, and one that is + itself a summary header drops the ids before it. Only the list changes: + a check's exit status, not this list, says whether it failed.""" starts = [match.end() for match in SUMMARY.finditer(log)] if not starts: return [] @@ -709,7 +711,9 @@ def read_preflight(text: str) -> dict: """The build job's report as the propose job receives it, a string: refused unless it has exactly the shape ``preflight`` gives. The counts and names are still the build job's word; CI on the pull request - runs the checks again.""" + runs the checks again. A count stays under a billion, because the body + prints it: a run that names more distinct failures stops here, with + nothing proposed.""" try: value = json.loads(text) except ValueError: diff --git a/tests/test_uk_replay_results_pr.py b/tests/test_uk_replay_results_pr.py index c82b58b7e..37f02445c 100644 --- a/tests/test_uk_replay_results_pr.py +++ b/tests/test_uk_replay_results_pr.py @@ -327,7 +327,9 @@ def function_body(script, name): # gh open an editor or a browser, however it is quoted, escaped, abbreviated # (git takes any unambiguous prefix of a long option) or bundled (gh -dw). # An option assembled at run time (u=--w; u+=eb) is beyond any rule on -# words, so these rules cover options written as words. +# words, so these rules cover options written as words. A default counts as +# one, and a word that splits (below) is refused, so a value cannot hide a +# second word. GIT_CONFIG = {"credential.helper=", "'credential.helper=!gh auth git-credential'"} GIT_OPTIONS_TO_AVOID = ("upload-pack", "receive-pack", "exec", "output") GH_OPTIONS_TO_AVOID = {"--editor", "-e", "--web", "-w"} @@ -352,8 +354,13 @@ def function_body(script, name): LOCAL_NAME = re.compile(r"[a-z_][a-z0-9_]*") PARAMETER = re.compile( r"\$\{#?(?:[A-Za-z_][A-Za-z0-9_]*|[0-9]+|[@*#?$-])(?:\[(?:[@*]|[0-9]+)\])?" - r"(?::?[-+?][^{}\[\]'\"$`\\<>()]*)?\}" + r"(?::?[-+?](?P[^{}\[\]'\"$`\\<>()]*))?\}" ) +# [ runs one of two shapes: -n or -z and a word, or a word, = or != and a +# word. -v evaluates a subscript, and the operator can come from a value or +# an array ([ "$op" "$x" ]), so it is a literal here and each operand is one +# word: no $@, $* or [@], and no unquoted expansion (Commands.splits). +SEVERAL = re.compile(r"\$[@*]|\$\{[@*]|\[[@*]\]") def unquoted(word): @@ -380,17 +387,21 @@ def avoided_option(word): class Commands: """Every simple command bash would run from ``text`` (a shell_residue), each with its words as written, its assignments and redirections, and - the function whose body holds it: the top level, the bodies of - if/while/until, ``{ }`` and ``( )``, and every ``$(...)``, ``<(...)``, - ``>(...)``, bash 5.3 ``${ ...; }`` and ``${|...;}``. A command word is - whatever starts a command, after an operator, a newline, ``!`` or a - reserved word, and after any assignments and redirections before it. - What it does not model (case, for, arithmetic, an array element's - index, a parameter expansion beyond PARAMETER, a word after a compound - command) raises Unlexed, so it is flagged rather than read past.""" + the function whose body holds it: the top level, the bodies of if, + ``{ }`` and ``( )``, and every ``$(...)``, ``<(...)``, ``>(...)``, bash + 5.3 ``${ ...; }`` and ``${|...;}``. A command word is whatever starts a + command, after an operator, a newline, ``!`` or a reserved word, and + after any assignments and redirections before it. What it does not model + is flagged rather than read past: arithmetic, case, an array element's + index, a parameter expansion beyond PARAMETER and a word after a compound + command raise Unlexed, and a loop's keywords are commands PROPOSE_RUNS + does not list. With no loop, each declaration runs at most once. + ``splits`` holds the words with an expansion or a glob outside double + quotes, which bash can turn into words the text does not show.""" def __init__(self, text): self.text, self.commands, self.functions, self.words = text, [], [], [] + self.splits = set() self.sequence(0, None, function=None) def blank(self, i): @@ -467,18 +478,16 @@ def sequence(self, i, closer, function): if command is not None and command["closed"]: raise Unlexed(f"{word} after a compound command") if command is None or command["name"] is None: - if command is None and word in ("if", "while", "until", "{"): - open_.append( - ({"if": "fi", "{": "}"}.get(word, "done"), None, start) - ) + if command is None and word in ("if", "{"): + open_.append(("fi" if word == "if" else "}", None, start)) continue - if command is None and word in ("then", "elif", "else", "do"): - if not open_ or open_[-1][0] != ("done" if word == "do" else "fi"): - raise Unlexed(f"{word} outside its compound command") + if command is None and word in ("then", "elif", "else"): + if not open_ or open_[-1][0] != "fi": + raise Unlexed(f"{word} outside its if") continue - if command is None and word in ("fi", "done"): - if not open_ or open_[-1][0] != word: - raise Unlexed(f"an unmatched {word}") + if command is None and word == "fi": + if not open_ or open_[-1][0] != "fi": + raise Unlexed("an unmatched fi") open_.pop() command = self.record(i, function, closed=True) continue @@ -519,7 +528,7 @@ def record(self, at, function, closed=False): def word(self, i, function): """The word at i as written, and the index past it. Its substitutions are read as commands.""" - t, start = self.text, i + t, start, bare = self.text, i, False while i < len(t) and t[i] not in WORD_END: if t[i] == "\\": i += 2 @@ -528,16 +537,18 @@ def word(self, i, function): elif t[i] == '"': i = self.quoted(i + 1, function) elif t[i] == "$": - i = self.dollar(i, function) + bare, i = True, self.dollar(i, function) elif t[i] == "{" and t[i + 1 : i + 2] not in ("", *WORD_END): raise Unlexed(f"a brace expansion at {t[i : i + 20]!r}") else: - i += 1 + bare, i = bare or t[i] in "*?[", i + 1 if t[i : i + 1] == "(" and ASSIGNMENT.fullmatch(t[start:i]): i = self.array(i + 1, function) if i == start: raise Unlexed(f"no word at {t[i : i + 10]!r}") self.words.append(t[start:i]) + if bare: + self.splits.add(t[start:i]) return t[start:i], i def quoted(self, i, function): @@ -563,6 +574,8 @@ def dollar(self, i, function): parameter = PARAMETER.match(t, i) if not parameter: raise Unlexed(f"the expansion {t[i : i + 20]!r}") + if parameter["default"]: + self.words.append(parameter["default"]) return parameter.end() if t.startswith('$"', i): return self.quoted(i + 2, function) @@ -584,6 +597,18 @@ def array(self, i, function): _, i = self.word(i, function) +def plain_test(args, splits): + """``args`` of ``[`` in one of the shapes it may run: see SEVERAL.""" + match args: + case ["-n" | "-z", word, "]"]: + operands = [word] + case [left, "=" | "!=", right, "]"]: + operands = [left, right] + case _: + return False + return not any(word in splits or SEVERAL.search(word) for word in operands) + + def disallowed(commands): """What in ``commands`` runs or writes beyond PROPOSE_RUNS and PROPOSE_WRITES, as a list of findings. pushgit's body is PUSHGIT, at the @@ -618,17 +643,24 @@ def disallowed(commands): continue if command["assigns"]: found.append(f"{shown} sets its command's environment") + for arg in args: + # local NAME=$x is an assignment, which bash does not split. + if arg in commands.splits and not ( + name == "local" and ASSIGNMENT.match(arg) + ): + found.append(f"{shown} splits {arg} into more words") if name not in PROPOSE_RUNS: found.append(f"{shown} runs {name}") - elif name == "[" and any(unquoted(arg) == "-v" for arg in args): - found.append(f"{shown} evaluates a subscript") + elif name == "[" and not plain_test(args, commands.splits): + found.append(f"{shown} is not a test it may run") elif name == "local": for arg in args: bound = ASSIGNMENT.match(arg) local = (bound.group().rstrip("+=") if bound else arg).split("[")[0] if local in declared: - # A second local of an array reads a quoted value as - # a compound assignment: local a='($(cmd))'. + # A second local of an array reads a quoted value as a + # compound assignment: local a='($(cmd))'. This counts + # declarations as written, which is enough with no loop. found.append(f"{shown} declares {local} again") declared.append(local) if not LOCAL_NAME.fullmatch( @@ -799,16 +831,20 @@ def test_the_builder_runs_no_release_code_and_never_merges(): GROUP = '{\necho "::error::; builder check"\n}' -# A function definition, wherever in a line it starts. +# A function definition, wherever in a line it starts, and eval, source or +# . as a word. Both read text after unquoted: a quote, a backslash or a line +# continuation inside a word does not change what bash runs. A word assembled +# at run time (n=ev; "${n}al") is beyond any rule on text. DEFINITION = re.compile( - r"(?:^|[\s;&|(){}'\"])" - r"(?:function\s+([^\s(){}]+)|([^\s(){}=;&|<>\"'$`]+)\s*\(\s*\))", + r"(?:^|[\s;&|(){}])" + r"(?:function\s+([^\s(){}]+)|([^\s(){}=;&|<>$`]+)\s*\(\s*\))", re.M, ) +RUNS_TEXT = re.compile(r"(?:^|[\s;&|({])(?:eval|source|\.)\s", re.M) def definitions(text): - return [keyword or plain for keyword, plain in DEFINITION.findall(text)] + return [keyword or plain for keyword, plain in DEFINITION.findall(unquoted(text))] # pushgit, defined with another program in git's place. @@ -897,6 +933,35 @@ def test_propose_runs_only_the_commands_it_lists(): 'local c=(--web)\ngh pr list "${c[@]}"', "gh pr list --{web,draft}", "gh pr list --we\\\nb", + # Review of f936b49c: bash 5.2 and 5.3 ran touch from a test whose + # operator sits in a value or an array, every bash from a declaration + # a loop repeats, and gh ran its browser from a word that splits or a + # default. + 'local o=-v\nlocal x=\'a[$(touch m)]\'\n[ "$o" "$x" ]', + 'local o=(-v)\nlocal x=\'a[$(touch m)]\'\n[ "${o[@]}" "$x" ]', + "local x=y\nwhile :; do\n local a='($(touch m))'\n a=(p)\ndone", + "until :; do :; done", + "local o='--web '\ngh pr list $o", + "gh pr list ${o:---web}", + 'gh pr list "${o:---web}"', + "gh pr list *", + "git ls-remote ?-upload-pack=x .", + "gh pr list [-]-web", + "gh pr list $'--web'", + # Every other test: a shape it does not run, or an operand that may + # be several words. + "[ -v x ]", + '[ ! -n "$x" ]', + '[ -n "$x"', + '[ "$x" ]', + '[ "$x" -eq 1 ]', + '[ "$a" = "$b" -o -v x ]', + "[ -n $x ]", + '[ $x = "$y" ]', + '[ -n "$@" ]', + '[ -n "${a[@]}" ]', + '[ "$x" = "${a[*]}" ]', + '[ "a"$x"b" = c ]', ): assert runs_pipeline_code(runs), runs for inert in ( @@ -907,6 +972,9 @@ def test_propose_runs_only_the_commands_it_lists(): 'if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then\n cat x >> "$GITHUB_STEP_SUMMARY"\nfi', 'echo "$branch already holds this tree" >&2', "n=$(gh pr list --head \"$b\" \\\n --json number --jq '.[0].number // empty')", + '[ -z "$x" ] || [ "$(plan branch)" != "${y:-}" ]', + '[ "$x" = true ]', + "local branch=$BUILT_BRANCH head", ): assert not runs_pipeline_code(inert), (inert, runs_pipeline_code(inert)) # A function shadows a program or builtin of the same name, so none in @@ -914,16 +982,20 @@ def test_propose_runs_only_the_commands_it_lists(): # once: pushgit as PUSHGIT, and plan as field on the plan. A definition # counts wherever it starts (after ;, &&, a quote...), and the script # holds no eval, source or . that could define one from text it builds - # (review of cf8066bc, 2). field, which plan runs, is the isolated - # runner's Python on a fixed program that imports json and sys alone. + # (reviews of cf8066bc, 2, and f936b49c, 2). field, which plan runs, is + # the isolated runner's Python on a fixed program that imports json and + # sys alone. code = "\n".join( line for line in script.splitlines() if not line.lstrip().startswith("#") ) - assert not re.findall(r"(?:^|[\s;&|({])(?:eval|source|\.)\s", code, re.M) + assert not RUNS_TEXT.findall(unquoted(code)) + for evaluates in ("e''val x", "'source' x", "\\. x", "e\\\nval x", ': ; . "$x"'): + assert RUNS_TEXT.search(unquoted(evaluates)), evaluates for elsewhere in ( ": ; cat() { :; }", "true && cat() { :; }", "eval 'cat() { :; }'", + "c\\\nat() { :; }", ): assert definitions(elsewhere) == ["cat"], elsewhere defined = definitions(script) @@ -953,9 +1025,9 @@ def test_propose_runs_only_the_commands_it_lists(): ] -# The names propose may run with any one argument (git, gh and pushgit +# The names propose may run with any one argument (git, gh, pushgit and [ # take only some), and names it may not run at all. -PLAIN_RUNS = sorted(PROPOSE_RUNS - {"git", "gh", "pushgit"}) +PLAIN_RUNS = sorted(PROPOSE_RUNS - {"git", "gh", "pushgit", "["}) NOT_RUNS = ["bash", "sh", "dash", "zsh", "ksh", "eval", "exec", "source", "."] NOT_RUNS += ["trap", "env", "command", "builtin", "xargs", "python3", "tee", "time"] CONTEXTS = [ @@ -968,8 +1040,6 @@ def test_propose_runs_only_the_commands_it_lists(): ">&2 {w} x", "if :; then {w} x; fi", "if :; then :; elif {w} x; then :; else {w} x; fi", - "while {w} x; do {w} x; done", - "until {w} x; do :; done", "x=$({w} x)", 'x="$({w} x)"', "( {w} x )", @@ -1079,10 +1149,11 @@ def order(section, *fragments): phase(script, "preflight"), "no GitHub token in the environment", "unset GITHUB_ENV GITHUB_OUTPUT GITHUB_PATH GITHUB_STATE GITHUB_STEP_SUMMARY", - 'echo "::stop-commands::$resume"', + "os.urandom(16).hex()", + "printf '\\n::stop-commands::%s\\n' \"$resume\"", '"${RUFF[@]}"', '"${SUITE[@]}"', - 'echo "::$resume::"', + "printf '\\n::%s::\\n' \"$resume\"", 'git -C "$TREE" status --porcelain', "builder preflight ", ) @@ -2168,6 +2239,16 @@ def test_a_commit_never_touches_github_even_inside_its_own_trees(path): OLD_RUFF_LOG = "Would reformat: tests/a.py\nWould reformat: pipeline/b.py\n2 files would be reformatted, 9 files already formatted\n" +def test_a_message_line_that_looks_like_a_summary_is_a_stated_limit(): + # The limits suite_failures states, as they behave: only the list + # changes, and a failing suite's exit status still makes the draft. + log = f"{SUMMARY_HEADER}FAILED tests/test_t.py::test_x - a\n{SUMMARY_HEADER}" + assert builder.suite_failures(log) == [] + assert builder.report(1, builder.suite_failures(log))["exit"] == 1 + log = f"{SUMMARY_HEADER}FAILED tests/test_t.py::test_x - a\nERROR b\n" + assert builder.suite_failures(log) == ["tests/test_t.py::test_x", "b"] + + def test_the_failures_are_what_the_last_summary_and_ruff_and_git_name(): assert builder.suite_failures(SUITE_LOG) == [ "tests/test_toy.py::test_bad", @@ -2215,7 +2296,12 @@ def test_the_failures_are_what_the_last_summary_and_ruff_and_git_name(): ) MESSAGE_LINE = st.text( st.characters(min_codepoint=32, max_codepoint=126), max_size=40 -).filter(lambda line: not line.startswith(("FAILED ", "ERROR "))) +).filter( + lambda line: ( + not line.startswith(("FAILED ", "ERROR ")) + and not builder.SUMMARY.fullmatch(line) + ) +) @settings(max_examples=200, deadline=None) @@ -2227,8 +2313,9 @@ def test_the_suites_failures_round_trip_through_its_summary(names, messages): # Invariant: the node ids of pytest's short summary come back exactly, # in order, whatever the messages hold (" - ", "]", more lines) and # whatever a parametrised id holds (" - " or an unmatched "[" inside its - # brackets). A message line that starts FAILED or ERROR is the stated - # limit, so the messages here hold none. + # brackets). A message line that starts FAILED or ERROR, or that is + # itself a summary header, is a stated limit, so the messages here hold + # none. lines = [] for name, message in zip(names, messages): word = "ERROR" if "::" not in name else "FAILED" @@ -2292,6 +2379,7 @@ def passing(): "a float exit": lambda r: r["suite"].update(exit=1.0), "a negative count": lambda r: r["suite"].update(exit=1, count=-1), "a boolean count": lambda r: r["suite"].update(exit=1, count=True), + "a count of a billion": lambda r: r["suite"].update(exit=1, count=10**9), "a pass with failures": lambda r: r["ruff"].update(count=1, names=["a.py"]), "more names than failures": lambda r: r["suite"].update( exit=1, count=1, names=["a", "b"] @@ -2321,6 +2409,12 @@ def test_the_propose_job_refuses_a_report_of_any_other_shape(edit): builder.read_preflight(text) +def test_a_count_under_a_billion_reads_back(): + report = passing() + report["suite"].update(exit=1, count=10**9 - 1) + assert builder.read_preflight(json.dumps(report)) == report + + @settings(max_examples=100, deadline=None) @given( incomplete=st.booleans(), @@ -2726,6 +2820,8 @@ def install_uv(tools): f"{{check}} {{head}} {{os.environ.get('PYTHONPATH', '-')}} {{exposed}} " + " ".join(args) + "\\n" ) +with open(os.environ["CHECK_LOG"] + ".env", "a") as seen: + seen.write(repr(dict(os.environ)) + "\\n") if check == "ruff": paths = [p for p in os.environ.get("RUFF_UNFORMATTED", "").split(",") if p] for path in paths: @@ -2741,7 +2837,7 @@ def install_uv(tools): names = [n for n in os.environ.get("SUITE_FAILS", "").split(",") if n] print("..F" if names else "...") if os.environ.get("SUITE_EXIT"): - print("INTERNALERROR> collection died") + print("INTERNALERROR> collection died", end="", flush=True) sys.exit(int(os.environ["SUITE_EXIT"])) if names: print("=" * 27 + " short test summary info " + "=" * 28) @@ -3118,7 +3214,9 @@ def test_a_certified_request_becomes_one_bot_commit_and_a_pull_request(remote): assert paused resumed = result.stdout.index(f"\n::{paused.group(1)}::\n") assert paused.end() < result.stdout.index("3 passed in 0.01s") < resumed - assert paused.group(1) not in remote.check_log.read_text() + seen = Path(f"{remote.check_log}.env").read_text() + assert seen.count("\n") == 2 and "CHECK_LOG" in seen + assert paused.group(1) not in remote.check_log.read_text() + seen assert remote.rebuilt["draft"] == "false" calls = remote.gh_calls() assert [call[:2] for call in calls] == [["pr", "list"], ["pr", "create"]] @@ -4037,6 +4135,10 @@ def test_a_failing_ci_check_opens_a_draft_that_names_it( result = remote.run(rid, **override) assert result.returncode == 0, result.stdout + result.stderr assert remote.branch(record) + # However the check's output ends, commands resume on a line of their + # own: the runner would read none after it otherwise (review of f936b49c). + paused = re.search(r"^::stop-commands::([0-9a-f]{32})$", result.stdout, re.M) + assert f"\n::{paused.group(1)}::\n" in result.stdout reported = json.loads(remote.outputs["preflight"]) assert reported[key] == {"exit": status, "count": len(names), "names": names} assert all(reported[other]["exit"] == 0 for other in set(reported) - {key}) From d3770d66742f350937d1938ffb9c8e74563f7b21 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 30 Oct 2026 10:51:13 -0400 Subject: [PATCH 08/10] Drop a check the split rule makes dead; test the script-wide pin itself A mutation run on 9078c449 showed plain_test's check on split words could not fail, because disallowed already flags them for every command, so it goes. It also showed that weakening the pin on eval, source and . passed: the test asserted on the script and on examples through separate code. Both now go through runs_text. Co-Authored-By: Claude Opus 5.5 --- tests/test_uk_replay_results_pr.py | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/tests/test_uk_replay_results_pr.py b/tests/test_uk_replay_results_pr.py index 37f02445c..c6f19d518 100644 --- a/tests/test_uk_replay_results_pr.py +++ b/tests/test_uk_replay_results_pr.py @@ -359,7 +359,8 @@ def function_body(script, name): # [ runs one of two shapes: -n or -z and a word, or a word, = or != and a # word. -v evaluates a subscript, and the operator can come from a value or # an array ([ "$op" "$x" ]), so it is a literal here and each operand is one -# word: no $@, $* or [@], and no unquoted expansion (Commands.splits). +# word: no $@, $* or [@]. An unquoted expansion is refused for every command +# (Commands.splits). SEVERAL = re.compile(r"\$[@*]|\$\{[@*]|\[[@*]\]") @@ -597,7 +598,7 @@ def array(self, i, function): _, i = self.word(i, function) -def plain_test(args, splits): +def plain_test(args): """``args`` of ``[`` in one of the shapes it may run: see SEVERAL.""" match args: case ["-n" | "-z", word, "]"]: @@ -606,7 +607,7 @@ def plain_test(args, splits): operands = [left, right] case _: return False - return not any(word in splits or SEVERAL.search(word) for word in operands) + return not any(SEVERAL.search(word) for word in operands) def disallowed(commands): @@ -651,7 +652,7 @@ def disallowed(commands): found.append(f"{shown} splits {arg} into more words") if name not in PROPOSE_RUNS: found.append(f"{shown} runs {name}") - elif name == "[" and not plain_test(args, commands.splits): + elif name == "[" and not plain_test(args): found.append(f"{shown} is not a test it may run") elif name == "local": for arg in args: @@ -847,6 +848,14 @@ def definitions(text): return [keyword or plain for keyword, plain in DEFINITION.findall(unquoted(text))] +def runs_text(script): + """Each eval, source or . in ``script``, comment lines aside.""" + code = "\n".join( + line for line in script.splitlines() if not line.lstrip().startswith("#") + ) + return RUNS_TEXT.findall(unquoted(code)) + + # pushgit, defined with another program in git's place. NOT_PUSHGIT = PUSHGIT.replace("git -C", "b''ash -C") @@ -985,12 +994,10 @@ def test_propose_runs_only_the_commands_it_lists(): # (reviews of cf8066bc, 2, and f936b49c, 2). field, which plan runs, is # the isolated runner's Python on a fixed program that imports json and # sys alone. - code = "\n".join( - line for line in script.splitlines() if not line.lstrip().startswith("#") - ) - assert not RUNS_TEXT.findall(unquoted(code)) + assert not runs_text(script) for evaluates in ("e''val x", "'source' x", "\\. x", "e\\\nval x", ': ; . "$x"'): - assert RUNS_TEXT.search(unquoted(evaluates)), evaluates + assert runs_text(evaluates), evaluates + assert not runs_text('# eval "$x"\n: x') for elsewhere in ( ": ; cat() { :; }", "true && cat() { :; }", From 25f4c9b2681692bd4afaf0948c9cb0362ecbe44d Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 30 Oct 2026 12:31:13 -0400 Subject: [PATCH 09/10] Refuse array elements that split; close the pins' redirection and $'...' words The review of d3770d66 found two detector misses. Both are test-side: propose uses neither. An array element splits as an argument does, unlike NAME=$x, so `local o='--web '; local a=($o)` hands gh --web, and `local a=(*)` does the same from a filename. Commands.array now raises Unlexed on an element that splits. A redirection can touch the builtin's word: `eval>x y` runs eval, and so do 'source'x, on bash 3.2, 5.2.37 and 5.3. Other characters that end the word leave it no arguments, so the boundary stays narrow: `grep -c .)`, which the script holds, must not match. $"eval" runs eval, and so do $'eval', $'\x65val' and $'\145val', which no normalising of quotes would read. The script holds no $'...' or $"...", so the script-wide pin now refuses both. Co-Authored-By: Claude Opus 5.5 --- tests/test_uk_replay_results_pr.py | 54 ++++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 14 deletions(-) diff --git a/tests/test_uk_replay_results_pr.py b/tests/test_uk_replay_results_pr.py index c6f19d518..5a310ae27 100644 --- a/tests/test_uk_replay_results_pr.py +++ b/tests/test_uk_replay_results_pr.py @@ -394,9 +394,10 @@ class Commands: command, after an operator, a newline, ``!`` or a reserved word, and after any assignments and redirections before it. What it does not model is flagged rather than read past: arithmetic, case, an array element's - index, a parameter expansion beyond PARAMETER and a word after a compound - command raise Unlexed, and a loop's keywords are commands PROPOSE_RUNS - does not list. With no loop, each declaration runs at most once. + index or a split in one, a parameter expansion beyond PARAMETER and a word + after a compound command raise Unlexed, and a loop's keywords are commands + PROPOSE_RUNS does not list. With no loop, each declaration runs at most + once. ``splits`` holds the words with an expansion or a glob outside double quotes, which bash can turn into words the text does not show.""" @@ -583,7 +584,8 @@ def dollar(self, i, function): return i + 1 def array(self, i, function): - """NAME=( WORD... ): the words, over lines, up to ``)``.""" + """NAME=( WORD... ): the words, over lines, up to ``)``. Bash splits + an element, as it does an argument and unlike NAME=$x.""" t = self.text while True: i = self.blank(i) @@ -595,7 +597,9 @@ def array(self, i, function): # ([expr]=value): the index is arithmetic. raise Unlexed("an array element's index") else: - _, i = self.word(i, function) + word, i = self.word(i, function) + if word in self.splits: + raise Unlexed(f"the array element {word}, which splits") def plain_test(args): @@ -834,14 +838,18 @@ def test_the_builder_runs_no_release_code_and_never_merges(): GROUP = '{\necho "::error::; builder check"\n}' # A function definition, wherever in a line it starts, and eval, source or # . as a word. Both read text after unquoted: a quote, a backslash or a line -# continuation inside a word does not change what bash runs. A word assembled -# at run time (n=ev; "${n}al") is beyond any rule on text. +# continuation inside a word does not change what bash runs. A redirection may +# touch the word (eval>x y), and anything else that ends it leaves it no +# arguments. $'...' and $"..." can spell a word in escapes ($'\x65val'), so the +# script holds neither. A word assembled at run time (n=ev; "${n}al") is beyond +# any rule on text. DEFINITION = re.compile( r"(?:^|[\s;&|(){}])" r"(?:function\s+([^\s(){}]+)|([^\s(){}=;&|<>$`]+)\s*\(\s*\))", re.M, ) -RUNS_TEXT = re.compile(r"(?:^|[\s;&|({])(?:eval|source|\.)\s", re.M) +RUNS_TEXT = re.compile(r"(?:^|[\s;&|({])(?:eval|source|\.)(?:[\s<>]|&>)", re.M) +SPELLS_WORD = re.compile(r"\$['\"]") def definitions(text): @@ -849,11 +857,12 @@ def definitions(text): def runs_text(script): - """Each eval, source or . in ``script``, comment lines aside.""" + """Each eval, source or . in ``script``, comment lines aside, and each + $'...' or $"...".""" code = "\n".join( line for line in script.splitlines() if not line.lstrip().startswith("#") ) - return RUNS_TEXT.findall(unquoted(code)) + return RUNS_TEXT.findall(unquoted(code)) + SPELLS_WORD.findall(code) # pushgit, defined with another program in git's place. @@ -957,6 +966,10 @@ def test_propose_runs_only_the_commands_it_lists(): "git ls-remote ?-upload-pack=x .", "gh pr list [-]-web", "gh pr list $'--web'", + # Review of d3770d66: gh ran its browser from an array element that + # splits or globs, under every bash. + "local o='--web '\nlocal a=($o)\ngh pr list \"${a[@]}\"", + 'local a=(*)\ngh pr list "${a[@]}"', # Every other test: a shape it does not run, or an operand that may # be several words. "[ -v x ]", @@ -991,11 +1004,24 @@ def test_propose_runs_only_the_commands_it_lists(): # once: pushgit as PUSHGIT, and plan as field on the plan. A definition # counts wherever it starts (after ;, &&, a quote...), and the script # holds no eval, source or . that could define one from text it builds - # (reviews of cf8066bc, 2, and f936b49c, 2). field, which plan runs, is - # the isolated runner's Python on a fixed program that imports json and - # sys alone. + # (reviews of cf8066bc, 2, f936b49c, 2, and d3770d66, 2). field, which plan + # runs, is the isolated runner's Python on a fixed program that imports + # json and sys alone. assert not runs_text(script) - for evaluates in ("e''val x", "'source' x", "\\. x", "e\\\nval x", ': ; . "$x"'): + for evaluates in ( + "e''val x", + "'source' x", + "\\. x", + "e\\\nval x", + ': ; . "$x"', + "eval>x y", + "'source'x y", + '$"eval" x', + "$'eval' x", + "$'\\x65val' x", + ): assert runs_text(evaluates), evaluates assert not runs_text('# eval "$x"\n: x') for elsewhere in ( From ed25ea09c883d0d0d0c46b35fd2047b2cf2fceaa Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 30 Oct 2026 13:18:54 -0400 Subject: [PATCH 10/10] Read every line in the script-wide pin; count a case pattern's ) The review of 25f4c9b2 found two more spellings of eval that the pin missed, which propose does not use. Each runs on bash 3.2, 5.2.37 and 5.3: : 'x # ';eval y case x in x)eval y;; esac The first line of the pair sits inside a quote, so the second is code that only looks like a comment. Setting comment lines aside needs quote state, and shell_residue, which tracks it, refuses the script's heredoc. So runs_text now sets no line aside. That removes code, and a line that looks like a comment can no longer hide anything. The script's comments had two hits, both prose sentences ending in ")."; this rewords both and changes nothing else in the script. The left boundary now counts ), which also covers `x). y` and `x)source y`. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/uk_replay_results_pr.sh | 5 +++-- tests/test_uk_replay_results_pr.py | 27 +++++++++++++------------ 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/.github/scripts/uk_replay_results_pr.sh b/.github/scripts/uk_replay_results_pr.sh index 5b4b80f00..5b010493c 100644 --- a/.github/scripts/uk_replay_results_pr.sh +++ b/.github/scripts/uk_replay_results_pr.sh @@ -117,7 +117,8 @@ assemble() { } build() { - # Every third-party module the builder and the checks import (tests check). + # Every third-party module the builder and the checks import, which tests + # check. local CONTROL=(uv run --with rfc8785==0.1.4 --with jsonschema python) builder() { PYTHONPATH="$HERE" "${CONTROL[@]}" -m pipeline.uk_replay_results_pr "$@"; } git fetch -q --no-tags origin "+refs/heads/$BASE:$BASE_REF" \ @@ -176,7 +177,7 @@ build() { # CI's format check and suite on the commit, as ci.yml's python job runs them # (tests check the lines are its lines), then its no-drift check. A failure # is reported, not fatal: the pull request opens as a draft that names it -# (review of 24434729, 3). This runs in the build job, which holds no write +# (review of 24434729, 3): this runs in the build job, which holds no write # credential. The variables that name the step's command files are unset for # it, so a test or tool that writes $GITHUB_OUTPUT or $GITHUB_ENV by name # writes nowhere. That is hygiene, not a sandbox: a process that finds the diff --git a/tests/test_uk_replay_results_pr.py b/tests/test_uk_replay_results_pr.py index 5a310ae27..1efe6c5f5 100644 --- a/tests/test_uk_replay_results_pr.py +++ b/tests/test_uk_replay_results_pr.py @@ -838,17 +838,19 @@ def test_the_builder_runs_no_release_code_and_never_merges(): GROUP = '{\necho "::error::; builder check"\n}' # A function definition, wherever in a line it starts, and eval, source or # . as a word. Both read text after unquoted: a quote, a backslash or a line -# continuation inside a word does not change what bash runs. A redirection may -# touch the word (eval>x y), and anything else that ends it leaves it no -# arguments. $'...' and $"..." can spell a word in escapes ($'\x65val'), so the -# script holds neither. A word assembled at run time (n=ev; "${n}al") is beyond -# any rule on text. +# continuation inside a word does not change what bash runs. Both read every +# line, comments included, because a line that starts with # inside a quote is +# not a comment: so a comment in the script avoids these words, and a sentence +# ending ")." with it. A redirection may touch the word (eval>x y), and anything +# else that ends it leaves it no arguments. $'...' and $"..." can spell a word +# in escapes ($'\x65val'), so the script holds neither. A word assembled at run +# time (n=ev; "${n}al") is beyond any rule on text. DEFINITION = re.compile( r"(?:^|[\s;&|(){}])" r"(?:function\s+([^\s(){}]+)|([^\s(){}=;&|<>$`]+)\s*\(\s*\))", re.M, ) -RUNS_TEXT = re.compile(r"(?:^|[\s;&|({])(?:eval|source|\.)(?:[\s<>]|&>)", re.M) +RUNS_TEXT = re.compile(r"(?:^|[\s;&|(){])(?:eval|source|\.)(?:[\s<>]|&>)", re.M) SPELLS_WORD = re.compile(r"\$['\"]") @@ -857,12 +859,9 @@ def definitions(text): def runs_text(script): - """Each eval, source or . in ``script``, comment lines aside, and each - $'...' or $"...".""" - code = "\n".join( - line for line in script.splitlines() if not line.lstrip().startswith("#") - ) - return RUNS_TEXT.findall(unquoted(code)) + SPELLS_WORD.findall(code) + """Each eval, source or . on any line of ``script``, and each $'...' or + $"...".""" + return RUNS_TEXT.findall(unquoted(script)) + SPELLS_WORD.findall(script) # pushgit, defined with another program in git's place. @@ -1021,9 +1020,11 @@ def test_propose_runs_only_the_commands_it_lists(): '$"eval" x', "$'eval' x", "$'\\x65val' x", + ": 'x\n# ';eval y", + "case x in x)eval y;; esac", ): assert runs_text(evaluates), evaluates - assert not runs_text('# eval "$x"\n: x') + assert not runs_text("x=$(grep -c .)\n: x") for elsewhere in ( ": ; cat() { :; }", "true && cat() { :; }",