From 7fa21601baf330ca0f43768d6ac40713b892250b Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:01:24 +0100 Subject: [PATCH 1/3] Group scheduled runtime updates and route site notifications from main --- .github/dependabot.yml | 4 ++++ .github/workflows/site-release-notify.yml | 17 +++++------------ docs/codex/TASKS_BACKLOG.md | 10 ++++++++++ docs/contributor-intake.md | 14 +++++++++++++- tests/test_site_release_notify.py | 13 ++++++++----- 5 files changed, 40 insertions(+), 18 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 9bd2596a..49d5369a 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -12,6 +12,10 @@ updates: development-tooling: dependency-type: development patterns: ["*"] + runtime-maintenance: + applies-to: version-updates + dependency-type: production + update-types: [minor, patch] labels: [dependencies, python] commit-message: prefix: deps diff --git a/.github/workflows/site-release-notify.yml b/.github/workflows/site-release-notify.yml index 4c23003c..cf591f51 100644 --- a/.github/workflows/site-release-notify.yml +++ b/.github/workflows/site-release-notify.yml @@ -3,6 +3,7 @@ name: Notify toolkit site of stable release on: workflow_run: workflows: [Release] + branches: [main] types: [completed] permissions: {} @@ -20,8 +21,7 @@ jobs: github.event.workflow_run.repository.full_name == github.repository && github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.conclusion == 'success' && - ((github.event.workflow_run.event == 'pull_request' && startsWith(github.event.workflow_run.head_branch, 'release/v')) || - (github.event.workflow_run.event == 'workflow_dispatch' && github.event.workflow_run.head_branch == 'main')) + github.event.workflow_run.event == 'workflow_dispatch' && github.event.workflow_run.head_branch == 'main' runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -104,11 +104,8 @@ jobs: exit 1 } read -r _ _ _ expected_tag expected_digest receipt_mode <<< "${marker}" - case "${SOURCE_EVENT}" in - pull_request) test "${SOURCE_HEAD_BRANCH}" = "release/${expected_tag}" ;; - workflow_dispatch) test "${SOURCE_HEAD_BRANCH}" = main ;; - *) exit 1 ;; - esac + test "${SOURCE_EVENT}" = workflow_dispatch + test "${SOURCE_HEAD_BRANCH}" = main gh api -H 'X-GitHub-Api-Version: 2026-03-10' "repos/${GITHUB_REPOSITORY}/releases/latest" \ > "${RUNNER_TEMP}/latest-release.json" @@ -137,21 +134,17 @@ jobs: exit 1 fi jq -e --arg tag "${expected_tag}" --arg mode "${receipt_mode}" \ - --arg event "${SOURCE_EVENT}" --arg head "${SOURCE_HEAD_SHA}" \ --argjson id "${SOURCE_RUN_ID}" --argjson attempt "${SOURCE_RUN_ATTEMPT}" ' def positive_integer: type == "number" and . == floor and . > 0; .schema_version == "ocr-toolkit.release-receipt/v2" and .tag == $tag and .version == ($tag | ltrimstr("v")) and (.reviewed.merge | type == "string" and test("^[0-9a-f]{40}$")) and .github.annotated_tag_target == .reviewed.merge and - ($event != "pull_request" or .reviewed.head == $head) and (.workflow.run_id | positive_integer) and (.workflow.run_attempt | positive_integer) and (if $mode == "created" then .workflow.run_id == $id and .workflow.run_attempt == $attempt - elif .workflow.run_id == $id then - .workflow.run_attempt <= $attempt else - $event == "workflow_dispatch" + .workflow.run_id != $id or .workflow.run_attempt <= $attempt end) ' "${RUNNER_TEMP}/release-receipt.json" >/dev/null diff --git a/docs/codex/TASKS_BACKLOG.md b/docs/codex/TASKS_BACKLOG.md index 725b0cd5..7f71e16c 100644 --- a/docs/codex/TASKS_BACKLOG.md +++ b/docs/codex/TASKS_BACKLOG.md @@ -136,3 +136,13 @@ The [signal-ownership audit](../engineering/review_signal_ownership.md) remains - **Exclusions:** Learned online routing, per-tool models, multiple agents, or silent policy changes. - **Validation:** Offline replay, adversarial boundaries, fallback tests, and quality thresholds. - **Release classification expectation:** `release-required`. + +## Maintainer CI + +### BL-026: Avoid redundant PR validations without replacing required checks + +- **Status:** planned +- **Activation trigger:** A hosted test repository can reproduce this project's required Actions and CodeQL app checks on protected branches. +- **Evidence:** A description edit on #361 cancelled checks and started a second validation of the same synthetic merge commit. During promotion, eight CI runs on Dependabot #346–349 used a combined 13,122 job-seconds on allocated runners. Four runs were created shortly after automatic closure and ran 22 test jobs to success. In #363 the macOS Python 3.12 runner waited 14m40s before starting. [Original validation](https://github.com/xeonvs/open-code-review-toolkit/actions/runs/46740538729) · [Replacement validation](https://github.com/xeonvs/open-code-review-toolkit/actions/runs/46740601948) · [Release CI](https://github.com/xeonvs/open-code-review-toolkit/actions/runs/46746189464) +- **Next safe action:** Measure runner queue and execution time separately across releases. Finalize PR descriptions before marking a PR ready. For later status updates, use PR comments. Evaluate metadata-only edits and already-closed Dependabot work in an isolated hosted repository. +- **Acceptance:** An edit to the title or body alone neither cancels work on the same revision nor emits a passing or skipped required check in place of a pending or failed one. Recheck the exact head, base and test-merge revisions on retarget, synchronization, draft/ready transitions, or ambiguous events. Verify merge eligibility for forks and repository-owned PRs with the actual required app identities. Preserve independent platform, secret, provenance and registry-install checks. diff --git a/docs/contributor-intake.md b/docs/contributor-intake.md index 7bc0490a..4930014c 100644 --- a/docs/contributor-intake.md +++ b/docs/contributor-intake.md @@ -12,4 +12,16 @@ 2. Review the full diff at those revisions before approving fork CI. Check workflow and executable changes, dependency and lockfile sources, installation and container inputs, Action pins and OCR qualification integrity values. Review additions and removals and both paths of renames and copies. Confirm a human updater's maintainer role in GitHub's repository access settings. For Dependabot updates to `dev`, verify the configured bot account, repository-owned branch and GitHub-verified commits through the reviewed head. Treat labels and branch names as context. Have a maintainer prepare dependency changes requested by an outside contributor. [Dependency audit and upstream review](development.md#dependency-audit-before-push) 3. Mark the PR ready and verify the full applicable protected CI ran and passed for the live base and head. Repeat review and checks when either revision changes. The maintainer verifies the author, source, target and revisions immediately before manual merge. Require an independent approval and dismiss stale approvals when there are two eligible maintainers. With a sole maintainer, record the exact revision reviewed and retain protected PR checks for maintainer-authored work. Squash eligible fork changes into `dev` with contributor attribution. For a CLI squash merge, supply the reviewed head with `gh pr merge "$PR_NUMBER" --squash --match-head-commit "$REVIEWED_HEAD"`. Whenever current main is no longer an ancestor of dev, including after a squash promotion or stable release, create a maintainer sync branch at the current `dev` tip, merge current `main` into it with a signed merge, and open a PR back to `dev`. Use a merge commit to preserve ancestry. Check that the current `main` tip is an ancestor of `dev` before the next promotion. [GitHub CLI merge options](https://cli.github.com/manual/gh_pr_merge) -Dependabot's `target-branch: dev` applies to scheduled version updates. GitHub opens security update PRs against the default branch. Retarget those to `dev` for review or prepare the fix there on a maintainer branch. [Dependabot target-branch behavior](https://docs.github.com/en/code-security/reference/supply-chain-security/dependabot-options-reference#target-branch) +Dependabot groups scheduled runtime minor and patch updates into one PR to `dev`. Review the lockfile changes for each package. GitHub opens security update PRs against the default branch. Retarget those to `dev` for review or prepare the fix there on a maintainer branch. [Dependabot target-branch behavior](https://docs.github.com/en/code-security/reference/supply-chain-security/dependabot-options-reference#target-branch) + +### Reconcile superseded Dependabot PRs before promotion + +Before merging a protected development promotion, list open Dependabot PRs targeting its base. This covers older version-update PRs that still target `main`. + +```sh +gh pr list --state open --base main --author app/dependabot --json number,title,headRefName,headRefOid +``` + +For a scheduled version update already incorporated in the reviewed promotion, compare the complete proposed dependency and lockfile or Action-pin diff, including transitive changes. If every change is accounted for, record the promotion PR and close the superseded bot PR before moving the base. Keep outstanding changes and security updates open until the target contains their fix. + +Check for queued or in-progress PR runs on the bot branch after closure. A queued event can create a run after the PR closes. Before cancelling an individual run, re-read the PR state and verify its closed, unmerged head, source repository and branch against the run. Limit cancellation to superseded pull-request validation runs in the same repository and confirm no open PR still uses that branch and revision. Use the run ID for cancellation and read back its terminal state. Ordinary dependency PRs continue through the usual required checks. diff --git a/tests/test_site_release_notify.py b/tests/test_site_release_notify.py index f73bbfa4..5502ce40 100644 --- a/tests/test_site_release_notify.py +++ b/tests/test_site_release_notify.py @@ -22,7 +22,10 @@ def _verification_step() -> str: def test_site_dispatch_occurs_once_after_read_only_verification() -> None: - jobs = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"] + workflow = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8")) + assert workflow[True]["workflow_run"]["branches"] == ["main"] + jobs = workflow["jobs"] + assert "workflow_dispatch" in jobs["verify"]["if"] steps = jobs["notify"]["steps"] assert "--method POST" not in _verification_step() assert "OCR_SITE_DISPATCH_TOKEN" not in str(jobs["verify"]) @@ -59,7 +62,7 @@ def test_site_dispatch_occurs_once_after_read_only_verification() -> None: (["success"], {"receipt_attempt": 3, "receipt_mode": "reused"}, 1, "", 1, False), ( ["success"], - {"receipt_run": 39784500000, "receipt_attempt": 1, "receipt_mode": "reused"}, + {"receipt_run": 39784500000, "receipt_attempt": 1}, 1, "", 1, @@ -87,7 +90,7 @@ def test_site_dispatch_occurs_once_after_read_only_verification() -> None: 1, False, ), - (["success"], {"reviewed_head": "3" * 40}, 1, "", 1, False), + (["success"], {"event": "pull_request", "branch": "release/v0.12.1"}, 1, "", 1, False), ], ) def test_release_job_readback_is_bounded_and_fail_closed( @@ -199,8 +202,8 @@ def test_release_job_readback_is_bounded_and_fail_closed( "SOURCE_RUN_ATTEMPT": str(run_attempt), "SOURCE_WORKFLOW_ID": "315030204", "SOURCE_HEAD_SHA": source_sha, - "SOURCE_EVENT": str(overrides.get("event", "pull_request")), - "SOURCE_HEAD_BRANCH": str(overrides.get("branch", "release/v0.12.1")), + "SOURCE_EVENT": str(overrides.get("event", "workflow_dispatch")), + "SOURCE_HEAD_BRANCH": str(overrides.get("branch", "main")), "RUNNER_TEMP": str(tmp_path), "GITHUB_OUTPUT": str(output), } From df4328f92a89893fdc092a3d4891d5210f594aa3 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:01:53 +0100 Subject: [PATCH 2/3] Run stable publishing on protected main and verify historical build provenance --- .github/workflows/release.yml | 125 ++++++++++++---------------- docs/release.md | 24 ++++-- tests/test_release_authorization.py | 90 ++++++++++++++++---- tests/test_release_receipt.py | 62 ++++++++++++++ 4 files changed, 206 insertions(+), 95 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8cb9f5bb..0be89cd3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,9 +1,6 @@ name: Release on: - pull_request: - types: [closed] - branches: [main] workflow_dispatch: inputs: pull-request-number: @@ -31,39 +28,23 @@ permissions: contents: read concurrency: - group: production-release + # Match authorize.if so skipped dispatches cannot replace a pending release. + group: >- + ${{ + github.event_name == 'workflow_dispatch' && + github.event.repository.private == false && + github.ref == 'refs/heads/main' && + 'production-release' || format('release-ignored-{0}', github.run_id) + }} cancel-in-progress: false jobs: - classify: - name: classify-release-trigger - runs-on: ubuntu-latest - timeout-minutes: 2 - outputs: - release: ${{ steps.classify.outputs.release }} - steps: - - id: classify - env: - EVENT_NAME: ${{ github.event_name }} - PR_MERGED: ${{ github.event.pull_request.merged }} - PR_HEAD_REF: ${{ github.event.pull_request.head.ref }} - run: | - release=false - if [ "${EVENT_NAME}" = workflow_dispatch ]; then - release=true - elif [ "${PR_MERGED}" = true ] && [[ "${PR_HEAD_REF}" == release/v* ]]; then - release=true - fi - echo "release=${release}" >> "${GITHUB_OUTPUT}" - authorize: name: authorize-release - needs: classify if: >- + github.event_name == 'workflow_dispatch' && github.event.repository.private == false && - github.ref == 'refs/heads/main' && - (github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && - needs.classify.outputs.release == 'true' + github.ref == 'refs/heads/main' runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -83,16 +64,14 @@ jobs: tree: ${{ steps.authorize.outputs.tree }} version: ${{ steps.authorize.outputs.version }} steps: - - name: Load the pinned main history for recovery - if: github.event_name == 'workflow_dispatch' + - name: Load the pinned main history uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.sha }} path: dispatch-main fetch-depth: 0 persist-credentials: false - - name: Verify the historical recovery policy reference before checkout - if: github.event_name == 'workflow_dispatch' + - name: Verify the protected release policy reference before checkout env: GH_TOKEN: ${{ github.token }} PR_NUMBER: ${{ inputs['pull-request-number'] }} @@ -102,6 +81,10 @@ jobs: BASE: ${{ inputs['reviewed-base'] }} shell: bash run: | + if [[ "${GITHUB_REF}" != refs/heads/main ]]; then + echo "release dispatch must run from refs/heads/main" >&2 + exit 1 + fi [[ "${PR_NUMBER}" =~ ^[1-9][0-9]*$ && "${VERSION}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] [[ "${MERGE}" =~ ^[0-9a-f]{40}$ && "${HEAD}" =~ ^[0-9a-f]{40}$ && "${BASE}" =~ ^[0-9a-f]{40}$ ]] [[ "${GITHUB_SHA}" =~ ^[0-9a-f]{40}$ ]] @@ -116,55 +99,46 @@ jobs: curl --fail --silent --show-error --proto '=https' \ --connect-timeout 10 --max-time 30 --max-filesize 1048576 \ --header 'Accept: application/vnd.github+json' \ - --header 'X-GitHub-Api-Version: 2026-03-10' \ + --header "X-GitHub-Api-Version: $1" \ --oauth2-bearer "${GH_TOKEN}" \ - "https://api.github.com/repos/${GITHUB_REPOSITORY}/$1" + "https://api.github.com/repos/${GITHUB_REPOSITORY}/$2" } - read_github_metadata "pulls/${PR_NUMBER}" | + # Pull request responses in 2026-03-10 omit merge_commit_sha. + if ! read_github_metadata 2022-11-28 "pulls/${PR_NUMBER}" | jq -e --arg repo "${GITHUB_REPOSITORY}" --argjson number "${PR_NUMBER}" \ --arg version "${VERSION}" --arg head "${HEAD}" --arg merge "${MERGE}" --arg base "${BASE}" ' .number == $number and .merged == true and .merge_commit_sha == $merge and .base.repo.full_name == $repo and .base.ref == "main" and .base.sha == $base and .head.repo.full_name == $repo and .head.ref == ("release/v" + $version) and .head.sha == $head and .title == ("Release v" + $version) - ' >/dev/null - read_github_metadata "git/commits/${MERGE}" | + ' >/dev/null; then + echo "release pull request does not match the requested identities" >&2 + exit 1 + fi + if ! read_github_metadata 2026-03-10 "git/commits/${MERGE}" | jq -e --arg merge "${MERGE}" --arg base "${BASE}" ' .sha == $merge and (.parents | length) == 1 and .parents[0].sha == $base - ' >/dev/null + ' >/dev/null; then + echo "release merge is not a squash of the requested protected base" >&2 + exit 1 + fi - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: # Authorization code must come from protected policy that predates the # release PR. Candidate head and merge commits are inspected only as data. - ref: ${{ github.event.pull_request.base.sha || inputs['reviewed-base'] }} + ref: ${{ inputs['reviewed-base'] }} persist-credentials: false - id: authorize env: GH_TOKEN: ${{ github.token }} - EVENT_NAME: ${{ github.event_name }} - EVENT_PR_NUMBER: ${{ github.event.pull_request.number }} - EVENT_BASE_SHA: ${{ github.event.pull_request.base.sha }} - INPUT_PR_NUMBER: ${{ inputs['pull-request-number'] }} - INPUT_VERSION: ${{ inputs.version }} - INPUT_COMMIT: ${{ inputs['merge-commit'] }} - INPUT_HEAD: ${{ inputs['reviewed-head'] }} - INPUT_BASE: ${{ inputs['reviewed-base'] }} + PR_NUMBER: ${{ inputs['pull-request-number'] }} + REQUESTED_VERSION: ${{ inputs.version }} + REQUESTED_COMMIT: ${{ inputs['merge-commit'] }} + REQUESTED_HEAD: ${{ inputs['reviewed-head'] }} + REQUESTED_BASE: ${{ inputs['reviewed-base'] }} REPOSITORY: ${{ github.repository }} run: | - if [ "${EVENT_NAME}" = workflow_dispatch ]; then - PR_NUMBER=${INPUT_PR_NUMBER} - REQUESTED_VERSION=${INPUT_VERSION} - REQUESTED_COMMIT=${INPUT_COMMIT} - REQUESTED_HEAD=${INPUT_HEAD} - REQUESTED_BASE=${INPUT_BASE} - else - PR_NUMBER=${EVENT_PR_NUMBER} - REQUESTED_VERSION= - REQUESTED_COMMIT= - REQUESTED_HEAD= - REQUESTED_BASE=${EVENT_BASE_SHA} - fi - test "$(scripts/bounded_github_api.sh \ + test "$(GITHUB_API_VERSION=2022-11-28 scripts/bounded_github_api.sh \ "repos/${REPOSITORY}/pulls/${PR_NUMBER}" /tmp/release-pr.json)" = 200 HEAD_SHA=$(jq -r .head.sha /tmp/release-pr.json) MERGE_SHA=$(jq -r .merge_commit_sha /tmp/release-pr.json) @@ -340,6 +314,21 @@ jobs: encoding="utf-8", ) PY + - name: Verify original source attestations before publication + if: github.sha != needs.authorize.outputs.commit + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_COMMIT: ${{ needs.authorize.outputs.commit }} + shell: bash + run: | + for artifact in dist/* runtime-requirements.txt; do + gh attestation verify "${artifact}" \ + --repo "${GITHUB_REPOSITORY}" \ + --signer-workflow "${GITHUB_REPOSITORY}/.github/workflows/release.yml" \ + --source-digest "${EXPECTED_COMMIT}" \ + --source-ref refs/heads/main \ + --deny-self-hosted-runners + done - name: Load protected v0.11.1 PyPI recovery policy if: github.event_name == 'workflow_dispatch' && inputs.version == '0.11.1' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -408,6 +397,7 @@ jobs: classify testpypi https://test.pypi.org/simple/open-code-review-toolkit/ /tmp/testpypi-index.json classify pypi https://pypi.org/simple/open-code-review-toolkit/ /tmp/pypi-index.json - uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + if: github.sha == needs.authorize.outputs.commit with: subject-path: | dist/* @@ -426,7 +416,7 @@ jobs: publish-testpypi: name: publish-testpypi needs: build - if: needs.build.outputs.testpypi-state == 'publish' + if: github.ref == 'refs/heads/main' && needs.build.outputs.testpypi-state == 'publish' runs-on: ubuntu-latest timeout-minutes: 10 environment: testpypi-public-disclosure @@ -479,7 +469,7 @@ jobs: publish-pypi: name: publish-pypi needs: [build, verify-testpypi] - if: needs.build.outputs.pypi-state == 'publish' + if: github.ref == 'refs/heads/main' && needs.build.outputs.pypi-state == 'publish' runs-on: ubuntu-latest timeout-minutes: 10 environment: pypi-production @@ -557,7 +547,7 @@ jobs: needs: [authorize, build, verify-pypi] if: >- always() && needs.authorize.result == 'success' && needs.build.result == 'success' && - needs.verify-pypi.result == 'success' + needs.verify-pypi.result == 'success' && github.ref == 'refs/heads/main' runs-on: ubuntu-latest timeout-minutes: 10 permissions: @@ -704,11 +694,6 @@ jobs: --hashes artifact-hashes.json \ --runtime-requirements runtime-requirements.txt \ --validate-existing release-receipt.json - if [[ "${GITHUB_EVENT_NAME}" == pull_request ]] && - ! jq -e --argjson run "${GITHUB_RUN_ID}" '.workflow.run_id == $run' release-receipt.json >/dev/null; then - echo "This receipt was created by another run. Use the main-branch release recovery dispatch." >&2 - exit 1 - fi ;; *) echo "duplicate GitHub Release receipt asset" >&2; exit 1 ;; esac diff --git a/docs/release.md b/docs/release.md index a24d4ce7..cbac5fc5 100644 --- a/docs/release.md +++ b/docs/release.md @@ -27,12 +27,12 @@ The delivery sequence is: 2. merge the protected feature pull request to `main`; 3. verify the deterministic `.devN` wheel and sdist on TestPyPI; 4. prepare and merge a protected signed `release/vX.Y.Z` pull request; -5. monitor stable TestPyPI and PyPI publication, annotated tag, provenance, attestations, and immutable GitHub Release; +5. start the Release workflow on protected `main` for the reviewed squash and monitor stable TestPyPI and PyPI publication, annotated tag, provenance, attestations, and immutable GitHub Release; 6. require the release CI jobs to independently compare artifact hashes and smoke-install every supported Python boundary; 7. require CI readback of the immutable `release-receipt.json`, then close the tracked issues and milestone; 8. independently read back the exact external state against the immutable receipt and issue comments, then close the delivery objective without another repository pull request. -The release pull request is the final repository mutation before stable publication. It owns stable and next version markers, deterministic source epoch, tracked authorization metadata, generated Towncrier changelog, release notes, and reconciliation of the plan and status documents. Follow the checked [plan archive and external reconciliation](#external-reconciliation-and-plan-archiving) below. `.release-reconciled-version` is historical evidence for releases that used a post-publication repository closure PR; it does not advance for plans closed in the release PR. Current validation uses the archived plan, stable index and immutable external receipts instead. The release PR must not claim that registry files, provenance, tag, immutable Release, receipt, or installs already exist. The protected-main merge may run the normal TestPyPI development workflow described below; verify its workflow outcome, but do not treat that development build as another stable release or repeat stable artifact readback. +The release pull request fixes the final source tree for stable publication. An explicitly authorized protected workflow repair can advance `main` before a historical recovery. The release PR owns stable and next version markers, deterministic source epoch, tracked authorization metadata, generated Towncrier changelog, release notes, and reconciliation of the plan and status documents. Follow the checked [plan archive and external reconciliation](#external-reconciliation-and-plan-archiving) below. `.release-reconciled-version` is historical evidence for releases that used a post-publication repository closure PR; it does not advance for plans closed in the release PR. Current validation uses the archived plan, stable index and immutable external receipts instead. The release PR must not claim that registry files, provenance, tag, immutable Release, receipt, or installs already exist. The protected-main merge may run the normal TestPyPI development workflow described below; verify its workflow outcome, but do not treat that development build as another stable release or repeat stable artifact readback. List tracked release issues in a release PR as bare references or ordinary non-closing prose. Do not use GitHub closing-keyword forms such as `close`, `closes`, `closed`, `fix`, `fixes`, `fixed`, `resolve`, or `resolves` together with those issue references: merging such a PR can close the issues before the immutable receipt exists. The Release workflow is the sole closure owner, and acts only after its post-publication receipt readback. @@ -87,9 +87,17 @@ are inputs to the release contracts, not bookkeeping covered by an earlier run. Other changed release boundaries add their own tests; this set does not replace the final quality gate or protected CI. -Squash-merging that exact repository-owned release PR is the only human publication gate. The **Release** workflow then: +Squash-merging the exact repository-owned release PR authorizes publication. Start the Release workflow once on protected `main` using the reviewed identities, preferably before advancing the branch again. -1. validates the branch, title, tracked metadata, reviewed head/base, exact required checks, squash-tree equivalence, merge parent, canonical version, and tracked build epoch; +```sh +gh workflow run release.yml --ref main \ + -f pull-request-number="$PR_NUMBER" -f version="$VERSION" \ + -f merge-commit="$MERGE_SHA" -f reviewed-head="$HEAD_SHA" -f reviewed-base="$BASE_SHA" +``` + +The **Release** workflow performs these steps. + +1. It validates the branch, title, tracked metadata, reviewed head/base, exact required checks, squash-tree equivalence, merge parent, canonical version, and tracked build epoch; 2. relies on successful required PR quality/build checks bound to the exact reviewed tree, then runs release dependency, packaging, and artifact-set checks; 3. builds wheel and sdist once, records SHA-256 values, and creates GitHub provenance attestations; 4. publishes or exact-hash-verifies the same bytes on TestPyPI through OIDC; @@ -131,7 +139,10 @@ After publication, independently verify the immutable release, workflow, tag, re Recovery dispatch is bound to the original release PR, version, merge commit, reviewed head, and protected reviewed base. Before loading the historical authorizer, the workflow confirms that the squash merge is on the first-parent -history of the exact `main` commit that started the dispatch. Recovery +history of the exact `main` commit that started the dispatch. If main has advanced, +the rebuilt wheel, sdist and runtime lock must each match an existing GitHub-hosted +release workflow attestation for the original squash on main before either +registry can receive files. Recovery evaluates the current effective `main` rules against the original reviewed head. Reconcile outstanding releases before adding new required check contexts, since the original reviewed head must still satisfy those checks. @@ -139,8 +150,7 @@ contexts, since the original reviewed head must still satisfy those checks. Recovery accepts only exact registry bytes and the existing immutable receipt's closed release identity, and rejects unknown receipt fields. When a prior dispatch created the receipt, resume through a new recovery dispatch -from `main`. A PR-triggered rerun can resume a receipt created by its own -workflow run. Draft +from `main`. Draft GitHub Releases are retained and addressed by their numeric release ID until publication because tag lookup does not expose private drafts reliably. Every numeric-ID read, asset upload, and publication step revalidates the expected diff --git a/tests/test_release_authorization.py b/tests/test_release_authorization.py index 17f8d5d1..ae66274c 100644 --- a/tests/test_release_authorization.py +++ b/tests/test_release_authorization.py @@ -333,33 +333,67 @@ def test_required_check_and_ruleset_synchronization_are_exact() -> None: authorize(protection=protection) -def test_release_workflow_classifies_ordinary_merges_before_authorization() -> None: - workflow = WORKFLOW.read_text(encoding="utf-8") +def test_release_workflow_accepts_only_main_dispatches_with_explicit_identities() -> None: + workflow = yaml.load(WORKFLOW.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) + assert set(workflow["on"]) == {"workflow_dispatch"} + inputs = workflow["on"]["workflow_dispatch"]["inputs"] + assert {name: (field["required"], field["type"]) for name, field in inputs.items()} == { + "pull-request-number": ("true", "number"), + "version": ("true", "string"), + "merge-commit": ("true", "string"), + "reviewed-head": ("true", "string"), + "reviewed-base": ("true", "string"), + } - assert "name: classify-release-trigger" in workflow - assert '[[ "${PR_HEAD_REF}" == release/v* ]]' in workflow - assert "needs: classify" in workflow - assert "needs.classify.outputs.release == 'true'" in workflow + jobs = workflow["jobs"] + assert {name for name, job in jobs.items() if "needs" not in job} == {"authorize"} + gate = jobs["authorize"]["if"] + assert gate == ( + "github.event_name == 'workflow_dispatch' && github.event.repository.private == false && " + "github.ref == 'refs/heads/main'" + ) + concurrency = workflow["concurrency"] + assert " ".join(concurrency["group"].split()) == ( + f"${{{{ {gate} && 'production-release' || format('release-ignored-{{0}}', github.run_id) }}}}" + ) + assert concurrency["cancel-in-progress"] == "false" + assert jobs["build"]["needs"] == "authorize" + assert jobs["build"]["if"] == "needs.authorize.outputs.approved == 'true'" + for publisher in ("publish-testpypi", "publish-pypi", "github-release"): + assert "github.ref == 'refs/heads/main'" in jobs[publisher]["if"] @pytest.mark.parametrize( - "scenario", ["matched", "wrong_base", "wrong_parent", "fork", "retired", "side_parent"] + "scenario", + [ + "matched", + "current", + "wrong_ref", + "wrong_base", + "wrong_parent", + "missing_merge", + "fork", + "retired", + "side_parent", + ], ) -def test_manual_recovery_verifies_protected_policy_before_checkout( - tmp_path: Path, scenario: str -) -> None: +def test_dispatch_verifies_protected_policy_before_checkout(tmp_path: Path, scenario: str) -> None: job = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"]["authorize"] assert "github.ref == 'refs/heads/main'" in job["if"] trusted_checkout, gate, checkout = job["steps"][:3] - assert trusted_checkout["if"] == "github.event_name == 'workflow_dispatch'" + assert "if" not in trusted_checkout assert trusted_checkout["with"] == { "ref": "${{ github.sha }}", "path": "dispatch-main", "fetch-depth": 0, "persist-credentials": False, } - assert gate["if"] == "github.event_name == 'workflow_dispatch'" + assert "if" not in gate assert checkout["uses"].startswith("actions/checkout@") + assert checkout["with"] == { + "ref": "${{ inputs['reviewed-base'] }}", + "persist-credentials": False, + } history = tmp_path / "dispatch-main" history.mkdir() @@ -376,7 +410,8 @@ def git(*args: str) -> str: merge = git("rev-parse", "HEAD") if scenario in {"retired", "side_parent"}: git("switch", "-qc", "restored-main", base) - git("commit", "--allow-empty", "-qm", "current policy") + if scenario != "current": + git("commit", "--allow-empty", "-qm", "current policy") if scenario == "side_parent": git("merge", "--no-ff", "-qm", "merge old history as a side parent", merge) git("merge-base", "--is-ancestor", merge, "HEAD") @@ -387,6 +422,8 @@ def git(*args: str) -> str: pr["base"]["repo"] = {"full_name": repository} pr["base"]["sha"] = base pr["merge_commit_sha"] = merge + if scenario == "missing_merge": + del pr["merge_commit_sha"] if scenario == "fork": pr["head"]["repo"]["full_name"] = "fork/open-code-review-toolkit" parent = dispatch_sha if scenario == "wrong_parent" else base @@ -401,8 +438,16 @@ def git(*args: str) -> str: "esac\n" "for url do :; done\n" 'case "$url" in\n' - ' "https://api.github.com/repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") cat pr.json ;;\n' - ' "https://api.github.com/repos/$GITHUB_REPOSITORY/git/commits/$MERGE") cat merge.json ;;\n' + ' "https://api.github.com/repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")\n' + ' case " $* " in\n' + ' *" X-GitHub-Api-Version: 2022-11-28 "*) cat pr.json ;;\n' + " *) jq 'del(.merge_commit_sha)' pr.json ;;\n" + " esac ;;\n" + ' "https://api.github.com/repos/$GITHUB_REPOSITORY/git/commits/$MERGE")\n' + ' case " $* " in\n' + ' *" X-GitHub-Api-Version: 2026-03-10 "*) cat merge.json ;;\n' + " *) exit 1 ;;\n" + " esac ;;\n" " *) exit 1 ;;\n" "esac\n" ) @@ -411,6 +456,7 @@ def git(*args: str) -> str: **os.environ, "PATH": f"{tmp_path}{os.pathsep}{os.environ['PATH']}", "GITHUB_REPOSITORY": repository, + "GITHUB_REF": "refs/heads/Main" if scenario == "wrong_ref" else "refs/heads/main", "GITHUB_SHA": dispatch_sha, "GH_TOKEN": "synthetic-token", "PR_NUMBER": "5", @@ -428,17 +474,26 @@ def git(*args: str) -> str: timeout=10, check=False, ) - assert (completed.returncode == 0) is (scenario == "matched"), completed.stderr + assert (completed.returncode == 0) is (scenario in {"matched", "current"}), completed.stderr if scenario in {"retired", "side_parent"}: assert "outside the dispatch main first-parent history" in completed.stderr + elif scenario == "wrong_ref": + assert "release dispatch must run from refs/heads/main" in completed.stderr + elif scenario in {"wrong_base", "fork", "missing_merge"}: + assert "release pull request does not match the requested identities" in completed.stderr + elif scenario == "wrong_parent": + assert "release merge is not a squash of the requested protected base" in completed.stderr def test_release_workflow_keeps_strict_release_authorization() -> None: workflow = WORKFLOW.read_text(encoding="utf-8") assert "python scripts/release_authorization.py" in workflow - assert "github.event.pull_request.base.sha || inputs['reviewed-base']" in workflow assert "Candidate head and merge commits are inspected only as data" in workflow + assert ( + "GITHUB_API_VERSION=2022-11-28 scripts/bounded_github_api.sh \\\n" + ' "repos/${REPOSITORY}/pulls/${PR_NUMBER}" /tmp/release-pr.json' + ) in workflow assert 'test "${RELEASE_BRANCH}" = "release/v${VERSION}"' in workflow assert "repos/${REPOSITORY}/rules/branches/main" in workflow assert "commits/${HEAD_SHA}/check-runs?filter=latest&per_page=100" in workflow @@ -460,7 +515,6 @@ def test_release_workflow_keeps_strict_release_authorization() -> None: assert "--validate-issue-only" in workflow assert 'test "$(git rev-parse HEAD^{tree})" = "${EXPECTED_TREE}"' in workflow assert 'test "$(git rev-parse FETCH_HEAD^{tree})" = "${EXPECTED_TREE}"' in workflow - assert "github.event.pull_request.merged == true" not in workflow def test_bounded_github_helper_rejects_unknown_endpoints_and_writes_atomically( diff --git a/tests/test_release_receipt.py b/tests/test_release_receipt.py index 6352bf9f..95ebe52c 100644 --- a/tests/test_release_receipt.py +++ b/tests/test_release_receipt.py @@ -158,6 +158,68 @@ def test_release_matrix_payload_reads_authorized_checkout_including_historical_b assert json.loads(completed.stdout.removeprefix("python-minors=")) == expected +@pytest.mark.parametrize("reject_sdist", [False, True]) +def test_historical_dispatch_verifies_original_artifacts_before_registry_work( + tmp_path: Path, reject_sdist: bool +) -> None: + import subprocess + + import yaml + + steps = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"]["build"]["steps"] + verify = next( + step + for step in steps + if step.get("name") == "Verify original source attestations before publication" + ) + classify = next(step for step in steps if step.get("id") == "registry") + attest = next( + step + for step in steps + if step.get("uses", "").startswith("actions/attest-build-provenance@") + ) + assert steps.index(verify) < steps.index(classify) + assert verify["if"] == "github.sha != needs.authorize.outputs.commit" + assert verify["env"]["EXPECTED_COMMIT"] == "${{ needs.authorize.outputs.commit }}" + assert attest["if"] == "github.sha == needs.authorize.outputs.commit" + + (tmp_path / "dist").mkdir() + files = ("dist/a.whl", "dist/b.tar.gz", "runtime-requirements.txt") + for path in files: + (tmp_path / path).touch() + gh = tmp_path / "gh" + gh.write_text( + '#!/bin/sh\nprintf "%s\\n" "$*" >> calls\n' + 'test "$REJECT_SDIST" != 1 || test "$3" != dist/b.tar.gz\n', + encoding="utf-8", + ) + gh.chmod(0o700) + repository = "example/open-code-review-toolkit" + merge = "c" * 40 + environment = { + **os.environ, + "PATH": f"{tmp_path}{os.pathsep}{os.environ['PATH']}", + "LC_ALL": "C", + "GITHUB_REPOSITORY": repository, + "EXPECTED_COMMIT": merge, + "REJECT_SDIST": str(int(reject_sdist)), + } + completed = subprocess.run( + ["bash", "-e", "-o", "pipefail", "-c", verify["run"]], + cwd=tmp_path, + env=environment, + timeout=10, + check=False, + ) + assert (completed.returncode != 0) is reject_sdist + assert (tmp_path / "calls").read_text(encoding="utf-8").splitlines() == [ + f"attestation verify {path} --repo {repository} " + f"--signer-workflow {repository}/.github/workflows/release.yml " + f"--source-digest {merge} --source-ref refs/heads/main --deny-self-hosted-runners" + for path in (files[:2] if reject_sdist else files) + ] + + def test_existing_receipt_recovery_ignores_new_run_but_rejects_delivery_drift() -> None: payload = build_receipt(run_id=555, run_attempt=3) receipt.validate_receipt( From e358067b695c7f1d63d667f8f1c7a759bff48593 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:03:22 +0100 Subject: [PATCH 3/3] Avoid duplicate advisory macOS jobs on protected promotions --- .github/workflows/ci.yml | 45 ++++++++++++++----- changelog.d/364.maintenance.md | 1 + docs/development.md | 22 ++++++---- tests/test_docs_only_ci.py | 79 +++++++++++++++++++++++++++++++++- tests/test_quality_script.py | 13 ++++-- tests/test_testpypi_preview.py | 40 ++++++++++------- 6 files changed, 161 insertions(+), 39 deletions(-) create mode 100644 changelog.d/364.maintenance.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bc5d6ab2..b23de81f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,7 @@ jobs: timeout-minutes: 5 outputs: docs_only: ${{ steps.paths.outputs.docs_only }} + skip_macos: ${{ steps.paths.outputs.skip_macos }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -30,17 +31,36 @@ jobs: env: BASE: ${{ github.event.pull_request.base.sha }} HEAD: ${{ github.event.pull_request.head.sha }} + BASE_REF: ${{ github.event.pull_request.base.ref }} + HEAD_REF: ${{ github.event.pull_request.head.ref }} + HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }} run: | result=docs_only=false + skip_macos=false trusted_script="$RUNNER_TEMP/docs_only.py" if git show "${BASE}:scripts/docs_only.py" > "$trusted_script"; then if output=$(env -u GITHUB_OUTPUT python "$trusted_script" --base "$BASE" --head "$HEAD"); then case "$output" in - docs_only=true|docs_only=false) result="$output" ;; + docs_only=true|docs_only=false) + result="$output" + if [ -n "$HEAD_REPO" ] && [ "$HEAD_REPO" = "$GITHUB_REPOSITORY" ]; then + if [ "$result" = docs_only=true ]; then + skip_macos=true + elif [ "$BASE_REF" = main ] && [ "$HEAD_REF" = dev ]; then + # Only exit 1 proves a nonempty delta for this direct promotion. + if git --no-replace-objects diff --quiet --no-ext-diff --no-textconv "$BASE" "$HEAD" --; then + : + elif [ "$?" -eq 1 ]; then + skip_macos=true + fi + fi + fi + ;; esac fi fi echo "$result" >> "$GITHUB_OUTPUT" + echo "skip_macos=$skip_macos" >> "$GITHUB_OUTPUT" test-python312: name: >- @@ -82,18 +102,21 @@ jobs: ${{ github.event_name != 'pull_request' && format('manual-test-{0}-py{1}', matrix.os, matrix.python) || github.event.pull_request.draft && 'draft-deferred-test-matrix' || format('test-{0}-py{1}', matrix.os, matrix.python) }} if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }} - continue-on-error: ${{ matrix.advisory }} + continue-on-error: ${{ matrix.os == 'macos-latest' }} env: UV_PYTHON: ${{ matrix.python }} strategy: fail-fast: false matrix: - include: - - { os: ubuntu-latest, python: "3.13", coverage: false, advisory: false } - - { os: ubuntu-latest, python: "3.14", coverage: true, advisory: false } - - { os: ubuntu-latest, python: "3.15", coverage: false, advisory: false } - - { os: macos-latest, python: "3.12", coverage: false, advisory: true } - - { os: macos-latest, python: "3.14", coverage: false, advisory: true } + os: >- + ${{ fromJSON(github.event_name == 'pull_request' && needs.classify.result == 'success' && + needs.classify.outputs.skip_macos == 'true' && '["ubuntu-latest"]' || + '["ubuntu-latest","macos-latest"]') }} + python: ["3.12", "3.13", "3.14", "3.15"] + exclude: + - { os: ubuntu-latest, python: "3.12" } + - { os: macos-latest, python: "3.13" } + - { os: macos-latest, python: "3.15" } runs-on: ${{ matrix.os }} timeout-minutes: 30 steps: @@ -104,7 +127,7 @@ jobs: persist-credentials: false - name: Install qualified OCR for native coverage id: native-ocr - if: ${{ needs.classify.outputs.docs_only != 'true' && matrix.coverage }} + if: ${{ needs.classify.outputs.docs_only != 'true' && matrix.os == 'ubuntu-latest' && matrix.python == '3.14' }} env: PR_BASE: ${{ github.event.pull_request.base.sha }} shell: bash @@ -173,10 +196,10 @@ jobs: - if: needs.classify.outputs.docs_only != 'true' run: uv sync --locked --python "${{ matrix.python }}" - name: Test - if: ${{ needs.classify.outputs.docs_only != 'true' && !matrix.coverage }} + if: ${{ needs.classify.outputs.docs_only != 'true' && (matrix.os != 'ubuntu-latest' || matrix.python != '3.14') }} run: uv run --no-sync pytest -q --ignore=tests/test_installed_policy_e2e.py - name: Test with boundary coverage gates - if: ${{ needs.classify.outputs.docs_only != 'true' && matrix.coverage }} + if: ${{ needs.classify.outputs.docs_only != 'true' && matrix.os == 'ubuntu-latest' && matrix.python == '3.14' }} env: OCR_FEDERATION_QUALIFY_BINARY: ${{ steps.native-ocr.outputs.binary }} OCR_GITLINK_QUALIFY_BINARY: ${{ steps.native-ocr.outputs.binary }} diff --git a/changelog.d/364.maintenance.md b/changelog.d/364.maintenance.md new file mode 100644 index 00000000..2e220ac5 --- /dev/null +++ b/changelog.d/364.maintenance.md @@ -0,0 +1 @@ +Start stable publication on protected main and verify historical rebuilds against the original source attestations before registry upload. Group scheduled minor and patch runtime dependency updates on dev. Skip advisory macOS jobs on internal documentation-only PRs and direct dev-to-main promotions. diff --git a/docs/development.md b/docs/development.md index 96e33f7a..db082db4 100644 --- a/docs/development.md +++ b/docs/development.md @@ -30,16 +30,22 @@ A high combined result cannot hide a weak group. Individual DLP/audit, source syntax, shared credential material/completion, diagram-source metadata and orientation owners have 90% floors in the local and hosted coverage gates. Structural evidence sizing, bounded store serialization and optional target admission each have an independent 90% floor. -Ready hosted pull requests run source and contract -tests on all six supported OS/Python combinations. The expensive +Ready product pull requests and manual CI runs cover all six supported +OS/Python combinations. The expensive clean-install wheel/sdist behavioral test runs once in the required Ubuntu/Python 3.12 job; the separate required build job smoke-tests both distribution paths. -The five matrix jobs start alongside Python 3.12 rather than waiting for it. -Each of the four Linux jobs can fail the CI workflow, with Ubuntu on Python -3.14 as the sole coverage owner. Effective branch rules determine which -individual checks GitHub requires before merge. The two macOS endpoint jobs are best-effort compatibility -diagnostics: they remain visible for follow-up, but a platform-only failure does -not block a Linux-priority release. Bandit scans only the supported runtime package +The matrix starts alongside Ubuntu/Python 3.12. All four Linux check identities +remain available to the branch rules, with Ubuntu/Python 3.14 as the sole +coverage owner. CI omits the two advisory macOS jobs for positively classified +same-repository documentation-only pull requests and direct promotions from +`dev` to `main`. Direct promotions still run the Linux tests and coverage. +Manual runs, release-preparation pull requests, fork pull requests and uncertain +classifications retain the full matrix. Once required checks pass for the verified head and base, +an advisory job waiting for a runner can finish independently. Use a manual CI +run to check macOS on a deferred change. +Inspect any reported product regression before promotion. Report runner capacity +separately from test failures and retry only the affected job when appropriate. +Bandit scans only the supported runtime package at medium-or-higher severity and confidence; tests and synthetic fixtures are outside that bounded gate. diff --git a/tests/test_docs_only_ci.py b/tests/test_docs_only_ci.py index 4ed733c0..01adc792 100644 --- a/tests/test_docs_only_ci.py +++ b/tests/test_docs_only_ci.py @@ -588,8 +588,85 @@ def test_pr_cannot_replace_trusted_classifier(tmp_path: Path) -> None: **os.environ, "BASE": base, "HEAD": _git(tmp_path, "rev-parse", "HEAD"), + "BASE_REF": "dev", + "HEAD_REF": "topic", + "HEAD_REPO": "owner/toolkit", + "GITHUB_REPOSITORY": "owner/toolkit", "RUNNER_TEMP": str(tmp_path), "GITHUB_OUTPUT": str(output), } subprocess.run(["bash", "-e", "-c", classifier], cwd=tmp_path, env=environment, check=True) - assert output.read_text() == "docs_only=false\n" + assert output.read_text() == "docs_only=false\nskip_macos=false\n" + + +@pytest.mark.parametrize( + ("path", "target", "source", "same_repo", "uncertainty", "docs", "skipped"), + [ + ("README.md", "dev", "topic", True, "", True, True), + ("README.md", "dev", "topic", False, "", True, False), + ("runtime.py", "dev", "topic", True, "", False, False), + ("runtime.py", "main", "dev", True, "", False, True), + ("runtime.py", "main", "dev", False, "", False, False), + ("runtime.py", "dev", "dev", True, "", False, False), + (".release-version", "main", "release/v1.2.3", True, "", False, False), + ("runtime.py", "main", "dev", True, "missing-script", False, False), + ("runtime.py", "main", "dev", True, "script-exit", False, False), + ("runtime.py", "main", "dev", True, "unknown-output", False, False), + ("runtime.py", "main", "dev", True, "missing-head", False, False), + ("runtime.py", "main", "dev", True, "empty-delta", False, False), + ], +) +def test_advisory_runner_skip_requires_positive_same_repository_evidence( + tmp_path: Path, + path: str, + target: str, + source: str, + same_repo: bool, + uncertainty: str, + docs: bool, + skipped: bool, +) -> None: + _git(tmp_path, "init", "-q") + _git(tmp_path, "config", "user.email", "test@example.invalid") + _git(tmp_path, "config", "user.name", "Test") + script = tmp_path / "scripts" / "docs_only.py" + script.parent.mkdir() + if uncertainty != "missing-script": + code = { + "script-exit": "raise SystemExit(2)\n", + "unknown-output": 'print("docs_only=false\\nskip_macos=true")\n', + }.get(uncertainty, SCRIPT.read_text()) + script.write_text(code) + _git(tmp_path, "add", ".") + _git(tmp_path, "commit", "--allow-empty", "-qm", "base") + base = _git(tmp_path, "rev-parse", "HEAD") + if uncertainty != "empty-delta": + (tmp_path / path).write_text("changed\n") + _git(tmp_path, "add", path) + _git(tmp_path, "commit", "--allow-empty", "-qm", "head") + head = "0" * 40 if uncertainty == "missing-head" else _git(tmp_path, "rev-parse", "HEAD") + workflow = yaml.safe_load((ROOT / ".github/workflows/ci.yml").read_text()) + classifier = workflow["jobs"]["classify"]["steps"][-1] + output = tmp_path / "github-output" + subprocess.run( + ["bash", "-e", "-c", classifier["run"]], + cwd=tmp_path, + env={ + **os.environ, + "BASE": base, + "HEAD": head, + "BASE_REF": target, + "HEAD_REF": source, + "HEAD_REPO": "owner/toolkit" if same_repo else "contributor/toolkit", + "GITHUB_REPOSITORY": "owner/toolkit", + "RUNNER_TEMP": str(tmp_path), + "GITHUB_OUTPUT": str(output), + }, + capture_output=True, + check=True, + timeout=15, + ) + assert output.read_text().splitlines() == [ + f"docs_only={str(docs).lower()}", + f"skip_macos={str(skipped).lower()}", + ] diff --git a/tests/test_quality_script.py b/tests/test_quality_script.py index 5ab11996..affb4ac4 100644 --- a/tests/test_quality_script.py +++ b/tests/test_quality_script.py @@ -47,9 +47,6 @@ def test_quality_script_enforces_combined_and_boundary_coverage(tmp_path: Path) "uv run --no-sync pytest --ignore=tests/test_installed_policy_e2e.py --cov=ocr_toolkit --cov-report=term-missing --cov-fail-under=88" in workflow ) - assert workflow.count("coverage: true") == 1 - assert "if: ${{ needs.classify.outputs.docs_only != 'true' && matrix.coverage }}" in workflow - assert "if: ${{ needs.classify.outputs.docs_only != 'true' && !matrix.coverage }}" in workflow assert ( "for audit_module in cli corpus scanner state limits worker_process report proof; do" in script @@ -101,6 +98,16 @@ def declared_modules(text: str) -> list[str]: steps = yaml.safe_load(workflow)["jobs"]["test-matrix"]["steps"] coverage_steps = [s for s in steps if s.get("name") == "Test with boundary coverage gates"] assert len(coverage_steps) == 1 + coverage_if = ( + "${{ needs.classify.outputs.docs_only != 'true' && " + "matrix.os == 'ubuntu-latest' && matrix.python == '3.14' }}" + ) + assert coverage_steps[0]["if"] == coverage_if + assert next(step["if"] for step in steps if step.get("id") == "native-ocr") == coverage_if + assert next(step["if"] for step in steps if step.get("name") == "Test") == ( + "${{ needs.classify.outputs.docs_only != 'true' && " + "(matrix.os != 'ubuntu-latest' || matrix.python != '3.14') }}" + ) hosted = subprocess.run( ["sh", "-eu", "-c", coverage_steps[0]["run"]], cwd=PROJECT_ROOT, diff --git a/tests/test_testpypi_preview.py b/tests/test_testpypi_preview.py index 44e39623..5980e852 100644 --- a/tests/test_testpypi_preview.py +++ b/tests/test_testpypi_preview.py @@ -3,11 +3,15 @@ from __future__ import annotations import importlib.util +import json +import re +from itertools import product from pathlib import Path from types import ModuleType from typing import Any import pytest +import yaml SCRIPT = Path(__file__).parents[1] / "scripts" / "testpypi_preview.py" PROJECT_ROOT = SCRIPT.parents[1] @@ -297,7 +301,8 @@ def test_production_release_verifies_reviewed_registry_artifacts() -> None: assert "release_id=$(jq -r .id" in workflow assert "release_is_draft=$(jq -r .draft" in workflow assert "invalid GitHub Release numeric identity" in workflow - assert workflow.count("timeout-minutes:") == 8 + jobs = yaml.safe_load(workflow)["jobs"] + assert all(0 < job["timeout-minutes"] <= 30 for job in jobs.values()) assert workflow.count("--max-filesize 10485760") >= 1 assert "--retry 3 --retry-delay 2 --retry-connrefused" in verifier assert "--connect-timeout 10 --max-time 120" in verifier @@ -345,31 +350,34 @@ def test_distribution_build_is_a_bounded_pull_request_gate() -> None: def test_ci_matrix_covers_supported_python_minors_and_os_boundaries() -> None: - """Keep Linux blocking and macOS visible but advisory at both endpoints.""" + """Keep all Linux identities and both advisory macOS endpoints in full runs.""" workflow = (PROJECT_ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") + jobs = yaml.safe_load(workflow)["jobs"] + job = jobs["test-matrix"] + matrix = job["strategy"]["matrix"] assert " push:" not in workflow - assert "continue-on-error: ${{ matrix.advisory }}" in workflow - assert "test-python312:" in workflow - assert "|| 'test-ubuntu-latest-py3.12' }}" in workflow - assert " test-matrix:\n needs: classify" in workflow + assert job["continue-on-error"] == "${{ matrix.os == 'macos-latest' }}" + assert jobs["test-python312"]["name"].endswith("|| 'test-ubuntu-latest-py3.12' }}") + assert job["name"].endswith("|| format('test-{0}-py{1}', matrix.os, matrix.python) }}") + assert job["needs"] == "classify" assert workflow.count("--ignore=tests/test_installed_policy_e2e.py") == 2 assert "run: uv run --no-sync pytest -q\n" in workflow assert 'UV_PYTHON: "3.12"' in workflow assert "UV_PYTHON: ${{ matrix.python }}" in workflow assert "uv sync --locked --python 3.12" in workflow assert 'uv sync --locked --python "${{ matrix.python }}"' in workflow - assert workflow.count("advisory: false") == 3 - assert workflow.count("advisory: true") == 2 - assert workflow.count("os: ubuntu-latest") == 3 - assert workflow.count("os: macos-latest") == 2 - assert workflow.count('python: "3.12"') == 1 - assert workflow.count('python: "3.13"') == 1 - assert workflow.count('python: "3.14"') == 2 - assert workflow.count('python: "3.15"') == 1 - for unsupported in ("3.10", "3.11"): - assert f'python: "{unsupported}"' not in workflow + assert ( + "github.event_name == 'pull_request' && needs.classify.result == 'success' && " + "needs.classify.outputs.skip_macos == 'true' &&" + ) in matrix["os"] + selected, fallback = (json.loads(value) for value in re.findall(r"'(\[[^']*\])'", matrix["os"])) + excluded = {(row["os"], row["python"]) for row in matrix["exclude"]} + required = {("ubuntu-latest", version) for version in ("3.13", "3.14", "3.15")} + advisory = {("macos-latest", version) for version in ("3.12", "3.14")} + assert set(product(selected, matrix["python"])) - excluded == required + assert set(product(fallback, matrix["python"])) - excluded == required | advisory def test_required_dependency_review_runs_for_every_pull_request() -> None: