diff --git a/.github/workflows/certify-uk-release.yaml b/.github/workflows/certify-uk-release.yaml deleted file mode 100644 index 2d126b53c..000000000 --- a/.github/workflows/certify-uk-release.yaml +++ /dev/null @@ -1,584 +0,0 @@ -# UK candidate qualification starts via workflow_dispatch and resolves legacy -# uk-data pairs. Scheduled recovery and requalification are disabled. -# -# A candidate pair (newest model wheel, the core it needs, newest data -# release) is resolved and deduplicated against the ledger, certified into a -# candidate commit on candidate/uk/- (manifest, pins, uv.lock, -# TRO, test constants and snapshots regenerated together), qualified by the -# mandatory gates on that exact commit, replayed by policyengine-scorecard, -# and recorded in the uk-qualification-ledger branch. Promotion runs -# serially. It readies the newest promotable candidate PR that advances -# main, closes superseded ones and those of pairs from another data line -# (which are never promoted), and (cos d1344) fast-forwards main to its -# qualified commit once every check on it has passed, which succeeds only -# while main is still the commit it was built on. -# -# A manual run with accept_pair_id records a reviewer's acceptance of a -# needs-review receipt. - -name: Certify UK release candidates - -on: - workflow_dispatch: - inputs: - model_version: - description: policyengine-uk version (default newest on PyPI) - required: false - data_version: - description: uk-data release (default newest) - required: false - core_version: - description: policyengine-core version (default the certified one if the model accepts it) - required: false - pair_id: - description: The exact pair to qualify; the run fails if the versions resolve to another - required: false - force: - description: Qualify even if the ledger already has a terminal receipt - type: boolean - default: false - accept_pair_id: - description: Accept the needs-review receipt of this pair (reviewer = you) - required: false - accept_receipt_sha256: - description: unreviewed_sha256 of the exact receipt being accepted - required: false - accept_explanation: - description: Why the flagged moves are expected - required: false - -permissions: - contents: write - pull-requests: write - -env: - LEDGER_BRANCH: uk-qualification-ledger - UV_VERSION: "0.13.4" - PYTHON_VERSION: "3.13" - # Keep equal to PYTHON_VERSION. The repository's .python-version asks for a - # newer Python, and every uv command here must use the 3.13 environment the - # job installed. For the same reason each `uv run` passes --no-sync: the - # environment is synchronized explicitly (with the uk and dev extras), and - # a step must run exactly that environment. - UV_PYTHON: "3.13" - # Run by .github/qualification-ledger.sh, inside the ledger worktree, when a - # concurrent publish touched a pair's published files: recompute them from - # the attempts rather than let git merge two receipts. This default uses - # the system Python that `uv pip install --system` provisions; jobs that - # `uv sync` override it with the synchronized environment's interpreter. - LEDGER_REDERIVE: >- - python ${{ github.workspace }}/scripts/check_uk_candidate.py rederive-ledger - -jobs: - resolve: - if: github.event_name != 'workflow_dispatch' || inputs.accept_pair_id == '' - runs-on: ubuntu-latest - timeout-minutes: 20 - permissions: - contents: read - actions: read - outputs: - action: ${{ steps.resolve.outputs.action }} - pair_id: ${{ steps.resolve.outputs.pair_id }} - branch: ${{ steps.resolve.outputs.branch }} - base_commit: ${{ steps.resolve.outputs.base_commit }} - attempt_key: ${{ steps.resolve.outputs.attempt_key }} - steps: - - uses: actions/checkout@v6 - with: - ref: main - fetch-depth: 0 - - uses: astral-sh/setup-uv@v8.1.0 - with: - version: ${{ env.UV_VERSION }} - - uses: actions/setup-python@v6 - with: - python-version: ${{ env.PYTHON_VERSION }} - - name: Install policyengine without country models - run: uv pip install --system -e . - - name: Check out the ledger - run: .github/qualification-ledger.sh checkout ledger - - name: Resolve and deduplicate the candidate - id: resolve - env: - GH_TOKEN: ${{ github.token }} - HUGGING_FACE_TOKEN: ${{ secrets.HUGGING_FACE_TOKEN }} - EVENT_NAME: ${{ github.event_name }} - EVENT_TYPE: ${{ github.event.action }} - PAYLOAD_VERSION: ${{ github.event.client_payload.version }} - INPUT_MODEL: ${{ inputs.model_version }} - INPUT_DATA: ${{ inputs.data_version }} - INPUT_CORE: ${{ inputs.core_version }} - INPUT_PAIR_ID: ${{ inputs.pair_id }} - INPUT_FORCE: ${{ inputs.force }} - run: | - model="${INPUT_MODEL:-}" - data="${INPUT_DATA:-}" - if [[ "$EVENT_NAME" == "repository_dispatch" && "$EVENT_TYPE" == "policyengine-uk-release" ]]; then - model="$PAYLOAD_VERSION" - elif [[ "$EVENT_NAME" == "repository_dispatch" && "$EVENT_TYPE" == "policyengine-uk-data-release" ]]; then - data="$PAYLOAD_VERSION" - fi - args=(resolve --out candidate.json --ledger ledger) - [[ -n "$model" ]] && args+=(--model-version "$model") - [[ -n "$data" ]] && args+=(--data-version "$data") - [[ -n "${INPUT_CORE:-}" ]] && args+=(--core-version "$INPUT_CORE") - [[ -n "${INPUT_PAIR_ID:-}" ]] && args+=(--pair-id "$INPUT_PAIR_ID") - [[ "${INPUT_FORCE:-false}" == "true" ]] && args+=(--force) - python scripts/check_uk_candidate.py "${args[@]}" - - uses: actions/upload-artifact@v4 - with: - name: candidate - path: candidate.json - - prepare: - needs: resolve - if: needs.resolve.outputs.action == 'qualify' - runs-on: ubuntu-latest - timeout-minutes: 60 - concurrency: - # Head replacement and readiness must hold the same lock. Otherwise - # promotion can ready a replacement after checking the previous head. - group: promote-uk - cancel-in-progress: false - permissions: - contents: write - pull-requests: write - actions: write - outputs: - candidate_commit: ${{ steps.stage.outputs.candidate_commit }} - duplicate: ${{ steps.duplicate.outputs.duplicate }} - env: - LEDGER_REDERIVE: >- - ${{ github.workspace }}/.venv/bin/python - ${{ github.workspace }}/scripts/check_uk_candidate.py rederive-ledger - steps: - - name: Generate GitHub App token - id: app-token - uses: actions/create-github-app-token@v1 - with: - app-id: ${{ secrets.APP_ID }} - private-key: ${{ secrets.APP_PRIVATE_KEY }} - - uses: actions/checkout@v6 - with: - ref: ${{ needs.resolve.outputs.base_commit }} - token: ${{ steps.app-token.outputs.token }} - fetch-depth: 0 - - uses: actions/download-artifact@v4 - with: - name: candidate - path: ${{ runner.temp }}/candidate - - uses: astral-sh/setup-uv@v8.1.0 - with: - version: ${{ env.UV_VERSION }} - - uses: actions/setup-python@v6 - with: - python-version: ${{ env.PYTHON_VERSION }} - - name: Install the base environment - run: uv sync --frozen --extra uk --extra dev --python ${{ env.PYTHON_VERSION }} - # Another run may have staged this attempt, or another attempt for the - # pair from another main commit, while this one waited for the - # promotion concurrency group: recheck against the ledger as it is now, - # and never overwrite another run's evidence. - - name: Check for an attempt staged by another run - id: duplicate - env: - ATTEMPT: ledger/uk/${{ needs.resolve.outputs.pair_id }}/attempts/${{ needs.resolve.outputs.attempt_key }} - # still-eligible asks gh whether an earlier attempt's run failed; - # without a token every unexpired failed run would read as live. - GH_TOKEN: ${{ github.token }} - run: | - .github/qualification-ledger.sh checkout ledger - if [[ -d "$ATTEMPT" ]]; then - echo "duplicate=true" >> "$GITHUB_OUTPUT" - echo "Attempt already staged by another run; nothing to do." - else - uv run --no-sync python scripts/check_uk_candidate.py still-eligible \ - --candidate "$RUNNER_TEMP/candidate/candidate.json" --ledger ledger - fi - git worktree remove --force ledger - - name: Certify the pair and regenerate pins, lock, TROs and constants - if: steps.duplicate.outputs.duplicate == 'false' - env: - HUGGING_FACE_TOKEN: ${{ secrets.HUGGING_FACE_TOKEN }} - BRANCH: ${{ needs.resolve.outputs.branch }} - run: | - git switch -C "$BRANCH" - uv run --no-sync python scripts/check_uk_candidate.py prepare \ - --candidate "$RUNNER_TEMP/candidate/candidate.json" \ - --out "$RUNNER_TEMP/prepared.json" --skip-snapshots - - name: Install the candidate environment from the regenerated lock - if: steps.duplicate.outputs.duplicate == 'false' - run: uv sync --frozen --extra uk --extra dev --python ${{ env.PYTHON_VERSION }} - - name: Refresh household snapshots on the candidate pair - if: steps.duplicate.outputs.duplicate == 'false' - env: - HUGGING_FACE_TOKEN: ${{ secrets.HUGGING_FACE_TOKEN }} - PE_UPDATE_SNAPSHOTS: "1" - run: uv run --no-sync pytest tests/test_household_calculator_snapshot.py -q - - name: Check the regenerated bundle - if: steps.duplicate.outputs.duplicate == 'false' - env: - HUGGING_FACE_TOKEN: ${{ secrets.HUGGING_FACE_TOKEN }} - run: uv run --no-sync python scripts/bundle.py check --include-tros --strict-tros - - name: Commit and push the candidate commit - if: steps.duplicate.outputs.duplicate == 'false' - env: - GH_TOKEN: ${{ steps.app-token.outputs.token }} - BRANCH: ${{ needs.resolve.outputs.branch }} - PAIR_ID: ${{ needs.resolve.outputs.pair_id }} - run: | - # A forced attempt may replace an already qualified head. Revoke - # its ready status before exposing any new, unqualified commit. - # Only this repository's pull request to main is the candidate's: - # head=: lists only this repository's, so a fork's - # with the same branch name can neither shadow nor crowd it out. - ready_pr=$(gh api -X GET "repos/$GITHUB_REPOSITORY/pulls" \ - -f head="${GITHUB_REPOSITORY%%/*}:$BRANCH" -f base=main -f state=open \ - --paginate --jq '.[] | select(.draft == false) | .number') - if [[ -n "$ready_pr" ]]; then - gh pr ready "$ready_pr" --undo - fi - git add -A - git -c user.name="policyengine-qualification[bot]" \ - -c user.email="qualification@policyengine.org" \ - commit -q -m "Certify UK candidate pair ${PAIR_ID:0:12} for qualification" - git push --force origin "HEAD:refs/heads/$BRANCH" - # Pull request runs test the candidate merged with main as it was then. - # Promotion needs the commit's own tree tested, so run the code-changes - # workflow on the candidate branch itself. - - name: Test the candidate commit's own tree - if: steps.duplicate.outputs.duplicate == 'false' - env: - GH_TOKEN: ${{ github.token }} - BRANCH: ${{ needs.resolve.outputs.branch }} - run: gh workflow run pr_code_changes.yaml --repo "$GITHUB_REPOSITORY" --ref "$BRANCH" - - name: Stage the attempt in the ledger - id: stage - if: steps.duplicate.outputs.duplicate == 'false' - run: | - .github/qualification-ledger.sh checkout ledger - uv run --no-sync python scripts/check_uk_candidate.py stage \ - --candidate "$RUNNER_TEMP/candidate/candidate.json" --ledger ledger - .github/qualification-ledger.sh publish ledger \ - "Stage UK candidate ${{ needs.resolve.outputs.pair_id }} attempt ${{ needs.resolve.outputs.attempt_key }}" - - name: Open or update the draft candidate PR - if: steps.duplicate.outputs.duplicate == 'false' - env: - GH_TOKEN: ${{ steps.app-token.outputs.token }} - BRANCH: ${{ needs.resolve.outputs.branch }} - PAIR_ID: ${{ needs.resolve.outputs.pair_id }} - run: | - title="Certify UK candidate ${BRANCH#candidate/uk/}" - body="Automated certification candidate for pair \`$PAIR_ID\`. Qualification is running: https://github.com/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID} - - Ledger: https://github.com/${GITHUB_REPOSITORY}/tree/${LEDGER_BRANCH}/uk/${PAIR_ID} - - 🤖 Generated with [Claude Code](https://claude.com/claude-code)" - # By number: gh looks a branch name up among pull requests a fork's - # can shadow. head=: lists only this repository's. - number=$(gh api -X GET "repos/$GITHUB_REPOSITORY/pulls" \ - -f head="${GITHUB_REPOSITORY%%/*}:$BRANCH" -f base=main -f state=open \ - --paginate --jq '.[].number') - if [[ -n "$number" ]]; then - gh pr edit "$number" --body "$body" - else - gh pr create --draft --base main --head "$BRANCH" --title "$title" --body "$body" - fi - - qualify: - needs: [resolve, prepare] - if: needs.prepare.outputs.duplicate == 'false' - runs-on: ${{ vars.CERTIFY_RUNNER_X64 != '' && (vars.CI_RUNNER_EVENTS == '' || contains(format(',{0},', vars.CI_RUNNER_EVENTS), format(',{0},', github.event_name))) && vars.CERTIFY_RUNNER_X64 || 'ubuntu-latest' }} - # The local gates took 80-89 minutes while every wrapper.household - # contract row errored at once. Since #651 those rows run the household - # calculator, which takes the gates past two hours, so a 120-minute limit - # cancelled every attempt. 330 stays under the 360-minute ceiling for - # GitHub-hosted jobs. - timeout-minutes: 330 - concurrency: - group: uk-candidate-${{ needs.resolve.outputs.pair_id }} - cancel-in-progress: false - env: - LEDGER_REDERIVE: >- - ${{ github.workspace }}/.venv/bin/python - ${{ github.workspace }}/scripts/check_uk_candidate.py rederive-ledger - steps: - - uses: actions/checkout@v6 - with: - ref: ${{ needs.prepare.outputs.candidate_commit }} - fetch-depth: 0 - - uses: astral-sh/setup-uv@v8.1.0 - with: - version: ${{ env.UV_VERSION }} - - uses: actions/setup-python@v6 - with: - python-version: ${{ env.PYTHON_VERSION }} - - name: Install the candidate environment - run: uv sync --frozen --extra uk --extra dev --python ${{ env.PYTHON_VERSION }} - - name: Check out the ledger - run: .github/qualification-ledger.sh checkout ledger - - name: Run the mandatory local gates - env: - HUGGING_FACE_TOKEN: ${{ secrets.HUGGING_FACE_TOKEN }} - ATTEMPT: ledger/uk/${{ needs.resolve.outputs.pair_id }}/attempts/${{ needs.resolve.outputs.attempt_key }} - run: uv run --no-sync python scripts/check_uk_candidate.py gates --attempt "$ATTEMPT" --work-dir "$RUNNER_TEMP/qualification" - - name: Generate a GitHub App token for the scorecard - id: scorecard-token - continue-on-error: true - uses: actions/create-github-app-token@v1 - with: - app-id: ${{ secrets.APP_ID }} - private-key: ${{ secrets.APP_PRIVATE_KEY }} - owner: PolicyEngine - repositories: policyengine-scorecard - - name: Send the pre-promotion replay request - if: steps.scorecard-token.outcome == 'success' - continue-on-error: true - env: - GH_TOKEN: ${{ steps.scorecard-token.outputs.token }} - ATTEMPT: ledger/uk/${{ needs.resolve.outputs.pair_id }}/attempts/${{ needs.resolve.outputs.attempt_key }} - run: uv run --no-sync python scripts/check_uk_candidate.py request-replay --attempt "$ATTEMPT" --dispatch - - name: Publish the gate evidence - if: always() - run: | - .github/qualification-ledger.sh publish ledger \ - "Gates for UK candidate ${{ needs.resolve.outputs.pair_id }} attempt ${{ needs.resolve.outputs.attempt_key }}" - - replay: - needs: [resolve, prepare, qualify] - if: always() && needs.prepare.result == 'success' && needs.prepare.outputs.duplicate == 'false' - runs-on: ${{ vars.CERTIFY_RUNNER_X64 != '' && (vars.CI_RUNNER_EVENTS == '' || contains(format(',{0},', vars.CI_RUNNER_EVENTS), format(',{0},', github.event_name))) && vars.CERTIFY_RUNNER_X64 || 'ubuntu-latest' }} - timeout-minutes: 355 - permissions: - contents: write - pull-requests: write - actions: write - steps: - - uses: actions/checkout@v6 - with: - ref: main - fetch-depth: 0 - - uses: astral-sh/setup-uv@v8.1.0 - with: - version: ${{ env.UV_VERSION }} - - uses: actions/setup-python@v6 - with: - python-version: ${{ env.PYTHON_VERSION }} - - name: Install policyengine without country models - run: uv pip install --system -e . - - name: Check out the ledger - run: .github/qualification-ledger.sh checkout ledger - - name: Wait for the replay receipt - env: - GH_TOKEN: ${{ github.token }} - ATTEMPT: ledger/uk/${{ needs.resolve.outputs.pair_id }}/attempts/${{ needs.resolve.outputs.attempt_key }} - run: | - if [[ -f "$ATTEMPT/replay/request.json" ]]; then - python scripts/check_uk_candidate.py poll-replay --attempt "$ATTEMPT" --wait-minutes 340 - else - echo "No replay request was sent; the replay gate stays unavailable." - fi - - name: Finalize and publish the qualification receipt - id: finalize - env: - ATTEMPT: ledger/uk/${{ needs.resolve.outputs.pair_id }}/attempts/${{ needs.resolve.outputs.attempt_key }} - run: | - python scripts/check_uk_candidate.py finalize --attempt "$ATTEMPT" --ledger ledger --pr-body "$RUNNER_TEMP/pr-body.md" - .github/qualification-ledger.sh publish ledger \ - "Qualification receipt for UK candidate ${{ needs.resolve.outputs.pair_id }}" - - name: Refresh failed candidate PR checks against the published receipt - env: - GH_TOKEN: ${{ github.token }} - run: python scripts/check_uk_candidate.py refresh-pr-checks --ledger ledger - - name: Generate GitHub App token - id: app-token - uses: actions/create-github-app-token@v1 - with: - app-id: ${{ secrets.APP_ID }} - private-key: ${{ secrets.APP_PRIVATE_KEY }} - - name: Update the candidate PR with the verdict - env: - GH_TOKEN: ${{ steps.app-token.outputs.token }} - BRANCH: ${{ needs.resolve.outputs.branch }} - run: | - number=$(gh api -X GET "repos/$GITHUB_REPOSITORY/pulls" \ - -f head="${GITHUB_REPOSITORY%%/*}:$BRANCH" -f base=main -f state=open \ - --paginate --jq '.[].number') - if [[ -z "$number" ]]; then - echo "::error::no open pull request from $BRANCH to main" - exit 1 - fi - gh pr edit "$number" --body-file "$RUNNER_TEMP/pr-body.md" - - # Intentionally dormant while workflow_dispatch is the only trigger. - # Its two self-dispatches cannot run without a schedule. - catch-up: - if: github.event_name == 'schedule' - runs-on: ubuntu-latest - timeout-minutes: 30 - permissions: - contents: write - pull-requests: write - actions: write - steps: - - uses: actions/checkout@v6 - with: - ref: main - fetch-depth: 0 - - uses: astral-sh/setup-uv@v8.1.0 - with: - version: ${{ env.UV_VERSION }} - - uses: actions/setup-python@v6 - with: - python-version: ${{ env.PYTHON_VERSION }} - - name: Install policyengine without country models - run: uv pip install --system -e . - - name: Restart abandoned attempts without replay requests - env: - GH_TOKEN: ${{ github.token }} - run: | - .github/qualification-ledger.sh checkout ledger - python scripts/check_uk_candidate.py recoverable --ledger ledger > recoverable.jsonl - python - <<'PY' - import json - import os - import subprocess - from pathlib import Path - - for line in Path("recoverable.jsonl").read_text().splitlines(): - entry = json.loads(line) - pair, pair_id = entry["pair"], entry["pair_id"] - subprocess.run( - [ - "gh", "workflow", "run", "certify-uk-release.yaml", - "--repo", os.environ["GITHUB_REPOSITORY"], "--ref", "main", - "-f", f"model_version={pair['model']['version']}", - "-f", f"data_version={pair['data']['release_version']}", - "-f", f"core_version={pair['core']['version']}", - "-f", f"pair_id={pair_id}", - "-f", "force=false", - ], - check=True, - ) - PY - - name: Finish attempts whose replay outlasted their run - env: - GH_TOKEN: ${{ github.token }} - run: | - python scripts/check_uk_candidate.py waiting --ledger ledger > waiting.txt - while read -r attempt; do - [[ -z "$attempt" ]] && continue - python scripts/check_uk_candidate.py poll-replay --attempt "$attempt" - python scripts/check_uk_candidate.py finalize --attempt "$attempt" --ledger ledger - done < waiting.txt - .github/qualification-ledger.sh publish ledger "Catch up waiting UK replay receipts" - - name: Refresh failed candidate PR checks against the published receipts - env: - GH_TOKEN: ${{ github.token }} - run: python scripts/check_uk_candidate.py refresh-pr-checks --ledger ledger - # Automatic promotion needs the target built on current main and compared - # against main's certificate. A run without force requalifies it once per - # main commit, one at a time; repeated catch-ups are duplicates. - - name: Requalify a promotable target qualified against an earlier certificate - env: - GH_TOKEN: ${{ github.token }} - run: | - python scripts/check_uk_candidate.py requalify --ledger ledger > requalify.jsonl - python - <<'PY' - import json - import os - import subprocess - from pathlib import Path - - for line in Path("requalify.jsonl").read_text().splitlines(): - entry = json.loads(line) - pair, pair_id = entry["pair"], entry["pair_id"] - subprocess.run( - [ - "gh", "workflow", "run", "certify-uk-release.yaml", - "--repo", os.environ["GITHUB_REPOSITORY"], "--ref", "main", - "-f", f"model_version={pair['model']['version']}", - "-f", f"data_version={pair['data']['release_version']}", - "-f", f"core_version={pair['core']['version']}", - "-f", f"pair_id={pair_id}", - "-f", "force=false", - ], - check=True, - ) - PY - - accept: - if: github.event_name == 'workflow_dispatch' && inputs.accept_pair_id != '' - runs-on: ubuntu-latest - timeout-minutes: 15 - permissions: - contents: write - pull-requests: write - actions: write - steps: - - uses: actions/checkout@v6 - with: - ref: main - fetch-depth: 0 - - uses: actions/setup-python@v6 - with: - python-version: ${{ env.PYTHON_VERSION }} - - uses: astral-sh/setup-uv@v8.1.0 - with: - version: ${{ env.UV_VERSION }} - - name: Install policyengine without country models - run: uv pip install --system -e . - - name: Record the reviewer's acceptance - env: - PAIR_ID: ${{ inputs.accept_pair_id }} - RECEIPT: ${{ inputs.accept_receipt_sha256 }} - EXPLANATION: ${{ inputs.accept_explanation }} - REVIEWER: ${{ github.actor }} - run: | - .github/qualification-ledger.sh checkout ledger - python scripts/check_uk_candidate.py accept --ledger ledger \ - --pair-id "$PAIR_ID" --receipt-sha256 "$RECEIPT" \ - --explanation "$EXPLANATION" --reviewer "$REVIEWER" - .github/qualification-ledger.sh publish ledger "Accept UK candidate $PAIR_ID on review by $REVIEWER" - - name: Refresh failed candidate PR checks against the accepted receipt - env: - GH_TOKEN: ${{ github.token }} - run: python scripts/check_uk_candidate.py refresh-pr-checks --ledger ledger - - promote: - needs: [resolve, replay, catch-up, accept] - if: always() - runs-on: ubuntu-latest - timeout-minutes: 15 - concurrency: - group: promote-uk - cancel-in-progress: false - steps: - # Promotion pushes main as the App, so the push starts main's release - # workflow; a push with the job's own token would not. - - name: Generate GitHub App token - id: app-token - uses: actions/create-github-app-token@v1 - with: - app-id: ${{ secrets.APP_ID }} - private-key: ${{ secrets.APP_PRIVATE_KEY }} - - uses: actions/checkout@v6 - with: - ref: main - fetch-depth: 0 - token: ${{ steps.app-token.outputs.token }} - - uses: astral-sh/setup-uv@v8.1.0 - with: - version: ${{ env.UV_VERSION }} - - uses: actions/setup-python@v6 - with: - python-version: ${{ env.PYTHON_VERSION }} - - name: Install policyengine without country models - run: uv pip install --system -e . - - name: Promote the newest qualified pair that advances main - env: - GH_TOKEN: ${{ steps.app-token.outputs.token }} - run: | - .github/qualification-ledger.sh checkout ledger - python scripts/check_uk_candidate.py promote --ledger ledger --apply diff --git a/.github/workflows/check-model-compatibility.yaml b/.github/workflows/check-model-compatibility.yaml new file mode 100644 index 000000000..416782f6b --- /dev/null +++ b/.github/workflows/check-model-compatibility.yaml @@ -0,0 +1,260 @@ +# Check each country's newest model release against the Microcosm builds the +# bundle pins, on Tuesdays and Fridays, and by hand for a named version. +# +# The plan job reads the bundle manifest and PyPI. For each country it picks +# the newest policyengine-us or policyengine-uk release (or the version named +# by hand) and leaves the country out when the bundle already pins that +# version, or a pull request from its branch exists (open, closed or merged), +# or the branch exists without one. +# +# The check job runs once per remaining country. scripts/bundle.py +# certify-build --in-place runs the compatibility check on the pinned national +# and local-area builds with that model version and certifies them for it, +# changing only this checkout's files. The checkout keeps no token while the +# check runs. A pass then makes a GitHub App token, commits the files +# certify-build lists to the new branch +# certify////-, +# and opens a draft pull request with its body, which a person merges. Earlier +# certification pull requests stay open, so any checked version can still be +# chosen. +# +# For each country it checks, a run uploads a compatibility- result +# file (the model version, the builds, passed, failed or cancelled, and the +# pull request), which the drift report reads to find the version that day's +# check passed. A failure opens or comments on the country's "Model +# compatibility check failed" issue; the next pass closes it, and a cancelled +# run leaves it as it is. + +name: Check model compatibility + +on: + schedule: + # 06:17 UTC on Tuesdays and Fridays. + - cron: "17 6 * * 2,5" + workflow_dispatch: + inputs: + country: + description: Country to check + type: choice + options: [both, us, uk] + default: both + model_version: + description: Model version to check (default the newest on PyPI); needs one country + required: false + +permissions: + contents: read + +# One run at a time, so two runs never push the same branch. Waiting runs +# queue in order (up to 100): without queue: max, a newly queued run would +# cancel the one already waiting. +concurrency: + group: check-model-compatibility + cancel-in-progress: false + queue: max + +env: + UV_VERSION: "0.13.4" + PYTHON_VERSION: "3.13" + # Keep equal to PYTHON_VERSION. The repository's .python-version asks for a + # newer Python, and every uv command here must use the 3.13 environment the + # job installed; each `uv run` passes --no-sync for the same reason. + UV_PYTHON: "3.13" + +jobs: + plan: + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + pull-requests: read + outputs: + matrix: ${{ steps.plan.outputs.matrix }} + any: ${{ steps.plan.outputs.any }} + steps: + - uses: actions/checkout@v6 + with: + ref: main + - uses: actions/setup-python@v6 + with: + python-version: ${{ env.PYTHON_VERSION }} + - name: Choose the model version to check for each country + id: plan + env: + GH_TOKEN: ${{ github.token }} + COUNTRY: ${{ inputs.country || 'both' }} + MODEL_VERSION: ${{ inputs.model_version }} + run: | + python scripts/compatibility_workflow.py plan \ + --country "$COUNTRY" \ + --model-version "$MODEL_VERSION" \ + --repository "$GITHUB_REPOSITORY" \ + --github-output "$GITHUB_OUTPUT" + # After the outputs are written, so the other country is still checked. + - name: Fail when a country could not be planned + if: steps.plan.outputs.unplanned != '' + env: + UNPLANNED: ${{ steps.plan.outputs.unplanned }} + run: | + echo "::error::Could not plan the check for: $UNPLANNED. The step above lists the error." + exit 1 + + check: + needs: plan + # Also when the plan job failed for the other country. + if: ${{ !cancelled() && needs.plan.outputs.any == 'true' }} + runs-on: ${{ vars.CERTIFY_RUNNER_X64 != '' && (vars.CI_RUNNER_EVENTS == '' || contains(format(',{0},', vars.CI_RUNNER_EVENTS), format(',{0},', github.event_name))) && vars.CERTIFY_RUNNER_X64 || 'ubuntu-latest' }} + timeout-minutes: 300 + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.plan.outputs.matrix) }} + permissions: + contents: read + issues: write + steps: + # First, so the result and issue steps below always have the script. + # The checkout keeps no token: certify-build runs without one. + - uses: actions/checkout@v6 + with: + ref: main + persist-credentials: false + # The US check downloads about 11 GB of builds and certify-build wants + # 5 GB more free; a GitHub-hosted runner starts with about 14 GB. These + # directories hold tools this job does not use. + - name: Free disk space on a GitHub-hosted runner + if: runner.environment == 'github-hosted' + run: | + df -h / + sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \ + /usr/local/.ghcup /opt/hostedtoolcache/CodeQL + df -h / + - uses: astral-sh/setup-uv@v8.1.0 + with: + version: ${{ env.UV_VERSION }} + - uses: actions/setup-python@v6 + with: + python-version: ${{ env.PYTHON_VERSION }} + - name: Install the pinned environment + env: + COUNTRY: ${{ matrix.country }} + run: uv sync --frozen --extra "$COUNTRY" --extra dev --python "$PYTHON_VERSION" + # A step that reaches its limit fails, and is recorded as a failed + # check. A job that reaches its limit is cancelled, which would be + # recorded as cancelled and leave the failure issue alone. + - name: Check and certify the pinned builds for the model version + id: certify + timeout-minutes: 270 + env: + HUGGING_FACE_TOKEN: ${{ secrets.HUGGING_FACE_TOKEN }} + COUNTRY: ${{ matrix.country }} + NATIONAL_RELEASE: ${{ matrix.national_release }} + NATIONAL_BUILD: ${{ matrix.national_build }} + LOCAL_AREA_RELEASE: ${{ matrix.local_area_release }} + LOCAL_AREA_BUILD: ${{ matrix.local_area_build }} + MODEL_VERSION: ${{ matrix.model_version }} + OUTPUT_DIR: ${{ runner.temp }}/certification + FOOTER: >- + Opened by the check-model-compatibility workflow in + ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}. + Each run opens its own pull request and leaves earlier ones open; + merge the version you want. + run: | + uv run --no-sync python scripts/bundle.py certify-build \ + --country "$COUNTRY" \ + --national-release "$NATIONAL_RELEASE" \ + --national-build "$NATIONAL_BUILD" \ + --local-area-release "$LOCAL_AREA_RELEASE" \ + --local-area-build "$LOCAL_AREA_BUILD" \ + --model-version "$MODEL_VERSION" \ + --in-place \ + --output-dir "$OUTPUT_DIR" \ + --pr-body-footer "$FOOTER" + # Made after the check, because App tokens last an hour and the check + # can take several. Pushes and pull requests made with the App's token + # start the pull request's own workflows; the job's token would not. + - name: Generate GitHub App token + id: app-token + uses: actions/create-github-app-token@v1 + with: + app-id: ${{ secrets.APP_ID }} + private-key: ${{ secrets.APP_PRIVATE_KEY }} + - name: Open a draft certification pull request + id: pull-request + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + BRANCH: ${{ matrix.branch }} + COUNTRY: ${{ matrix.country }} + MODEL_PACKAGE: ${{ matrix.model_package }} + MODEL_VERSION: ${{ matrix.model_version }} + NATIONAL_BUILD: ${{ matrix.national_build }} + OUTPUT_DIR: ${{ runner.temp }}/certification + run: | + # certify-build wrote one pull request body and one list of the + # files it changed into this directory, next to its log and the + # builds it downloaded. + shopt -s nullglob + bodies=("$OUTPUT_DIR"/*.pr-body.md) + changed=("$OUTPUT_DIR"/*.changed-paths.txt) + if (( ${#bodies[@]} != 1 || ${#changed[@]} != 1 )); then + echo "::error::certify-build left ${#bodies[@]} pull request bodies and ${#changed[@]} changed-path lists in $OUTPUT_DIR, not one of each." + exit 1 + fi + body="${bodies[0]}" + label=$(printf '%s' "$COUNTRY" | tr '[:lower:]' '[:upper:]') + git switch -c "$BRANCH" + git add --pathspec-from-file="${changed[0]}" + git -c user.name="github-actions[bot]" \ + -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ + commit -q -m "Certify Microcosm $label build $NATIONAL_BUILD for $MODEL_PACKAGE $MODEL_VERSION" + # git asks gh for credentials, and gh gives it GH_TOKEN. + gh auth setup-git + git push origin "HEAD:refs/heads/$BRANCH" + url=$(gh pr create --draft --base main --head "$BRANCH" \ + --title "Certify Microcosm $label build $NATIONAL_BUILD for $MODEL_PACKAGE $MODEL_VERSION" \ + --body-file "$body") + echo "url=$url" >> "$GITHUB_OUTPUT" + # python3, not python: the runner has it even when setup-python failed. + - name: Write the result file + if: always() + env: + ENTRY: ${{ toJSON(matrix) }} + COUNTRY: ${{ matrix.country }} + CERTIFY_OUTCOME: ${{ steps.certify.outcome }} + PULL_REQUEST_OUTCOME: ${{ steps.pull-request.outcome }} + JOB_STATUS: ${{ job.status }} + PULL_REQUEST: ${{ steps.pull-request.outputs.url }} + run: | + python3 scripts/compatibility_workflow.py record \ + --entry "$ENTRY" \ + --certify-outcome "$CERTIFY_OUTCOME" \ + --pull-request-outcome "$PULL_REQUEST_OUTCOME" \ + --job-status "$JOB_STATUS" \ + --pull-request "$PULL_REQUEST" \ + --run-url "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" \ + --out "$RUNNER_TEMP/compatibility/compatibility-$COUNTRY.json" + - name: Upload the result file + if: always() + uses: actions/upload-artifact@v4 + with: + name: compatibility-${{ matrix.country }} + path: ${{ runner.temp }}/compatibility/compatibility-${{ matrix.country }}.json + if-no-files-found: error + - name: Open, update or close the failure issue + if: always() + env: + GH_TOKEN: ${{ github.token }} + ENTRY: ${{ toJSON(matrix) }} + CERTIFY_OUTCOME: ${{ steps.certify.outcome }} + PULL_REQUEST_OUTCOME: ${{ steps.pull-request.outcome }} + JOB_STATUS: ${{ job.status }} + PULL_REQUEST: ${{ steps.pull-request.outputs.url }} + run: | + python3 scripts/compatibility_workflow.py report \ + --entry "$ENTRY" \ + --certify-outcome "$CERTIFY_OUTCOME" \ + --pull-request-outcome "$PULL_REQUEST_OUTCOME" \ + --job-status "$JOB_STATUS" \ + --pull-request "$PULL_REQUEST" \ + --run-url "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" \ + --repository "$GITHUB_REPOSITORY" diff --git a/.github/workflows/pr_code_changes.yaml b/.github/workflows/pr_code_changes.yaml index 706e45493..490718f70 100644 --- a/.github/workflows/pr_code_changes.yaml +++ b/.github/workflows/pr_code_changes.yaml @@ -6,16 +6,16 @@ # run on ubuntu-latest unless a repository variable names another runner # (Settings > Secrets and variables > Actions > Variables): # CI_RUNNER_X64 instead of ubuntu-latest for those jobs -# CERTIFY_RUNNER_X64 instead of ubuntu-latest for the UK certification's -# qualify and replay jobs, which hold the GitHub App -# key and a write token: a GitHub-hosted larger runner -# only +# CERTIFY_RUNNER_X64 instead of ubuntu-latest for the model compatibility +# workflow's check job, which holds the GitHub App key +# and a token that can write issues: a GitHub-hosted +# larger runner only # CI_RUNNER_EVENTS optional: event names separated by commas, no # spaces, such as push,workflow_dispatch. Only those # events use the variables. Empty means every event. # Delete a variable to go back to ubuntu-latest for the next run. Versioning, -# Publish, NotifyConsumers, the docs deploy and the other certification jobs -# always keep GitHub-hosted runners. Each CI_RUNNER_X64 job has a read-only +# Publish, NotifyConsumers, the docs deploy and the compatibility workflow's +# plan job always keep GitHub-hosted runners. Each CI_RUNNER_X64 job has a read-only # GITHUB_TOKEN, since the organisation's default token can write. Test and # BundleVerification read the dataset with HUGGING_FACE_TOKEN, so point the # variables only at runners where that data may be processed, such as the diff --git a/changelog.d/787.changed.md b/changelog.d/787.changed.md new file mode 100644 index 000000000..871ec454d --- /dev/null +++ b/changelog.d/787.changed.md @@ -0,0 +1 @@ +On Tuesdays and Fridays, and by hand for a named version, a workflow now checks each country's newest model release against the Microcosm builds the bundle pins and opens a draft certification pull request when it passes. It replaces `certify-uk-release.yaml`, which checked policyengine-uk wheels only against policyengine-uk-data releases. diff --git a/docs/engineering/runbooks/uk-qualification.md b/docs/engineering/runbooks/uk-qualification.md deleted file mode 100644 index a1cad6e2e..000000000 --- a/docs/engineering/runbooks/uk-qualification.md +++ /dev/null @@ -1,144 +0,0 @@ -# UK candidate qualification: what the ledger shows, and reproducing a gate - -UK candidate qualification starts via `workflow_dispatch` and resolves legacy -uk-data pairs. Scheduled recovery and requalification are disabled. - -The workflow qualifies candidate policyengine-uk and uk-data pairs before -promotion (`scripts/check_uk_candidate.py`, `policyengine.provenance.uk_candidate`). -It writes each attempt's gate results and evidence to the public -`uk-qualification-ledger` branch and withholds any survey data that could -identify a record. - -## What the ledger withholds - -- **Reform contract, population checks.** These run on the survey data. Each - row's check, route, status and the runner's fixed fields - (`POPULATION_ROW_FIELDS`) are published; from its `detail`, only top-level - `True`/`False`/`None` findings are kept, and every count, total, amount, - text, list or nested mapping reads `"withheld"`. The digest the gate - records is of that published copy, never of the full report. -- **Metrics review and responsiveness.** The aggregate-impact tool publishes - a figure from fewer than 10 records as suppressed, and the gate records no - value from a report that breaks that format; such a report is published - only as its digest and problems. - -## Reproducing a failed population check - -The withheld figures exist only in the runner's report, which is not saved. -To see them, rerun the contract on a machine with access to the private UK -dataset, and keep the output local: it holds figures from the survey data, -some from fewer than 10 records, so never commit, paste or publish it. - -1. Check out the candidate commit the attempt ran on (`git_commit` in the - attempt's `harness.json` in the ledger): its bundle manifest names the - dataset `materialize_dataset` fetches, so an older checkout would fetch - older data even with the candidate's wheels installed. -2. Install the candidate pair (the attempt's `candidate.json` names the - wheels) and export `HUGGING_FACE_TOKEN` for the private dataset. -3. Materialize the certified dataset, check its SHA-256 against - `data.dataset_sha256` in the pair's `pair.json`, and run the contract - with the seed and sample size in - `src/policyengine/data/qualification/uk.json`: - - ```python - import hashlib - import json - from pathlib import Path - - from policyengine.provenance.dataset_materialization import materialize_dataset - from policyengine.tax_benefit_models.uk.budget_reform_contract import ( - run_budget_reform_contract, - ) - - dataset = materialize_dataset("uk", data_dir=Path("data")).path - pair = json.loads(Path("path/to/ledger/uk//pair.json").read_text()) - digest = hashlib.sha256(Path(dataset).read_bytes()).hexdigest() - assert digest == pair["data"]["dataset_sha256"], "not the certified dataset" - report = run_budget_reform_contract( - routes=None, dataset_path=str(dataset), seed=0, max_examples=20 - ) - failing = [row for row in report["population"] if row["status"] != "pass"] - ``` - -4. Read `failing[...]["detail"]` locally. Report only the finding (which - condition failed, on which route), never the figures. - -## A candidate stranded before automatic promotion - -Automatic promotion moves main to a qualified candidate only once the newest -run of each workflow and event on the candidate branch, from this repository, -has passed, including a `pr_code_changes.yaml` run dispatched on the branch -itself. The candidate-tree code-check dispatch remains reachable. Replay and -acceptance still refresh candidate PR checks. The schedule-only recovery job -and its two self-dispatches are unreachable. Runs of pull requests from other -branches or forks at the same commit do not count. The `refresh-pr-checks` -step re-runs a failed, timed-out or cancelled run until it has had four -attempts, within GitHub's 30 days of its first attempt. - -When the candidate waits on a run that refresh will not re-run, the promote -job fails with `::error:: waits on runs refresh will not re-run`, -naming each run, its result and its attempts. That covers a run at four -attempts, one older than 30 days, and one whose result refresh never re-runs -(`action_required`, `skipped`, `stale`, `startup_failure` and the like). The -job fails on each run until one of these clears it: - -- Fix the cause, then re-run the named run by hand - (`gh run rerun --repo PolicyEngine/policyengine.py`); a passing - newest attempt clears it. GitHub refuses this for a run whose first - attempt is more than 30 days old. -- For the run on the candidate's own tree, dispatch a new one: - `gh workflow run pr_code_changes.yaml --repo PolicyEngine/policyengine.py --ref `. -- Requalify the pair: run `certify-uk-release` with its versions, `pair_id` - and `force` set. - -### Another pull request from the candidate branch - -Any other pull request from a candidate branch runs the same workflows with -the same commit and branch as the candidate's own pull request, and -GitHub's run records say neither which pull request a run is for nor which -base it tested; a pull request's current base does not settle it, since a -base renamed into main records no event. So while another pull request from -the branch is open, or after one was closed or merged at the candidate's -commit (whatever its base), or when the candidate's own pull request's base -was ever changed, the promote job fails with -`::error:: is not promoted: runs at its commit may have tested another base`, -naming the pull requests, and refresh re-runs none of the candidate's runs. -Close those pull requests, then requalify the pair as above: the new -candidate commit leaves their runs behind, and prepare opens a new pull -request to main if none is open. - -### What promotion trusts - -Promotion guards against mistakes by people who can write to this -repository and against anything people who cannot can do (forks' pull -requests, whatever their branch names, and other pull requests opened from -a candidate branch, which make promotion refuse; one to main that prepare's -lookup adopts is the candidate's own, and promotion refuses it if its base -was ever changed). Whatever else happens, main only -ever becomes the exact qualified commit, built on main as it is at the push, -after the dispatched `pr_code_changes.yaml` run on that commit's own tree -passed. It does not try to resist deliberate disguise by people who can -write here, such as renaming another branch into main to make a run against -another base look like the candidate's: main is not protected, so they -could push it directly. Treat any such change as an incident, not as -something the gate will catch. - -## A pair from another data line - -Promotion compares only pairs on main's data line (its UK certificate's data -package and repository). While Microcosm UK is the default, the -policyengine-uk-data candidates the workflow resolves are `other_line`. An -unforced run of one stops there and writes nothing to the ledger. Recovery and -check refreshes skip such pairs, and promotion closes their open pull requests; -the ledger keeps their evidence. - -`force` still qualifies such a pair, for evidence only. Its candidate commit -drops main's area routing (`--drop-regional-release`), because the routing -belongs to the line the pair would replace, and leaves the test constants that -pin main's certificate as they are, so the candidate's own tests fail. Its pull -request says it is never promoted, and promotion closes it once its receipt is -published, at the commit that receipt qualified. Re-run the workflow by hand -with `force` to recover an attempt. If an attempt dies before publishing a -receipt, close its open pull request by hand. Changing the data line -is a reviewed certification pull request (see -`docs/engineering/skills/data-certification.md`), not a promotion. diff --git a/scripts/check_uk_candidate.py b/scripts/check_uk_candidate.py index 7920b8c33..32235bf25 100644 --- a/scripts/check_uk_candidate.py +++ b/scripts/check_uk_candidate.py @@ -1,7 +1,7 @@ """Qualify a UK model/data candidate before it can be promoted. -Run by ``.github/workflows/certify-uk-release.yaml``; every step also runs -locally. Network access: PyPI, Hugging Face (``HUGGING_FACE_TOKEN``) and, for +``.github/workflows/certify-uk-release.yaml`` ran it until that workflow was +removed; every step still runs locally. Network access: PyPI, Hugging Face (``HUGGING_FACE_TOKEN``) and, for the replay and promotion steps, GitHub (``GH_TOKEN``). Each attempt lives in one ledger directory, ``/uk//attempts/ @@ -21,7 +21,7 @@ python scripts/check_uk_candidate.py accept --ledger ledger/ --pair-id ... \\ --receipt-sha256 ... --explanation "..." [--reviewer login] -Steps that the workflow branches on also write ``key=value`` lines to +Steps that the workflow branched on also write ``key=value`` lines to ``$GITHUB_OUTPUT`` when it is set. """ diff --git a/scripts/compatibility_workflow.py b/scripts/compatibility_workflow.py new file mode 100644 index 000000000..28b6e8b97 --- /dev/null +++ b/scripts/compatibility_workflow.py @@ -0,0 +1,619 @@ +#!/usr/bin/env python3 +"""Steps of the model compatibility workflow that are more than one command. + +``.github/workflows/check-model-compatibility.yaml`` runs on Tuesdays and +Fridays, and by hand for a named model version. It uses three commands: + +``plan`` + For each country, choose the model version to check: the newest + ``policyengine-us`` or ``policyengine-uk`` release on PyPI, or the + version named by hand. Leave out a country whose version the bundle + already pins, or whose version already has a certification pull request + or a pushed branch without one. + A country whose lookup fails is named in the ``unplanned`` output, and + the other country is still checked. + Write the remaining countries as the check job's matrix, each with the + national and local-area Microcosm builds the bundle pins and the branch + ``certify////-``. + +``record`` + Write one run's result for one country: the file the workflow uploads as + the ``compatibility-`` artifact, which says whether the model + version passed, failed or was cancelled against which builds. + +``report`` + Keep one open issue per country while its check fails: open it on the + first failure, comment on it at each later failure, and close it when a + run passes. A cancelled run changes nothing. + +It reads only the bundle manifest, PyPI and GitHub (through ``gh`` and +``git ls-remote``), so it runs without installing .py. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +import sys +import urllib.request +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, Callable, Iterable, Mapping, Optional, Protocol, Sequence + +REPO_ROOT = Path(__file__).resolve().parents[1] +BUNDLE_PATH = REPO_ROOT / "src" / "policyengine" / "data" / "bundle" / "manifest.json" +COUNTRIES = ("us", "uk") +COUNTRY_LABELS = {"us": "US", "uk": "UK"} +BRANCH_PREFIX = "certify" +ISSUE_TITLE = "Model compatibility check failed: {label}" +RECORD_SCHEMA_VERSION = 1 +OUTCOMES = ("passed", "failed", "cancelled") +PYPI_TIMEOUT_SECONDS = 60 + +_VERSION = re.compile(r"[0-9]+(\.[0-9]+)*") +_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*") +_RELEASE_PATH = re.compile(r"/releases/([^/]+)/([^/]+)/release_manifest\.json$") + + +def _check_version(version: Optional[str]) -> str: + if not version or not _VERSION.fullmatch(version): + raise ValueError( + f"The model version {version!r} is not a plain release number such as 2.150.0." + ) + return version + + +def _check_name(kind: str, value: str) -> str: + if not _NAME.fullmatch(value) or ".." in value: + raise ValueError(f"The {kind} {value!r} is not a plain name.") + return value + + +def release_and_build(manifest_uri: str) -> tuple[str, str]: + """The release and build names in a build's ``release_manifest.json`` address.""" + + match = _RELEASE_PATH.search(manifest_uri) + if match is None: + raise ValueError( + f"{manifest_uri!r} is not a Microcosm build's release_manifest.json address." + ) + release, build = match.groups() + return _check_name("release", release), _check_name("build", build) + + +def certification_branch( + country: str, + national_build: str, + local_area_build: str, + model_package: str, + model_version: str, +) -> str: + """The branch for one check of a model version against both pinned builds. + + It names both builds, so a version already checked is checked again once a + new national or local-area build is pinned. + """ + + return ( + f"{BRANCH_PREFIX}/{country}/{national_build}/{local_area_build}/" + f"{model_package}-{model_version}" + ) + + +def plan_countries( + bundle: Mapping[str, Any], + *, + countries: Sequence[str], + model_version: Optional[str], + newest_version: Callable[[str], str], + pull_request_exists: Callable[[str], bool], + branch_exists: Optional[Callable[[str], bool]] = None, +) -> list[dict[str, Any]]: + """One entry per country: what to check, or why the country is left out. + + ``model_version`` names the version to check by hand; it needs exactly one + country, because the US and UK models are versioned separately. Without + it, each country checks ``newest_version()``. + + A country whose lookup fails gets an entry with the action ``error`` and + the error as its reason; the other country is still planned. + + A version is left out when its branch already has a pull request, or when + ``branch_exists`` says the branch was pushed without one (a run whose + pull request step failed after the push): the push would fail, so the + version waits until someone opens that pull request or deletes the branch. + """ + + unknown = [country for country in countries if country not in COUNTRIES] + if unknown or not countries: + raise ValueError( + f"Choose countries from {', '.join(COUNTRIES)}, not {unknown}." + ) + if model_version is not None and len(countries) != 1: + raise ValueError("A named model version needs one country, not both.") + if model_version is not None: + _check_version(model_version) + + entries = [] + for country in countries: + try: + entries.append( + _plan_country( + bundle, + country, + model_version=model_version, + newest_version=newest_version, + pull_request_exists=pull_request_exists, + branch_exists=branch_exists, + ) + ) + except Exception as error: + # One country's lookup failing (PyPI, gh, git, its manifest entry) + # must not stop the other's check. The plan command names it, and + # the workflow fails the plan job after writing the matrix. + entries.append( + { + "country": country, + "action": "error", + "reason": f"{type(error).__name__}: {error}", + } + ) + return entries + + +def _plan_country( + bundle: Mapping[str, Any], + country: str, + *, + model_version: Optional[str], + newest_version: Callable[[str], str], + pull_request_exists: Callable[[str], bool], + branch_exists: Optional[Callable[[str], bool]], +) -> dict[str, Any]: + model_package = _check_name( + "model package", bundle["countries"][country]["model_package"] + ) + pinned_version = bundle["packages"][model_package]["version"] + version = _check_version( + model_version if model_version is not None else newest_version(model_package) + ) + release = bundle["data_releases"][country] + national_release, national_build = release_and_build( + release["release_manifest_uri"] + ) + if release.get("build_id") not in (None, national_build): + raise ValueError( + f"The {country} bundle pins build {release['build_id']!r} but its " + f"manifest address names {national_build!r}." + ) + local_area_release, local_area_build = release_and_build( + release["regional_release_manifest_uri"] + ) + branch = certification_branch( + country, national_build, local_area_build, model_package, version + ) + + if version == pinned_version: + action, reason = "skip", "already_pinned" + elif pull_request_exists(branch): + action, reason = "skip", "pull_request_exists" + elif branch_exists is not None and branch_exists(branch): + action, reason = "skip", "branch_exists" + else: + action, reason = "check", None + + return { + "country": country, + "model_package": model_package, + "pinned_version": pinned_version, + "model_version": version, + "national_release": national_release, + "national_build": national_build, + "local_area_release": local_area_release, + "local_area_build": local_area_build, + "branch": branch, + "action": action, + "reason": reason, + } + + +def newest_pypi_version(package: str) -> str: + """The newest release of ``package`` on PyPI.""" + + url = f"https://pypi.org/pypi/{package}/json" + with urllib.request.urlopen(url, timeout=PYPI_TIMEOUT_SECONDS) as response: + return json.load(response)["info"]["version"] + + +def pull_request_exists(repository: str, branch: str) -> bool: + """Whether any pull request, open or closed, comes from ``branch``. + + ``head=:`` lists only this repository's pull requests, so + a fork's branch with the same name never counts. + """ + + owner = repository.split("/", 1)[0] + result = subprocess.run( + [ + "gh", + "api", + "-X", + "GET", + f"repos/{repository}/pulls", + "-f", + f"head={owner}:{branch}", + "-f", + "state=all", + "--jq", + "length", + ], + check=True, + capture_output=True, + text=True, + ) + return int(result.stdout.strip() or 0) > 0 + + +def remote_branch_exists(branch: str) -> bool: + """Whether this checkout's ``origin`` has the branch ``branch``. + + ``git ls-remote`` matches the end of each ref's name, so the listing is + compared with the full ref name. + """ + + ref = f"refs/heads/{branch}" + result = subprocess.run( + ["git", "-C", str(REPO_ROOT), "ls-remote", "--heads", "origin", ref], + check=True, + capture_output=True, + text=True, + ) + return any(line.split("\t", 1)[-1] == ref for line in result.stdout.splitlines()) + + +# ── Results ─────────────────────────────────────────────────────────────── + + +def outcome_of( + certify_outcome: str, pull_request_outcome: str, job_status: str = "" +) -> tuple[str, Optional[str]]: + """``passed``, ``failed`` or ``cancelled``, and the step that failed. + + A step's outcome is ``success``, ``failure``, ``cancelled`` or ``skipped``; + the job's status is ``success``, ``failure`` or ``cancelled``. A skipped + certification step means an earlier step (setup) failed, or the job was + cancelled before certification began. A skipped pull request step after + a passing check means the App token step failed. + """ + + if certify_outcome == "success" and pull_request_outcome == "success": + return "passed", None + if "cancelled" in (certify_outcome, pull_request_outcome, job_status): + return "cancelled", None + if certify_outcome == "failure": + return "failed", "certification" + if certify_outcome != "success": + return "failed", "setup" + return "failed", "pull_request" + + +def result_record( + entry: Mapping[str, Any], + *, + outcome: str, + failed_step: Optional[str], + pull_request: Optional[str], + run_url: str, + checked_at: Optional[datetime] = None, +) -> dict[str, Any]: + if outcome not in OUTCOMES: + raise ValueError( + f"The outcome must be one of {', '.join(OUTCOMES)}, not {outcome!r}." + ) + moment = checked_at or datetime.now(UTC) + return { + "schema_version": RECORD_SCHEMA_VERSION, + "country": entry["country"], + "model_package": entry["model_package"], + "model_version": entry["model_version"], + "pinned_version": entry["pinned_version"], + "national_release": entry["national_release"], + "national_build": entry["national_build"], + "local_area_release": entry["local_area_release"], + "local_area_build": entry["local_area_build"], + "result": outcome, + "failed_step": failed_step if outcome == "failed" else None, + "branch": entry["branch"], + "pull_request": pull_request or None, + "run_url": run_url, + "checked_at": moment.strftime("%Y-%m-%dT%H:%M:%SZ"), + } + + +# ── The failure issue ───────────────────────────────────────────────────── + + +class Issues(Protocol): + def list_open(self, repository: str) -> list[dict[str, Any]]: ... + + def create(self, repository: str, title: str, body: str) -> None: ... + + def comment(self, repository: str, number: int, body: str) -> None: ... + + def close(self, repository: str, number: int, comment: str) -> None: ... + + +class GitHubIssues: + """Issue calls through the ``gh`` command, authenticated by ``GH_TOKEN``.""" + + def _gh(self, *arguments: str) -> str: + return subprocess.run( + ["gh", *arguments], check=True, capture_output=True, text=True + ).stdout + + def list_open(self, repository: str) -> list[dict[str, Any]]: + return json.loads( + self._gh( + "issue", + "list", + "--repo", + repository, + "--state", + "open", + "--limit", + "500", + "--json", + "number,title", + ) + ) + + def create(self, repository: str, title: str, body: str) -> None: + self._gh( + "issue", "create", "--repo", repository, "--title", title, "--body", body + ) + + def comment(self, repository: str, number: int, body: str) -> None: + self._gh("issue", "comment", str(number), "--repo", repository, "--body", body) + + def close(self, repository: str, number: int, comment: str) -> None: + self._gh( + "issue", "close", str(number), "--repo", repository, "--comment", comment + ) + + +def issue_title(country: str) -> str: + return ISSUE_TITLE.format(label=COUNTRY_LABELS[country]) + + +def _describe(entry: Mapping[str, Any]) -> list[str]: + return [ + f"- Model: {entry['model_package']} {entry['model_version']} " + f"(the bundle pins {entry['pinned_version']})", + f"- National build: {entry['national_release']} / {entry['national_build']}", + f"- Local-area build: {entry['local_area_release']} / {entry['local_area_build']}", + ] + + +def report( + entry: Mapping[str, Any], + *, + outcome: str, + failed_step: Optional[str], + run_url: str, + repository: str, + issues: Issues, + pull_request: Optional[str] = None, +) -> None: + """Open, update or close the country's failure issue for one run's result. + + A cancelled run says nothing about the model version, so it changes nothing. + """ + + if outcome == "cancelled": + return + title = issue_title(entry["country"]) + matching = [ + issue for issue in issues.list_open(repository) if issue["title"] == title + ] + label = COUNTRY_LABELS[entry["country"]] + + if outcome == "passed": + lines = [ + f"The {label} model compatibility check passed, so this issue is closed.", + "", + *_describe(entry), + ] + if pull_request: + lines.append(f"- Certification pull request: {pull_request}") + lines.append(f"- Run: {run_url}") + for issue in matching: + issues.close(repository, issue["number"], "\n".join(lines)) + return + + lines = [ + f"The {label} model compatibility check failed.", + "", + *_describe(entry), + f"- Failed step: {failed_step or 'unknown'}", + f"- Run: {run_url}", + ] + if matching: + issues.comment(repository, matching[0]["number"], "\n".join(lines)) + return + lines += [ + "", + "The check-model-compatibility workflow comments here at each later " + "failure and closes this issue when a run passes.", + ] + issues.create(repository, title, "\n".join(lines)) + + +# ── Command line ────────────────────────────────────────────────────────── + + +def _write_outputs(path: Optional[str], outputs: Mapping[str, str]) -> None: + lines = [f"{name}={value}" for name, value in outputs.items()] + if path: + with open(path, "a", encoding="utf-8") as handle: + handle.write("\n".join(lines) + "\n") + else: + print("\n".join(lines)) + + +def _summary(entries: Iterable[Mapping[str, Any]]) -> str: + rows = [ + "| Country | Model | Pinned | National build | Local-area build | Action |", + "|---|---|---|---|---|---|", + ] + for entry in entries: + if entry["action"] == "error": + reason = " ".join(entry["reason"].split()).replace("|", "\\|") + rows.append( + f"| {COUNTRY_LABELS[entry['country']]} | | | | | " + f"could not plan: {reason} |" + ) + continue + action = ( + entry["action"] + if entry["reason"] is None + else (f"{entry['action']} ({entry['reason']})") + ) + rows.append( + f"| {COUNTRY_LABELS[entry['country']]} | {entry['model_package']} " + f"{entry['model_version']} | {entry['pinned_version']} | " + f"{entry['national_build']} | {entry['local_area_build']} | {action} |" + ) + return "\n".join(rows) + "\n" + + +def _cmd_plan(args: argparse.Namespace) -> int: + bundle = json.loads(Path(BUNDLE_PATH).read_text()) + countries = list(COUNTRIES) if args.country == "both" else [args.country] + entries = plan_countries( + bundle, + countries=countries, + model_version=args.model_version or None, + newest_version=newest_pypi_version, + pull_request_exists=lambda branch: pull_request_exists(args.repository, branch), + branch_exists=remote_branch_exists, + ) + to_check = [entry for entry in entries if entry["action"] == "check"] + unplanned = [entry["country"] for entry in entries if entry["action"] == "error"] + _write_outputs( + args.github_output, + { + "matrix": json.dumps(to_check, separators=(",", ":"), sort_keys=True), + "any": "true" if to_check else "false", + "unplanned": ",".join(unplanned), + }, + ) + summary = _summary(entries) + print(summary, end="") + step_summary = os.environ.get("GITHUB_STEP_SUMMARY") + if step_summary: + with open(step_summary, "a", encoding="utf-8") as handle: + handle.write(summary) + return 0 + + +def _outcome(args: argparse.Namespace) -> tuple[str, Optional[str]]: + if args.outcome is not None: + return args.outcome, args.failed_step + return outcome_of( + args.certify_outcome or "", + args.pull_request_outcome or "", + args.job_status or "", + ) + + +def _cmd_record(args: argparse.Namespace) -> int: + outcome, failed_step = _outcome(args) + record = result_record( + json.loads(args.entry), + outcome=outcome, + failed_step=failed_step, + pull_request=args.pull_request, + run_url=args.run_url, + ) + out = Path(args.out) + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n") + return 0 + + +def _cmd_report(args: argparse.Namespace) -> int: + outcome, failed_step = _outcome(args) + report( + json.loads(args.entry), + outcome=outcome, + failed_step=failed_step, + run_url=args.run_url, + repository=args.repository, + issues=GitHubIssues(), + pull_request=args.pull_request, + ) + return 0 + + +def _add_outcome_options(parser: argparse.ArgumentParser) -> None: + parser.add_argument("--entry", required=True, help="The plan's entry, as JSON") + parser.add_argument("--outcome", choices=OUTCOMES) + parser.add_argument("--failed-step") + parser.add_argument( + "--certify-outcome", + help="The certification step's outcome, instead of --outcome", + ) + parser.add_argument( + "--pull-request-outcome", + help="The pull request step's outcome, instead of --outcome", + ) + parser.add_argument( + "--job-status", + help="The job's status (success, failure or cancelled), with the steps' outcomes", + ) + parser.add_argument("--pull-request", help="The certification pull request's URL") + parser.add_argument("--run-url", required=True) + + +def main(argv: Optional[Sequence[str]] = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + commands = parser.add_subparsers(dest="command", required=True) + + plan = commands.add_parser("plan", help="Choose the model version per country") + plan.add_argument("--country", choices=("both", *COUNTRIES), default="both") + plan.add_argument("--model-version", help="Check this version (one country only)") + plan.add_argument("--repository", required=True, help="owner/name") + plan.add_argument("--github-output", help="Append the outputs to this file") + plan.set_defaults(handler=_cmd_plan) + + record = commands.add_parser("record", help="Write one country's result file") + _add_outcome_options(record) + record.add_argument("--out", required=True) + record.set_defaults(handler=_cmd_record) + + report_command = commands.add_parser( + "report", help="Open, update or close the country's failure issue" + ) + _add_outcome_options(report_command) + report_command.add_argument("--repository", required=True, help="owner/name") + report_command.set_defaults(handler=_cmd_report) + + args = parser.parse_args(argv) + if ( + args.command in ("record", "report") + and args.outcome is None + and (args.certify_outcome is None and args.pull_request_outcome is None) + ): + parser.error("give --outcome, or the steps' outcomes") + try: + return args.handler(args) + except ValueError as error: + print(f"error: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/policyengine/provenance/uk_candidate.py b/src/policyengine/provenance/uk_candidate.py index 4599babf8..71c771b3b 100644 --- a/src/policyengine/provenance/uk_candidate.py +++ b/src/policyengine/provenance/uk_candidate.py @@ -1393,7 +1393,7 @@ def publishable_contract_report(report: Mapping[str, Any]) -> dict[str, Any]: top-level true/false findings (``_publishable_detail``), and any other field is withheld. The gate judges the report as the runner returned it. To see a failed population check's figures, rerun the contract with - access to the dataset (``docs/engineering/runbooks/uk-qualification.md``). + access to the dataset. """ published = dict(report) diff --git a/src/policyengine/provenance/uk_qualification.py b/src/policyengine/provenance/uk_qualification.py index 0ae373212..ef23f5556 100644 --- a/src/policyengine/provenance/uk_qualification.py +++ b/src/policyengine/provenance/uk_qualification.py @@ -1,7 +1,7 @@ """Orchestration for qualifying a UK model/data candidate. -``scripts/check_uk_candidate.py`` is the command-line front end and -``.github/workflows/certify-uk-release.yaml`` runs it. The steps are: +``scripts/check_uk_candidate.py`` is the command-line front end. The removed +``.github/workflows/certify-uk-release.yaml`` workflow ran it. The steps are: ``resolve`` Find the candidate pair: the newest (or requested) policyengine-uk wheel diff --git a/tests/test_ci_runner_variables.py b/tests/test_ci_runner_variables.py index 3083b8d38..8184d9a2d 100644 --- a/tests/test_ci_runner_variables.py +++ b/tests/test_ci_runner_variables.py @@ -6,16 +6,16 @@ 1. Each covered job's ``runs-on`` is the one runner expression, built from its variable and ubuntu-latest, so an unset variable keeps ubuntu-latest. 2. Every other job keeps a literal GitHub-hosted label. Versioning, Publish, - NotifyConsumers, the docs deploy and the certification jobs that resolve, - prepare, catch up, accept and promote never move. + NotifyConsumers, the docs deploy and the compatibility workflow's plan job + never move. 3. The expression picks the variable's runner exactly when the variable is set and CI_RUNNER_EVENTS is empty or lists the run's event, matched as a whole name: "pull_request" never matches "pull_request_target". 4. Every job that CI_RUNNER_X64 can move has a GITHUB_TOKEN that can only read: the organisation's default token can write, and a moved job takes - its token to the other runner. The certification jobs keep their write - token and the GitHub App key, so they have their own variable, for - GitHub-hosted larger runners only. + its token to the other runner. The compatibility workflow's check job + keeps the GitHub App key and a token that can write issues, so it has its + own variable, for GitHub-hosted larger runners only. """ from itertools import product @@ -39,8 +39,7 @@ ("pr_docs_changes.yaml", "Test"): "CI_RUNNER_X64", ("push.yaml", "Lint"): "CI_RUNNER_X64", ("push.yaml", "Test"): "CI_RUNNER_X64", - ("certify-uk-release.yaml", "qualify"): "CERTIFY_RUNNER_X64", - ("certify-uk-release.yaml", "replay"): "CERTIFY_RUNNER_X64", + ("check-model-compatibility.yaml", "check"): "CERTIFY_RUNNER_X64", } NEVER_MOVED = { @@ -48,11 +47,7 @@ ("push.yaml", "Versioning"), ("push.yaml", "Publish"), ("push.yaml", "NotifyConsumers"), - ("certify-uk-release.yaml", "resolve"), - ("certify-uk-release.yaml", "prepare"), - ("certify-uk-release.yaml", "catch-up"), - ("certify-uk-release.yaml", "accept"), - ("certify-uk-release.yaml", "promote"), + ("check-model-compatibility.yaml", "plan"), } @@ -82,6 +77,7 @@ def jobs(): def test_covered_jobs_use_the_runner_expression(): found = dict(jobs()) for key, variable in COVERED.items(): + assert key in found, key assert found[key] == runner_expression(variable), key diff --git a/tests/test_model_compatibility_workflow.py b/tests/test_model_compatibility_workflow.py new file mode 100644 index 000000000..11d09c8e1 --- /dev/null +++ b/tests/test_model_compatibility_workflow.py @@ -0,0 +1,1263 @@ +"""The Tuesday and Friday model compatibility workflow and its helper script. + +``.github/workflows/check-model-compatibility.yaml`` checks each country's +newest model release against the Microcosm builds the bundle pins, on +Tuesdays and Fridays and by hand. A pass opens a draft certification pull +request on a branch named after the country and model version; a failure +opens or updates one issue per country. ``scripts/compatibility_workflow.py`` +holds the steps that are more than one command. No test here calls GitHub or +PyPI. +""" + +from __future__ import annotations + +import importlib.util +import json +import os +import shutil +import subprocess +from pathlib import Path + +import pytest +import yaml + +REPO_ROOT = Path(__file__).resolve().parents[1] +WORKFLOWS = REPO_ROOT / ".github" / "workflows" +WORKFLOW_PATH = WORKFLOWS / "check-model-compatibility.yaml" +SCRIPT_PATH = REPO_ROOT / "scripts" / "compatibility_workflow.py" +BUNDLE_PATH = REPO_ROOT / "src" / "policyengine" / "data" / "bundle" / "manifest.json" + +US_NATIONAL_URI = ( + "https://huggingface.co/datasets/policyengine/populace-us/resolve/" + "0ff35303e4e5c10bf1cfb2da8f65c83d7dfa9ab3/releases/microcosm-us-2024-national/" + "populace-us-2024-spm-20260915/release_manifest.json" +) +US_LOCAL_AREA_URI = ( + "https://huggingface.co/datasets/policyengine/populace-us/resolve/" + "28f355b8931d14fd9705ebe818554f578f1719d6/releases/microcosm-us-2024-local/" + "populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z/release_manifest.json" +) +UK_NATIONAL_URI = ( + "https://huggingface.co/datasets/policyengine/populace-uk-private/resolve/" + "a80a4bf70ab4ffeac77357fe0633d3cee4ce7401/releases/microcosm-uk-2024-25-national/" + "uk-frs-calibration-attempt-20261122T100732Z-b891aa69/release_manifest.json" +) +UK_LOCAL_AREA_URI = ( + "https://huggingface.co/datasets/policyengine/populace-uk-private/resolve/" + "9da099465da06f020d9125f60e49c88180a9e607/releases/microcosm-uk-2024-25-dense/" + "uk-local-candidate-f100-s42-20261123T075147Z-7081d968/release_manifest.json" +) + + +def load_script(): + assert SCRIPT_PATH.exists(), SCRIPT_PATH + spec = importlib.util.spec_from_file_location( + "compatibility_workflow_for_test", SCRIPT_PATH + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def make_bundle(us_version="2.2.2", uk_version="2.179.2"): + """The fields of a bundle manifest that the plan reads.""" + + return { + "countries": { + "us": {"model_package": "policyengine-us"}, + "uk": {"model_package": "policyengine-uk"}, + }, + "packages": { + "policyengine-us": {"name": "policyengine-us", "version": us_version}, + "policyengine-uk": {"name": "policyengine-uk", "version": uk_version}, + }, + "data_releases": { + "us": { + "build_id": "populace-us-2024-spm-20260915", + "release_manifest_uri": US_NATIONAL_URI, + "regional_release_manifest_uri": US_LOCAL_AREA_URI, + }, + "uk": { + "build_id": "uk-frs-calibration-attempt-20261122T100732Z-b891aa69", + "release_manifest_uri": UK_NATIONAL_URI, + "regional_release_manifest_uri": UK_LOCAL_AREA_URI, + }, + }, + } + + +def newest_versions(**versions): + def newest(package): + return versions[package] + + return newest + + +def no_pull_requests(branch): + return False + + +def workflow(): + assert WORKFLOW_PATH.exists(), WORKFLOW_PATH + return yaml.safe_load(WORKFLOW_PATH.read_text()) + + +def triggers(document): + # PyYAML reads the bare key ``on`` as the boolean True. + return document.get("on", document.get(True)) + + +def steps_of(job): + return job["steps"] + + +def step_named(job, name): + matches = [step for step in steps_of(job) if step.get("name") == name] + assert len(matches) == 1, (name, [step.get("name") for step in steps_of(job)]) + return matches[0] + + +def step_running(job, command): + matches = [step for step in steps_of(job) if command in step.get("run", "")] + assert len(matches) == 1, (command, [step.get("name") for step in steps_of(job)]) + return matches[0] + + +# ── The plan: which model version each country checks ───────────────────── + + +def test_plan_checks_each_countrys_newest_release_against_its_pinned_builds(): + script = load_script() + + entries = script.plan_countries( + make_bundle(), + countries=["us", "uk"], + model_version=None, + newest_version=newest_versions( + **{"policyengine-us": "2.150.0", "policyengine-uk": "2.180.0"} + ), + pull_request_exists=no_pull_requests, + ) + + assert [entry["country"] for entry in entries] == ["us", "uk"] + us_entry, uk_entry = entries + assert us_entry == { + "country": "us", + "model_package": "policyengine-us", + "pinned_version": "2.2.2", + "model_version": "2.150.0", + "national_release": "microcosm-us-2024-national", + "national_build": "populace-us-2024-spm-20260915", + "local_area_release": "microcosm-us-2024-local", + "local_area_build": "populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z", + "branch": "certify/us/populace-us-2024-spm-20260915/populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z/policyengine-us-2.150.0", + "action": "check", + "reason": None, + } + assert uk_entry["national_build"] == ( + "uk-frs-calibration-attempt-20261122T100732Z-b891aa69" + ) + assert uk_entry["local_area_release"] == "microcosm-uk-2024-25-dense" + assert uk_entry["local_area_build"] == ( + "uk-local-candidate-f100-s42-20261123T075147Z-7081d968" + ) + assert ( + uk_entry["branch"] + == "certify/uk/uk-frs-calibration-attempt-20261122T100732Z-b891aa69/uk-local-candidate-f100-s42-20261123T075147Z-7081d968/policyengine-uk-2.180.0" + ) + assert uk_entry["action"] == "check" + + +def test_plan_skips_a_country_whose_newest_release_is_already_pinned(): + script = load_script() + + entries = script.plan_countries( + make_bundle(uk_version="2.180.0"), + countries=["us", "uk"], + model_version=None, + newest_version=newest_versions( + **{"policyengine-us": "2.150.0", "policyengine-uk": "2.180.0"} + ), + pull_request_exists=no_pull_requests, + ) + + by_country = {entry["country"]: entry for entry in entries} + assert by_country["us"]["action"] == "check" + assert by_country["uk"]["action"] == "skip" + assert by_country["uk"]["reason"] == "already_pinned" + + +def test_plan_skips_a_version_that_already_has_a_pull_request(): + script = load_script() + asked = [] + + def pull_request_exists(branch): + asked.append(branch) + return ( + branch + == "certify/us/populace-us-2024-spm-20260915/populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z/policyengine-us-2.150.0" + ) + + entries = script.plan_countries( + make_bundle(), + countries=["us", "uk"], + model_version=None, + newest_version=newest_versions( + **{"policyengine-us": "2.150.0", "policyengine-uk": "2.180.0"} + ), + pull_request_exists=pull_request_exists, + ) + + by_country = {entry["country"]: entry for entry in entries} + assert by_country["us"]["action"] == "skip" + assert by_country["us"]["reason"] == "pull_request_exists" + assert by_country["uk"]["action"] == "check" + assert sorted(asked) == [ + "certify/uk/uk-frs-calibration-attempt-20261122T100732Z-b891aa69/uk-local-candidate-f100-s42-20261123T075147Z-7081d968/policyengine-uk-2.180.0", + "certify/us/populace-us-2024-spm-20260915/populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z/policyengine-us-2.150.0", + ] + + +def test_plan_skips_a_version_whose_branch_was_pushed_without_a_pull_request(): + """A run that pushed its branch but failed to open the pull request. + + Pushing to the same branch again would fail, so the version is left out + until someone opens the pull request or deletes the branch. + """ + + script = load_script() + + entries = script.plan_countries( + make_bundle(), + countries=["us", "uk"], + model_version=None, + newest_version=newest_versions( + **{"policyengine-us": "2.150.0", "policyengine-uk": "2.180.0"} + ), + pull_request_exists=no_pull_requests, + branch_exists=lambda branch: branch.startswith("certify/us/"), + ) + + by_country = {entry["country"]: entry for entry in entries} + assert by_country["us"]["action"] == "skip" + assert by_country["us"]["reason"] == "branch_exists" + assert by_country["uk"]["action"] == "check" + + +def test_plan_still_checks_one_country_when_the_other_cannot_be_planned(): + """PyPI, gh or a manifest entry failing for one country leaves the other's + check in the matrix; the failed country is listed with its error.""" + + script = load_script() + + def newest_version(package): + if package == "policyengine-uk": + raise OSError("HTTP Error 503: Service Unavailable") + return "2.150.0" + + entries = script.plan_countries( + make_bundle(), + countries=["us", "uk"], + model_version=None, + newest_version=newest_version, + pull_request_exists=no_pull_requests, + ) + + by_country = {entry["country"]: entry for entry in entries} + assert by_country["us"]["action"] == "check" + assert by_country["uk"]["action"] == "error" + assert "HTTP Error 503" in by_country["uk"]["reason"] + + +def test_plan_lists_a_country_whose_github_lookup_failed(): + script = load_script() + + def pull_request_exists(branch): + if branch.startswith("certify/us/"): + raise subprocess.CalledProcessError(1, ["gh", "api"]) + return False + + entries = script.plan_countries( + make_bundle(), + countries=["us", "uk"], + model_version=None, + newest_version=newest_versions( + **{"policyengine-us": "2.150.0", "policyengine-uk": "2.180.0"} + ), + pull_request_exists=pull_request_exists, + ) + + by_country = {entry["country"]: entry for entry in entries} + assert by_country["us"]["action"] == "error" + assert "CalledProcessError" in by_country["us"]["reason"] + assert by_country["uk"]["action"] == "check" + + +def test_plan_checks_a_version_again_after_a_new_local_area_build_is_pinned(): + """Pull requests for this version and national build that were checked + against another local-area build do not stop the check: the branch names + both builds.""" + + script = load_script() + + def pull_request_exists(branch): + # Every earlier pull request names some other local-area build. + return ( + "populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z" not in branch + ) + + entries = script.plan_countries( + make_bundle(), + countries=["us"], + model_version="2.150.0", + newest_version=newest_versions(), + pull_request_exists=pull_request_exists, + ) + + assert entries[0]["action"] == "check" + assert entries[0]["branch"] == ( + "certify/us/populace-us-2024-spm-20260915/" + "populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z/" + "policyengine-us-2.150.0" + ) + + +def test_plan_checks_a_named_version_for_one_country_without_asking_pypi(): + script = load_script() + + def newest_version(package): + raise AssertionError("a named version must not look up the newest") + + entries = script.plan_countries( + make_bundle(), + countries=["uk"], + model_version="2.179.5", + newest_version=newest_version, + pull_request_exists=no_pull_requests, + ) + + assert len(entries) == 1 + assert entries[0]["country"] == "uk" + assert entries[0]["model_version"] == "2.179.5" + assert ( + entries[0]["branch"] + == "certify/uk/uk-frs-calibration-attempt-20261122T100732Z-b891aa69/uk-local-candidate-f100-s42-20261123T075147Z-7081d968/policyengine-uk-2.179.5" + ) + assert entries[0]["action"] == "check" + + +def test_plan_refuses_a_named_version_for_both_countries(): + script = load_script() + + with pytest.raises(ValueError, match="one country"): + script.plan_countries( + make_bundle(), + countries=["us", "uk"], + model_version="2.150.0", + newest_version=newest_versions(), + pull_request_exists=no_pull_requests, + ) + + +@pytest.mark.parametrize("version", ["2.150.0 ", "2.150.0;rm", "../2.150.0", ""]) +def test_plan_refuses_a_version_that_is_not_a_plain_release_number(version): + script = load_script() + + with pytest.raises(ValueError, match="version"): + script.plan_countries( + make_bundle(), + countries=["us"], + model_version=version, + newest_version=newest_versions(), + pull_request_exists=no_pull_requests, + ) + + +def test_plan_reads_the_committed_bundle(): + """The committed bundle has every field the plan reads, for both countries.""" + + script = load_script() + bundle = json.loads(BUNDLE_PATH.read_text()) + + entries = script.plan_countries( + bundle, + countries=["us", "uk"], + model_version=None, + newest_version=lambda package: "999.0.0", + pull_request_exists=no_pull_requests, + ) + + for entry in entries: + assert entry["action"] == "check" + assert ( + entry["national_build"] + == bundle["data_releases"][entry["country"]]["build_id"] + ) + assert entry["local_area_build"] + assert ( + entry["pinned_version"] + == (bundle["packages"][entry["model_package"]]["version"]) + ) + + +def test_plan_command_writes_the_matrix_of_countries_to_check(tmp_path, monkeypatch): + script = load_script() + bundle_path = tmp_path / "manifest.json" + bundle_path.write_text(json.dumps(make_bundle(uk_version="2.180.0"))) + github_output = tmp_path / "github_output" + monkeypatch.setattr(script, "BUNDLE_PATH", bundle_path) + monkeypatch.setattr( + script, + "newest_pypi_version", + newest_versions(**{"policyengine-us": "2.150.0", "policyengine-uk": "2.180.0"}), + ) + monkeypatch.setattr( + script, + "pull_request_exists", + lambda repository, branch: False, + ) + monkeypatch.setattr(script, "remote_branch_exists", lambda branch: False) + + exit_code = script.main( + [ + "plan", + "--country", + "both", + "--repository", + "PolicyEngine/policyengine.py", + "--github-output", + str(github_output), + ] + ) + + assert exit_code == 0 + outputs = dict( + line.split("=", 1) for line in github_output.read_text().splitlines() + ) + matrix = json.loads(outputs["matrix"]) + assert [entry["country"] for entry in matrix] == ["us"] + assert matrix[0]["model_version"] == "2.150.0" + assert outputs["any"] == "true" + assert outputs.get("unplanned") == "" + + +def test_plan_command_reports_nothing_to_check(tmp_path, monkeypatch): + script = load_script() + bundle_path = tmp_path / "manifest.json" + bundle_path.write_text(json.dumps(make_bundle(us_version="2.150.0"))) + github_output = tmp_path / "github_output" + monkeypatch.setattr(script, "BUNDLE_PATH", bundle_path) + monkeypatch.setattr(script, "newest_pypi_version", lambda package: "2.150.0") + monkeypatch.setattr(script, "pull_request_exists", lambda repository, branch: False) + monkeypatch.setattr(script, "remote_branch_exists", lambda branch: False) + + exit_code = script.main( + [ + "plan", + "--country", + "us", + "--repository", + "PolicyEngine/policyengine.py", + "--github-output", + str(github_output), + ] + ) + + assert exit_code == 0 + outputs = dict( + line.split("=", 1) for line in github_output.read_text().splitlines() + ) + assert json.loads(outputs["matrix"]) == [] + assert outputs["any"] == "false" + + +def test_plan_command_skips_a_branch_already_on_github(tmp_path, monkeypatch): + script = load_script() + bundle_path = tmp_path / "manifest.json" + bundle_path.write_text(json.dumps(make_bundle())) + github_output = tmp_path / "github_output" + asked = [] + monkeypatch.setattr(script, "BUNDLE_PATH", bundle_path) + monkeypatch.setattr(script, "newest_pypi_version", lambda package: "2.150.0") + monkeypatch.setattr(script, "pull_request_exists", lambda repository, branch: False) + monkeypatch.setattr( + script, + "remote_branch_exists", + lambda branch: asked.append(branch) or True, + ) + + exit_code = script.main( + [ + "plan", + "--country", + "us", + "--repository", + "PolicyEngine/policyengine.py", + "--github-output", + str(github_output), + ] + ) + + assert exit_code == 0 + assert asked == [ + "certify/us/populace-us-2024-spm-20260915/populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z/policyengine-us-2.150.0" + ] + outputs = dict( + line.split("=", 1) for line in github_output.read_text().splitlines() + ) + assert json.loads(outputs["matrix"]) == [] + assert outputs["any"] == "false" + + +def test_plan_command_names_the_countries_it_could_not_plan( + tmp_path, monkeypatch, capsys +): + script = load_script() + bundle_path = tmp_path / "manifest.json" + bundle_path.write_text(json.dumps(make_bundle())) + github_output = tmp_path / "github_output" + + def newest_pypi_version(package): + if package == "policyengine-uk": + raise OSError("HTTP Error 503: Service Unavailable") + return "2.150.0" + + monkeypatch.setattr(script, "BUNDLE_PATH", bundle_path) + monkeypatch.setattr(script, "newest_pypi_version", newest_pypi_version) + monkeypatch.setattr(script, "pull_request_exists", lambda repository, branch: False) + monkeypatch.setattr(script, "remote_branch_exists", lambda branch: False) + + exit_code = script.main( + [ + "plan", + "--country", + "both", + "--repository", + "PolicyEngine/policyengine.py", + "--github-output", + str(github_output), + ] + ) + + # The outputs are written, so the US check runs; a later step fails the + # plan job for the UK. + assert exit_code == 0 + outputs = dict( + line.split("=", 1) for line in github_output.read_text().splitlines() + ) + assert [entry["country"] for entry in json.loads(outputs["matrix"])] == ["us"] + assert outputs["any"] == "true" + assert outputs["unplanned"] == "uk" + assert "HTTP Error 503" in capsys.readouterr().out + + +class FakeRun: + """Stands in for subprocess.run and records the commands it is given.""" + + def __init__(self, stdout): + self.stdout = stdout + self.commands = [] + + def __call__(self, command, **options): + self.commands.append(command) + return subprocess.CompletedProcess(command, 0, stdout=self.stdout, stderr="") + + +def test_pull_request_exists_lists_this_repositorys_pull_requests_from_the_branch( + monkeypatch, +): + script = load_script() + branch = "certify/us/populace-us-2024-spm-20260915/populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z/policyengine-us-2.150.0" + one_pull_request = FakeRun("1\n") + monkeypatch.setattr(script.subprocess, "run", one_pull_request) + + assert script.pull_request_exists("PolicyEngine/policyengine.py", branch) is True + assert one_pull_request.commands == [ + [ + "gh", + "api", + "-X", + "GET", + "repos/PolicyEngine/policyengine.py/pulls", + "-f", + f"head=PolicyEngine:{branch}", + "-f", + "state=all", + "--jq", + "length", + ] + ] + + monkeypatch.setattr(script.subprocess, "run", FakeRun("0\n")) + assert script.pull_request_exists("PolicyEngine/policyengine.py", branch) is False + + +def test_remote_branch_exists_asks_origin_for_that_branch_only(monkeypatch): + script = load_script() + branch = "certify/us/populace-us-2024-spm-20260915/populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z/policyengine-us-2.150.0" + listed = FakeRun(f"0123abcd\trefs/heads/{branch}\n") + monkeypatch.setattr(script.subprocess, "run", listed) + + assert script.remote_branch_exists(branch) is True + assert listed.commands == [ + [ + "git", + "-C", + str(script.REPO_ROOT), + "ls-remote", + "--heads", + "origin", + f"refs/heads/{branch}", + ] + ] + + # git ls-remote matches the end of a ref's name, so a longer branch name + # that ends the same way is listed too; it is not this branch. + monkeypatch.setattr( + script.subprocess, + "run", + FakeRun(f"0123abcd\trefs/heads/someone/refs/heads/{branch}\n"), + ) + assert script.remote_branch_exists(branch) is False + + monkeypatch.setattr(script.subprocess, "run", FakeRun("")) + assert script.remote_branch_exists(branch) is False + + +# ── The outcome of a run ────────────────────────────────────────────────── + + +@pytest.mark.parametrize( + ("certify", "pull_request", "job_status", "expected"), + [ + ("success", "success", "success", ("passed", None)), + ("failure", "skipped", "failure", ("failed", "certification")), + # A setup step (checkout, install) failed before certification ran. + ("skipped", "skipped", "failure", ("failed", "setup")), + ("success", "failure", "failure", ("failed", "pull_request")), + # The App token step failed, so the pull request step was skipped. + ("success", "skipped", "failure", ("failed", "pull_request")), + ("cancelled", "skipped", "cancelled", ("cancelled", None)), + # Cancelled during setup: both steps were skipped. + ("skipped", "skipped", "cancelled", ("cancelled", None)), + ("success", "cancelled", "cancelled", ("cancelled", None)), + # Cancelled after the pull request was opened. + ("success", "success", "cancelled", ("passed", None)), + ], +) +def test_outcome_of_a_run_from_its_steps_and_the_job( + certify, pull_request, job_status, expected +): + script = load_script() + + assert script.outcome_of(certify, pull_request, job_status) == expected + + +# ── The result file each run uploads per country ────────────────────────── + + +def test_record_writes_the_result_a_later_drift_run_reads(tmp_path): + script = load_script() + entry = script.plan_countries( + make_bundle(), + countries=["us"], + model_version="2.150.0", + newest_version=newest_versions(), + pull_request_exists=no_pull_requests, + )[0] + out = tmp_path / "compatibility-us.json" + + exit_code = script.main( + [ + "record", + "--entry", + json.dumps(entry), + "--outcome", + "passed", + "--pull-request", + "https://github.com/PolicyEngine/policyengine.py/pull/900", + "--run-url", + "https://github.com/PolicyEngine/policyengine.py/actions/runs/1", + "--out", + str(out), + ] + ) + + assert exit_code == 0 + record = json.loads(out.read_text()) + assert record["schema_version"] == 1 + assert record["country"] == "us" + assert record["model_package"] == "policyengine-us" + assert record["model_version"] == "2.150.0" + assert record["pinned_version"] == "2.2.2" + assert record["national_build"] == "populace-us-2024-spm-20260915" + assert record["local_area_build"] == ( + "populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z" + ) + assert record["result"] == "passed" + assert record["failed_step"] is None + assert ( + record["branch"] + == "certify/us/populace-us-2024-spm-20260915/populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z/policyengine-us-2.150.0" + ) + assert record["pull_request"] == ( + "https://github.com/PolicyEngine/policyengine.py/pull/900" + ) + assert record["run_url"].endswith("/actions/runs/1") + assert record["checked_at"].endswith("Z") + + +def test_record_names_the_step_that_failed(tmp_path): + script = load_script() + entry = script.plan_countries( + make_bundle(), + countries=["uk"], + model_version="2.180.0", + newest_version=newest_versions(), + pull_request_exists=no_pull_requests, + )[0] + out = tmp_path / "compatibility-uk.json" + + script.main( + [ + "record", + "--entry", + json.dumps(entry), + "--outcome", + "failed", + "--failed-step", + "certification", + "--run-url", + "https://github.com/PolicyEngine/policyengine.py/actions/runs/2", + "--out", + str(out), + ] + ) + + record = json.loads(out.read_text()) + assert record["result"] == "failed" + assert record["failed_step"] == "certification" + assert record["pull_request"] is None + + +def test_record_marks_a_cancelled_run_as_cancelled(tmp_path): + script = load_script() + entry = script.plan_countries( + make_bundle(), + countries=["us"], + model_version="2.150.0", + newest_version=newest_versions(), + pull_request_exists=no_pull_requests, + )[0] + out = tmp_path / "compatibility-us.json" + + exit_code = script.main( + [ + "record", + "--entry", + json.dumps(entry), + "--certify-outcome", + "skipped", + "--pull-request-outcome", + "skipped", + "--job-status", + "cancelled", + "--run-url", + "https://github.com/PolicyEngine/policyengine.py/actions/runs/4", + "--out", + str(out), + ] + ) + + assert exit_code == 0 + record = json.loads(out.read_text()) + assert record["result"] == "cancelled" + assert record["failed_step"] is None + + +# ── The failure issue ───────────────────────────────────────────────────── + + +class FakeIssues: + """The issue calls the report makes, recorded instead of sent to GitHub.""" + + def __init__(self, open_issues=()): + self.open_issues = list(open_issues) + self.calls = [] + + def list_open(self, repository): + self.calls.append(("list", repository)) + return list(self.open_issues) + + def create(self, repository, title, body): + self.calls.append(("create", repository, title, body)) + + def comment(self, repository, number, body): + self.calls.append(("comment", repository, number, body)) + + def close(self, repository, number, comment): + self.calls.append(("close", repository, number, comment)) + + +def make_entry(script, country="us", version="2.150.0"): + return script.plan_countries( + make_bundle(), + countries=[country], + model_version=version, + newest_version=newest_versions(), + pull_request_exists=no_pull_requests, + )[0] + + +RUN_URL = "https://github.com/PolicyEngine/policyengine.py/actions/runs/3" +REPOSITORY = "PolicyEngine/policyengine.py" + + +def test_a_failure_opens_one_issue_for_the_country(): + script = load_script() + issues = FakeIssues( + open_issues=[{"number": 5, "title": "Model compatibility check failed: UK"}] + ) + + script.report( + make_entry(script, "us"), + outcome="failed", + failed_step="certification", + run_url=RUN_URL, + repository=REPOSITORY, + issues=issues, + ) + + created = [call for call in issues.calls if call[0] == "create"] + assert len(created) == 1 + _, repository, title, body = created[0] + assert repository == REPOSITORY + assert title == "Model compatibility check failed: US" + assert "policyengine-us 2.150.0" in body + assert "populace-us-2024-spm-20260915" in body + assert "certification" in body + assert RUN_URL in body + assert not [call for call in issues.calls if call[0] in ("comment", "close")] + + +def test_a_repeated_failure_comments_on_the_open_issue(): + script = load_script() + issues = FakeIssues( + open_issues=[{"number": 7, "title": "Model compatibility check failed: US"}] + ) + + script.report( + make_entry(script, "us", "2.151.0"), + outcome="failed", + failed_step="certification", + run_url=RUN_URL, + repository=REPOSITORY, + issues=issues, + ) + + comments = [call for call in issues.calls if call[0] == "comment"] + assert len(comments) == 1 + assert comments[0][2] == 7 + assert "policyengine-us 2.151.0" in comments[0][3] + assert RUN_URL in comments[0][3] + assert not [call for call in issues.calls if call[0] in ("create", "close")] + + +def test_a_pass_closes_the_countrys_open_issue(): + script = load_script() + issues = FakeIssues( + open_issues=[ + {"number": 7, "title": "Model compatibility check failed: US"}, + {"number": 8, "title": "Model compatibility check failed: UK"}, + ] + ) + + script.report( + make_entry(script, "us", "2.152.0"), + outcome="passed", + failed_step=None, + run_url=RUN_URL, + repository=REPOSITORY, + issues=issues, + ) + + closed = [call for call in issues.calls if call[0] == "close"] + assert len(closed) == 1 + assert closed[0][2] == 7 + assert "policyengine-us 2.152.0" in closed[0][3] + assert not [call for call in issues.calls if call[0] in ("create", "comment")] + + +def test_a_pass_with_no_open_issue_changes_nothing(): + script = load_script() + issues = FakeIssues() + + script.report( + make_entry(script, "uk", "2.180.0"), + outcome="passed", + failed_step=None, + run_url=RUN_URL, + repository=REPOSITORY, + issues=issues, + ) + + assert [call[0] for call in issues.calls] == ["list"] + + +def test_a_cancelled_run_leaves_the_issue_alone(): + script = load_script() + issues = FakeIssues( + open_issues=[{"number": 7, "title": "Model compatibility check failed: US"}] + ) + + script.report( + make_entry(script, "us"), + outcome="cancelled", + failed_step=None, + run_url=RUN_URL, + repository=REPOSITORY, + issues=issues, + ) + + assert issues.calls == [] + + +# ── The workflow file ───────────────────────────────────────────────────── + + +def test_the_uk_only_certification_workflow_is_removed(): + assert not (WORKFLOWS / "certify-uk-release.yaml").exists() + for path in WORKFLOWS.glob("*.y*ml"): + text = path.read_text() + assert "policyengine-uk-release" not in text, path.name + assert "policyengine-uk-data-release" not in text, path.name + + +def test_the_workflow_runs_on_tuesdays_and_fridays_and_by_hand(): + on = triggers(workflow()) + + assert set(on) == {"schedule", "workflow_dispatch"} + assert on["schedule"] == [{"cron": "17 6 * * 2,5"}] + inputs = on["workflow_dispatch"]["inputs"] + assert set(inputs) == {"country", "model_version"} + assert inputs["country"]["type"] == "choice" + assert inputs["country"]["options"] == ["both", "us", "uk"] + assert inputs["country"]["default"] == "both" + assert inputs["model_version"].get("required", False) is False + + +def test_the_workflow_token_only_reads_by_default(): + document = workflow() + + assert document["permissions"] == {"contents": "read"} + assert document["concurrency"]["cancel-in-progress"] is False + + +def test_waiting_runs_queue_instead_of_replacing_each_other(): + """By default a newly queued run cancels the one already waiting, so a + second manual run would drop the first, or a scheduled run.""" + + concurrency = workflow()["concurrency"] + + assert concurrency.get("queue") == "max" + assert concurrency["cancel-in-progress"] is False + + +def test_the_plan_job_passes_the_inputs_to_the_plan_command(): + plan = workflow()["jobs"]["plan"] + + assert plan["runs-on"] == "ubuntu-latest" + assert plan["permissions"] == {"contents": "read", "pull-requests": "read"} + step = step_running(plan, "scripts/compatibility_workflow.py plan") + assert step["env"]["COUNTRY"] == "${{ inputs.country || 'both' }}" + assert step["env"]["MODEL_VERSION"] == "${{ inputs.model_version }}" + assert step["env"]["GH_TOKEN"] == "${{ github.token }}" + assert '--country "$COUNTRY"' in step["run"] + assert '--model-version "$MODEL_VERSION"' in step["run"] + assert '--github-output "$GITHUB_OUTPUT"' in step["run"] + assert set(plan["outputs"]) == {"matrix", "any"} + + +def test_the_plan_job_fails_after_its_outputs_when_a_country_was_not_planned(): + plan = workflow()["jobs"]["plan"] + steps = steps_of(plan) + step = step_running(plan, "scripts/compatibility_workflow.py plan") + fail = step_named(plan, "Fail when a country could not be planned") + + assert step["id"] == "plan" + assert steps.index(step) < steps.index(fail) + assert fail["if"] == "steps.plan.outputs.unplanned != ''" + assert fail["env"]["UNPLANNED"] == "${{ steps.plan.outputs.unplanned }}" + assert "exit 1" in fail["run"] + + +def test_the_check_job_runs_once_per_planned_country(): + check = workflow()["jobs"]["check"] + + assert check["needs"] == "plan" + # Runs for the countries planned even when the plan job failed for + # another country. + assert check["if"] == "${{ !cancelled() && needs.plan.outputs.any == 'true' }}" + assert check["strategy"]["fail-fast"] is False + assert check["strategy"]["matrix"] == { + "include": "${{ fromJSON(needs.plan.outputs.matrix) }}" + } + assert check["permissions"] == {"contents": "read", "issues": "write"} + + +def test_a_check_that_runs_too_long_fails_its_step_before_the_job_limit(): + """GitHub cancels a job that reaches its own time limit, which would be + recorded as cancelled and leave the issue alone. A step that reaches its + limit fails instead, and the result and issue steps still have time.""" + + check = workflow()["jobs"]["check"] + certify = step_running(check, "scripts/bundle.py certify-build") + + step_limit = certify.get("timeout-minutes") + assert isinstance(step_limit, int), step_limit + assert step_limit <= check["timeout-minutes"] - 20 + + +def test_the_check_job_certifies_the_pinned_builds_with_the_planned_version(): + check = workflow()["jobs"]["check"] + step = step_running(check, "scripts/bundle.py certify-build") + + assert step["id"] == "certify" + assert step["env"]["HUGGING_FACE_TOKEN"] == "${{ secrets.HUGGING_FACE_TOKEN }}" + for option, variable, field in ( + ("--country", "COUNTRY", "country"), + ("--national-release", "NATIONAL_RELEASE", "national_release"), + ("--national-build", "NATIONAL_BUILD", "national_build"), + ("--local-area-release", "LOCAL_AREA_RELEASE", "local_area_release"), + ("--local-area-build", "LOCAL_AREA_BUILD", "local_area_build"), + ("--model-version", "MODEL_VERSION", "model_version"), + ): + assert step["env"][variable] == f"${{{{ matrix.{field} }}}}", variable + assert f'{option} "${variable}"' in step["run"], option + # The job commits the result itself, so certify-build only changes this + # checkout's files and writes the pull request body and the list of the + # files it changed to an empty directory. + assert "--in-place" in step["run"] + assert step["env"].get("OUTPUT_DIR") == "${{ runner.temp }}/certification" + assert '--output-dir "$OUTPUT_DIR"' in step["run"] + assert '--pr-body-footer "$FOOTER"' in step["run"] + assert "actions/runs/${{ github.run_id }}" in step["env"].get("FOOTER", "") + + +def test_no_shell_script_interpolates_a_planned_or_typed_value(): + """Inputs and matrix values reach shell scripts only through env. + + A value written into ``run`` by ``${{ }}`` becomes part of the script, so + a crafted version or build name could run commands. + """ + + for job_name, job in workflow()["jobs"].items(): + for step in steps_of(job): + script = step.get("run", "") + for source in ("inputs.", "matrix.", "github.event."): + assert "${{ " + source not in script, (job_name, step.get("name")) + + +def test_a_pass_opens_a_draft_pull_request_as_the_github_app(): + check = workflow()["jobs"]["check"] + app_token = step_named(check, "Generate GitHub App token") + checkout = next( + step + for step in steps_of(check) + if step.get("uses", "").startswith("actions/checkout@") + ) + pull_request = step_running(check, "gh pr create") + + assert app_token["uses"].startswith("actions/create-github-app-token@") + assert app_token["with"]["app-id"] == "${{ secrets.APP_ID }}" + assert app_token["with"]["private-key"] == "${{ secrets.APP_PRIVATE_KEY }}" + assert checkout["with"]["ref"] == "main" + assert pull_request["env"]["GH_TOKEN"] == "${{ steps.app-token.outputs.token }}" + assert pull_request["env"]["BRANCH"] == "${{ matrix.branch }}" + assert pull_request["id"] == "pull-request" + assert "--draft" in pull_request["run"] + assert '--head "$BRANCH"' in pull_request["run"] + assert "--base main" in pull_request["run"] + # Each run's branch is new: nothing is force-pushed over an earlier run. + assert "--force" not in pull_request["run"] + assert 'git push origin "HEAD:refs/heads/$BRANCH"' in pull_request["run"] + # Only the files certify-build says it changed are committed, and its + # pull request body is the pull request's. + assert pull_request["env"].get("OUTPUT_DIR") == "${{ runner.temp }}/certification" + assert "git add -A" not in pull_request["run"] + assert "--pathspec-from-file" in pull_request["run"] + assert ".changed-paths.txt" in pull_request["run"] + assert ".pr-body.md" in pull_request["run"] + assert '--body-file "$body"' in pull_request["run"] + # The same title certify-build gives the pull requests it opens itself. + assert ( + '--title "Certify Microcosm $label build $NATIONAL_BUILD for ' + '$MODEL_PACKAGE $MODEL_VERSION"' + ) in pull_request["run"] + + +def test_a_github_hosted_runner_frees_disk_space_before_installing(): + """The US check downloads about 11 GB and certify-build wants 5 GB more + free; a GitHub-hosted runner starts with about 14 GB.""" + + check = workflow()["jobs"]["check"] + steps = steps_of(check) + free = step_named(check, "Free disk space on a GitHub-hosted runner") + install = step_running(check, "uv sync") + + # A self-hosted runner's directories are not this job's to delete. + assert free["if"] == "runner.environment == 'github-hosted'" + for directory in ("/usr/share/dotnet", "/usr/local/lib/android", "/opt/ghc"): + assert directory in free["run"], directory + assert steps.index(free) < steps.index(install) + + +def test_the_app_token_is_made_after_certification_for_the_push_only(): + """App tokens last an hour and the check can take several, so the token is + made when the check has passed. Until then the checkout keeps no token.""" + + check = workflow()["jobs"]["check"] + steps = steps_of(check) + checkout = next( + step for step in steps if step.get("uses", "").startswith("actions/checkout@") + ) + certify = step_running(check, "scripts/bundle.py certify-build") + app_token = step_named(check, "Generate GitHub App token") + pull_request = step_running(check, "gh pr create") + script = pull_request["run"] + + # Checked out first, so the result and issue steps always have the script. + assert steps.index(checkout) == 0 + assert checkout["with"].get("persist-credentials") is False + assert "token" not in checkout["with"] + assert steps.index(certify) < steps.index(app_token) < steps.index(pull_request) + assert "gh auth setup-git" in script + assert script.index("gh auth setup-git") < script.index("git push") + + +# How GitHub runs a step that names no shell, on Linux. +GITHUB_BASH = ["bash", "-e"] +FAKE_COMMAND = """#!/bin/sh +{{ + printf '%s' '{name}' + for argument in "$@"; do printf ' [%s]' "$argument"; done + printf '\\n' +}} >> "$CALL_LOG" +if [ '{name}' = gh ] && [ "$1" = pr ] && [ "$2" = create ]; then + echo https://github.com/PolicyEngine/policyengine.py/pull/901 +fi +""" +US_BRANCH = "certify/us/populace-us-2024-spm-20260915/populace-us-2024-buildo-acs-local-766b7c7-20261017T030317Z/policyengine-us-2.150.0" + + +def run_pull_request_step(tmp_path, *, bodies=1, changed_lists=1): + """Run the pull request step's script as GitHub runs it, with stand-in + ``git`` and ``gh`` commands that log their arguments.""" + + step = step_running(workflow()["jobs"]["check"], "gh pr create") + output_dir = tmp_path / "certification" + output_dir.mkdir() + for index in range(bodies): + (output_dir / f"py{index}.pr-body.md").write_text("Body\n") + for index in range(changed_lists): + (output_dir / f"py{index}.changed-paths.txt").write_text("changelog.d/x.md\n") + commands = tmp_path / "bin" + commands.mkdir() + for name in ("git", "gh"): + command = commands / name + command.write_text(FAKE_COMMAND.format(name=name)) + command.chmod(0o755) + call_log = tmp_path / "calls.log" + github_output = tmp_path / "github_output" + github_output.write_text("") + step_script = tmp_path / "step.sh" + step_script.write_text(step["run"]) + environment = { + "PATH": f"{commands}{os.pathsep}{os.environ['PATH']}", + "CALL_LOG": str(call_log), + "GITHUB_OUTPUT": str(github_output), + "GH_TOKEN": "app-token-for-test", + "BRANCH": US_BRANCH, + "COUNTRY": "us", + "MODEL_PACKAGE": "policyengine-us", + "MODEL_VERSION": "2.150.0", + "NATIONAL_BUILD": "populace-us-2024-spm-20260915", + "OUTPUT_DIR": str(output_dir), + } + assert set(step["env"]) <= set(environment), set(step["env"]) - set(environment) + + result = subprocess.run( + [*GITHUB_BASH, str(step_script)], + env=environment, + cwd=tmp_path, + capture_output=True, + text=True, + ) + calls = call_log.read_text().splitlines() if call_log.exists() else [] + return result, calls, github_output.read_text() + + +@pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash") +def test_the_pull_request_step_commits_the_listed_files_and_pushes_as_the_app( + tmp_path, +): + result, calls, outputs = run_pull_request_step(tmp_path) + + assert result.returncode == 0, result.stderr + title = ( + "Certify Microcosm US build populace-us-2024-spm-20260915 " + "for policyengine-us 2.150.0" + ) + changed = tmp_path / "certification" / "py0.changed-paths.txt" + body = tmp_path / "certification" / "py0.pr-body.md" + assert calls == [ + f"git [switch] [-c] [{US_BRANCH}]", + f"git [add] [--pathspec-from-file={changed}]", + "git [-c] [user.name=github-actions[bot]] " + "[-c] [user.email=41898282+github-actions[bot]@users.noreply.github.com] " + f"[commit] [-q] [-m] [{title}]", + "gh [auth] [setup-git]", + f"git [push] [origin] [HEAD:refs/heads/{US_BRANCH}]", + f"gh [pr] [create] [--draft] [--base] [main] [--head] [{US_BRANCH}] " + f"[--title] [{title}] [--body-file] [{body}]", + ] + assert outputs == "url=https://github.com/PolicyEngine/policyengine.py/pull/901\n" + + +@pytest.mark.skipif(shutil.which("bash") is None, reason="needs bash") +@pytest.mark.parametrize(("bodies", "changed_lists"), [(0, 1), (2, 1), (1, 0), (1, 2)]) +def test_the_pull_request_step_needs_one_body_and_one_list_of_changed_files( + tmp_path, bodies, changed_lists +): + result, calls, outputs = run_pull_request_step( + tmp_path, bodies=bodies, changed_lists=changed_lists + ) + + assert result.returncode == 1 + assert calls == [] + assert outputs == "" + + +def test_every_run_records_and_reports_its_result(): + check = workflow()["jobs"]["check"] + record = step_running(check, "scripts/compatibility_workflow.py record") + upload = next( + step + for step in steps_of(check) + if step.get("uses", "").startswith("actions/upload-artifact@") + ) + report = step_running(check, "scripts/compatibility_workflow.py report") + + for step in (record, upload, report): + assert step["if"] == "always()", step.get("name") + assert upload["with"]["name"] == "compatibility-${{ matrix.country }}" + assert report["env"]["GH_TOKEN"] == "${{ github.token }}" + for step in (record, report): + assert step["env"]["ENTRY"] == "${{ toJSON(matrix) }}" + assert "steps.certify.outcome" in step["env"]["CERTIFY_OUTCOME"] + assert "steps.pull-request.outcome" in step["env"]["PULL_REQUEST_OUTCOME"] + # A cancelled job is recorded as cancelled, whichever step it stopped. + assert step["env"].get("JOB_STATUS") == "${{ job.status }}" + assert '--job-status "$JOB_STATUS"' in step["run"] + # The runner's own Python, in case the setup-python step failed. + assert "python3 scripts/compatibility_workflow.py" in step["run"] diff --git a/tests/test_uk_qualification_pipeline.py b/tests/test_uk_qualification_pipeline.py index ec1d58b9d..b669f1e66 100644 --- a/tests/test_uk_qualification_pipeline.py +++ b/tests/test_uk_qualification_pipeline.py @@ -2414,274 +2414,6 @@ def test_a_forced_rerun_stages_a_new_attempt(tmp_path): assert attempt_key(pair, tmp_path, base_commit=base, force=True) == f"{base[:12]}-3" -#: Source for the fake gh's REST pull request listing, embedded in the -#: workflow shell tests (they run gh in another process): `pulls(args, -#: listing)` answers `gh api -X GET repos//pulls -f head=: -#: -f base=... -f state=...` as GitHub does, keeping only pull requests from -#: that owner's branch (a fork's has another owner; an item's branch is the -#: BRANCH environment variable's unless it names another), and applies the -#: call's --jq to REST-shaped objects with the real jq. -FAKE_GH_PULLS = """ -import shutil -import subprocess - - -def pulls(args, listing): - fields = dict( - value.split("=", 1) for flag, value in zip(args, args[1:]) if flag == "-f" - ) - owner, _, branch = fields["head"].partition(":") - page = [] - for pr in listing: - pr = { - "headRefName": os.environ["BRANCH"], - "state": "OPEN", - "isDraft": True, - **pr, - } - pr_owner = "someone" if pr.get("isCrossRepository") else "PolicyEngine" - state = "open" if pr["state"] == "OPEN" else "closed" - if ( - pr_owner == owner - and pr["headRefName"] == branch - and pr["baseRefName"] == fields.get("base", pr["baseRefName"]) - and fields.get("state", "open") in ("all", state) - ): - page.append( - { - "number": pr["number"], - "state": state, - "draft": pr["isDraft"], - "base": {"ref": pr["baseRefName"]}, - "head": {"ref": pr["headRefName"]}, - } - ) - sys.stdout.write( - subprocess.run( - [shutil.which("jq"), "-r", args[args.index("--jq") + 1]], - input=json.dumps(page), - capture_output=True, - text=True, - check=True, - ).stdout - ) -""" - -#: Forks' pull requests with the candidate branch's name, newer than its own: -#: gh pr list's default listing of 30 would hold only these (round 7 of #635). -FORK_PULLS = [ - { - "number": 600 + n, - "baseRefName": "main", - "isCrossRepository": True, - "isDraft": False, - } - for n in range(40) -] - - -@pytest.mark.parametrize("step_name", ["open", "verdict"]) -@pytest.mark.parametrize("exists", [True, False]) -def test_the_workflow_writes_to_the_candidates_own_pull_request_by_number( - tmp_path, step_name, exists -): - """Round 6 of #635: the steps that open or update the candidate's pull - request find it among this repository's pull requests to main and write - by number; a fork's pull request with the branch's name, or this - repository's from the branch to another base, is never edited. With no - candidate pull request, the prepare step opens one to main and the - verdict step fails.""" - - import yaml - - assert shutil.which("jq"), "jq is required to run the workflow's jq" - workflow = yaml.safe_load( - (REPO_ROOT / ".github/workflows/certify-uk-release.yaml").read_text() - ) - job, name = { - "open": ("prepare", "Open or update the draft candidate PR"), - "verdict": ("replay", "Update the candidate PR with the verdict"), - }[step_name] - step = next(s for s in workflow["jobs"][job]["steps"] if s.get("name") == name) - log_path = tmp_path / "commands.jsonl" - listing = [ - *FORK_PULLS, - {"number": 576, "baseRefName": "release", "isCrossRepository": False}, - { - "number": 577, - "baseRefName": "main", - "isCrossRepository": False, - "state": "CLOSED", - }, - ] - if exists: - listing.append( - {"number": 574, "baseRefName": "main", "isCrossRepository": False} - ) - fake = f"""#!{sys.executable} -import json -import os -import sys -from pathlib import Path - -{FAKE_GH_PULLS} -args = sys.argv[1:] -with Path(os.environ["COMMAND_LOG"]).open("a") as log: - log.write(json.dumps(["gh", *args]) + "\\n") -if args[:1] == ["api"] and "repos/PolicyEngine/policyengine.py/pulls" in args: - pulls(args, {listing!r}) -""" - binary_dir = tmp_path / "bin" - binary_dir.mkdir() - (binary_dir / "gh").write_text(fake) - (binary_dir / "gh").chmod(0o755) - branch = "candidate/uk/2.126.8-1.58.0" - result = subprocess.run( - ["bash", "-e", "-o", "pipefail", "-c", step["run"]], - cwd=tmp_path, - env={ - **os.environ, - "PATH": f"{binary_dir}{os.pathsep}{os.environ['PATH']}", - "BRANCH": branch, - "PAIR_ID": "a" * 64, - "GITHUB_REPOSITORY": "PolicyEngine/policyengine.py", - "GITHUB_RUN_ID": "1", - "LEDGER_BRANCH": "uk-qualification-ledger", - "RUNNER_TEMP": str(tmp_path), - "COMMAND_LOG": str(log_path), - }, - capture_output=True, - text=True, - timeout=30, - ) - commands = [json.loads(line) for line in log_path.read_text().splitlines()] - writes = [c for c in commands if c[1:3] in (["pr", "edit"], ["pr", "create"])] - if exists: - assert result.returncode == 0, result.stdout + result.stderr - assert [c[:4] for c in writes] == [["gh", "pr", "edit", "574"]] - elif step_name == "open": - assert result.returncode == 0, result.stdout + result.stderr - assert len(writes) == 1 and writes[0][1:3] == ["pr", "create"] - create = writes[0] - assert create[create.index("--base") + 1] == "main" - assert create[create.index("--head") + 1] == branch - else: - assert result.returncode == 1 - assert f"no open pull request from {branch} to main" in result.stdout - assert writes == [] - - -@pytest.mark.parametrize( - ("pr_state", "reset_fails"), - [("ready", False), ("draft", False), ("absent", False), ("ready", True)], -) -def test_the_workflow_drafts_existing_prs_before_replacing_their_head( - tmp_path, pr_state, reset_fails -): - """Execute the workflow shell with local gh/git stand-ins and no remote writes.""" - - import yaml - - workflow = yaml.safe_load( - (REPO_ROOT / ".github/workflows/certify-uk-release.yaml").read_text() - ) - step = next( - step - for step in workflow["jobs"]["prepare"]["steps"] - if step.get("name") == "Commit and push the candidate commit" - ) - state_path = tmp_path / "pr-state.json" - state_path.write_text(json.dumps({"status": pr_state})) - log_path = tmp_path / "commands.jsonl" - fake = f"""#!{sys.executable} -import json -import os -import sys -from pathlib import Path - -{FAKE_GH_PULLS} -command = Path(sys.argv[0]).name -args = sys.argv[1:] -state_path = Path(os.environ["PR_STATE"]) -state = json.loads(state_path.read_text()) -with Path(os.environ["COMMAND_LOG"]).open("a") as log: - log.write(json.dumps([command, *args]) + "\\n") -if command == "gh" and args[:1] == ["api"]: - # Forty newer ready forks' pull requests with the branch's name, and one - # of this repository's from the branch to another base, are never undone - # and never hide the candidate's own (round 7 of #635). - listing = [ - *{FORK_PULLS!r}, - {{ - "number": 576, - "baseRefName": "release", - "isCrossRepository": False, - "isDraft": False, - }}, - ] - if state["status"] != "absent": - listing.append( - {{ - "number": 574, - "baseRefName": "main", - "isCrossRepository": False, - "isDraft": state["status"] != "ready", - }} - ) - pulls(args, listing) -elif command == "gh" and args[:2] == ["pr", "ready"]: - assert args[2:] == ["574", "--undo"] - if os.environ["RESET_FAILS"] == "1": - sys.exit(42) - state["status"] = "draft" - state_path.write_text(json.dumps(state)) -elif command == "git" and args[0] == "push": - if state["status"] == "ready": - sys.exit(91) -""" - binary_dir = tmp_path / "bin" - binary_dir.mkdir() - for command in ("gh", "git"): - executable = binary_dir / command - executable.write_text(fake) - executable.chmod(0o755) - result = subprocess.run( - ["bash", "-e", "-o", "pipefail", "-c", step["run"]], - cwd=tmp_path, - env={ - **os.environ, - "PATH": f"{binary_dir}{os.pathsep}{os.environ['PATH']}", - "BRANCH": "candidate/uk/2.126.8-1.58.0", - "PAIR_ID": "a" * 64, - "GITHUB_REPOSITORY": "PolicyEngine/policyengine.py", - "GH_TOKEN": "local-workflow-test", - "PR_STATE": str(state_path), - "COMMAND_LOG": str(log_path), - "RESET_FAILS": "1" if reset_fails else "0", - }, - capture_output=True, - text=True, - timeout=30, - ) - commands = [json.loads(line) for line in log_path.read_text().splitlines()] - pushes = [i for i, command in enumerate(commands) if command[:2] == ["git", "push"]] - resets = [ - i for i, command in enumerate(commands) if command[:3] == ["gh", "pr", "ready"] - ] - if reset_fails: - assert result.returncode == 42, result.stdout + result.stderr - assert not pushes - else: - assert result.returncode == 0, result.stdout + result.stderr - assert len(pushes) == 1 - if pr_state == "ready": - assert len(resets) == 1 and resets[0] < pushes[0] - assert json.loads(state_path.read_text())["status"] == "draft" - else: - assert not resets - assert step["env"]["GH_TOKEN"] == "${{ steps.app-token.outputs.token }}" - - # --- Attempt lifecycle ----------------------------------------------------------------- diff --git a/tests/test_uk_qualification_workflow.py b/tests/test_uk_qualification_workflow.py index f3ad4568a..cccf8697c 100644 --- a/tests/test_uk_qualification_workflow.py +++ b/tests/test_uk_qualification_workflow.py @@ -1,22 +1,20 @@ -"""Qualification workflow readiness and failed-check refresh (no remote writes).""" +"""``scripts/check_uk_candidate.py``'s readiness and failed-check refresh (no remote writes). + +The ``certify-uk-release.yaml`` workflow that ran these commands is removed; +the tests of its YAML went with it. +""" from __future__ import annotations import argparse import json -import os -import subprocess -import sys -from pathlib import Path from types import SimpleNamespace import pytest -import yaml from policyengine.provenance.uk_qualification import ( accept_review, candidate_branch, - previous_certificate, ) from tests.qualification_fixtures import ( HARNESS, @@ -30,158 +28,11 @@ PULLS = ["repos/PolicyEngine/policyengine.py/pulls"] -REPO_ROOT = Path(__file__).resolve().parents[1] -WORKFLOW_PATH = REPO_ROOT / ".github/workflows/certify-uk-release.yaml" - def _cli(): return load_candidate_cli("qualification_workflow_cli") -def _workflow(): - return yaml.safe_load(WORKFLOW_PATH.read_text()) - - -def test_resolution_can_authenticate_the_staged_attempt_owner_lookup(): - resolve = _workflow()["jobs"]["resolve"] - assert resolve["permissions"]["contents"] == "read" - assert resolve["permissions"]["actions"] == "read" - step = next( - step - for step in resolve["steps"] - if step.get("name") == "Resolve and deduplicate the candidate" - ) - assert step["env"]["GH_TOKEN"] == "${{ github.token }}" - - -def test_every_uv_step_runs_the_environment_its_job_installed(): - """The repository's .python-version asks for a newer Python than the 3.13 - environment each job installs. A syncing `uv run` would replace that - environment, extras and all, so every step and the ledger re-derivation - must run the interpreter the job provisioned.""" - workflow = _workflow() - assert (REPO_ROOT / ".python-version").read_text().strip() != ( - workflow["env"]["PYTHON_VERSION"] - ) - assert workflow["env"]["UV_PYTHON"] == workflow["env"]["PYTHON_VERSION"] - command = "${{ github.workspace }}/scripts/check_uk_candidate.py rederive-ledger" - publishing_jobs = [] - for name, job in workflow["jobs"].items(): - runs = [step.get("run", "") for step in job["steps"]] - synced = any( - "uv sync --frozen --extra uk --extra dev --python " - "${{ env.PYTHON_VERSION }}" in run - for run in runs - ) - system = any("uv pip install --system" in run for run in runs) - assert not (synced and system), name - for line in (line for run in runs for line in run.splitlines()): - if "uv run" in line: - assert synced, (name, line) - assert "uv run --no-sync " in line, (name, line) - if any(".github/qualification-ledger.sh publish" in run for run in runs): - publishing_jobs.append(name) - rederive = job.get("env", {}).get( - "LEDGER_REDERIVE", workflow["env"]["LEDGER_REDERIVE"] - ) - if synced: - interpreter = "${{ github.workspace }}/.venv/bin/python" - else: - assert system, name - interpreter = "python" - assert rederive == f"{interpreter} {command}", name - assert sorted(publishing_jobs) == [ - "accept", - "catch-up", - "prepare", - "qualify", - "replay", - ] - - -def test_catch_up_requalifies_a_stale_target_after_finishing_receipts(): - """The requalification dispatch runs without force, after waiting - receipts are finished and published, so it reads the newest ledger.""" - - job = _workflow()["jobs"]["catch-up"] - runs = [step.get("run", "") for step in job["steps"]] - requalify = next( - index - for index, run in enumerate(runs) - if "check_uk_candidate.py requalify" in run - ) - published = next( - index - for index, run in enumerate(runs) - if "qualification-ledger.sh publish" in run - ) - assert published < requalify - assert '"-f", "force=false"' in runs[requalify] - assert "force=true" not in runs[requalify] - assert job["steps"][requalify]["env"]["GH_TOKEN"] == "${{ github.token }}" - assert job["permissions"]["actions"] == "write" - - -def test_every_dispatch_names_the_exact_pair(): - """Recovery and requalification dispatch one pair: its versions, its core - and its id, which resolve checks, so another pair is never qualified in - its place.""" - - workflow = _workflow() - triggers = workflow[True] - assert set(triggers) == {"workflow_dispatch"} - inputs = triggers["workflow_dispatch"]["inputs"] - assert {"core_version", "pair_id"} <= set(inputs) - resolve = next( - step - for step in workflow["jobs"]["resolve"]["steps"] - if step.get("name") == "Resolve and deduplicate the candidate" - ) - assert '--core-version "$INPUT_CORE"' in resolve["run"] - assert '--pair-id "$INPUT_PAIR_ID"' in resolve["run"] - dispatches = [ - step["run"] - for step in workflow["jobs"]["catch-up"]["steps"] - if 'gh", "workflow", "run' in step.get("run", "") - or '"gh", "workflow", "run"' in step.get("run", "") - ] - assert len(dispatches) == 2 - for run in dispatches: - assert "core_version={pair['core']['version']}" in run - assert "pair_id={pair_id}" in run - assert 'entry["pair_id"]' in run - - -def test_preparation_rechecks_eligibility_and_tests_the_candidates_own_tree(): - """Round 2 of #635: under the preparation lock, a run whose pair another - run is already qualifying (from any main commit) stops; and the - code-changes workflow runs on the candidate branch itself, the tree - promotion would put on main.""" - - job = _workflow()["jobs"]["prepare"] - steps = job["steps"] - names = [step.get("name") for step in steps] - duplicate = steps[names.index("Check for an attempt staged by another run")] - assert "check_uk_candidate.py still-eligible" in duplicate["run"] - # It asks gh whether an earlier attempt's run failed (round 3 of #635). - assert duplicate["env"]["GH_TOKEN"] == "${{ github.token }}" - assert names.index("Install the base environment") < names.index( - "Check for an attempt staged by another run" - ) - own_tree = steps[names.index("Test the candidate commit's own tree")] - assert own_tree["run"].startswith("gh workflow run pr_code_changes.yaml") - assert '--ref "$BRANCH"' in own_tree["run"] - assert own_tree["env"]["GH_TOKEN"] == "${{ github.token }}" - assert names.index("Commit and push the candidate commit") < names.index( - "Test the candidate commit's own tree" - ) - assert job["permissions"]["actions"] == "write" - triggers = yaml.safe_load( - (REPO_ROOT / ".github/workflows/pr_code_changes.yaml").read_text() - )[True] - assert "workflow_dispatch" in triggers - - def test_still_eligible_reports_a_pair_another_run_is_qualifying(monkeypatch, tmp_path): from policyengine.provenance.qualification_ledger import attempt_directory from policyengine.provenance.uk_qualification import stage_attempt @@ -222,279 +73,6 @@ def test_still_eligible_reports_a_pair_another_run_is_qualifying(monkeypatch, tm assert outputs[-1] == {"duplicate": "false"} -def test_preparation_syncs_the_candidate_lock_before_using_it(): - """Snapshots, the bundle check and staging must run in the candidate's - environment: synced from the lock preparation regenerates, after it is - regenerated, with the 3.13 interpreter and both extras.""" - - steps = _workflow()["jobs"]["prepare"]["steps"] - runs = [step.get("run", "") for step in steps] - sync = "uv sync --frozen --extra uk --extra dev --python ${{ env.PYTHON_VERSION }}" - - def position(text): - return next(index for index, run in enumerate(runs) if text in run) - - syncs = [index for index, run in enumerate(runs) if sync in run] - regenerate = position("check_uk_candidate.py prepare") - assert len(syncs) == 2 and syncs[0] < regenerate < syncs[1] - for later in ( - "tests/test_household_calculator_snapshot.py", - "scripts/bundle.py check", - "check_uk_candidate.py stage", - ): - assert syncs[1] < position(later), later - - -@pytest.mark.parametrize("prepare_first", [False, True]) -def test_head_replacement_and_readiness_share_one_serialization( - monkeypatch, tmp_path, prepare_first -): - """Replay a branch replacement after the real promotion's head snapshot. - - The scheduler's locks come from the workflow, and preparation executes its - actual draft-and-push shell with command stand-ins. Different lock groups - allow the reviewer's failing interleaving; one shared group defers it. - """ - - cli = _cli() - workflow = _workflow() - jobs = workflow["jobs"] - bundle = json.loads(cli.BUNDLE_PATH.read_text()) - qualified = make_receipt( - pair=make_pair( - model="2.200.0", - data=bundle["data_releases"]["uk"]["data_package"]["version"], - core=bundle["packages"]["policyengine-core"]["version"], - ) - ).model_copy(update={"previous_certificate": previous_certificate(bundle)}) - branch = candidate_branch(qualified.pair) - state_path = tmp_path / "state.json" - state_path.write_text( - json.dumps({"status": "ready", "head": qualified.harness.git_commit}) - ) - new_head = "f" * 40 - binary_dir = tmp_path / "bin" - binary_dir.mkdir() - fake = f"""#!{sys.executable} -import json, os, sys -from pathlib import Path -path = Path(os.environ["PR_STATE"]) -state = json.loads(path.read_text()) -command, args = Path(sys.argv[0]).name, sys.argv[1:] -if command == "gh" and args[:1] == ["api"] and "--paginate" in args: - # The REST listing of this repository's pull request to main, through - # the step's jq (only a ready one's number is printed). - if state["status"] == "ready": - print("574") -elif command == "gh" and args[:2] == ["pr", "ready"]: - assert args[2:] == ["574", "--undo"] - state["status"] = "draft" - path.write_text(json.dumps(state)) -elif command == "git" and args[0] == "push": - assert state["status"] == "draft" - state["head"] = {new_head!r} - path.write_text(json.dumps(state)) -""" - for command in ("gh", "git"): - executable = binary_dir / command - executable.write_text(fake) - executable.chmod(0o755) - push_step = next( - step - for step in jobs["prepare"]["steps"] - if step.get("name") == "Commit and push the candidate commit" - ) - groups = { - job: jobs[job]["concurrency"]["group"].replace( - "${{ needs.resolve.outputs.pair_id }}", qualified.pair_id - ) - for job in ("prepare", "promote") - } - running = set() - deferred = [] - ready_heads = [] - - def prepare(): - subprocess.run( - ["bash", "-e", "-o", "pipefail", "-c", push_step["run"]], - cwd=tmp_path, - env={ - **os.environ, - "PATH": f"{binary_dir}{os.pathsep}{os.environ['PATH']}", - "BRANCH": branch, - "PAIR_ID": qualified.pair_id, - "PR_STATE": str(state_path), - "GITHUB_REPOSITORY": "PolicyEngine/policyengine.py", - }, - check=True, - capture_output=True, - timeout=30, - ) - - def schedule(job, operation): - if groups[job] in running: - deferred.append((job, operation)) - return - running.add(groups[job]) - try: - operation() - finally: - running.remove(groups[job]) - - def fake_run(argv, **kwargs): - if argv[:3] == ["gh", "pr", "list"]: - state = json.loads(state_path.read_text()) - return SimpleNamespace( - stdout=json.dumps( - [ - { - "number": 1, - "headRefName": branch, - "headRefOid": state["head"], - "isDraft": state["status"] != "ready", - "isCrossRepository": False, - "baseRefName": "main", - } - ] - ) - ) - # Promotion reads the branch head and checks main is its parent. - if argv[:2] == ["git", "fetch"]: - return SimpleNamespace(returncode=0, stdout="") - if argv[:3] == ["git", "rev-parse", "FETCH_HEAD"]: - head = json.loads(state_path.read_text())["head"] - return SimpleNamespace(returncode=0, stdout=head) - if argv[:2] == ["git", "rev-parse"]: - return SimpleNamespace(returncode=0, stdout="p" * 40) - if argv[:2] == ["git", "ls-remote"]: - return SimpleNamespace(returncode=0, stdout="p" * 40 + "\trefs/heads/main") - assert argv[:3] == ["gh", "pr", "ready"] - if "--undo" in argv: - return SimpleNamespace(returncode=0) - if not prepare_first: - schedule("prepare", prepare) - state = json.loads(state_path.read_text()) - ready_heads.append(state["head"]) - state["status"] = "ready" - state_path.write_text(json.dumps(state)) - return SimpleNamespace(returncode=0) - - monkeypatch.setattr(cli, "latest_receipts", lambda root, **_: [qualified]) - monkeypatch.setattr(cli, "subprocess", SimpleNamespace(run=fake_run)) - monkeypatch.setattr(cli, "config", lambda: {"promotion": {"automatic": False}}) - if prepare_first: - schedule("prepare", prepare) - schedule( - "promote", - lambda: cli.cmd_promote(argparse.Namespace(ledger=str(tmp_path), apply=True)), - ) - for job, operation in deferred: - schedule(job, operation) - assert all(head == qualified.harness.git_commit for head in ready_heads) - assert json.loads(state_path.read_text()) == {"status": "draft", "head": new_head} - assert jobs["prepare"]["concurrency"]["cancel-in-progress"] is False - assert jobs["promote"]["concurrency"]["cancel-in-progress"] is False - - -@pytest.mark.parametrize("job", ["replay", "catch-up", "accept"]) -def test_workflow_refreshes_failed_checks_after_publishing_receipts(job): - workflow = _workflow() - configured = workflow["jobs"][job] - refresh = next( - step - for step in configured["steps"] - if "refresh-pr-checks" in step.get("run", "") - ) - assert configured["permissions"]["actions"] == "write" - assert refresh["env"]["GH_TOKEN"] == "${{ github.token }}" - steps = configured["steps"] - publish_positions = [ - index - for index, step in enumerate(steps) - if ".github/qualification-ledger.sh publish" in step.get("run", "") - ] - assert publish_positions - assert max(publish_positions) < steps.index(refresh) - - -def test_catch_up_dispatches_recovery_for_the_original_pair(tmp_path): - workflow = _workflow() - job = workflow["jobs"]["catch-up"] - step = next( - step for step in job["steps"] if "recoverable --ledger" in step.get("run", "") - ) - pair = make_pair(model="2.200.0", data="1.58.9") - candidate_path = tmp_path / "candidate.json" - candidate_path.write_text( - json.dumps({"pair": pair.canonical_payload(), "pair_id": pair.pair_id}) - ) - command_log = tmp_path / "commands.jsonl" - binary_dir = tmp_path / "bin" - binary_dir.mkdir() - fake = f"""#!{sys.executable} -import json, os, sys -from pathlib import Path -command, args = Path(sys.argv[0]).name, sys.argv[1:] -if command == "python": - if args == ["scripts/check_uk_candidate.py", "recoverable", "--ledger", "ledger"]: - assert Path("ledger").is_dir() - print(Path(os.environ["RECOVERY_CANDIDATE"]).read_text()) - else: - assert args == ["-"] - os.execv(sys.executable, [sys.executable, *args]) -else: - assert command == "gh" - assert Path("ledger").is_dir() - with Path(os.environ["COMMAND_LOG"]).open("a") as stream: - stream.write(json.dumps(args) + "\\n") -""" - for command in ("python", "gh"): - executable = binary_dir / command - executable.write_text(fake) - executable.chmod(0o755) - ledger_script = tmp_path / ".github" / "qualification-ledger.sh" - ledger_script.parent.mkdir() - ledger_script.write_text("#!/bin/bash\nset -e\nmkdir ledger\n") - ledger_script.chmod(0o755) - subprocess.run( - ["bash", "-e", "-o", "pipefail", "-c", step["run"]], - cwd=tmp_path, - env={ - **os.environ, - "PATH": f"{binary_dir}{os.pathsep}{os.environ['PATH']}", - "RECOVERY_CANDIDATE": str(candidate_path), - "COMMAND_LOG": str(command_log), - "GITHUB_REPOSITORY": "PolicyEngine/policyengine.py", - }, - check=True, - capture_output=True, - timeout=30, - ) - assert [json.loads(line) for line in command_log.read_text().splitlines()] == [ - [ - "workflow", - "run", - "certify-uk-release.yaml", - "--repo", - "PolicyEngine/policyengine.py", - "--ref", - "main", - "-f", - "model_version=2.200.0", - "-f", - "data_version=1.58.9", - "-f", - f"core_version={pair.core.version}", - "-f", - f"pair_id={pair.pair_id}", - "-f", - "force=false", - ] - ] - assert job["permissions"]["actions"] == "write" - assert step["env"]["GH_TOKEN"] == "${{ github.token }}" - - @pytest.mark.parametrize("head_matches", [False, True]) @pytest.mark.parametrize("verdict", ["qualified", "rejected", "accepted_review"]) def test_refresh_checks_reruns_only_failed_pr_runs_for_the_qualified_head( @@ -791,25 +369,3 @@ def fake_run(argv, **kwargs): else "#1 (the candidate's own, after a base change)" ) in output assert [call[3] for call in calls if call[:3] == ["gh", "run", "rerun"]] == ["32"] - - -def test_manual_qualification_documents_dormant_schedule_recovery(): - root = Path(__file__).resolve().parents[1] - source = (root / ".github/workflows/certify-uk-release.yaml").read_text() - workflow = yaml.safe_load(source) - assert set(workflow.get("on", workflow.get(True))) == {"workflow_dispatch"} - assert workflow["jobs"]["catch-up"]["if"] == "github.event_name == 'schedule'" - assert "Intentionally dormant while workflow_dispatch is the only trigger" in source - assert ( - sum( - '"gh", "workflow", "run", "certify-uk-release.yaml"' in step.get("run", "") - for step in workflow["jobs"]["catch-up"]["steps"] - ) - == 2 - ) - assert any( - "gh workflow run pr_code_changes.yaml" in step.get("run", "") - for step in workflow["jobs"]["prepare"]["steps"] - ) - runbook = (root / "docs/engineering/runbooks/uk-qualification.md").read_text() - assert "Scheduled recovery and requalification are disabled." in runbook