diff --git a/.github/workflows/promote-stable.yml b/.github/workflows/promote-stable.yml index ddc788263..2d7a151fe 100644 --- a/.github/workflows/promote-stable.yml +++ b/.github/workflows/promote-stable.yml @@ -5,6 +5,14 @@ on: workflow_run: workflows: [SkillEvaluator release published] types: [completed] + workflow_call: + inputs: + expected-release: + type: string + required: true + secrets: + STABLE_CHANNEL_APP_PRIVATE_KEY: + required: true workflow_dispatch: inputs: expected-release: @@ -16,25 +24,28 @@ on: type: string required: false -concurrency: - group: skillevaluator-stable - cancel-in-progress: false - queue: max - permissions: {} jobs: promote: - # Accept only the relay's release event for automatic promotion. + # Reusable workflows use the caller's workflow identity. if: >- github.repository == 'NVIDIA/SkillEvaluator' && github.ref == 'refs/heads/main' && - (github.event_name == 'workflow_dispatch' || - (github.event.workflow_run.event == 'release' && + ((github.event_name == 'workflow_dispatch' && + (github.workflow_ref == 'NVIDIA/SkillEvaluator/.github/workflows/promote-stable.yml@refs/heads/main' || + github.workflow_ref == 'NVIDIA/SkillEvaluator/.github/workflows/release.yml@refs/heads/main')) || + (github.event_name == 'workflow_run' && + github.workflow_ref == 'NVIDIA/SkillEvaluator/.github/workflows/promote-stable.yml@refs/heads/main' && + github.event.workflow_run.event == 'release' && github.event.workflow_run.conclusion == 'success')) runs-on: ubuntu-24.04 timeout-minutes: 10 environment: stable-channel + concurrency: + group: skillevaluator-stable + cancel-in-progress: false + queue: max permissions: contents: read steps: diff --git a/.github/workflows/release-tier1-image.yml b/.github/workflows/release-tier1-image.yml index 244778550..e89d7cd6f 100644 --- a/.github/workflows/release-tier1-image.yml +++ b/.github/workflows/release-tier1-image.yml @@ -19,6 +19,12 @@ on: bundle_artifact: description: Artifact containing the bundle and packaged descriptors value: ${{ jobs.onboarding.outputs.bundle_artifact }} + bundle_artifact_id: + description: Numeric artifact ID for the exact generated bundle + value: ${{ jobs.onboarding.outputs.bundle_artifact_id }} + bundle_artifact_digest: + description: SHA-256 digest of the generated bundle artifact archive + value: ${{ jobs.onboarding.outputs.bundle_artifact_digest }} permissions: {} @@ -132,6 +138,8 @@ jobs: outputs: image_digest: ${{ needs.publish.outputs.image_digest }} bundle_artifact: ${{ steps.bundle.outputs.artifact }} + bundle_artifact_id: ${{ steps.retained.outputs.artifact-id }} + bundle_artifact_digest: ${{ steps.retained.outputs.artifact-digest }} env: VERSION: ${{ inputs.version }} SOURCE_SHA: ${{ inputs.source_sha }} @@ -168,6 +176,7 @@ jobs: path: ${{ runner.temp }}/public-image-verification retention-days: 30 - name: Upload pinned bundle and consumers + id: retained uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: ci-bundle-${{ inputs.version }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1ac0b99cd..e132f34fa 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -9,7 +9,7 @@ on: required: true type: string source_sha: - description: Full upstream main SHA of the version PR (image) or bundle PR (validation and publication) + description: Full main SHA of the version PR (image/full release) or bundle PR (validation/publication) required: true type: string phase: @@ -18,8 +18,14 @@ on: default: Validate release options: - Validate release + - Validate and publish + - Full release - Build CI image and bundle - Publish release + promote_stable: + description: Promote this release after verification if it is GitHub Latest (publishing phases only) + type: boolean + default: false validation_run: description: Run ID and attempt from the successful Validate release summary (e.g. 123-1) type: string @@ -59,14 +65,41 @@ jobs: VERSION: ${{ inputs.version }} SOURCE_SHA: ${{ inputs.source_sha }} PHASE: ${{ inputs.phase }} + PROMOTE_STABLE: ${{ inputs.promote_stable }} run: | + if [[ "$PROMOTE_STABLE" == 'true' && "$PHASE" != 'Full release' && + "$PHASE" != 'Validate and publish' && "$PHASE" != 'Publish release' ]]; then + echo 'Stable promotion requires Full release, Validate and publish, or Publish release.' >&2 + exit 1 + fi python3 ci/github_release.py preflight --version "$VERSION" --source-sha "$SOURCE_SHA" \ --main-sha "$GITHUB_SHA" --phase "$PHASE" printf 'version=%s\nsource_sha=%s\n' "$VERSION" "$SOURCE_SHA" >> "$GITHUB_OUTPUT" - image: + bundle-configuration: needs: preflight - if: inputs.phase == 'Build CI image and bundle' + if: inputs.phase == 'Full release' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + environment: release-bundle-pr + permissions: {} + steps: + - name: Check bundle PR App configuration before building the image + env: + APP_CLIENT_ID: ${{ vars.RELEASE_BUNDLE_APP_CLIENT_ID }} + APP_PRIVATE_KEY: ${{ secrets.RELEASE_BUNDLE_APP_PRIVATE_KEY }} + run: | + if [[ -z "$APP_CLIENT_ID" || -z "$APP_PRIVATE_KEY" ]]; then + echo "Configure the bundle PR GitHub App in the release-bundle-pr environment." >&2 + exit 1 + fi + + image: + needs: [preflight, bundle-configuration] + if: >- + !cancelled() && needs.preflight.result == 'success' && + (inputs.phase == 'Build CI image and bundle' || + (inputs.phase == 'Full release' && needs.bundle-configuration.result == 'success')) uses: ./.github/workflows/release-tier1-image.yml permissions: contents: read @@ -75,9 +108,128 @@ jobs: version: ${{ needs.preflight.outputs.version }} source_sha: ${{ needs.preflight.outputs.source_sha }} + bundle-pr: + needs: [preflight, image] + if: inputs.phase == 'Full release' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + environment: release-bundle-pr + permissions: + actions: read + contents: read + outputs: + number: ${{ steps.pin.outputs.number }} + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.workflow_sha }} + fetch-depth: 0 + persist-credentials: false + - name: Verify and extract the exact generated bundle + env: + GH_TOKEN: ${{ github.token }} + ARTIFACT_ID: ${{ needs.image.outputs.bundle_artifact_id }} + ARTIFACT_DIGEST: ${{ needs.image.outputs.bundle_artifact_digest }} + run: | + archive="$RUNNER_TEMP/ci-bundle.zip" + digest="${ARTIFACT_DIGEST#sha256:}" + if [[ ! "$ARTIFACT_ID" =~ ^[1-9][0-9]*$ || ! "$digest" =~ ^[0-9a-f]{64}$ ]]; then + echo "The image job did not provide a valid bundle artifact ID and digest." >&2 + exit 1 + fi + gh api "repos/$GITHUB_REPOSITORY/actions/artifacts/$ARTIFACT_ID/zip" > "$archive" + printf '%s %s\n' "$digest" "$archive" | sha256sum --check --status + python3 -m zipfile -e "$archive" "$RUNNER_TEMP/ci-bundle" + - name: Create the bundle PR writer token + id: writer + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 + with: + client-id: ${{ vars.RELEASE_BUNDLE_APP_CLIENT_ID }} + private-key: ${{ secrets.RELEASE_BUNDLE_APP_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + permission-workflows: write + - name: Open or reuse the generated bundle PR + id: pin + env: + GH_TOKEN: ${{ steps.writer.outputs.token }} + RELEASE_BUNDLE_APP_SLUG: ${{ steps.writer.outputs.app-slug }} + VERSION: ${{ needs.preflight.outputs.version }} + CANDIDATE_SHA: ${{ needs.preflight.outputs.source_sha }} + IMAGE_DIGEST: ${{ needs.image.outputs.image_digest }} + run: | + pr="$(python3 ci/release_pin_pr.py open --version "$VERSION" --source-sha "$CANDIDATE_SHA" \ + --image "$IMAGE_DIGEST" --bundle "$RUNNER_TEMP/ci-bundle")" + printf 'number=%s\n' "$pr" >> "$GITHUB_OUTPUT" + printf 'Review and merge [the generated bundle PR](%s/%s/pull/%s) to continue.\n' \ + "$GITHUB_SERVER_URL" "$GITHUB_REPOSITORY" "$pr" >> "$GITHUB_STEP_SUMMARY" + + bundle-merge: + needs: [preflight, image, bundle-pr] + if: inputs.phase == 'Full release' + runs-on: ubuntu-24.04 + timeout-minutes: 125 + permissions: + contents: read + pull-requests: read + outputs: + source_sha: ${{ steps.reviewed.outputs.source_sha }} + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.workflow_sha }} + fetch-depth: 0 + persist-credentials: false + - name: Wait for the bundle PR and verify its exact merge commit + id: reviewed + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ needs.preflight.outputs.version }} + CANDIDATE_SHA: ${{ needs.preflight.outputs.source_sha }} + IMAGE_DIGEST: ${{ needs.image.outputs.image_digest }} + PR: ${{ needs.bundle-pr.outputs.number }} + run: | + source_sha="$(python3 ci/release_pin_pr.py wait --version "$VERSION" --source-sha "$CANDIDATE_SHA" \ + --image "$IMAGE_DIGEST" --pr "$PR")" + python3 ci/github_release.py preflight --version "$VERSION" --source-sha "$source_sha" \ + --main-sha "$(git rev-parse origin/main)" --phase 'Publish release' + printf 'source_sha=%s\n' "$source_sha" >> "$GITHUB_OUTPUT" + + release-source: + needs: [preflight, bundle-merge] + if: >- + !cancelled() && needs.preflight.result == 'success' && + ((inputs.phase == 'Full release' && needs.bundle-merge.result == 'success') || + (inputs.phase != 'Full release' && inputs.phase != 'Build CI image and bundle')) + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: {} + outputs: + version: ${{ needs.preflight.outputs.version }} + source_sha: ${{ steps.source.outputs.sha }} + steps: + - name: Select the reviewed product release commit + id: source + env: + PHASE: ${{ inputs.phase }} + CANDIDATE_SHA: ${{ needs.preflight.outputs.source_sha }} + MERGED_SHA: ${{ needs.bundle-merge.outputs.source_sha }} + run: | + source_sha="$CANDIDATE_SHA" + if [[ "$PHASE" == 'Full release' ]]; then + source_sha="$MERGED_SHA" + fi + if [[ ! "$source_sha" =~ ^[0-9a-f]{40}$ ]]; then + echo "The workflow did not identify the reviewed release commit." >&2 + exit 1 + fi + printf 'sha=%s\n' "$source_sha" >> "$GITHUB_OUTPUT" + prepare: - needs: preflight - if: inputs.phase == 'Validate release' + needs: release-source + if: >- + !cancelled() && needs.release-source.result == 'success' && + (inputs.phase == 'Validate release' || inputs.phase == 'Validate and publish' || inputs.phase == 'Full release') runs-on: ubuntu-24.04 timeout-minutes: 35 defaults: @@ -87,12 +239,17 @@ jobs: actions: read contents: read env: - VERSION: ${{ needs.preflight.outputs.version }} - SOURCE_SHA: ${{ needs.preflight.outputs.source_sha }} + VERSION: ${{ needs.release-source.outputs.version }} + SOURCE_SHA: ${{ needs.release-source.outputs.source_sha }} + outputs: + run: ${{ steps.artifact.outputs.run }} + artifact_id: ${{ steps.retained.outputs.artifact-id }} + artifact_digest: ${{ steps.retained.outputs.artifact-digest }} + manifest_sha256: ${{ steps.verified.outputs.manifest_sha256 }} steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: - ref: ${{ needs.preflight.outputs.source_sha }} + ref: ${{ needs.release-source.outputs.source_sha }} path: source fetch-depth: 0 persist-credentials: false @@ -136,6 +293,7 @@ jobs: python3 ../release-control/ci/github_release.py verify-release-metadata --version "$VERSION" \ --source-sha "$SOURCE_SHA" --assets "$RUNNER_TEMP/product-release" - name: Check that the package indexes can accept these release bytes + if: inputs.phase == 'Validate release' || steps.restore.outputs.restored == 'false' run: | python3 ci/product_release.py inspect-indexes --version "$VERSION" --assets "$RUNNER_TEMP/product-release" - name: Smoke-test fresh wheel and sdist installations @@ -158,29 +316,42 @@ jobs: run="$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" printf 'name=validated-release-%s-%s\nrun=%s\n' "$VERSION" "$run" "$run" >> "$GITHUB_OUTPUT" - name: Retain the reviewed release bytes + id: retained uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: ${{ steps.artifact.outputs.name }} path: ${{ runner.temp }}/product-release if-no-files-found: error retention-days: 90 - - name: Record the Publish release inputs + - name: Record the validated release artifact env: + PHASE: ${{ inputs.phase }} VALIDATION_RUN: ${{ steps.artifact.outputs.run }} + VALIDATION_ARTIFACT_ID: ${{ steps.retained.outputs.artifact-id }} MANIFEST_SHA256: ${{ steps.verified.outputs.manifest_sha256 }} run: | { - printf '### Publish release inputs\n\n' - printf '| Input | Value |\n| --- | --- |\n' + if [[ "$PHASE" == 'Validate release' ]]; then + printf '### Publish release inputs\n\n| Input | Value |\n| --- | --- |\n' + else + printf '### Validated release artifacts\n\n| Field | Value |\n| --- | --- |\n' + fi printf '| `version` | `%s` |\n' "$VERSION" printf '| `source_sha` | `%s` |\n' "$SOURCE_SHA" printf '| `validation_run` | `%s` |\n' "$VALIDATION_RUN" printf '| `validation_manifest_sha256` | `%s` |\n' "$MANIFEST_SHA256" + if [[ "$PHASE" != 'Validate release' ]]; then + printf '| Validation artifact ID | `%s` |\n' "$VALIDATION_ARTIFACT_ID" + fi } >> "$GITHUB_STEP_SUMMARY" stage: - needs: preflight - if: inputs.phase == 'Publish release' + needs: [release-source, prepare] + if: >- + !cancelled() && needs.release-source.result == 'success' && + ((inputs.phase == 'Publish release' && needs.prepare.result == 'skipped') || + ((inputs.phase == 'Validate and publish' || inputs.phase == 'Full release') && + needs.prepare.result == 'success')) runs-on: ubuntu-24.04 timeout-minutes: 15 environment: release-github @@ -194,8 +365,8 @@ jobs: artifact: ${{ steps.public.outputs.artifact }} manifest_sha256: ${{ steps.public.outputs.manifest_sha256 }} env: - VERSION: ${{ needs.preflight.outputs.version }} - SOURCE_SHA: ${{ needs.preflight.outputs.source_sha }} + VERSION: ${{ needs.release-source.outputs.version }} + SOURCE_SHA: ${{ needs.release-source.outputs.source_sha }} steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: @@ -204,7 +375,7 @@ jobs: persist-credentials: false - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: - ref: ${{ needs.preflight.outputs.source_sha }} + ref: ${{ needs.release-source.outputs.source_sha }} path: source fetch-depth: 0 persist-credentials: false @@ -212,14 +383,22 @@ jobs: id: acquire env: GH_TOKEN: ${{ github.token }} - VALIDATION_RUN: ${{ inputs.validation_run }} - MANIFEST_SHA256: ${{ inputs.validation_manifest_sha256 }} + PHASE: ${{ inputs.phase }} + VALIDATION_RUN: ${{ inputs.phase == 'Publish release' && inputs.validation_run || needs.prepare.outputs.run }} + MANIFEST_SHA256: ${{ inputs.phase == 'Publish release' && inputs.validation_manifest_sha256 || needs.prepare.outputs.manifest_sha256 }} + VALIDATION_ARTIFACT_ID: ${{ needs.prepare.outputs.artifact_id }} + VALIDATION_ARTIFACT_DIGEST: ${{ needs.prepare.outputs.artifact_digest }} run: | # A draft can be invisible to read-only tokens. Check after approval. # Use the workflow checkout because an older reviewed source may predate the acquire command. + artifact_args=() + if [[ "$PHASE" != 'Publish release' ]]; then + artifact_args=(--validation-artifact-id "$VALIDATION_ARTIFACT_ID" \ + --validation-artifact-digest "$VALIDATION_ARTIFACT_DIGEST") + fi new_release="$(python3 ../release-control/ci/github_release.py acquire --version "$VERSION" \ - --source-sha "$SOURCE_SHA" --assets "$RUNNER_TEMP/staged-release" \ - --validation-run "$VALIDATION_RUN" --validation-manifest-sha256 "$MANIFEST_SHA256")" + --source-sha "$SOURCE_SHA" --assets "$RUNNER_TEMP/staged-release" --phase "$PHASE" \ + --validation-run "$VALIDATION_RUN" --validation-manifest-sha256 "$MANIFEST_SHA256" "${artifact_args[@]}")" run="$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" printf 'new_release=%s\nname=product-release-%s-%s\nrun=%s\n' \ "$new_release" "$VERSION" "$run" "$run" >> "$GITHUB_OUTPUT" @@ -256,30 +435,34 @@ jobs: retention-days: 90 kitmaker: - needs: [preflight, stage] + needs: [release-source, stage] + if: ${{ !cancelled() && needs.release-source.result == 'success' && needs.stage.result == 'success' }} uses: ./.github/workflows/release-kitmaker.yml permissions: contents: read id-token: write with: - version: ${{ needs.preflight.outputs.version }} - source_sha: ${{ needs.preflight.outputs.source_sha }} + version: ${{ needs.release-source.outputs.version }} + source_sha: ${{ needs.release-source.outputs.source_sha }} manifest_sha256: ${{ needs.stage.outputs.manifest_sha256 }} verify-indexes: - needs: [preflight, stage, kitmaker] + needs: [release-source, stage, kitmaker] + if: >- + !cancelled() && needs.release-source.result == 'success' && + needs.stage.result == 'success' && needs.kitmaker.result == 'success' runs-on: ubuntu-24.04 timeout-minutes: 35 permissions: contents: read env: - VERSION: ${{ needs.preflight.outputs.version }} - SOURCE_SHA: ${{ needs.preflight.outputs.source_sha }} + VERSION: ${{ needs.release-source.outputs.version }} + SOURCE_SHA: ${{ needs.release-source.outputs.source_sha }} PYTHON_DOTENV_DISABLED: "1" steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: - ref: ${{ needs.preflight.outputs.source_sha }} + ref: ${{ needs.release-source.outputs.source_sha }} persist-credentials: false - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: @@ -308,19 +491,21 @@ jobs: "$uv_env/bin/python" -I ci/smoke_distribution.py "$VERSION" finalize: - needs: [preflight, verify-indexes] + needs: [release-source, verify-indexes] + if: >- + !cancelled() && needs.release-source.result == 'success' && needs.verify-indexes.result == 'success' runs-on: ubuntu-24.04 timeout-minutes: 10 environment: release-github permissions: contents: write env: - VERSION: ${{ needs.preflight.outputs.version }} - SOURCE_SHA: ${{ needs.preflight.outputs.source_sha }} + VERSION: ${{ needs.release-source.outputs.version }} + SOURCE_SHA: ${{ needs.release-source.outputs.source_sha }} steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: - ref: ${{ needs.preflight.outputs.source_sha }} + ref: ${{ needs.release-source.outputs.source_sha }} persist-credentials: false - name: Record the verified PyPI and DevZone publication env: @@ -331,3 +516,48 @@ jobs: python3 ci/github_release.py finalize --version "$VERSION" --source-sha "$SOURCE_SHA" --assets "$assets" printf 'To promote this release when it is GitHub Latest, run **Promote stable GitHub workflows** on `main` with `expected-release` set to `v%s`.\n' \ "$VERSION" >> "$GITHUB_STEP_SUMMARY" + + promotion-candidate: + needs: [release-source, finalize] + if: >- + !cancelled() && inputs.promote_stable && + needs.release-source.result == 'success' && needs.finalize.result == 'success' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + outputs: + is_latest: ${{ steps.latest.outputs.matches }} + steps: + - name: Check whether the verified release is GitHub Latest + id: latest + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ needs.release-source.outputs.version }} + run: | + latest="$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq \ + 'select(.immutable == true and .draft == false and .prerelease == false and .published_at != null) | .tag_name')" + if [[ ! "$latest" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ || + "$(printf '%s\n' "$latest" "v$VERSION" | sort -V | tail -n 1)" != "$latest" ]]; then + echo 'Expected GitHub Latest to be the verified release or a newer immutable release.' >&2 + exit 1 + fi + if [[ "$latest" == "v$VERSION" ]]; then + echo 'matches=true' >> "$GITHUB_OUTPUT" + else + echo 'matches=false' >> "$GITHUB_OUTPUT" + printf 'Stable promotion skipped because GitHub Latest is `%s`.\n' "$latest" >> "$GITHUB_STEP_SUMMARY" + fi + + promote-stable: + needs: [release-source, promotion-candidate] + if: >- + !cancelled() && needs.release-source.result == 'success' && + needs.promotion-candidate.result == 'success' && needs.promotion-candidate.outputs.is_latest == 'true' + uses: ./.github/workflows/promote-stable.yml + permissions: + contents: read + with: + expected-release: v${{ needs.release-source.outputs.version }} + secrets: + STABLE_CHANNEL_APP_PRIVATE_KEY: ${{ secrets.STABLE_CHANNEL_APP_PRIVATE_KEY }} diff --git a/RELEASING.md b/RELEASING.md index 00a72abe3..69b58a321 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -44,6 +44,50 @@ listing for `/skillevaluator/`. Kitmaker and run the protected dry-run job successfully before approving the first upload. The checked-in dry-run job sends `upload: false`. Apply that restriction in Ferry policy as well if the tenant supports it. +- For **Full release**, install a dedicated bundle PR GitHub App on SkillEvaluator + with repository Contents, Pull requests, and Workflows write access. Keep the + App subject to the normal `main` rules. In a `release-bundle-pr` Actions + environment restricted to `main`, add the + `RELEASE_BUNDLE_APP_CLIENT_ID` variable and `RELEASE_BUNDLE_APP_PRIVATE_KEY` + secret. The workflow checks both are present before it builds an image. + The App writes generated files to a release branch and opens the PR. + +## Start a release from GitHub Actions + +1. Merge the version-preparation PR described below. Open **SkillEvaluator + Release → Run workflow** on `main`, choose **Full release**, and enter the + version and the version-preparation merge SHA. +2. Approve the image job. The workflow builds or reuses the immutable image, + verifies the public digest, generates the bundle and pins, and opens or + reuses the bundle PR. Its link appears in the run summary. +3. Review the PR and qualify the generated GitHub and GitLab configurations. + Update the bundle catalog and current onboarding links in the PR if needed. + Merge the PR after the required checks pass. The run waits up to two hours + for that merge and verifies the exact squash-merge commit on `main`. If the + wait expires, merge the PR and use **Re-run failed jobs** on the original run. + Before the version tag exists, a fresh dispatch can reuse an open or + merged bundle PR for the same candidate. If intervening changes require a + new image candidate, close the old bundle PR if it is still open and + dispatch **Full release** with the new reviewed SHA. The workflow generates + a separate branch and PR for that candidate. +4. Review the validated bundle merge SHA, artifact ID, and manifest checksum + in the run summary. Follow the GitHub release and Kitmaker approvals from + the same run. Publication uses the exact validated artifacts, verifies PyPI + and DevZone, runs fresh install smoke tests, and finalizes the release. + +If the bundle PR is already merged, choose **Validate and publish** with the +version and the bundle merge SHA. This starts at package validation and skips +image building and bundle PR creation. + +Select **promote_stable** with **Full release**, **Validate and publish**, or +**Publish release**. After both package indexes pass verification, the workflow +promotes the exact version if it is GitHub Latest and the stable writer App is +configured. Use the standalone promotion workflow for retries and the first +`v1.0.1` bootstrap. Docs publish through **Publish Docs** on pushes to `main`, +including the bundle PR merge. + +The individual image, validation and publication phases are also available for +manual qualification and recovery. ## Prepare the CI release @@ -104,16 +148,22 @@ image and consumer qualification details. fresh pip and uv installations, a Tier 1 report, and the installed CI pins before recording verification in the GitHub release notes. -On interruption, use **Re-run failed jobs** or open **Run workflow** with the -same version, product SHA, and **Publish release** phase. Supply the validation -inputs if a GitHub draft has yet to be created. For an existing draft, the -approved job restores the bytes retained by the original Publish release run. -Preserve that artifact until completion. An immutable GitHub release uses its -published bytes and resumes any recorded Kitmaker submission. Both recovery -paths accept blank validation inputs. If GitHub rejects the workflow token -when creating the version tag, an authorized maintainer can create that tag at -the exact reviewed product SHA and resume the same run. The workflow checks -the tag target on every attempt. +On interruption, use **Re-run failed jobs** on the original run first. To +start a fresh run, enter the same version and reviewed bundle merge SHA. + +- If the tag exists and the GitHub draft was never created, use **Validate and + publish**. The standalone **Publish release** phase can also continue with + the receipt from a successful standalone **Validate release** run. +- For an existing draft, choose **Publish release** with blank validation + inputs. The approved job restores the exact bytes retained by the original + publishing run. Preserve that artifact until completion. +- For an immutable GitHub release, choose **Publish release** with blank + validation inputs. The workflow uses the published bytes and resumes any + recorded Kitmaker submission. + +If GitHub rejects the workflow token when creating the version tag, an +authorized maintainer can create that tag at the exact reviewed product SHA +and resume the same run. The workflow checks the tag target on every attempt. For a Kitmaker timeout or partial publication, inspect the private receipt, Kitmaker status and both public indexes. The workflow polls a saved submission @@ -179,8 +229,8 @@ access. If the DevZone URL is unset or invalid, package verification stops promotion before the `stable` tag can move. -After the manual product release finishes verification, open **Promote stable -GitHub workflows** in Actions and select **Run workflow** on `main`. Set +For a standalone promotion after the product release finishes verification, +open **Promote stable GitHub workflows** in Actions and select **Run workflow** on `main`. Set `expected-release` to the reviewed `vX.Y.Z` tag shown in the release workflow summary. Manual promotion stops if GitHub Latest differs from that tag. The product workflow's GitHub Actions token does not trigger the release relay. diff --git a/ci/github_release.py b/ci/github_release.py index b4b54e9b0..51d344acb 100644 --- a/ci/github_release.py +++ b/ci/github_release.py @@ -9,6 +9,7 @@ import argparse import hashlib import json +import os import re import subprocess import sys @@ -29,6 +30,7 @@ GITHUB = f"https://github.com/{REPOSITORY}" GITHUB_RAW = f"https://raw.githubusercontent.com/{REPOSITORY}" RUN_ATTEMPT = r"([1-9][0-9]*)-([1-9][0-9]*)" +SAME_RUN_PHASES = {"Validate and publish", "Full release"} STAGING_MARKER = re.compile(rf"") PENDING = "**Package publication:** Pending PyPI and NVIDIA DevZone verification." VERIFIED = "**Package publication:** Verified on PyPI and NVIDIA DevZone." @@ -134,7 +136,16 @@ def preflight(version: str, source_sha: str, main_sha: str, phase: str) -> None: tag = f"v{version}" if phase == "Build CI image and bundle" and check_tag(tag, source_sha) is not None: raise ValueError(f"{tag} already exists. Use the reviewed product SHA to validate or resume publication.") - if phase != "Build CI image and bundle": + if phase == "Full release": + # A fresh full run must not open a pin PR for a version already staged or published. + if tag_target(tag) is not None: + raise ValueError( + f"{tag} already exists. Re-run failed jobs on the original run. " + "For a fresh run, enter the reviewed bundle merge SHA. " + "Choose Validate and publish if the run stopped before creating a draft. " + "Choose Publish release to resume an existing draft or immutable release." + ) + elif phase != "Build CI image and bundle": check_tag(tag, source_sha) @@ -216,7 +227,14 @@ def digest(path: Path) -> str: return hashlib.file_digest(stream, "sha256").hexdigest() -def download_run_artifact(version: str, name: str, origin: dict, output: Path) -> None: +def download_run_artifact( + version: str, + name: str, + origin: dict, + output: Path, + *, + expected_artifact: tuple[int, str] | None = None, +) -> None: listing = api(f"actions/runs/{origin['id']}/artifacts?name={name}") artifacts = listing.get("artifacts") if isinstance(listing, dict) else None if not isinstance(artifacts, list) or len(artifacts) != 1 or listing.get("total_count") != 1: @@ -243,6 +261,8 @@ def download_run_artifact(version: str, name: str, origin: dict, output: Path) - or not re.fullmatch(r"sha256:[0-9a-f]{64}", str(artifact.get("digest"))) ): raise ValueError("The retained Actions artifact is expired or its identity is invalid.") + if expected_artifact is not None and (artifact["id"], artifact["digest"]) != expected_artifact: + raise ValueError("The validation artifact ID or SHA-256 digest differs from the producer job output.") with tempfile.TemporaryDirectory() as temp: archive = Path(temp) / "release-artifact.zip" @@ -280,18 +300,83 @@ def restore_validation(version: str, run: str, attempt: str, output: Path) -> No raise ValueError(f"Could not verify the validation artifact. {exc} Run Validate release again.") from exc -def acquire_publication(version: str, source_sha: str, output: Path, run_ref: str, manifest_sha256: str) -> bool: +def restore_same_run_validation( + version: str, + run: str, + attempt: str, + output: Path, + *, + phase: str | None, + artifact_id: str | None, + artifact_digest: str | None, +) -> None: + if phase not in SAME_RUN_PHASES: + raise ValueError("Same-run validation requires the Validate and publish or Full release phase.") + artifact_digest = (artifact_digest or "").removeprefix("sha256:") + if ( + not artifact_id + or not re.fullmatch(r"[1-9][0-9]*", artifact_id) + or not product_release.SHA256.fullmatch(artifact_digest) + ): + raise ValueError("Same-run validation requires the artifact ID and SHA-256 digest from the producer job.") + + current_attempt = os.environ.get("GITHUB_RUN_ATTEMPT", "") + if ( + run != os.environ.get("GITHUB_RUN_ID") + or not re.fullmatch(r"[1-9][0-9]*", current_attempt) + or int(attempt) > int(current_attempt) + ): + raise ValueError( + "The validation artifact must come from the current workflow run and a valid producer attempt." + ) + + # The stage job requires successful prepare outputs. The enclosing workflow is still running, + # and an earlier producer attempt may have failed in a later publication job. + try: + origin = upstream_release_run(run, attempt) + if origin is None or origin.get("display_title") != f"{phase} · SkillEvaluator {version}": + raise ValueError("Select the expected upstream manual release run, phase and version.") + download_run_artifact( + version, + f"validated-release-{version}-{run}-{attempt}", + origin, + output, + expected_artifact=(int(artifact_id), f"sha256:{artifact_digest}"), + ) + except (BadZipFile, ValueError, subprocess.CalledProcessError) as exc: + raise ValueError(f"Could not verify the same-run validation artifact. {exc}") from exc + + +def acquire_publication( + version: str, + source_sha: str, + output: Path, + run_ref: str, + manifest_sha256: str, + *, + phase: str | None = None, + artifact_id: str | None = None, + artifact_digest: str | None = None, +) -> bool: """Restore a release, or verify its validation receipt and return True for a new draft.""" if restore(version, source_sha, output): return False + same_run = phase in SAME_RUN_PHASES or artifact_id is not None or artifact_digest is not None match = re.fullmatch(RUN_ATTEMPT, run_ref) if match is None or not product_release.SHA256.fullmatch(manifest_sha256): + if same_run: + raise ValueError("Same-run validation requires the producer run attempt and manifest SHA-256.") raise ValueError( "Copy validation_run and validation_manifest_sha256 from a successful Validate release summary." ) run, attempt = match.groups() - restore_validation(version, run, attempt, output) + if same_run: + restore_same_run_validation( + version, run, attempt, output, phase=phase, artifact_id=artifact_id, artifact_digest=artifact_digest + ) + else: + restore_validation(version, run, attempt, output) manifest, actual_sha256 = product_release.checked_manifest(version, output) if actual_sha256 != manifest_sha256 or manifest.get("source_commit") != source_sha: @@ -462,6 +547,8 @@ def main() -> int: parser.add_argument("--run") parser.add_argument("--validation-run", default="") parser.add_argument("--validation-manifest-sha256", default="") + parser.add_argument("--validation-artifact-id") + parser.add_argument("--validation-artifact-digest") args = parser.parse_args() commands = { "restore": restore, @@ -474,7 +561,14 @@ def main() -> int: preflight(args.version, args.source_sha, args.main_sha, args.phase) elif args.command == "acquire": new_release = acquire_publication( - args.version, args.source_sha, args.assets, args.validation_run, args.validation_manifest_sha256 + args.version, + args.source_sha, + args.assets, + args.validation_run, + args.validation_manifest_sha256, + phase=args.phase, + artifact_id=args.validation_artifact_id, + artifact_digest=args.validation_artifact_digest, ) print(str(new_release).lower()) elif args.command == "stage": diff --git a/ci/release_pin_pr.py b/ci/release_pin_pr.py new file mode 100644 index 000000000..3466b1a1e --- /dev/null +++ b/ci/release_pin_pr.py @@ -0,0 +1,311 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# ruff: noqa: INP001, T201 + +"""Open or resume the bundle PR and identify its reviewed squash merge.""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +import sys +import tempfile +import time +import tomllib +from pathlib import Path +from urllib.parse import quote, urlencode +from zipfile import BadZipFile + +try: + import github_api + import product_release + import stable_channel + from github_release import API_ROOT, api, gh +except ModuleNotFoundError: + from ci.github_release import API_ROOT, api, gh + + from ci import github_api, product_release, stable_channel + +UPSTREAM = "https://github.com/NVIDIA/SkillEvaluator" +MAIN = "refs/remotes/origin/main" +APP_SLUG = re.compile(r"[a-z0-9][a-z0-9-]*") +GIT_CREDENTIALS = ("-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential") +MAX_WAIT_MINUTES = 120 + + +def git(*args: str, env: dict | None = None, data: bytes | None = None) -> bytes: + if env is None and data is None: + return product_release.git(*args) + result = subprocess.run(["git", *args], env=env, input=data, capture_output=True, check=False) + if result.returncode: + raise ValueError(result.stderr.decode("utf-8", errors="replace").strip() or f"git {args[0]} failed.") + return result.stdout + + +def branch_for(version: str, candidate: str) -> str: + return f"release/pin-v{version}-{candidate}" + + +def bundle_paths(version: str) -> set[str]: + prefix = f"ci/bundles/{version}" + names = {file.name for file in product_release.render_templates.TEMPLATES.glob("*.yml")} + names.update( + { + "README.md", + "release.json", + product_release.VERIFICATION, + product_release.SCANNERS, + product_release.CHECKSUMS, + product_release.names_for(version)[2], + } + ) + return ( + {f"{prefix}/{name}" for name in names} + | {f"{product_release.PACKAGE}/{name}" for name in product_release.DESCRIPTORS} + | set(product_release.STABLE_PATHS.values()) + ) + + +def fetch_main() -> set[str]: + remote = git("remote", "get-url", "origin").decode().strip() + if remote not in (UPSTREAM, f"{UPSTREAM}.git"): + raise ValueError("Check out the upstream SkillEvaluator repository before preparing a release.") + git(*GIT_CREDENTIALS, "fetch", "--no-tags", "origin", f"+refs/heads/main:{MAIN}") + return set(git("rev-list", "--first-parent", MAIN).decode().splitlines()) + + +def verify_source(version: str, candidate: str, image: str) -> None: + product_release.names_for(version) + if not github_api.COMMIT_SHA.fullmatch(candidate) or not stable_channel.OFFICIAL_IMAGE.fullmatch(image): + raise ValueError("A full candidate SHA and official Tier 1 GHCR digest are required.") + + +def require_reviewed_candidate(version: str, candidate: str, main: set[str]) -> None: + if candidate not in main: + raise ValueError("The image candidate must be on upstream main's first-parent history.") + project = tomllib.loads(product_release.source_file(candidate, "pyproject.toml").decode()) + if project["project"]["version"] != version: + raise ValueError("The reviewed image candidate does not match the release version.") + + +def verify_bundle_commit(version: str, candidate: str, image: str, source: str) -> None: + paths = bundle_paths(version) + entries = git("ls-tree", "-r", "-z", "--format=%(objectmode) %(path)", source, "--", *sorted(paths)) + if set(entries.decode().split("\0")) != {"", *(f"100644 {path}" for path in paths)}: + raise ValueError("The release bundle commit must contain regular generated files at the expected paths.") + + descriptors = { + name: product_release.source_file(source, f"{product_release.PACKAGE}/{name}") + for name in product_release.DESCRIPTORS + } + pins, _ = product_release.verify_bundle(version, source, product_release.names_for(version)[2], descriptors) + if pins != {"image_source_commit": candidate, "image": image}: + raise ValueError("The release bundle does not pin the selected image candidate and digest.") + + +def checked_bundle(version: str, directory: Path) -> dict[str, bytes]: + if directory.is_symlink() or not directory.is_dir(): + raise ValueError("The CI bundle must be a regular artifact directory.") + files = {} + for entry in directory.rglob("*"): + path = entry.relative_to(directory).as_posix() + if entry.is_symlink() or not (entry.is_file() or entry.is_dir()): + raise ValueError(f"Unexpected non-regular CI bundle artifact entry {path}.") + if entry.is_file(): + files[path] = entry + if set(files) != bundle_paths(version): + raise ValueError("The CI bundle artifact does not contain exactly the expected generated files.") + return {path: file.read_bytes() for path, file in files.items()} + + +def app_identity() -> tuple[str, str]: + slug = os.environ.get("RELEASE_BUNDLE_APP_SLUG", "") + if not APP_SLUG.fullmatch(slug): + raise ValueError("The release bundle writer App must provide its GitHub slug.") + login = f"{slug}[bot]" + user = json.loads(gh("api", f"users/{quote(login, safe='')}")) + user_id = user.get("id") + if user.get("login") != login or type(user_id) is not int or user_id < 1: + raise ValueError("GitHub did not return the configured release bundle App identity.") + return login, f"{user_id}+{login}@users.noreply.github.com" + + +def bundle_commit(version: str, candidate: str, files: dict[str, bytes]) -> str: + name, email = app_identity() + with tempfile.TemporaryDirectory(prefix="release-pin-") as temp: + env = { + **os.environ, + "GIT_INDEX_FILE": str(Path(temp) / "index"), + "GIT_AUTHOR_NAME": name, + "GIT_AUTHOR_EMAIL": email, + "GIT_COMMITTER_NAME": name, + "GIT_COMMITTER_EMAIL": email, + } + git("read-tree", candidate, env=env) + for path, content in sorted(files.items()): + blob = git("hash-object", "-w", "--stdin", data=content).decode().strip() + git("update-index", "--add", "--cacheinfo", f"100644,{blob},{path}", env=env) + tree = git("write-tree", env=env).decode().strip() + message = f"chore(ci): pin SkillEvaluator {version} release bundle\n\nSigned-off-by: {name} <{email}>" + return git("commit-tree", tree, "-p", candidate, "-m", message, env=env).decode().strip() + + +def check_pull(pull: dict, branch: str, *, number: int | None = None) -> None: + repo = product_release.REPOSITORY + if ( + not isinstance(pull, dict) + or type(pull.get("number")) is not int + or pull["number"] < 1 + or (number is not None and pull["number"] != number) + or pull["base"]["ref"] != "main" + or pull["base"]["repo"]["full_name"] != repo + or pull["head"]["ref"] != branch + or (pull["head"]["repo"] or {}).get("full_name") != repo + or not github_api.COMMIT_SHA.fullmatch(str(pull["head"]["sha"])) + ): + raise ValueError("The bundle PR does not use the expected upstream branches.") + + +def check_competing_pulls(version: str, branch: str) -> None: + path = f"{API_ROOT}/pulls?state=open&base=main&per_page=100" + pages = json.loads(gh("api", "--paginate", "--slurp", path)) + if not isinstance(pages, list) or not pages or any(not isinstance(page, list) for page in pages): + raise ValueError("GitHub did not provide the open bundle PR listing.") + prefix = f"release/pin-v{version}" + same_version = re.compile(rf"{re.escape(prefix)}(?:-[0-9a-f]{{40}})?") + for page in pages: + for pull in page: + head = pull["head"] + ref = head["ref"] + if ( + ref != branch + and same_version.fullmatch(ref) + and (head["repo"] or {}).get("full_name") == product_release.REPOSITORY + ): + check_pull(pull, ref) + raise ValueError( + f"Close the stale bundle PR {UPSTREAM}/pull/{pull['number']} before preparing a new candidate." + ) + + +def existing_pull(branch: str) -> dict | None: + query = urlencode({"state": "all", "head": f"NVIDIA:{branch}", "base": "main"}) + matches = api(f"pulls?{query}") + if not isinstance(matches, list) or len(matches) > 1: + raise ValueError("Cannot identify a unique bundle PR for this release branch.") + if not matches: + return None + pull = matches[0] + check_pull(pull, branch) + return pull + + +def verified_merge(version: str, candidate: str, image: str, pull: dict, main: set[str]) -> str: + source = pull.get("merge_commit_sha") + if pull.get("state") != "closed" or not pull.get("merged_at"): + raise ValueError("The release bundle PR was closed without a merge.") + if not github_api.COMMIT_SHA.fullmatch(str(source)) or source not in main: + raise ValueError("The release bundle merge SHA is not on upstream main's first-parent history.") + verify_bundle_commit(version, candidate, image, source) + return source + + +def read_remote_branch(branch: str) -> str: + ref = f"refs/heads/{branch}" + remote = git(*GIT_CREDENTIALS, "ls-remote", "--refs", "origin", ref) + if not remote: + return "" + git(*GIT_CREDENTIALS, "fetch", "--no-tags", "origin", f"+{ref}:refs/remotes/origin/{branch}") + return git("rev-parse", f"refs/remotes/origin/{branch}").decode().strip() + + +def open_pull(version: str, candidate: str, image: str, bundle: Path) -> int: + verify_source(version, candidate, image) + main = fetch_main() + require_reviewed_candidate(version, candidate, main) + branch = branch_for(version, candidate) + check_competing_pulls(version, branch) + pull = existing_pull(branch) + if pull is not None and pull.get("state") != "open": + verified_merge(version, candidate, image, pull, main) + return pull["number"] + + product_release.check_candidate_diff(candidate, MAIN, f"ci/bundles/{version}/") + source = read_remote_branch(branch) + if source: + verify_bundle_commit(version, candidate, image, source) + if pull is not None: + if pull["head"]["sha"] != source: + raise ValueError("The bundle PR head changed during inspection. Retry the release.") + return pull["number"] + else: + if pull is not None: + raise ValueError("The open bundle PR is missing its release branch.") + source = bundle_commit(version, candidate, checked_bundle(version, bundle)) + verify_bundle_commit(version, candidate, image, source) + git(*GIT_CREDENTIALS, "push", "origin", f"{source}:refs/heads/{branch}") + + payload = { + "title": f"chore(ci): pin SkillEvaluator {version} release bundle", + "head": branch, + "base": "main", + "body": ( + f"Pin the generated bundle and consumer configs for SkillEvaluator `{version}`.\n\n" + f"Image source `{candidate}`\n\nVerified image `{image}`\n\n" + "Review the generated files and qualify the GitHub and GitLab consumer configs before merging." + ), + } + pull = api("pulls", "POST", payload) + check_pull(pull, branch) + if pull.get("state") != "open" or pull["head"]["sha"] != source: + raise ValueError("GitHub did not open the expected release bundle PR.") + return pull["number"] + + +def wait_for_merge(version: str, candidate: str, image: str, number: int, timeout_minutes: int) -> str: + verify_source(version, candidate, image) + if number < 1 or not 1 <= timeout_minutes <= MAX_WAIT_MINUTES: + raise ValueError(f"Specify a pull request number and a timeout up to {MAX_WAIT_MINUTES} minutes.") + branch = branch_for(version, candidate) + deadline = time.monotonic() + timeout_minutes * 60 + print(f"Waiting for review and merge of {UPSTREAM}/pull/{number}", file=sys.stderr) + while True: + pull = api(f"pulls/{number}") + check_pull(pull, branch, number=number) + if pull.get("state") != "open": + main = fetch_main() + require_reviewed_candidate(version, candidate, main) + return verified_merge(version, candidate, image, pull, main) + remaining = deadline - time.monotonic() + if remaining <= 0: + raise ValueError(f"Timed out waiting for pull request #{number}. Rerun the failed job after it merges.") + time.sleep(min(30, remaining)) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + prepare = commands.add_parser("open") + prepare.add_argument("--bundle", type=Path, required=True) + wait = commands.add_parser("wait") + wait.add_argument("--pr", type=int, required=True) + wait.add_argument("--timeout-minutes", type=int, default=MAX_WAIT_MINUTES) + for command in (prepare, wait): + command.add_argument("--version", required=True) + command.add_argument("--source-sha", required=True) + command.add_argument("--image", required=True) + args = parser.parse_args() + try: + if args.command == "open": + print(open_pull(args.version, args.source_sha, args.image, args.bundle)) + else: + print(wait_for_merge(args.version, args.source_sha, args.image, args.pr, args.timeout_minutes)) + except (BadZipFile, KeyError, OSError, TypeError, ValueError, subprocess.SubprocessError) as error: + parser.exit(1, f"CI bundle PR failed: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/tests/ci/test_image_build.py b/tests/ci/test_image_build.py index 0b0f3a8b2..c04e4520a 100644 --- a/tests/ci/test_image_build.py +++ b/tests/ci/test_image_build.py @@ -168,24 +168,35 @@ def test_pull_requests_read_but_never_write_the_layer_cache(): assert caller["secrets"] == {"NVSKILLS_CI_DISPATCH_TOKEN": "${{ secrets.NVSKILLS_CI_DISPATCH_TOKEN }}"} if "workflow_run" in triggers: if path.name == "promote-stable.yml": - assert set(triggers) == {"workflow_run", "workflow_dispatch"} + assert set(triggers) == {"workflow_run", "workflow_dispatch", "workflow_call"} assert triggers["workflow_run"] == { "workflows": ["SkillEvaluator release published"], "types": ["completed"], } expected_release = triggers["workflow_dispatch"]["inputs"]["expected-release"] assert expected_release["required"] == "true" and expected_release["type"] == "string" - assert document["concurrency"] == { - "group": "skillevaluator-stable", - "cancel-in-progress": "false", - "queue": "max", + assert triggers["workflow_call"] == { + "inputs": {"expected-release": {"required": "true", "type": "string"}}, + "secrets": {"STABLE_CHANNEL_APP_PRIVATE_KEY": {"required": "true"}}, } assert document["permissions"] == {} + assert "concurrency" not in document assert set(document["jobs"]) == {"promote"} promote = document["jobs"]["promote"] assert promote["environment"] == "stable-channel" assert promote["permissions"] == {"contents": "read"} + assert promote["concurrency"] == { + "group": "skillevaluator-stable", + "cancel-in-progress": "false", + "queue": "max", + } assert "github.ref == 'refs/heads/main'" in promote["if"] + assert set(re.findall(r"github\.workflow_ref == '([^']+)'", promote["if"])) == { + "NVIDIA/SkillEvaluator/.github/workflows/promote-stable.yml@refs/heads/main", + "NVIDIA/SkillEvaluator/.github/workflows/release.yml@refs/heads/main", + } + assert "github.event_name == 'workflow_dispatch'" in promote["if"] + assert "github.event_name == 'workflow_run'" in promote["if"] checkout, writer, update = promote["steps"] assert re.fullmatch(r"actions/checkout@[0-9a-f]{40}", checkout["uses"]) assert checkout["with"] == { @@ -194,6 +205,7 @@ def test_pull_requests_read_but_never_write_the_layer_cache(): "persist-credentials": "false", } assert re.fullmatch(r"actions/create-github-app-token@[0-9a-f]{40}", writer["uses"]) + assert writer["with"]["private-key"] == "${{ secrets.STABLE_CHANNEL_APP_PRIVATE_KEY }}" assert writer["with"]["permission-contents"] == "write" assert update["run"] == "bash ci/promote_stable.sh" assert update["env"]["RELEASE_DEVZONE_INDEX_URL"] == "${{ vars.RELEASE_DEVZONE_INDEX_URL }}" diff --git a/tests/ci/test_manual_release.py b/tests/ci/test_manual_release.py index 3f38de6af..bceb7a837 100644 --- a/tests/ci/test_manual_release.py +++ b/tests/ci/test_manual_release.py @@ -5,7 +5,9 @@ import importlib.util import io import json +import os import re +import subprocess from pathlib import Path from unittest.mock import Mock from zipfile import ZipFile @@ -23,18 +25,73 @@ def test_release_is_only_dispatched_manually_and_defaults_to_validation(): assert set(workflow["on"]) == {"workflow_dispatch"} phase = workflow["on"]["workflow_dispatch"]["inputs"]["phase"] assert phase["default"] == "Validate release" - assert phase["options"] == ["Validate release", "Build CI image and bundle", "Publish release"] + assert phase["options"] == [ + "Validate release", + "Validate and publish", + "Full release", + "Build CI image and bundle", + "Publish release", + ] jobs = workflow["jobs"] assert "workflow_dispatch" in jobs["preflight"]["if"] assert "refs/heads/main" in jobs["preflight"]["if"] + reviewed = next(step for step in jobs["preflight"]["steps"] if step.get("id") == "reviewed") + assert reviewed["env"]["PROMOTE_STABLE"] == "${{ inputs.promote_stable }}" assert jobs["image"]["uses"] == "./.github/workflows/release-tier1-image.yml" assert jobs["stage"]["environment"] == "release-github" assert "Publish release" in jobs["stage"]["if"] - assert jobs["kitmaker"]["needs"] == ["preflight", "stage"] - assert jobs["finalize"]["needs"] == ["preflight", "verify-indexes"] + assert jobs["kitmaker"]["needs"] == ["release-source", "stage"] + assert jobs["finalize"]["needs"] == ["release-source", "verify-indexes"] assert any("inspect-indexes" in step.get("run", "") for step in jobs["prepare"]["steps"]) +@pytest.mark.parametrize("promote_stable", ["false", "true"]) +@pytest.mark.parametrize( + ("phase", "publishes"), + [ + ("Validate release", False), + ("Build CI image and bundle", False), + ("Validate and publish", True), + ("Full release", True), + ("Publish release", True), + ], +) +def test_preflight_validates_stable_promotion_phase(phase, publishes, promote_stable, tmp_path): + workflow = yaml.load((ROOT / ".github/workflows/release.yml").read_text(), Loader=yaml.BaseLoader) + step = next(step for step in workflow["jobs"]["preflight"]["steps"] if step.get("id") == "reviewed") + command = tmp_path / "python3" + command.write_text('#!/bin/sh\nprintf "%s\\n" "$@" > "$PREFLIGHT_ARGS"\n', encoding="utf-8") + command.chmod(0o755) + args_file = tmp_path / "args" + output = tmp_path / "output" + result = subprocess.run( + ["bash", "-e", "-c", step["run"]], + env={ + **os.environ, + "PATH": str(tmp_path) + os.pathsep + os.environ["PATH"], + "PHASE": phase, + "PROMOTE_STABLE": promote_stable, + "VERSION": VERSION, + "SOURCE_SHA": SHA, + "GITHUB_SHA": SHA, + "PREFLIGHT_ARGS": str(args_file), + "GITHUB_OUTPUT": str(output), + }, + check=False, + capture_output=True, + text=True, + ) + if promote_stable == "true" and not publishes: + assert result.returncode == 1 + assert "Stable promotion requires Full release, Validate and publish, or Publish release." in result.stderr + assert not args_file.exists() and not output.exists() + else: + assert result.returncode == 0, result.stderr + arguments = args_file.read_text(encoding="utf-8").splitlines() + assert arguments[arguments.index("--phase") + 1] == phase + assert output.read_text(encoding="utf-8") == f"version={VERSION}\nsource_sha={SHA}\n" + + def test_validate_checks_release_metadata_with_the_current_workflow_from_the_reviewed_checkout(): workflow = yaml.load((ROOT / ".github/workflows/release.yml").read_text(), Loader=yaml.BaseLoader) job = workflow["jobs"]["prepare"] @@ -52,19 +109,68 @@ def test_validate_checks_release_metadata_with_the_current_workflow_from_the_rev } assert checkout_refs == { "release-control": "${{ github.workflow_sha }}", - "source": "${{ needs.preflight.outputs.source_sha }}", + "source": "${{ needs.release-source.outputs.source_sha }}", } verify = next(i for i, step in enumerate(steps) if "product_release.py verify-assets" in step.get("run", "")) retain = next(i for i, step in enumerate(steps) if "upload-artifact@" in step.get("uses", "")) assert verify < metadata_index < retain +@pytest.mark.parametrize("phase", ["Validate release", "Validate and publish", "Full release"]) +def test_prepare_summarizes_the_exact_validated_release_before_publication(phase, tmp_path): + workflow = yaml.load((ROOT / ".github/workflows/release.yml").read_text(), Loader=yaml.BaseLoader) + steps = workflow["jobs"]["prepare"]["steps"] + summary = next(step for step in steps if "$GITHUB_STEP_SUMMARY" in step.get("run", "")) + output = tmp_path / "summary" + subprocess.run( + ["bash", "-e", "-c", summary["run"]], + env={ + **os.environ, + "PHASE": phase, + "VERSION": VERSION, + "SOURCE_SHA": SHA, + "VALIDATION_RUN": "42-1", + "VALIDATION_ARTIFACT_ID": "123", + "MANIFEST_SHA256": "b" * 64, + "GITHUB_STEP_SUMMARY": str(output), + }, + check=True, + ) + contents = output.read_text(encoding="utf-8") + assert f"| `version` | `{VERSION}` |" in contents + assert f"| `source_sha` | `{SHA}` |" in contents + assert "| `validation_run` | `42-1` |" in contents + assert f"| `validation_manifest_sha256` | `{'b' * 64}` |" in contents + if phase == "Validate release": + assert contents.startswith("### Publish release inputs\n") + assert "Validation artifact ID" not in contents + else: + assert contents.startswith("### Validated release artifacts\n") + assert "| Validation artifact ID | `123` |" in contents + assert "if" not in summary + assert summary["env"]["VALIDATION_ARTIFACT_ID"] == "${{ steps.retained.outputs.artifact-id }}" + + @pytest.mark.parametrize("name", ["release", "release-tier1-image", "release-kitmaker"]) def test_release_workflows_scope_permissions_and_credentials(name): source = (ROOT / ".github" / "workflows" / f"{name}.yml").read_text(encoding="utf-8") workflow = yaml.load(source, Loader=yaml.BaseLoader) assert workflow["permissions"] == {} - assert re.search(r"\bsecrets\s*(?:\.|\[|:)", source, re.IGNORECASE) is None + secrets = re.findall(r"\bsecrets\.([A-Z_]+)", source) + if name == "release": + assert sorted(secrets) == [ + "RELEASE_BUNDLE_APP_PRIVATE_KEY", + "RELEASE_BUNDLE_APP_PRIVATE_KEY", + "STABLE_CHANNEL_APP_PRIVATE_KEY", + ] + assert workflow["jobs"]["bundle-pr"]["environment"] == "release-bundle-pr" + assert workflow["jobs"]["bundle-configuration"]["environment"] == "release-bundle-pr" + assert workflow["jobs"]["promote-stable"]["secrets"] == { + "STABLE_CHANNEL_APP_PRIVATE_KEY": "${{ secrets.STABLE_CHANNEL_APP_PRIVATE_KEY }}" + } + else: + assert not secrets + assert not re.search(r"\bsecrets\s*(?:\[|:\s*inherit)", source, re.IGNORECASE) checkouts = [ step for job in workflow["jobs"].values() @@ -172,19 +278,120 @@ def release_run(**overrides): } -def test_validation_is_the_only_phase_that_builds_and_smoke_tests_release_assets(): +def test_publish_uses_the_required_validation_artifact_and_retains_recovery_bytes(): workflow = yaml.load((ROOT / ".github/workflows/release.yml").read_text(), Loader=yaml.BaseLoader) inputs = workflow["on"]["workflow_dispatch"]["inputs"] assert {"validation_run", "validation_manifest_sha256"} <= inputs.keys() jobs = workflow["jobs"] - assert jobs["prepare"]["if"] == "inputs.phase == 'Validate release'" - assert "prepare" not in jobs["stage"]["needs"] + prepare = jobs["prepare"] + assert "inputs.phase == 'Publish release'" not in prepare["if"] + assert prepare["outputs"] == { + "run": "${{ steps.artifact.outputs.run }}", + "artifact_id": "${{ steps.retained.outputs.artifact-id }}", + "artifact_digest": "${{ steps.retained.outputs.artifact-digest }}", + "manifest_sha256": "${{ steps.verified.outputs.manifest_sha256 }}", + } + stage_job = jobs["stage"] + assert stage_job["needs"] == ["release-source", "prepare"] + assert "inputs.phase == 'Publish release' && needs.prepare.result == 'skipped'" in stage_job["if"] + assert "needs.prepare.result == 'success'" in stage_job["if"] + for name in ("prepare", "stage", "kitmaker", "verify-indexes", "finalize"): + assert "!cancelled()" in jobs[name]["if"] + for dependency in jobs[name]["needs"] if isinstance(jobs[name]["needs"], list) else [jobs[name]["needs"]]: + assert f"needs.{dependency}.result" in jobs[name]["if"] + acquire = next(step for step in stage_job["steps"] if step.get("id") == "acquire") + assert acquire["env"]["VALIDATION_ARTIFACT_ID"] == "${{ needs.prepare.outputs.artifact_id }}" + assert acquire["env"]["VALIDATION_ARTIFACT_DIGEST"] == "${{ needs.prepare.outputs.artifact_digest }}" + assert acquire["env"]["VALIDATION_RUN"].endswith(" || needs.prepare.outputs.run }}") + assert acquire["env"]["MANIFEST_SHA256"].endswith(" || needs.prepare.outputs.manifest_sha256 }}") + assert '--validation-artifact-id "$VALIDATION_ARTIFACT_ID"' in acquire["run"] + assert '--validation-artifact-digest "$VALIDATION_ARTIFACT_DIGEST"' in acquire["run"] steps = jobs["stage"]["steps"] retain = next(i for i, step in enumerate(steps) if "upload-artifact@" in step.get("uses", "")) stage = next(i for i, step in enumerate(steps) if "github_release.py stage" in step.get("run", "")) assert retain < stage +@pytest.mark.parametrize("phase", ["Publish release", "Validate and publish", "Full release"]) +def test_stage_passes_same_run_artifact_options_only_for_combined_phases(phase, tmp_path): + workflow = yaml.load((ROOT / ".github/workflows/release.yml").read_text(), Loader=yaml.BaseLoader) + step = next(step for step in workflow["jobs"]["stage"]["steps"] if step.get("id") == "acquire") + command = tmp_path / "python3" + command.write_text('#!/bin/sh\nprintf "%s\\n" "$@" > "$ACQUIRE_ARGS"\nprintf "true\\n"\n', encoding="utf-8") + command.chmod(0o755) + args_file = tmp_path / "args" + output = tmp_path / "output" + subprocess.run( + ["bash", "-e", "-c", step["run"]], + env={ + **os.environ, + "PATH": str(tmp_path) + os.pathsep + os.environ["PATH"], + "PHASE": phase, + "VERSION": VERSION, + "SOURCE_SHA": SHA, + "RUNNER_TEMP": str(tmp_path), + "VALIDATION_RUN": "42-1", + "MANIFEST_SHA256": "b" * 64, + "VALIDATION_ARTIFACT_ID": "123", + "VALIDATION_ARTIFACT_DIGEST": "c" * 64, + "ACQUIRE_ARGS": str(args_file), + "GITHUB_OUTPUT": str(output), + "GITHUB_RUN_ID": "100", + "GITHUB_RUN_ATTEMPT": "2", + }, + check=True, + ) + arguments = args_file.read_text(encoding="utf-8").splitlines() + assert arguments[arguments.index("--validation-run") + 1] == "42-1" + if phase == "Publish release": + assert "--validation-artifact-id" not in arguments + assert "--validation-artifact-digest" not in arguments + else: + assert arguments[arguments.index("--validation-artifact-id") + 1] == "123" + assert arguments[arguments.index("--validation-artifact-digest") + 1] == "c" * 64 + assert "new_release=true" in output.read_text(encoding="utf-8") + + +def test_full_release_uses_an_approved_bundle_pr_and_only_promotes_after_finalization(): + workflow = yaml.load((ROOT / ".github/workflows/release.yml").read_text(), Loader=yaml.BaseLoader) + jobs = workflow["jobs"] + assert "needs.bundle-configuration.result == 'success'" in jobs["image"]["if"] + bundle = jobs["bundle-pr"] + assert bundle["needs"] == ["preflight", "image"] + assert bundle["permissions"] == {"actions": "read", "contents": "read"} + verify = next(i for i, step in enumerate(bundle["steps"]) if "sha256sum --check" in step.get("run", "")) + writer = next(i for i, step in enumerate(bundle["steps"]) if step.get("id") == "writer") + assert verify < writer + assert jobs["bundle-merge"]["permissions"] == {"contents": "read", "pull-requests": "read"} + assert "bundle-pr" in jobs["bundle-merge"]["needs"] + source = jobs["release-source"] + assert "inputs.phase == 'Full release' && needs.bundle-merge.result == 'success'" in source["if"] + assert jobs["promotion-candidate"]["needs"] == ["release-source", "finalize"] + assert "needs.promotion-candidate.outputs.is_latest == 'true'" in jobs["promote-stable"]["if"] + assert jobs["promote-stable"]["with"]["expected-release"] == "v${{ needs.release-source.outputs.version }}" + + +@pytest.mark.parametrize( + ("phase", "merged", "expected"), + [("Full release", "2" * 40, "2" * 40), ("Full release", "", None), ("Validate and publish", "", SHA)], +) +def test_full_release_cannot_fall_back_to_the_image_candidate(phase, merged, expected, tmp_path): + workflow = yaml.load((ROOT / ".github/workflows/release.yml").read_text(), Loader=yaml.BaseLoader) + run = workflow["jobs"]["release-source"]["steps"][0]["run"] + output = tmp_path / "output" + result = subprocess.run( + ["bash", "-e", "-c", run], + env={**os.environ, "PHASE": phase, "CANDIDATE_SHA": SHA, "MERGED_SHA": merged, "GITHUB_OUTPUT": str(output)}, + check=False, + ) + if expected is None: + assert result.returncode != 0 + assert not output.exists() + else: + assert result.returncode == 0 + assert output.read_text(encoding="utf-8") == f"sha={expected}\n" + + @pytest.mark.parametrize("run_ref, manifest", [("", "a" * 64), ("123", "a" * 64), ("123-2", "A" * 64)]) def test_new_release_requires_a_validation_attempt_and_manifest_digest( release, monkeypatch, tmp_path, run_ref, manifest diff --git a/tests/ci/test_release_pin_pr.py b/tests/ci/test_release_pin_pr.py new file mode 100644 index 000000000..42f3effed --- /dev/null +++ b/tests/ci/test_release_pin_pr.py @@ -0,0 +1,192 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import json +import subprocess +from types import SimpleNamespace +from urllib.parse import parse_qs, urlsplit + +import pytest +from test_product_release import IMAGE, VERSION, commit, git +from test_product_release import release as release # noqa: PLC0414 -- pytest fixture + +from ci import release_pin_pr + +REPOSITORY = "NVIDIA/SkillEvaluator" +BRANCH = f"release/pin-v{VERSION}" + + +@pytest.fixture +def pin_repo(release, tmp_path, monkeypatch): + repo, source, _, _, candidate = release + git(repo, "switch", "--detach", source) + remote = tmp_path / "upstream.git" + subprocess.run(["git", "init", "--bare", str(remote)], check=True, capture_output=True) + git(repo, "update-ref", "refs/heads/main", candidate) + git(repo, "remote", "add", "origin", str(remote)) + git(repo, "push", "origin", "main") + monkeypatch.setattr(release_pin_pr, "UPSTREAM", str(remote)) + monkeypatch.setenv("RELEASE_BUNDLE_APP_SLUG", "release-bot") + monkeypatch.setattr( + release_pin_pr, + "gh", + lambda *args: "[[]]" if "--paginate" in args else '{"id":765,"login":"release-bot[bot]"}', + ) + monkeypatch.chdir(repo) + return repo, candidate, tmp_path / "generated" + + +def pull(head, candidate, *, state="open", merge=None): + return { + "number": 12, + "state": state, + "base": {"ref": "main", "repo": {"full_name": REPOSITORY}}, + "head": {"ref": f"{BRANCH}-{candidate}", "sha": head, "repo": {"full_name": REPOSITORY}}, + "merged_at": "2026-11-20T00:00:00Z" if merge else None, + "merge_commit_sha": merge, + } + + +def test_reuses_signed_bundle_commit_after_interrupted_pr_creation(pin_repo, monkeypatch): + repo, candidate, generated = pin_repo + selected = None + submissions = [] + previous_head = git(repo, "rev-parse", "HEAD") + branch = f"{BRANCH}-{candidate}" + + def api(path, method="GET", data=None): + nonlocal selected + if path.startswith("pulls?"): + return [selected] if selected else [] + assert path == "pulls" and method == "POST" + submissions.append(data) + if len(submissions) == 1: + raise ValueError("Interrupted before PR creation") + selected = pull(git(repo, "rev-parse", "refs/remotes/origin/" + branch), candidate) + return selected + + monkeypatch.setattr(release_pin_pr, "api", api) + with pytest.raises(ValueError, match="Interrupted"): + release_pin_pr.open_pull(VERSION, candidate, IMAGE, generated) + + ref = f"refs/heads/{branch}" + original = git(repo, "ls-remote", "--refs", "origin", ref) + asserted_sha = original.split()[0] + assert original.endswith(ref) + assert release_pin_pr.open_pull(VERSION, candidate, IMAGE, generated) == 12 + assert release_pin_pr.open_pull(VERSION, candidate, IMAGE, generated) == 12 + assert len(submissions) == 2 + assert all(data["head"] == branch and data["base"] == "main" for data in submissions) + assert git(repo, "ls-remote", "--refs", "origin", ref) == original + assert git(repo, "rev-parse", "HEAD") == previous_head + assert git(repo, "rev-parse", f"{asserted_sha}^") == candidate + assert "Signed-off-by: release-bot[bot] <765+release-bot[bot]@users.noreply.github.com>" in git( + repo, "show", "-s", "--format=%B", asserted_sha + ) + + +@pytest.mark.parametrize("unexpected", ["extra", "symlink", "modified-wrapper"]) +def test_invalid_bundle_cannot_be_pushed(pin_repo, monkeypatch, unexpected): + repo, candidate, generated = pin_repo + if unexpected == "extra": + (generated / "unexpected").write_text("invalid") + path = generated / ".github/workflows/skill-checks-stable.yml" + if unexpected == "symlink": + path.unlink() + path.symlink_to(repo / ".github/workflows/skill-checks-stable.yml") + if unexpected == "modified-wrapper": + path.write_text("# unexpected wrapper\n") + monkeypatch.setattr(release_pin_pr, "api", lambda *_args, **_kwargs: []) + + with pytest.raises(ValueError, match=r"bundle|stable\.yml"): + release_pin_pr.open_pull(VERSION, candidate, IMAGE, generated) + assert not git(repo, "ls-remote", "--refs", "origin", f"refs/heads/{BRANCH}-{candidate}") + + +def test_wait_returns_merge_from_protected_main(pin_repo, monkeypatch): + repo, candidate, _ = pin_repo + head = git(repo, "rev-parse", "HEAD") + git(repo, "switch", "main") + git(repo, "merge", "--squash", head) + merge = commit(repo) + git(repo, "push", "origin", "main") + statuses = iter([pull(head, candidate), pull(head, candidate, state="closed", merge=merge)]) + monkeypatch.setattr(release_pin_pr, "api", lambda _path: next(statuses)) + monkeypatch.setattr(release_pin_pr, "time", SimpleNamespace(monotonic=lambda: 100, sleep=lambda _seconds: None)) + + assert release_pin_pr.wait_for_merge(VERSION, candidate, IMAGE, 12, 1) == merge + monkeypatch.setattr(release_pin_pr, "api", lambda _path: [pull(head, candidate, state="closed", merge=merge)]) + assert release_pin_pr.open_pull(VERSION, candidate, IMAGE, repo / "absent-artifact") == 12 + + +def test_wait_rejects_commit_unmerged_from_main(pin_repo, monkeypatch): + repo, candidate, _ = pin_repo + head = git(repo, "rev-parse", "HEAD") + monkeypatch.setattr(release_pin_pr, "api", lambda _path: pull(head, candidate, state="closed", merge=head)) + + with pytest.raises(ValueError, match="first-parent"): + release_pin_pr.wait_for_merge(VERSION, candidate, IMAGE, 12, 1) + + +def test_wait_does_not_accept_a_different_head_repository(pin_repo, monkeypatch): + repo, candidate, _ = pin_repo + head = git(repo, "rev-parse", "HEAD") + result = pull(head, candidate) + result["head"]["repo"]["full_name"] = "elsewhere/SkillEvaluator" + monkeypatch.setattr(release_pin_pr, "api", lambda _path: result) + + with pytest.raises(ValueError, match="expected upstream"): + release_pin_pr.wait_for_merge(VERSION, candidate, IMAGE, 12, 1) + + +def test_wait_stops_at_deadline_without_creating_a_pull_request(pin_repo, monkeypatch): + repo, candidate, _ = pin_repo + head = git(repo, "rev-parse", "HEAD") + timestamps = iter([100, 161]) + monkeypatch.setattr(release_pin_pr, "time", SimpleNamespace(monotonic=lambda: next(timestamps))) + monkeypatch.setattr(release_pin_pr, "api", lambda _path: pull(head, candidate)) + + with pytest.raises(ValueError, match="Timed out"): + release_pin_pr.wait_for_merge(VERSION, candidate, IMAGE, 12, 1) + + +@pytest.mark.parametrize("stale_branch", [BRANCH, f"{BRANCH}-{'a' * 40}"]) +def test_closed_stale_pr_does_not_block_a_replacement_candidate(pin_repo, monkeypatch, stale_branch): + repo, candidate, generated = pin_repo + git(repo, "push", "origin", f"{candidate}:refs/heads/{stale_branch}") + stale = pull(candidate, "a" * 40, state="closed") + stale["head"]["ref"] = stale_branch + expected_branch = f"{BRANCH}-{candidate}" + + def api(path, method="GET", data=None): + if path.startswith("pulls?"): + head = parse_qs(urlsplit(path).query)["head"][0] + return [stale] if head == f"NVIDIA:{stale_branch}" else [] + assert method == "POST" + assert data["head"] == expected_branch + return pull(git(repo, "rev-parse", f"refs/remotes/origin/{expected_branch}"), candidate) + + monkeypatch.setattr(release_pin_pr, "api", api) + + assert release_pin_pr.open_pull(VERSION, candidate, IMAGE, generated) == 12 + for branch in (stale_branch, expected_branch): + assert git(repo, "ls-remote", "--refs", "origin", f"refs/heads/{branch}").endswith(branch) + + +def test_open_stale_pr_on_later_page_prevents_replacement(pin_repo, monkeypatch): + repo, candidate, generated = pin_repo + stale = pull("b" * 40, "a" * 40) + unrelated = pull("b" * 40, "b" * 40) + unrelated["head"]["ref"] = "release/pin-v12.0.0-" + "b" * 40 + monkeypatch.setattr( + release_pin_pr, + "gh", + lambda *args: ( + json.dumps([[unrelated], [stale]]) if "--paginate" in args else '{"id":765,"login":"release-bot[bot]"}' + ), + ) + monkeypatch.setattr(release_pin_pr, "api", lambda *_args, **_kwargs: []) + + with pytest.raises(ValueError, match=r"Close.*?/pull/12"): + release_pin_pr.open_pull(VERSION, candidate, IMAGE, generated) + assert not git(repo, "ls-remote", "--refs", "origin", f"refs/heads/{BRANCH}*") diff --git a/tests/ci/test_same_run_release.py b/tests/ci/test_same_run_release.py new file mode 100644 index 000000000..e60a4b805 --- /dev/null +++ b/tests/ci/test_same_run_release.py @@ -0,0 +1,362 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import hashlib +import io +import json +import sys +from types import SimpleNamespace +from unittest.mock import Mock +from zipfile import ZipFile + +import pytest + +from ci import github_release + +VERSION = "2.3.4" +SOURCE = "1" * 40 +WORKFLOW_COMMIT = "2" * 40 +RUN = "45112" +PRODUCER_ATTEMPT = "2" +ARTIFACT_ID = "789" +PHASE = "Validate and publish" +PREFIX = "repos/NVIDIA/SkillEvaluator/" + + +def sha256(data): + return hashlib.sha256(data).hexdigest() + + +@pytest.fixture +def producer(monkeypatch): + wheel = f"skillevaluator-{VERSION}-py3-none-any.whl" + sdist = f"skillevaluator-{VERSION}.tar.gz" + bundle = f"skillevaluator-ci-{VERSION}.zip" + contents = {wheel: b"validated wheel", sdist: b"validated sdist", bundle: b"validated bundle"} + + def entry(name): + return {"filename": name, "size": len(contents[name]), "sha256": sha256(contents[name])} + + contents["artifact-manifest.json"] = json.dumps( + { + "version": VERSION, + "source_commit": SOURCE, + "artifacts": [entry(wheel), entry(sdist)], + "ci_bundle": entry(bundle), + } + ).encode() + contents["SHA256SUMS.txt"] = "".join(f"{sha256(data)} {name}\n" for name, data in contents.items()).encode() + archive = io.BytesIO() + with ZipFile(archive, "w") as files: + for name, data in contents.items(): + files.writestr(name, data) + zipped = archive.getvalue() + artifact_digest = sha256(zipped) + + origin = { + "id": int(RUN), + "run_attempt": int(PRODUCER_ATTEMPT), + "event": "workflow_dispatch", + "path": ".github/workflows/release.yml", + "head_branch": "main", + "head_sha": WORKFLOW_COMMIT, + "repository": {"id": 42, "full_name": "NVIDIA/SkillEvaluator"}, + "head_repository": {"id": 42, "full_name": "NVIDIA/SkillEvaluator"}, + "status": "in_progress", + "conclusion": None, + "display_title": f"{PHASE} · SkillEvaluator {VERSION}", + } + name = f"validated-release-{VERSION}-{RUN}-{PRODUCER_ATTEMPT}" + artifact = { + "name": name, + "id": int(ARTIFACT_ID), + "expired": False, + "size_in_bytes": len(zipped), + "digest": f"sha256:{artifact_digest}", + "workflow_run": { + "id": int(RUN), + "head_branch": "main", + "head_sha": WORKFLOW_COMMIT, + "repository_id": 42, + "head_repository_id": 42, + }, + } + attempt_path = f"actions/runs/{RUN}/attempts/{PRODUCER_ATTEMPT}" + artifact_path = f"actions/runs/{RUN}/artifacts?name={name}" + api = Mock( + side_effect={attempt_path: origin, artifact_path: {"total_count": 1, "artifacts": [artifact]}}.__getitem__ + ) + producer = SimpleNamespace( + origin=origin, + artifact=artifact, + digest=artifact_digest, + zipped=zipped, + manifest_digest=sha256(contents["artifact-manifest.json"]), + contents=contents, + api=api, + attempt_path=attempt_path, + artifact_path=artifact_path, + ) + + def download(args, *, stdout, check): + assert args == ["gh", "api", f"{PREFIX}actions/artifacts/{ARTIFACT_ID}/zip"] + assert check + stdout.write(producer.zipped) + + producer.download = Mock(side_effect=download) + monkeypatch.setenv("GITHUB_RUN_ID", RUN) + monkeypatch.setenv("GITHUB_RUN_ATTEMPT", PRODUCER_ATTEMPT) + monkeypatch.setattr(github_release, "tag_target", lambda _: None) + monkeypatch.setattr(github_release, "get_release", lambda _: None) + monkeypatch.setattr(github_release, "api", api) + monkeypatch.setattr(github_release.subprocess, "run", producer.download) + return producer + + +def acquire(producer, output, **overrides): + arguments = { + "version": VERSION, + "source_sha": SOURCE, + "output": output, + "run_ref": f"{RUN}-{PRODUCER_ATTEMPT}", + "manifest_sha256": producer.manifest_digest, + "phase": PHASE, + "artifact_id": ARTIFACT_ID, + "artifact_digest": producer.digest, + } + return github_release.acquire_publication(**(arguments | overrides)) + + +@pytest.mark.parametrize( + ("phase", "publishing_attempt", "conclusion"), + [(PHASE, "2", None), ("Full release", "3", "failure")], +) +def test_same_run_acquires_exact_producer_bytes( + producer, monkeypatch, tmp_path, capsys, phase, publishing_attempt, conclusion +): + monkeypatch.setenv("GITHUB_RUN_ATTEMPT", publishing_attempt) + producer.origin.update( + display_title=f"{phase} · SkillEvaluator {VERSION}", + status="completed" if conclusion else "in_progress", + conclusion=conclusion, + ) + output = tmp_path / "assets" + supplied_digest = f"sha256:{producer.digest}" if conclusion else producer.digest + + monkeypatch.setattr( + sys, + "argv", + [ + "github_release.py", + "acquire", + "--version", + VERSION, + "--source-sha", + SOURCE, + "--assets", + str(output), + "--phase", + phase, + "--validation-run", + f"{RUN}-{PRODUCER_ATTEMPT}", + "--validation-manifest-sha256", + producer.manifest_digest, + "--validation-artifact-id", + ARTIFACT_ID, + "--validation-artifact-digest", + supplied_digest, + ], + ) + + assert github_release.main() == 0 + assert capsys.readouterr().out == "true\n" + assert {path.name: path.read_bytes() for path in output.iterdir()} == producer.contents + assert [call.args[0] for call in producer.api.call_args_list] == [producer.attempt_path, producer.artifact_path] + producer.download.assert_called_once() + + +@pytest.mark.parametrize( + ("overrides", "message"), + [ + ({"artifact_id": None}, "artifact ID and SHA-256 digest"), + ({"artifact_digest": None}, "artifact ID and SHA-256 digest"), + ({"artifact_id": "", "artifact_digest": ""}, "artifact ID and SHA-256 digest"), + ({"artifact_id": None, "artifact_digest": None}, "artifact ID and SHA-256 digest"), + ({"artifact_id": "0"}, "artifact ID and SHA-256 digest"), + ({"artifact_digest": "invalid"}, "artifact ID and SHA-256 digest"), + ({"phase": "Publish release"}, "Validate and publish or Full release"), + ({"run_ref": "99999-2"}, "current workflow run"), + ({"run_ref": f"{RUN}-3"}, "current workflow run"), + ({"manifest_sha256": ""}, "run attempt and manifest SHA-256"), + ], +) +def test_same_run_rejects_invalid_producer_inputs(producer, tmp_path, overrides, message): + output = tmp_path / "assets" + with pytest.raises(ValueError, match=message): + acquire(producer, output, **overrides) + assert not output.exists() + producer.api.assert_not_called() + producer.download.assert_not_called() + + +@pytest.mark.parametrize( + "mutation", + [ + "wrong-phase", + "wrong-version", + "wrong-attempt", + "wrong-workflow", + "fork", + "wrong-lineage", + "wrong-name", + "wrong-id", + "wrong-digest", + ], +) +def test_same_run_rejects_wrong_actions_identity_before_downloading(producer, tmp_path, mutation): + changes = { + "wrong-phase": (producer.origin, "display_title", f"Full release · SkillEvaluator {VERSION}"), + "wrong-version": (producer.origin, "display_title", f"{PHASE} · SkillEvaluator 9.9.9"), + "wrong-attempt": (producer.origin, "run_attempt", 1), + "wrong-workflow": (producer.origin, "path", ".github/workflows/other.yml"), + "fork": (producer.origin["head_repository"], "full_name", "someone/SkillEvaluator"), + "wrong-lineage": (producer.artifact["workflow_run"], "head_sha", "3" * 40), + "wrong-name": (producer.artifact, "name", f"validated-release-{VERSION}-{RUN}-3"), + "wrong-id": (producer.artifact, "id", 900), + "wrong-digest": (producer.artifact, "digest", "sha256:" + "f" * 64), + } + metadata, key, value = changes[mutation] + metadata[key] = value + output = tmp_path / "assets" + with pytest.raises(ValueError, match=r"validation artifact|upstream manual release run"): + acquire(producer, output) + assert not output.exists() + producer.download.assert_not_called() + + +@pytest.mark.parametrize("mutation", ["archive", "manifest", "source"]) +def test_same_run_rejects_different_release_bytes(producer, tmp_path, mutation): + overrides = {} + if mutation == "archive": + producer.zipped = b"!" + producer.zipped[1:] + if mutation == "manifest": + overrides["manifest_sha256"] = "c" * 64 + if mutation == "source": + overrides["source_sha"] = "d" * 40 + + with pytest.raises(ValueError, match=r"ZIP differs|manifest SHA-256 or source commit"): + acquire(producer, tmp_path / "assets", **overrides) + + +@pytest.mark.parametrize("conclusion", ["success", "failure"]) +def test_standalone_publish_checks_completed_validation_without_same_run_outputs( + producer, monkeypatch, tmp_path, conclusion +): + monkeypatch.setenv("GITHUB_RUN_ID", "9000") + producer.origin.update( + display_title=f"Validate release · SkillEvaluator {VERSION}", status="completed", conclusion=conclusion + ) + output = tmp_path / "assets" + arguments = {"phase": "Publish release", "artifact_id": None, "artifact_digest": None} + if conclusion == "failure": + with pytest.raises(ValueError, match="successful Validate release"): + acquire(producer, output, **arguments) + producer.download.assert_not_called() + else: + assert acquire(producer, output, **arguments) is True + assert {path.name: path.read_bytes() for path in output.iterdir()} == producer.contents + + +@pytest.mark.parametrize("previous_receipt", [False, True], ids=["blank", "failed-full-release"]) +def test_standalone_publish_requires_a_qualifying_receipt_after_a_tag_only_failure( + producer, monkeypatch, tmp_path, previous_receipt +): + monkeypatch.setattr(github_release, "tag_target", lambda _: SOURCE) + producer.origin.update( + display_title=f"Full release · SkillEvaluator {VERSION}", status="completed", conclusion="failure" + ) + output = tmp_path / "assets" + with pytest.raises(ValueError, match="successful Validate release"): + acquire( + producer, + output, + phase="Publish release", + artifact_id=None, + artifact_digest=None, + run_ref=f"{RUN}-{PRODUCER_ATTEMPT}" if previous_receipt else "", + manifest_sha256=producer.manifest_digest if previous_receipt else "", + ) + producer.download.assert_not_called() + assert not output.exists() + + +@pytest.mark.parametrize(("phase", "publishing_attempt"), [(PHASE, "2"), ("Full release", "3")]) +def test_combined_publication_acquires_validated_bytes_after_a_tag_only_failure( + producer, monkeypatch, tmp_path, phase, publishing_attempt +): + monkeypatch.setattr(github_release, "tag_target", lambda _: SOURCE) + monkeypatch.setenv("GITHUB_RUN_ATTEMPT", publishing_attempt) + original_run = phase == "Full release" + producer.origin.update( + display_title=f"{phase} · SkillEvaluator {VERSION}", + status="completed" if original_run else "in_progress", + conclusion="failure" if original_run else None, + ) + output = tmp_path / "assets" + + assert acquire(producer, output, phase=phase) is True + assert {path.name: path.read_bytes() for path in output.iterdir()} == producer.contents + assert [call.args[0] for call in producer.api.call_args_list] == [producer.attempt_path, producer.artifact_path] + + +def test_same_run_command_preserves_restore_first(producer, monkeypatch, tmp_path, capsys): + restore = Mock(return_value=True) + monkeypatch.setattr(github_release, "restore", restore) + output = tmp_path / "assets" + monkeypatch.setattr( + sys, + "argv", + [ + "github_release.py", + "acquire", + "--version", + VERSION, + "--source-sha", + SOURCE, + "--assets", + str(output), + "--phase", + PHASE, + "--validation-artifact-id", + "invalid", + ], + ) + + assert github_release.main() == 0 + assert capsys.readouterr().out == "false\n" + restore.assert_called_once_with(VERSION, SOURCE, output) + producer.api.assert_not_called() + + +def test_full_release_preflight_rejects_an_existing_version_before_creating_a_bundle_pr(monkeypatch): + def git_output(args, *, text): + assert text + if args == ["git", "rev-list", "--first-parent", WORKFLOW_COMMIT]: + return f"{WORKFLOW_COMMIT}\n{SOURCE}\n" + assert args == ["git", "show", f"{SOURCE}:pyproject.toml"] + return f'[project]\nversion = "{VERSION}"\n' + + monkeypatch.setattr(github_release.subprocess, "check_output", git_output) + tag_target = Mock(side_effect=[None, "3" * 40, SOURCE, "3" * 40]) + monkeypatch.setattr(github_release, "tag_target", tag_target) + + github_release.preflight(VERSION, SOURCE, WORKFLOW_COMMIT, "Full release") + with pytest.raises(ValueError, match=r"already exists\. Re-run failed jobs") as error: + github_release.preflight(VERSION, SOURCE, WORKFLOW_COMMIT, "Full release") + assert "reviewed bundle merge SHA" in str(error.value) + assert "Validate and publish if the run stopped before creating a draft" in str(error.value) + assert "Publish release to resume an existing draft or immutable release" in str(error.value) + github_release.preflight(VERSION, SOURCE, WORKFLOW_COMMIT, "Validate and publish") + with pytest.raises(ValueError, match="points to a different commit"): + github_release.preflight(VERSION, SOURCE, WORKFLOW_COMMIT, "Publish release") + assert [call.args for call in tag_target.call_args_list] == [(f"v{VERSION}",)] * 4