~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(release): preserve Docker tags and pending release runs (#7138)
LearningCircuit6b0dccd688fb
diff --git a/.github/scripts/strip-concurrency-queue.py b/.github/scripts/strip-concurrency-queue.pynew file mode 100644index 0000000000..d9e5e0c385--- /dev/null+++ b/.github/scripts/strip-concurrency-queue.py@@ -0,0 +1,44 @@+#!/usr/bin/env python3+"""Blank `concurrency.queue` in workflow files, in place, for scanners.++Checkov 3.2.499 validates workflows against a schema that predates+`concurrency.queue`. A workflow that fails the schema is skipped silently,+so the release gate would not scan it. Blanking removes only that cause of+skipping; other schema failures still skip a workflow. Run this on the CI checkout (never on+committed files) before scanning. The key is replaced by spaces, so line numbers+stay the same (line endings are normalised to LF when the file is rewritten). It reuses the actionlint adapter,+which also rejects invalid queue values.+"""++import importlib.util+import sys+from pathlib import Path++HOOK = (+ Path(__file__).resolve().parents[2]+ / ".pre-commit-hooks"+ / "actionlint-self-repository.py"+)+++def main(paths) -> int:+ spec = importlib.util.spec_from_file_location("actionlint_adapter", HOOK)+ adapter = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(adapter)+ failed = False+ for path in map(Path, paths):+ try:+ source = path.read_text(encoding="utf-8")+ stripped = adapter.strip_concurrency_queue(source)+ except Exception as exc: # noqa: BLE001 - report and fail the step+ print(f"{path}: {exc}", file=sys.stderr)+ failed = True+ continue+ if stripped != source:+ path.write_text(stripped, encoding="utf-8")+ print(f"{path}: blanked concurrency.queue")+ return int(failed)+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/.github/workflows/checkov.yml b/.github/workflows/checkov.ymlindex 7df6155ccd..ea9ce11d4f 100644--- a/.github/workflows/checkov.yml+++ b/.github/workflows/checkov.yml@@ -55,6 +55,16 @@ jobs:-o cli -o sarif \--output-file-path console,checkov-compose.sarif+ # Checkov 3.2.499's workflow schema rejects `concurrency.queue` and+ # silently skips any workflow that fails it, so release-gate.yml would go+ # unscanned. Blank the key in this CI checkout only (line numbers are+ # preserved) so the queue key no longer causes a skip. Checkov still+ # skips workflows that fail its schema for other reasons (for example+ # release.yml's `attestations` key and an expression in docker-tests.yml's+ # `cancel-in-progress`).+ - name: Blank concurrency.queue for Checkov+ run: python3 .github/scripts/strip-concurrency-queue.py .github/workflows/*.yml+- name: Run Checkov on GitHub Actions workflowsrun: |checkov -d .github/workflows \diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.ymlindex 8886b0b5a4..936953dad7 100644--- a/.github/workflows/docker-publish.yml+++ b/.github/workflows/docker-publish.yml@@ -48,8 +48,8 @@ permissions: {} # Minimal top-level for OSSF Scorecard Token-Permissions# NOTE: no workflow-level `concurrency:` block. As a reusable workflow# called from release.yml, this workflow runs as part of the caller's run,-# and release.yml's caller-level concurrency (keyed on github.workflow +-# github.ref) already serialises release runs for the same tag. Adding a+# and release.yml's caller-level concurrency (keyed on github.workflow+# alone) already serialises all release runs across refs. Adding a# callee-level block would be a no-op for the documented threat model# (two simultaneous releases for the same ref) and would not be reachable# anyway because there is no longer any standalone invocation path.diff --git a/.github/workflows/release-cleanup-tests.yml b/.github/workflows/release-cleanup-tests.ymlnew file mode 100644index 0000000000..13f2a8155d--- /dev/null+++ b/.github/workflows/release-cleanup-tests.yml@@ -0,0 +1,35 @@+name: Release Cleanup Tests++# Runs the cleanup-on-rejection shell block from release.yml against a+# simulated registry. Kept apart from release-package-tests.yml so that+# file stays identical on the release branch and main.+on:+ pull_request:+ paths:+ - ".github/workflows/release-cleanup-tests.yml"+ - ".github/workflows/release.yml"+ - "tests/ci/standalone/test_release_cleanup.py"+ workflow_dispatch:++permissions:+ contents: read++jobs:+ cleanup-tests:+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - name: Harden runner+ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1+ with:+ egress-policy: audit+ - name: Checkout+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - name: Set up Python+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: '3.12'+ - name: Test release cleanup without loading the application+ run: python -m unittest discover -s tests/ci/standalone -p 'test_release_cleanup.py' -vdiff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.ymlindex d453926f9c..b148efe23c 100644--- a/.github/workflows/release-gate.yml+++ b/.github/workflows/release-gate.yml@@ -41,17 +41,22 @@ permissions: {} # Minimal top-level for OSSF Scorecard# The group MUST use a literal prefix, not ${{ github.workflow }}: inside a# workflow_call invocation github.workflow resolves to the *caller's* name# (release.yml = "Create Release"), so ${{ github.workflow }} would collide-# with release.yml's own "Create Release-<ref>" group. The parent holds that+# with release.yml's own "Create Release" group. The parent holds that# group and waits for this called workflow, which can't acquire the same group# (cancel-in-progress: false) — GitHub detects the deadlock and cancels the# whole release run. A literal "release-gate-" prefix keeps the called group# distinct from the parent while still serializing standalone runs.#-# cancel-in-progress stays false — this gate is the only path to publishing,-# so an in-flight run must never be killed by a newer trigger.+# queue: max lets up to 100 runs wait instead of the default single pending+# slot, so a scheduled or manual gate run does not replace a release's waiting+# gate invocation. When 100 are pending GitHub cancels additional runs.+# cancel-in-progress stays false (queue: max cannot be combined with true) —+# this gate is the only path to publishing, so an in-flight run must not be+# killed.concurrency:group: release-gate-${{ github.ref }}cancel-in-progress: false+ queue: maxjobs:# ============================================diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex cad0fa1337..9ad9b25f5d 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -10,12 +10,25 @@ on:permissions: {} # Minimal permissions at workflow level for OSSF Scorecard-# Prevent multiple full pipeline runs from competing for runners simultaneously.-# cancel-in-progress: false ensures the active run completes; new runs queue (at most-# 1 in-progress + 1 pending). Tag pushes get their own group (refs/tags/v1.2.3).+# Serialize the entire release workflow so main and tag pushes for the same+# version/SHA cannot race. queue: max lets up to 100 runs wait instead of the+# default single pending slot, which a later main push would replace. When 100+# are pending GitHub cancels additional runs (the newest arrivals).+# queue: max cannot be combined with cancel-in-progress: true.+# Trade-off: this workflow runs on every push to main, and every waiting run+# now takes its own serial turn. Before, a burst of pushes collapsed to one+# running plus one pending run; in a 100-run history spanning 161 hours, 50+# runs were replaced that way. Under queue: max all 100 would have run (about+# 66 serial group-hours), and even a version-check-only no-op run held the+# group for a median of 30 minutes (p90 99), mostly waiting for a runner. A+# push burst can therefore delay a real release run and the workflow_dispatch+# retry behind stale-SHA runs. This is accepted so a release tag run is not+# replaced by a later push; it can still be cancelled once 100 runs are+# already pending (see above).concurrency:- group: ${{ github.workflow }}-${{ github.ref }}+ group: ${{ github.workflow }}cancel-in-progress: false+ queue: maxjobs:# ============================================================================@@ -638,13 +651,14 @@ jobs:# Retag the prerelease manifest as the release tags (:VERSION, :MAJOR_MINOR,# :latest). Runs as a reusable workflow_call so its result is visible to# downstream jobs in this run — specifically: create-release blocks on- # success here, and cleanup-on-rejection keys its cosign-deletion logic on- # `needs.publish-docker.result`. Before this refactor, docker-publish.yml- # was triggered via repository_dispatch and its outcome was invisible to- # the parent release.yml run, which made cosign artifact cleanup unsafe- # after a partial retag failure (release tags could exist sharing the- # prerelease manifest digest, and deleting `sha256-<digest>.{sig,att}`- # would invalidate those release-tag signatures).+ # success here, and cleanup-on-rejection fires on+ # `needs.publish-docker.result` (it retains cosign artifacts). Before this+ # refactor, docker-publish.yml was triggered via repository_dispatch and+ # its outcome was invisible to the parent release.yml run, which made+ # cosign artifact cleanup unsafe after a partial retag failure (release+ # tags could exist sharing the prerelease manifest digest, and deleting+ # `sha256-<digest>.{sig,att}` would invalidate those release-tag+ # signatures).publish-docker:needs: [build, prerelease-docker]if: ${{ !cancelled() && needs.prerelease-docker.result == 'success' && needs.build.outputs.release_exists == 'false' }}@@ -1804,35 +1818,19 @@ jobs:# ============================================================================# CLEANUP ON REJECTION# ============================================================================- # In the build-once-promote model, prerelease-docker signs the manifest- # BEFORE the publish step runs. If publish-docker (the retag step) fails- # or the maintainer rejects the `release` env approval, the prerelease- # tag and its cosign artifacts (`sha256-<digest>.{sig,att}`) are left- # orphaned on Docker Hub forever — the existing cleanup loop inside- # docker-publish.yml only runs on its success path.+ # A failed promotion can leave some release tags pointing at this build.+ # Only roll back tags whose digest still matches the failed build. A+ # mismatched tag that shares this build's platform images, or :VERSION on+ # another build, is kept and fails the job for manual review. The+ # workflow-wide concurrency group serializes publishers across refs.+ # Recheck the release at cleanup time: a rerun can have stale build outputs+ # from before another run successfully published this version.#- # SAFETY: cosign signature/attestation artifacts are stored at a tag named- # `sha256-<manifest-digest>.{sig,att}` and discovered by manifest digest,- # NOT by image tag. After publish-docker SUCCEEDS, the release tags- # (`:VERSION`, `:MAJOR_MINOR`, `:latest`) share the prerelease manifest- # digest (imagetools retag preserves the digest), so the cosign artifacts- # anchor BOTH the deleted prerelease tag AND the live release tags.- # Deleting them after a successful retag would invalidate release-tag- # cosign verification.- #- # Therefore: this job ONLY fires when publish-docker did not succeed.- # Beyond that point, docker-publish.yml's success-path cleanup handles- # prerelease-tag deletion, and cosign artifacts must stay.- #- # Edge case: partial retag failure (e.g., `:1.6.9` lands but `:latest`- # fails) — publish-docker exits failure with some release tags already- # created. The cleanup script enumerates the three possible release tags- # against Docker Hub and rolls back any that exist BEFORE deleting- # cosign artifacts. This is the only case where we delete release tags- # rather than leave them.- # ============================================================================+ # Preserve content-addressed cosign artifacts. Historical release tags or+ # other manifest lists can still reference those digests, including shared+ # per-architecture images. Tag ownership cannot prove artifact exclusivity.cleanup-on-rejection:- name: Clean up orphan prerelease tags and signatures+ name: Clean up rejected release tagsneeds: [build, prerelease-docker, publish-docker]if: >-${{ always()@@ -1846,10 +1844,9 @@ jobs:# DOCKER_USERNAME / DOCKER_PASSWORD are env-scoped to `release`# (deliberately not repo-level — see comment on the build job above).# Without `environment: release` here, those secrets resolve to empty- # strings and the Docker Hub login at the bottom of this job exits 1,- # leaving the orphan tags + cosign artifacts the cleanup is meant to- # remove. The `release` env approval was already granted upstream in- # this run, so this does not add a new prompt.+ # strings and Docker Hub login fails. Rejecting this job's protected+ # environment approval also prevents cleanup; maintainer recovery is+ # documented in the release guide.environment: releasepermissions:contents: read@@ -1860,8 +1857,9 @@ jobs:with:egress-policy: audit- - name: Roll back partial release tags then delete prerelease + cosign artifacts+ - name: Roll back verified tags from the failed releaseenv:+ GITHUB_TOKEN: ${{ github.token }}DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}VERSION: ${{ needs.build.outputs.version }}@@ -1869,13 +1867,25 @@ jobs:DIGEST: ${{ needs.prerelease-docker.outputs.manifest_digest }}run: |set -euo pipefail- # Authenticate with Docker Hub API (same JWT flow as docker-publish.yml cleanup)++ # A previous attempt's release_exists output is not fresh enough for a+ # destructive rollback. A published version must survive later retries.+ RELEASE_STATUS=$(curl -sS -o /dev/null -w "%{http_code}" \+ -H "Authorization: Bearer ${GITHUB_TOKEN}" \+ "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/releases/tags/v${VERSION}" || echo "ERR")+ case "$RELEASE_STATUS" in+ 200) echo "Version ${VERSION} has a release; preserving its tags and artifacts"; exit 0;;+ 404) ;;+ *) echo "::error::Could not verify release absence (HTTP ${RELEASE_STATUS}); refusing cleanup"; exit 1;;+ esac++ printf '%s' "${DOCKER_PASSWORD}" | docker login \+ --username "${DOCKER_USERNAME}" --password-stdinTOKEN=$(curl -sS -X POST -H "Content-Type: application/json" \-d "{\"username\":\"${DOCKER_USERNAME}\",\"password\":\"${DOCKER_PASSWORD}\"}" \https://hub.docker.com/v2/users/login/ | jq -r .token)-if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then- echo "::error::Failed to authenticate with Docker Hub API — cannot clean up orphans"+ echo "::error::Failed to authenticate with Docker Hub API"exit 1fi@@ -1883,135 +1893,239 @@ jobs:MANIFEST_TAG="prerelease-v${VERSION}-${SHORT_SHA}"MAJOR_MINOR=$(echo "$VERSION" | cut -d. -f1,2)+ # Each tag is judged on its own evidence, so one failed registry call+ # must not skip the remaining tags. Record failures, keep going, and+ # fail the job at the end.+ FAILED=false+ fail() {+ echo "::error::$1"+ FAILED=true+ }+delete_tag() {local TAG="$1"local STATUSSTATUS=$(curl -sS -o /dev/null -w "%{http_code}" -X DELETE \-H "Authorization: JWT ${TOKEN}" \"https://hub.docker.com/v2/repositories/${REPO}/tags/${TAG}/" || echo "ERR")+ DELETE_STATUS="$STATUS"case "$STATUS" in200|204) echo "Deleted ${TAG}";;- 404) echo "Skip ${TAG} (already absent — expected)";;- 401|403)- echo "::error::Auth failure deleting ${TAG} — DOCKER_PASSWORD may be missing Delete scope on the Docker Hub PAT"- exit 1- ;;- *) echo "::warning::Unexpected HTTP ${STATUS} for ${TAG}";;+ 404) echo "Skip ${TAG} (already absent)";;+ *) fail "Failed to delete ${TAG} (HTTP ${STATUS}); continuing with other tags";;esac}- # =====================================================================- # STEP 1 — Partial retag rollback.- # =====================================================================- # If publish-docker failed mid-way through `docker buildx imagetools- # create -t :VERSION -t :MAJOR_MINOR -t :latest`, one or two of the- # three release tags may have landed. Those tags would point at the- # prerelease manifest digest, which we're about to delete cosign- # artifacts for. We MUST roll back any landed release tags BEFORE- # touching cosign — otherwise the rollback leaves them broken.- #- # If publish-docker was skipped (prerelease failed before reaching- # retag), the release tags can't exist, so this loop is a cheap no-op- # (three 404 responses).- # =====================================================================- echo "STEP 1 — Roll back any release tags that landed during a partial retag..."- for RELEASE_TAG in "${VERSION}" "${MAJOR_MINOR}" "latest"; do- # HEAD-check before DELETE so the "expected absent" case is silent.- # Docker Hub's tag endpoint returns 200 on HEAD if tag exists, 404 if not.- CHECK=$(curl -sS -o /dev/null -w "%{http_code}" \+ DIGEST_RE='^sha256:[0-9a-f]{64}$'++ # Platform image digests of a multi-platform index, one per line,+ # sorted. Attestation entries (platform unknown) are excluded: they+ # are not images and say nothing about which build a tag serves.+ platform_digests() {+ docker buildx imagetools inspect "$1" --raw \+ | jq -r '[.manifests[]? | select(.platform.architecture != "unknown") | .digest] | sort | .[]'+ }++ valid_platforms() {+ local P+ [[ -n "$1" ]] || return 1+ while IFS= read -r P; do+ [[ "$P" =~ $DIGEST_RE ]] || return 1+ done <<< "$1"+ }++ # BUILD_DIGEST is the index whose platform images identify this build.+ BUILD_DIGEST="${DIGEST:-}"+ BUILD_PLATFORMS=""+ load_build_platforms() {+ if [[ -n "$BUILD_PLATFORMS" ]]; then+ return 0+ fi+ if ! BUILD_PLATFORMS=$(platform_digests "${REPO}@${BUILD_DIGEST}") \+ || ! valid_platforms "$BUILD_PLATFORMS"; then+ BUILD_PLATFORMS=""+ return 1+ fi+ }++ shares_build_platform() {+ local P B+ while IFS= read -r P; do+ while IFS= read -r B; do+ if [[ "$P" == "$B" ]]; then+ return 0+ fi+ done <<< "$BUILD_PLATFORMS"+ done <<< "$1"+ return 1+ }++ # Resolve a shared tag to REMOTE_DIGEST. Returns 0 only for a present+ # tag with a valid digest. An absent tag is skipped; any other lookup+ # or inspect failure is a fail(), so no tag is left unclassified.+ REMOTE_DIGEST=""+ read_shared_tag() {+ local TAG="$1"+ local STATUS+ REMOTE_DIGEST=""+ STATUS=$(curl -sS -o /dev/null -w "%{http_code}" \-H "Authorization: JWT ${TOKEN}" \- "https://hub.docker.com/v2/repositories/${REPO}/tags/${RELEASE_TAG}/" || echo "ERR")- if [ "$CHECK" = "200" ]; then- echo "::warning::Release tag ${RELEASE_TAG} exists from a partial retag — rolling back"- delete_tag "${RELEASE_TAG}"- else- echo "Release tag ${RELEASE_TAG}: not present (HTTP ${CHECK}) — nothing to roll back"+ "https://hub.docker.com/v2/repositories/${REPO}/tags/${TAG}/" || echo "ERR")+ case "$STATUS" in+ 404) echo "Skip ${TAG} (absent)"; return 1;;+ 200) ;;+ *) fail "Could not verify ${TAG} (HTTP ${STATUS}); keeping it"; return 1;;+ esac+ if ! REMOTE_DIGEST=$(docker buildx imagetools inspect \+ "${REPO}:${TAG}" --format '{{json .Manifest.Digest}}' | tr -d '"'); then+ REMOTE_DIGEST=""+ fail "Could not inspect ${TAG}; keeping it"+ return 1fi- done+ if [[ ! "$REMOTE_DIGEST" =~ $DIGEST_RE ]]; then+ REMOTE_DIGEST=""+ fail "Invalid digest for ${TAG}; keeping it"+ return 1+ fi+ }- # =====================================================================- # STEP 2 — Prerelease tag cleanup.- # =====================================================================- # Always-safe targets: the prerelease manifest list + its per-arch- # children + the floating `:prerelease` tag. Cleanup is best-effort- # here (404s are normal — e.g., build failed before pushing arm64).- #- # The floating `:prerelease` tag (re-pointed by prerelease-docker.yml- # to the current run's manifest) is included so a rejected release- # does not leave `:prerelease` pointing at a manifest whose cosign- # artifacts step 4 below is about to delete — pulling `:prerelease`- # in that window would yield an image whose signature is gone, and- # the README cosign-verify recipe would fail. Returning 404 on- # `:prerelease` is unambiguously safer than serving an unverifiable- # image; the next successful prerelease-docker run re-creates it.- # =====================================================================- echo "STEP 2 — Delete prerelease tags..."- for TAG in "${MANIFEST_TAG}" "${MANIFEST_TAG}-amd64" "${MANIFEST_TAG}-arm64" "prerelease"; do- delete_tag "${TAG}"- done+ # imagetools create can re-encode the index it copies (the reason+ # docker-publish verifies promoted digests). A re-encoded copy of+ # this build has a new index digest but the same platform images,+ # so an index mismatch alone does not prove another build owns the+ # tag. An identical image of a published release also shares them,+ # so a shared platform image is reported and kept, not deleted.+ # Returns 0 when the tag shares a platform image with BUILD_DIGEST,+ # 1 when it shares none, and 2 after a fail() when either side's+ # platform images cannot be read.+ compare_platforms() {+ local TAG="$1"+ local REMOTE_PLATFORMS+ if ! load_build_platforms; then+ fail "${TAG} points at ${REMOTE_DIGEST}, but this build's platform images (${BUILD_DIGEST}) could not be read; keeping it, verify it manually"+ return 2+ fi+ if ! REMOTE_PLATFORMS=$(platform_digests "${REPO}:${TAG}") \+ || ! valid_platforms "$REMOTE_PLATFORMS"; then+ fail "Could not read the platform images of ${TAG} (${REMOTE_DIGEST}); keeping it, verify it manually"+ return 2+ fi+ if shares_build_platform "$REMOTE_PLATFORMS"; then+ return 0+ fi+ return 1+ }- # =====================================================================- # STEP 3 — Discover per-arch digests from the manifest list BEFORE- # we delete cosign artifacts.- # =====================================================================- # prerelease-docker.yml's per-arch SBOM step attests against each- # per-arch digest, producing artifacts at- # `sha256-<per-arch-digest>.{sig,att,sbom}` in addition to the- # manifest-list-digest artifacts. Need to enumerate from the manifest- # while it still exists (we just deleted the TAG, but the manifest- # body persists until Docker Hub GC, and we can inspect by digest).- # Use the captured DIGEST to inspect the manifest list directly.- # =====================================================================- PER_ARCH_TAGS=()- if [[ -n "${DIGEST:-}" && "$DIGEST" == sha256:* ]]; then- echo "STEP 3 — Discovering per-arch digests from manifest list ${DIGEST}..."- if docker buildx imagetools inspect "${REPO}@${DIGEST}" --raw > /tmp/manifest.json 2>/dev/null; then- while IFS= read -r PER_ARCH_DIGEST; do- if [[ -n "${PER_ARCH_DIGEST}" && "${PER_ARCH_DIGEST}" == sha256:* ]]; then- PER_ARCH_TAG_PREFIX="${PER_ARCH_DIGEST/:/-}"- PER_ARCH_TAGS+=(- "${PER_ARCH_TAG_PREFIX}.sig"- "${PER_ARCH_TAG_PREFIX}.att"- "${PER_ARCH_TAG_PREFIX}.sbom"- )- echo " queued cleanup for per-arch artifacts at ${PER_ARCH_DIGEST}"- fi- done < <(jq -r '.manifests[] | select(.platform.architecture != "unknown") | .digest' /tmp/manifest.json)- else- echo "::warning::Could not inspect manifest at ${DIGEST} — skipping per-arch attestation cleanup"+ # v${VERSION} has no GitHub Release, so no published build owns+ # :${VERSION}. Another build there is an earlier unreleased attempt,+ # with or without a verified digest: report it, keep it and fail.+ # Returns 0 after the fail(), 1 for any other tag.+ report_unreleased_version_tag() {+ local TAG="$1"+ if [[ "$TAG" != "$VERSION" ]]; then+ return 1fi- else- echo "STEP 3 — No valid manifest digest captured (got '${DIGEST:-<empty>}'); skipping per-arch discovery"+ fail "${TAG} points at another unreleased build (${REMOTE_DIGEST}) although v${VERSION} has no GitHub Release; keeping it, verify it manually"+ }++ rollback_owned_tag() {+ local TAG="$1"+ local SHARES=0+ read_shared_tag "$TAG" || return 0+ if [[ "$REMOTE_DIGEST" == "$DIGEST" ]]; then+ delete_tag "$TAG"+ return 0+ fi+ compare_platforms "$TAG" || SHARES=$?+ case "$SHARES" in+ 0)+ fail "${TAG} points at ${REMOTE_DIGEST}, which shares platform images with this build (${DIGEST}), for example a re-encoded promotion; keeping it, verify and remove it manually"+ return 0;;+ 2) return 0;;+ esac+ report_unreleased_version_tag "$TAG" && return 0+ echo "Preserving ${TAG}; it points at another build (${REMOTE_DIGEST})"+ }++ # Without a verified digest nothing shared is deleted, but every+ # shared tag is still classified against the manifest tag's digest+ # with the same reads and the same failure handling as above.+ report_manifest_tag() {+ local TAG="$1"+ local SHARES=0+ read_shared_tag "$TAG" || return 0+ if [[ "$REMOTE_DIGEST" == "$MANIFEST_DIGEST" ]]; then+ fail "${TAG} still points at ${MANIFEST_TAG} (${MANIFEST_DIGEST}), which this run never verified; kept, remove it manually"+ return 0+ fi+ compare_platforms "$TAG" || SHARES=$?+ case "$SHARES" in+ 0)+ fail "${TAG} (${REMOTE_DIGEST}) shares platform images with ${MANIFEST_TAG} (${MANIFEST_DIGEST}), which this run never verified; kept, remove it manually"+ return 0;;+ 2) return 0;;+ esac+ report_unreleased_version_tag "$TAG" && return 0+ echo "Keeping ${TAG}; it points at another build (${REMOTE_DIGEST})"+ }++ # Shared tags may belong to another build. Roll them back first, and+ # only when their digest matches this build's verified digest, so a+ # published-but-rejected build stops serving as soon as possible.+ DIGEST_VALID=false+ if [[ "${DIGEST:-}" =~ $DIGEST_RE ]]; then+ DIGEST_VALID=true+ for TAG in "${VERSION}" "${MAJOR_MINOR}" latest prerelease; do+ rollback_owned_tag "$TAG"+ donefi- # =====================================================================- # STEP 4 — Cosign signature/attestation artifact cleanup.- # =====================================================================- # Safe to delete only because STEP 1 already rolled back any release- # tags that might be sharing these digests. The .sbom entries are- # legacy from `cosign attach sbom` (current code uses `cosign attest- # --type spdxjson` which writes to .att) — kept as belt-and-suspenders- # cleanup for any leftovers from older releases.- # =====================================================================- COSIGN_TAGS=()- if [[ -n "${DIGEST:-}" && "$DIGEST" == sha256:* ]]; then- DIGEST_TAG_PREFIX="${DIGEST/:/-}"- COSIGN_TAGS+=(- "${DIGEST_TAG_PREFIX}.sig"- "${DIGEST_TAG_PREFIX}.att"- "${DIGEST_TAG_PREFIX}.sbom"- )+ # Without a verified digest, record what the build-specific manifest+ # tag resolves to before it is deleted, and report every shared tag+ # that still points at it or shares its platform images. A shared+ # tag that cannot be read, or :VERSION on another build, fails the+ # job like it does above. The digest is read from a mutable tag+ # rather than from this run's verified output, so matching tags are+ # kept for a maintainer to remove.+ MANIFEST_DIGEST=""+ if [[ "$DIGEST_VALID" != "true" ]]; then+ if MANIFEST_DIGEST=$(docker buildx imagetools inspect \+ "${REPO}:${MANIFEST_TAG}" --format '{{json .Manifest.Digest}}' | tr -d '"') \+ && [[ "$MANIFEST_DIGEST" =~ $DIGEST_RE ]]; then+ echo "${MANIFEST_TAG} resolves to ${MANIFEST_DIGEST}"+ BUILD_DIGEST="$MANIFEST_DIGEST"+ for TAG in "${VERSION}" "${MAJOR_MINOR}" latest prerelease; do+ report_manifest_tag "$TAG"+ done+ else+ MANIFEST_DIGEST=""+ fifi- COSIGN_TAGS+=("${PER_ARCH_TAGS[@]}")- if [ "${#COSIGN_TAGS[@]}" -gt 0 ]; then- echo "STEP 4 — Delete cosign signature/attestation artifacts..."- for TAG in "${COSIGN_TAGS[@]}"; do- delete_tag "${TAG}"- done- else- echo "STEP 4 — No cosign artifact tags to clean up (no captured digest)"+ # These build-specific tags cannot belong to a different source+ # revision, so they need no digest. The per-arch tags are pushed+ # before the vulnerability scan and create-manifest (the only digest+ # producer) finish, so a failed scan or arch build leaves them+ # behind with no digest.+ MANIFEST_TAG_FOUND=false+ for TAG in "${MANIFEST_TAG}" "${MANIFEST_TAG}-amd64" "${MANIFEST_TAG}-arm64"; do+ delete_tag "$TAG"+ if [[ "$TAG" == "$MANIFEST_TAG" && "$DELETE_STATUS" != "404" ]]; then+ MANIFEST_TAG_FOUND=true+ fi+ done++ if [[ "$DIGEST_VALID" != "true" ]]; then+ if [[ -n "$MANIFEST_DIGEST" ]]; then+ fail "No valid build digest; kept shared tags. ${MANIFEST_TAG} was ${MANIFEST_DIGEST}; every shared tag reported above as serving it or as unreadable may still serve this unsigned build, verify and remove it manually"+ elif [[ "$MANIFEST_TAG_FOUND" == "true" ]]; then+ fail "No valid build digest, but ${MANIFEST_TAG} existed; :prerelease may still point at this unsigned build; kept shared tags, verify :prerelease manually"+ else+ fail "No valid build digest; kept shared tags unverified. If this build's manifest was ever created, verify :prerelease manually"+ fi+ fi+ echo "Preserving signatures, attestations and SBOM artifacts for retained digest references"+ if [[ "$FAILED" == "true" ]]; then+ echo "::error::Cleanup incomplete; see errors above"+ exit 1fi- # NOTE: NO `continue-on-error: true` at job level — auth failures- # (401/403) are loud so missing token scopes can't silently let- # orphans accumulate forever.diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex ad2e444794..699f9c0cf5 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -85,11 +85,12 @@ repos:name: Lint GitHub Actions workflowsdescription: "Static checker for GitHub Actions workflow files"files: ^\.github/workflows/.*\.ya?ml$- # The pinned actionlint predates `$/`. Normalize workflow-call and- # step-level local action refs in stdin so its input, secret, output+ # The pinned actionlint predates `$/` and concurrency.queue. Adapt+ # those validated constructs in stdin so its input, secret, output# and callee checks still run.# Keep the original filename for local metadata lookup/diagnostics.- # Remove the adapter once actionlint supports self-repository refs.+ # Remove the adapter only once actionlint supports both self-repository+ # refs and concurrency.queue; Checkov's strip step also imports it.entry: python3 .pre-commit-hooks/actionlint-self-repository.pyrequire_serial: true- id: actionlintdiff --git a/.pre-commit-hooks/actionlint-self-repository.py b/.pre-commit-hooks/actionlint-self-repository.pyindex d77c411ef3..ada8b7f7e4 100644--- a/.pre-commit-hooks/actionlint-self-repository.py+++ b/.pre-commit-hooks/actionlint-self-repository.py@@ -1,15 +1,25 @@#!/usr/bin/env python3-"""Validate self-repository workflow calls with the pinned actionlint.+"""Validate workflows with pinned actionlint plus current GitHub syntax.Until actionlint understands `$/`, normalize job-level call references andstep-level local action references to `./` in stdin only. Keeping theoriginal filename lets actionlint load the callee's inputs, secrets andoutputs, and the local action's inputs, from the repository. No diagnosticsare suppressed and no workflow files are rewritten.++The pinned actionlint also predates GitHub's `concurrency.queue` setting.+Validate its allowed values and blank that key in stdin, keeping the line+number while actionlint checks the remainder of the workflow. This covers the+workflow-level and job-level `concurrency` mappings. GitHub rejects+`queue: max` together with `cancel-in-progress: true`, so `queue: max` is+accepted only with `cancel-in-progress: false` or no such key; an expression+cannot be proven false and is rejected. A duplicated `queue` key in one+mapping is rejected, as actionlint rejects every other duplicated key."""import argparseimport json+import reimport subprocessimport sysfrom pathlib import Path@@ -19,6 +29,13 @@ from yaml.nodes import MappingNode, ScalarNode, SequenceNodefrom yaml.tokens import ScalarToken+# The exact text a blanked `queue` pair may have: a plain or quoted key, one+# colon, and an optional anchor plus a plain or quoted single/max value.+QUEUE_PAIR = re.compile(+ r"""(["']?)queue\1[ \t]*:[ \t]*(?:&[^\s,\[\]{}]+[ \t]+)?(["']?)(?:single|max)\2"""+)++def mapping_values(node, key):if isinstance(node, MappingNode):for name, value in node.value:@@ -26,10 +43,97 @@ def mapping_values(node, key):yield value+def queue_edits(document, source: str) -> list:+ """Validate concurrency.queue and return edits that blank it."""+ edits = []+ concurrencies = list(mapping_values(document, "concurrency"))+ for jobs in mapping_values(document, "jobs"):+ for _, job in jobs.value if isinstance(jobs, MappingNode) else ():+ concurrencies.extend(mapping_values(job, "concurrency"))+ for concurrency in concurrencies:+ if not isinstance(concurrency, MappingNode):+ continue+ if len(list(mapping_values(concurrency, "queue"))) > 1:+ # actionlint rejects any other duplicated key; blanking every+ # copy would hide a workflow GitHub rejects.+ raise ValueError("concurrency.queue key is duplicated")+ for key, value in concurrency.value:+ if not isinstance(key, ScalarNode) or key.value != "queue":+ continue+ if not isinstance(value, ScalarNode) or value.value not in {+ "single",+ "max",+ }:+ raise ValueError("concurrency.queue must be single or max")+ if value.value == "max" and any(+ not isinstance(cancel, ScalarNode) or cancel.value != "false"+ for cancel in mapping_values(concurrency, "cancel-in-progress")+ ):+ # GitHub documents this pair as a workflow validation error.+ # An expression cannot be proven false, so it is rejected too.+ raise ValueError(+ "concurrency.queue max requires cancel-in-progress: false"+ " or no cancel-in-progress"+ )+ start, end = key.start_mark.index, value.end_mark.index+ if end <= start:+ # An alias value points back at its earlier anchor.+ raise ValueError("concurrency.queue must not be an alias")+ if "\n" in source[start:end]:+ raise ValueError(+ "concurrency.queue must be a scalar on one line"+ )+ if not QUEUE_PAIR.fullmatch(source[start:end]):+ # An aliased or anchored key reports the position of its+ # anchor, so the span may reach back over unrelated text.+ # Blank only a span that is exactly the queue pair.+ raise ValueError(+ "concurrency.queue key must be a plain, unanchored"+ " scalar and not an alias"+ )+ edits.append((start, end, " " * (end - start)))+ return edits+++def checked_edits(source: str, edits) -> str:+ """Apply edits and fail closed if the result is no longer valid YAML."""+ result = apply_edits(source, edits)+ if edits:+ try:+ yaml.compose(result, Loader=yaml.SafeLoader)+ except yaml.YAMLError as exc:+ # Blanking a pair in a flow mapping can leave an empty entry.+ raise ValueError(+ "blanking concurrency.queue leaves invalid YAML; put queue"+ " last in a flow mapping or use a block mapping"+ ) from exc+ return result+++def apply_edits(source: str, edits) -> str:+ """Apply position-ordered, de-duplicated edits from the end backwards."""+ # An aliased mapping or job is reached more than once and yields the+ # same edit each time; identical edits count as one.+ edits = sorted(set(edits), key=lambda edit: edit[:2], reverse=True)+ for (later_start, _, _), (_, end, _) in zip(edits, edits[1:]):+ if end > later_start:+ raise RuntimeError("workflow edits must not overlap")+ for start, end, value in edits:+ source = source[:start] + value + source[end:]+ return source+++def strip_concurrency_queue(source: str) -> str:+ """Blank only concurrency.queue, for scanners that predate it."""+ document = yaml.compose(source, Loader=yaml.SafeLoader)+ return checked_edits(source, queue_edits(document, source))++def normalize_workflow_calls(source: str) -> str:- """Rewrite only job- and step-level uses scalars, retaining line numbers."""+ """Adapt supported new syntax for the pinned linter in memory only."""document = yaml.compose(source, Loader=yaml.SafeLoader)ends = set()+ edits = queue_edits(document, source)for jobs in mapping_values(document, "jobs"):if not isinstance(jobs, MappingNode):continue@@ -43,7 +147,6 @@ def normalize_workflow_calls(source: str) -> str:if isinstance(uses, ScalarNode) and uses.value.startswith("$/"):ends.add(uses.end_mark.index)- edits = []# Scalar tokens exclude any anchor before the value. Their end marks# also identify aliased uses nodes, so a shared scalar is replaced once.for token in yaml.scan(source):@@ -63,9 +166,7 @@ def normalize_workflow_calls(source: str) -> str:# are valid YAML scalars; blank lines preserve following locations.value = json.dumps("./" + token.value[2:])edits.append((start, end, value + "\n" * raw.count("\n")))- for start, end, value in reversed(edits):- source = source[:start] + value + source[end:]- return source+ return checked_edits(source, edits)def main() -> int:@@ -83,6 +184,10 @@ def main() -> int:# Let actionlint report malformed YAML using its normal# diagnostics. A parse failure must never skip validation.pass+ except (ValueError, RuntimeError) as exc:+ print(f"{filename}: {exc}", file=sys.stderr)+ failed = True+ continueresult = subprocess.run(["actionlint",diff --git a/changelog.d/+release-cleanup-preserve-tags.bugfix.md b/changelog.d/+release-cleanup-preserve-tags.bugfix.mdnew file mode 100644index 0000000000..1cc8a9412d--- /dev/null+++ b/changelog.d/+release-cleanup-preserve-tags.bugfix.md@@ -0,0 +1 @@+Failed Docker release cleanup now removes shared tags only when they still belong to the failed build. It preserves previously published tags and digest-based signatures, reports uncertain registry state as a failure, and continues cleaning tags whose ownership is known.diff --git a/changelog.d/+release-queue-preserve-pending.bugfix.md b/changelog.d/+release-queue-preserve-pending.bugfix.mdnew file mode 100644index 0000000000..0080fbd38f--- /dev/null+++ b/changelog.d/+release-queue-preserve-pending.bugfix.md@@ -0,0 +1 @@+Let up to 100 release and security-gate runs wait in their workflow concurrency queues (`queue: max`) instead of a later push, tag, or scheduled check replacing the single pending run. Once 100 runs are pending, GitHub cancels the newest arrivals. Trade-off: release.yml runs on every push to main, so a push burst no longer collapses to one running plus one pending run; every push takes a serial turn (in a 100-run, 161-hour history, 50 runs were replaced before and all 100 would now run, about 66 serial group-hours), which can delay a real release run or the `workflow_dispatch` retry behind stale-SHA runs. The actionlint adapter validates `queue` at workflow and job level, blanks only a `queue` pair whose key is plain (no alias, anchor or tag; an anchor on the value is allowed), fails closed on an aliased or anchored key or when blanking would leave invalid YAML (such as `queue` not last in a flow mapping), rejects a `queue` key duplicated within one concurrency mapping (as actionlint does for every other key), and rejects `queue: max` with `cancel-in-progress: true`, which GitHub treats as a validation error. The Checkov workflow scan blanks `queue` in its CI checkout first, because Checkov 3.2.499's schema rejects the key and silently skips such workflows.diff --git a/docs/CI_CD_INFRASTRUCTURE.md b/docs/CI_CD_INFRASTRUCTURE.mdindex f3fd61650d..2753dda717 100644--- a/docs/CI_CD_INFRASTRUCTURE.md+++ b/docs/CI_CD_INFRASTRUCTURE.md@@ -130,7 +130,7 @@ pre-commit install-hooks| Workflow | Trigger | Purpose ||----------|---------|---------|| `prerelease-docker.yml` | `workflow_call` from release.yml | Canonical multi-arch Docker build, cosign sign, SBOM/SLSA attestations. Jobs declare `environment: release` so the first `release` env approval gates the build (env-scoped Docker Hub secrets). |-| `docker-publish.yml` | `workflow_call` from release.yml | Retag prerelease manifest as `:1.6.9` / `:1.6` / `:latest` (gated by `release` env). No rebuild — registry-side metadata only. Inlined as a reusable workflow so its result is visible to downstream jobs in release.yml (lets create-release block on Docker success, lets cleanup-on-rejection safely scope cosign artifact deletion). |+| `docker-publish.yml` | `workflow_call` from release.yml | Retag prerelease manifest as `:1.6.9` / `:1.6` / `:latest` (gated by `release` env). No rebuild — registry-side metadata only. Inlined as a reusable workflow so its result is visible to downstream jobs in release.yml (lets create-release block on Docker success, lets cleanup-on-rejection skip rollback once release tags are published). || `docker-multiarch-test.yml` | PR, push | Multi-architecture build test || `publish.yml` | `repository_dispatch` from release.yml | Publish to PyPI. Stays on `repository_dispatch` (not `workflow_call`) because PyPI Trusted Publishing rejects OIDC claims from reusable workflows — `pypa/gh-action-pypi-publish#166`, `pypi/warehouse#11096`. || `release.yml` | Push to `main`, tag `v*.*.*`, manual | Orchestrate release: gates → build → provenance → prerelease-docker → publish-docker → trigger-pypi → monitor-pypi → create-release (last) |diff --git a/docs/RELEASE_GUIDE.md b/docs/RELEASE_GUIDE.mdindex 31e8f6c6ee..06c6ffee53 100644--- a/docs/RELEASE_GUIDE.md+++ b/docs/RELEASE_GUIDE.md@@ -95,15 +95,80 @@ If any of `prerelease-docker`, `publish-docker`, or `monitor-pypi` fails,`cleanup-on-rejection` job then handles failure-mode cleanup:- If `publish-docker` failed mid-retag (e.g., `:1.6.9` landed but- `:latest` failed), it rolls back any landed release tags BEFORE- deleting prerelease tags and cosign artifacts (deleting cosign- artifacts while release tags share the manifest digest would invalidate- release-tag signatures).+ `:latest` failed), cleanup first rechecks that this version has no+ GitHub Release. It removes shared tags only when their current digest+ matches the failed build, then removes that build's prerelease tags.+ Main and tag-triggered release runs use one concurrency group with+ `queue: max`: up to 100 runs can wait instead of GitHub's default single+ pending slot. Once 100 are pending, GitHub cancels additional runs.+ GitHub processes waiting runs first-in-first-out by when each began+ waiting, but documents that ordering is not guaranteed.+ Trade-off: this workflow runs on every push to main, so a burst of+ merges no longer collapses to one running plus one pending run; each push+ takes its own serial turn. In a measured 100-run history over 161 hours,+ 50 runs had been replaced under the old single-pending behavior, while+ `queue: max` would have run all 100 (about 66 serial group-hours). Even a+ version-check-only run held the group for a median of 30 minutes (p90 99),+ mostly waiting for a runner. After a push burst, a real release run or the+ `workflow_dispatch` retry recommended after a failed release can wait+ behind stale-SHA runs, and when 100 are pending GitHub cancels the newest+ arrivals rather than the stale ones. The release gate's own group is+ unaffected, since its standalone triggers are rare.+- Missing digests, failed registry inspections and unexpected HTTP+ responses for a tag, including unreadable platform images, keep that tag+ and fail cleanup only after every other tag has been handled, with or+ without a valid build digest: an uncertain lookup does not prove a tag+ is absent, safe to delete or unrelated to the failed build. If the+ GitHub Release lookup or Docker Hub authentication fails, cleanup stops+ before touching any tag. Investigate the failed check before retrying.+- A shared tag with a different digest is kept. If it still shares a+ platform image with the failed build (for example, `imagetools create`+ re-encoded the index during promotion), or if it is `:<version>` itself+ (no GitHub Release exists for that version, so another build there is an+ earlier unreleased attempt), cleanup reports it and fails. Other+ mismatches, such as `:latest` on an earlier release, are preserved+ without failing cleanup.+- If this version already has a GitHub Release, cleanup deletes nothing+ and succeeds.+- The build-specific tags (`prerelease-v<version>-<sha>` and its+ `-amd64`/`-arm64` tags) are removed even without a build digest. The+ per-arch tags are pushed before the vulnerability scan and manifest+ creation finish, so a failed scan or arch build leaves them with no+ digest.+- Without a valid build digest, cleanup keeps the shared tags and fails.+ When a failed scan or arch build stopped the run before+ `prerelease-v<version>-<sha>` was created, the shared tags were never+ moved and retrying cannot help. If that tag existed, cleanup logs its+ digest before deleting it and reports each shared tag that still points+ at it, shares its platform images or cannot be read, and `:<version>` if+ it points at another build; verify those tags and repair them manually.+ If the digest could not be read, check whether `:prerelease` still+ points at the unsigned build and repair it manually.+- Signatures, attestations and SBOM artifacts are retained. Their names+ identify content digests, which historical release tags and other+ multi-platform manifests may still reference. Tag rollback cannot prove+ those artifacts are unused; retaining some orphan artifacts preserves+ verification for existing images.- If `publish-docker` succeeded but a later step (PyPI orcreate-release) failed, `cleanup-on-rejection` does NOT fire — Dockerrelease tags exist and their cosign artifacts must stay. See"Recovery from PyPI failure" below.+Cleanup also uses the protected `release` environment. If its approval is+rejected, its credentials are unavailable and no automatic deletion runs.+Have a maintainer review the failed run before manual registry recovery.++### Activating the shared release queue++Before allowing the first release with the workflow-wide concurrency group to+publish, let older `Create Release` runs finish or cancel them after checking+whether they already published artifacts. Older workflow revisions use a+per-ref group, so their runs do not share the new lock. Retrying an old run+retains that revision; it does not adopt the new queue or cleanup logic.+Start new release attempts from a revision containing this change. If an old+attempt partially published, use the recovery guidance below before starting+another publisher for that version.+### Recovery from PyPI failure (atomicity hole)The one orphan state the pipeline cannot fully clean up: `publish-docker`diff --git a/docs/ci/workflow-status.md b/docs/ci/workflow-status.mdindex 5ca4ba325b..e459cd42dc 100644--- a/docs/ci/workflow-status.md+++ b/docs/ci/workflow-status.md@@ -130,6 +130,7 @@| `mcp-tests.yml` | last 30 days | push:main, PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/mcp-tests.yml) || `milvus-tests.yml` | last 30 days | push:main, PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/milvus-tests.yml) || `pr-triage.yml` | last 30 days | PR, pull_request_review | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/pr-triage.yml) |+| `release-cleanup-tests.yml` | never | PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/release-cleanup-tests.yml) || `release-package-tests.yml` | last 30 days | PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/release-package-tests.yml) || `release.yml` | last 30 days | push:main, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/release.yml) || `ui-full-shards.yml` | last 30 days | PR, manual | [](https://github.com/LearningCircuit/local-deep-research/actions/workflows/ui-full-shards.yml) |diff --git a/tests/ci/standalone/test_release_cleanup.py b/tests/ci/standalone/test_release_cleanup.pynew file mode 100644index 0000000000..b779b78493--- /dev/null+++ b/tests/ci/standalone/test_release_cleanup.py@@ -0,0 +1,516 @@+"""Run the release cleanup shell against a simulated registry, without Docker."""++# allow: no-sut-import — executes the actual release workflow shell block.++import json+import os+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+++ROOT = Path(__file__).resolve().parents[3]+WORKFLOW = ROOT / ".github/workflows/release.yml"+CURRENT = "sha256:" + "a" * 64+PREVIOUS = "sha256:" + "b" * 64+REENCODED = "sha256:" + "c" * 64+RUN_TAG = "prerelease-v2.0.0-1234567"+SHARED_TAGS = ("2.0.0", "2.0", "latest", "prerelease")+BUILD_TAGS = (RUN_TAG, f"{RUN_TAG}-amd64", f"{RUN_TAG}-arm64")++REGISTRY_COMMAND = r"""+import hashlib+import json+import os+import sys+from pathlib import Path++args = sys.argv[1:]+command = Path(sys.argv[0]).name+state = json.loads(Path(os.environ["CLEANUP_TEST_STATE"]).read_text())+with Path(os.environ["CLEANUP_TEST_CALLS"]).open("a") as stream:+ stream.write(json.dumps({"command": command, "args": args}) + "\n")++if command == "docker":+ if args[0] == "login":+ sys.stdin.read()+ sys.exit(state.get("login_exit", 0))+ assert args[:3] == ["buildx", "imagetools", "inspect"], args+ ref = args[3]+ if "@" in ref:+ record = {"digest": ref.split("@", 1)[1]}+ else:+ record = state["tags"].get(ref.split(":", 1)[1])+ if record is None:+ print(f"ERROR: {ref}: not found", file=sys.stderr)+ sys.exit(1)+ digest = record.get("digest", "")+ if "--raw" in args:+ if not digest or record.get("raw_exit"):+ sys.exit(record.get("raw_exit", 1))+ # Distinct builds get distinct platform images unless a test says+ # otherwise. Every index carries the same attestation entry, which+ # must not count as a shared image.+ platforms = state.get("platforms", {}).get(digest) or [+ "sha256:" + hashlib.sha256(f"{digest}/{arch}".encode()).hexdigest()+ for arch in ("amd64", "arm64")+ ]+ manifests = [+ {"digest": child, "platform": {"os": "linux", "architecture": "amd64"}}+ for child in platforms+ ]+ manifests.append({+ "digest": "sha256:" + "f" * 64,+ "platform": {"os": "unknown", "architecture": "unknown"},+ })+ print(json.dumps({"manifests": manifests}))+ sys.exit(0)+ print(json.dumps(digest))+ sys.exit(record.get("inspect_exit", 0))++assert command == "curl", command+url = args[-1]+if "/releases/tags/" in url:+ # Only the exact release tag form the build job uses is recognised.+ expected = "https://api.github.com/repos/example/research/releases/tags/v2.0.0"+ print(state.get("release_status", "404") if url == expected else "999", end="")+ sys.exit(0)+if url.endswith("/users/login/"):+ print(json.dumps({"token": "test-token"}))+ sys.exit(0)+tag = url.rstrip("/").rsplit("/", 1)[1]+record = state["tags"].get(tag)+if "DELETE" in args:+ print((record or {}).get("delete_status", "204"), end="")+else:+ print((record or {}).get("status", "200" if record else "404"), end="")+"""+++class ReleaseCleanupTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.directory = Path(self.temp.name)+ self.state = {+ "tags": {tag: {"digest": CURRENT} for tag in SHARED_TAGS},+ }+ text = WORKFLOW.read_text()+ job = text.split(" cleanup-on-rejection:\n", 1)[1]+ block = job.split(" run: |\n", 1)[1]+ lines = []+ for line in block.splitlines():+ if line.strip() and not line.startswith(" "):+ break+ lines.append(line[10:])+ self.script = self.directory / "cleanup.sh"+ self.script.write_text("\n".join(lines) + "\n")+ for command in ("curl", "docker"):+ path = self.directory / command+ path.write_text(f"#!{sys.executable}\n" + REGISTRY_COMMAND)+ path.chmod(0o755)++ def run_cleanup(self, digest=CURRENT):+ state_file = self.directory / "state.json"+ calls_file = self.directory / "calls.jsonl"+ state_file.write_text(json.dumps(self.state))+ calls_file.write_text("")+ env = {+ **os.environ,+ "PATH": f"{self.directory}:{os.environ['PATH']}",+ "CLEANUP_TEST_STATE": str(state_file),+ "CLEANUP_TEST_CALLS": str(calls_file),+ "DOCKER_USERNAME": "example",+ "DOCKER_PASSWORD": "test-password",+ "VERSION": "2.0.0",+ "SHORT_SHA": "1234567",+ "DIGEST": digest,+ "GITHUB_TOKEN": "test-github-token",+ "GITHUB_API_URL": "https://api.github.com",+ "GITHUB_REPOSITORY": "example/research",+ }+ result = subprocess.run(+ ["bash", str(self.script)],+ env=env,+ capture_output=True,+ text=True,+ timeout=15,+ )+ calls = [+ json.loads(line) for line in calls_file.read_text().splitlines()+ ]+ deleted = [+ call["args"][-1].rstrip("/").rsplit("/", 1)[1]+ for call in calls+ if call["command"] == "curl" and "DELETE" in call["args"]+ ]+ return result, deleted++ def assert_fails_but_handles_other_tags(self, kept_tag):+ # One uncertain tag is kept, the job fails, and every other tag is+ # still rolled back so a rejected build stops being served.+ result, deleted = self.run_cleanup()+ self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)+ expected = [tag for tag in SHARED_TAGS + BUILD_TAGS if tag != kept_tag]+ self.assertEqual(deleted, expected)+ self.assertIn("Cleanup incomplete", result.stdout)++ def test_preserves_tags_owned_by_a_previous_release(self):+ # :2.0, :latest and :prerelease normally point at an earlier+ # release or RC. v2.0.0 has no GitHub Release, so :2.0.0 is absent.+ self.state["tags"] = {+ tag: {"digest": PREVIOUS} for tag in SHARED_TAGS if tag != "2.0.0"+ }+ result, deleted = self.run_cleanup()+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertEqual(deleted, list(BUILD_TAGS))+ self.assertNotIn("::error::", result.stdout)++ def test_reencoded_promotion_of_this_build_is_reported_and_kept(self):+ # imagetools create can re-encode the index: the tag gets a new+ # digest but still serves this build's platform images. That must+ # not pass as another build's tag.+ current_platforms = ["sha256:" + "1" * 64, "sha256:" + "2" * 64]+ for tag in SHARED_TAGS:+ for shared in (current_platforms, current_platforms[:1]):+ with self.subTest(tag=tag, shared=len(shared)):+ self.state["platforms"] = {+ CURRENT: current_platforms,+ REENCODED: shared,+ }+ self.state["tags"][tag] = {"digest": REENCODED}+ result, deleted = self.run_cleanup()+ self.assertNotEqual(+ result.returncode, 0, result.stdout + result.stderr+ )+ expected = [t for t in SHARED_TAGS + BUILD_TAGS if t != tag]+ self.assertEqual(deleted, expected)+ self.assertIn(+ f"::error::{tag} points at {REENCODED}, which shares "+ "platform images with this build",+ result.stdout,+ )+ self.state["tags"][tag] = {"digest": CURRENT}++ def test_unreadable_platform_images_keep_mismatched_tag_and_fail(self):+ for tag in ("latest", "prerelease"):+ with self.subTest(tag=tag, side="remote"):+ self.state["tags"][tag] = {"digest": PREVIOUS, "raw_exit": 1}+ self.assert_fails_but_handles_other_tags(tag)+ with self.subTest(tag=tag, side="build"):+ # This build's own index cannot be read, so no mismatched+ # tag can be classified.+ self.state["tags"][tag] = {"digest": PREVIOUS}+ self.state["platforms"] = {CURRENT: ["not-a-digest"]}+ self.assert_fails_but_handles_other_tags(tag)+ self.state.pop("platforms")+ self.state["tags"][tag] = {"digest": CURRENT}++ def test_version_tag_of_another_unreleased_build_is_reported_and_kept(self):+ # v2.0.0 has no GitHub Release, so no published build owns :2.0.0.+ self.state["tags"]["2.0.0"] = {"digest": PREVIOUS}+ self.assert_fails_but_handles_other_tags("2.0.0")+ result, _ = self.run_cleanup()+ self.assertIn(+ f"::error::2.0.0 points at another unreleased build ({PREVIOUS})",+ result.stdout,+ )++ def test_rolls_back_owned_tags_and_preserves_digest_artifacts(self):+ result, deleted = self.run_cleanup()+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ # Exact list: shared tags first, then build tags; no signature,+ # attestation or SBOM artifact is deleted.+ self.assertEqual(deleted, list(SHARED_TAGS + BUILD_TAGS))++ def test_absent_shared_tags_are_safe(self):+ self.state["tags"] = {}+ result, deleted = self.run_cleanup()+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertTrue(set(SHARED_TAGS).isdisjoint(deleted), deleted)++ def test_unexpected_tag_lookup_status_keeps_tag_and_fails(self):+ for tag in ("latest", "prerelease"):+ for status in ("401", "403", "429", "500", "000ERR"):+ with self.subTest(tag=tag, status=status):+ self.state["tags"][tag]["status"] = status+ self.assert_fails_but_handles_other_tags(tag)+ self.state["tags"][tag].pop("status")++ def test_unreadable_or_invalid_remote_digest_keeps_tag_and_fails(self):+ for tag in ("latest", "prerelease"):+ for digest, status in (+ (CURRENT, 1),+ ("", 0),+ ("not-a-digest", 0),+ ("sha256:abc", 0),+ ):+ with self.subTest(tag=tag, digest=digest, status=status):+ self.state["tags"][tag] = {+ "digest": digest,+ "inspect_exit": status,+ }+ self.assert_fails_but_handles_other_tags(tag)+ self.state["tags"][tag] = {"digest": CURRENT}++ def test_failed_tag_deletion_continues_then_fails(self):+ # A transient error deleting one tag must not leave the other shared+ # tags serving the rejected build.+ for tag in ("latest", "prerelease") + BUILD_TAGS:+ for status in ("401", "403", "429", "500", "000ERR"):+ with self.subTest(tag=tag, status=status):+ self.state["tags"].setdefault(tag, {})["delete_status"] = (+ status+ )+ result, deleted = self.run_cleanup()+ self.assertNotEqual(+ result.returncode, 0, result.stdout + result.stderr+ )+ # Every tag is attempted, in shared-then-build order.+ self.assertEqual(deleted, list(SHARED_TAGS + BUILD_TAGS))+ self.assertIn(f"Failed to delete {tag}", result.stdout)+ self.state["tags"][tag].pop("delete_status")++ def test_invalid_run_digest_removes_only_build_specific_tags(self):+ # A failed vulnerability scan or arch build leaves the per-arch tags+ # pushed while create-manifest, the only digest producer, never runs.+ existed = "but prerelease-v2.0.0-1234567 existed"+ never = "If this build's manifest was ever created"+ for digest in ("", "sha256:abc", "not-a-digest"):+ for manifest_status in ("204", "404"):+ with self.subTest(digest=digest, manifest=manifest_status):+ # The manifest tag exists but its digest is unreadable,+ # or it is absent.+ if manifest_status == "204":+ self.state["tags"][RUN_TAG] = {"digest": ""}+ else:+ self.state["tags"][RUN_TAG] = {"delete_status": "404"}+ result, deleted = self.run_cleanup(digest=digest)+ self.assertNotEqual(result.returncode, 0)+ self.assertEqual(deleted, list(BUILD_TAGS))+ self.assertIn("kept shared tags", result.stdout)+ if manifest_status == "204":+ self.assertIn(existed, result.stdout)+ self.assertNotIn(never, result.stdout)+ else:+ self.assertIn(never, result.stdout)+ self.assertNotIn(existed, result.stdout)++ def test_invalid_run_digest_reports_shared_tags_on_the_manifest(self):+ # The manifest tag's digest is read before the tag is deleted, so+ # shared tags still serving it (directly or re-encoded) are named.+ current_platforms = ["sha256:" + "1" * 64, "sha256:" + "2" * 64]+ self.state["platforms"] = {+ CURRENT: current_platforms,+ REENCODED: current_platforms,+ }+ self.state["tags"] = {+ "prerelease": {"digest": CURRENT},+ "latest": {"digest": REENCODED},+ "2.0": {"digest": PREVIOUS},+ RUN_TAG: {"digest": CURRENT},+ }+ result, deleted = self.run_cleanup(digest="")+ self.assertNotEqual(result.returncode, 0)+ self.assertEqual(deleted, list(BUILD_TAGS))+ self.assertIn(f"{RUN_TAG} resolves to {CURRENT}", result.stdout)+ self.assertIn(+ f"::error::prerelease still points at {RUN_TAG} ({CURRENT})",+ result.stdout,+ )+ self.assertIn(+ f"::error::latest ({REENCODED}) shares platform images with {RUN_TAG}",+ result.stdout,+ )+ self.assertNotIn("::error::2.0", result.stdout)+ self.assertIn(f"{RUN_TAG} was {CURRENT}", result.stdout)++ def test_invalid_run_digest_fails_on_every_unreadable_shared_tag(self):+ # Without a verified digest, a shared tag that cannot be classified+ # against the manifest tag is a failure that names it, exactly as in+ # the verified path. It must never pass silently as "not this build".+ current_platforms = ["sha256:" + "1" * 64, "sha256:" + "2" * 64]+ cases = {+ "lookup 429": (+ {"digest": CURRENT, "status": "429"},+ "Could not verify {tag} (HTTP 429); keeping it",+ ),+ "lookup 503": (+ {"digest": CURRENT, "status": "503", "inspect_exit": 1},+ "Could not verify {tag} (HTTP 503); keeping it",+ ),+ "lookup transport error": (+ {"digest": CURRENT, "status": "000ERR"},+ "Could not verify {tag} (HTTP 000ERR); keeping it",+ ),+ "inspect fails": (+ {"digest": CURRENT, "inspect_exit": 1},+ "Could not inspect {tag}; keeping it",+ ),+ "invalid digest": (+ {"digest": "sha256:abc"},+ "Invalid digest for {tag}; keeping it",+ ),+ "re-encoded, raw read fails": (+ {"digest": REENCODED, "raw_exit": 1},+ f"Could not read the platform images of {{tag}} ({REENCODED})",+ ),+ }+ for tag in ("prerelease", "latest", "2.0.0"):+ for name, (record, message) in cases.items():+ with self.subTest(tag=tag, case=name):+ self.state["platforms"] = {+ CURRENT: current_platforms,+ REENCODED: current_platforms,+ }+ # :2.0.0 on another build is itself a failure, so it is+ # absent unless it is the tag under test.+ self.state["tags"] = {+ other: {"digest": PREVIOUS}+ for other in SHARED_TAGS+ if other not in (tag, "2.0.0")+ }+ self.state["tags"][tag] = record+ self.state["tags"][RUN_TAG] = {"digest": CURRENT}+ result, deleted = self.run_cleanup(digest="")+ self.assertNotEqual(result.returncode, 0)+ self.assertEqual(deleted, list(BUILD_TAGS))+ errors = [+ line+ for line in result.stdout.splitlines()+ if "::error::" in line+ ]+ # The unreadable tag, the no-digest summary and the+ # final verdict; the other shared tags are classified.+ self.assertEqual(len(errors), 3, result.stdout)+ self.assertIn(message.format(tag=tag), errors[0])+ self.assertIn("No valid build digest", errors[1])+ for other in SHARED_TAGS:+ if other == "2.0.0" and tag != "2.0.0":+ self.assertIn("Skip 2.0.0 (absent)", result.stdout)+ elif other != tag:+ self.assertIn(+ f"Keeping {other}; it points at another build "+ f"({PREVIOUS})",+ result.stdout,+ )++ def test_invalid_run_digest_with_unreadable_build_reports_every_tag(self):+ # The manifest tag's own platform images cannot be read, so no shared+ # tag with another digest can be classified: each one is reported.+ self.state["platforms"] = {CURRENT: ["not-a-digest"]}+ self.state["tags"] = {+ "2.0.0": {"digest": REENCODED},+ "2.0": {"digest": PREVIOUS},+ "latest": {"digest": PREVIOUS},+ "prerelease": {"digest": PREVIOUS},+ RUN_TAG: {"digest": CURRENT},+ }+ result, deleted = self.run_cleanup(digest="")+ self.assertNotEqual(result.returncode, 0)+ self.assertEqual(deleted, list(BUILD_TAGS))+ for tag in SHARED_TAGS:+ remote = REENCODED if tag == "2.0.0" else PREVIOUS+ self.assertIn(+ f"::error::{tag} points at {remote}, but this build's platform "+ f"images ({CURRENT}) could not be read",+ result.stdout,+ )+ self.assertNotIn("Keeping", result.stdout)++ def test_version_tag_of_another_build_fails_with_or_without_digest(self):+ # v2.0.0 has no GitHub Release, so :2.0.0 on a build that is neither+ # this one nor the manifest tag's is an earlier unreleased attempt.+ # Both paths must name it as a failure, not keep it silently.+ self.state["tags"] = {+ "2.0.0": {"digest": PREVIOUS},+ RUN_TAG: {"digest": CURRENT},+ }+ message = (+ f"::error::2.0.0 points at another unreleased build ({PREVIOUS}) "+ "although v2.0.0 has no GitHub Release; keeping it"+ )+ for digest in (CURRENT, ""):+ with self.subTest(digest=digest):+ result, deleted = self.run_cleanup(digest=digest)+ self.assertNotEqual(result.returncode, 0)+ self.assertNotIn("2.0.0", deleted)+ self.assertIn(message, result.stdout)+ self.assertNotIn("Keeping 2.0.0", result.stdout)+ self.assertNotIn("Preserving 2.0.0", result.stdout)+ # Other tags on another build are still kept without a failure.+ self.state["tags"]["2.0.0"] = {"digest": CURRENT}+ self.state["tags"]["2.0"] = {"digest": PREVIOUS}+ result, _ = self.run_cleanup(digest="")+ self.assertIn(+ f"Keeping 2.0; it points at another build ({PREVIOUS})",+ result.stdout,+ )+ self.assertNotIn("::error::2.0 ", result.stdout)++ def test_invalid_run_digest_skips_absent_shared_tags_quietly(self):+ self.state["tags"] = {+ "latest": {"digest": PREVIOUS},+ RUN_TAG: {"digest": CURRENT},+ }+ result, deleted = self.run_cleanup(digest="")+ self.assertNotEqual(result.returncode, 0)+ self.assertEqual(deleted, list(BUILD_TAGS))+ for tag in ("2.0.0", "2.0", "prerelease"):+ self.assertIn(f"Skip {tag} (absent)", result.stdout)+ self.assertIn(+ f"Keeping latest; it points at another build ({PREVIOUS})",+ result.stdout,+ )+ # Only the no-digest summary itself is an error.+ errors = [+ line for line in result.stdout.splitlines() if "::error::" in line+ ]+ self.assertEqual(len(errors), 2, errors)+ self.assertIn("No valid build digest; kept shared tags", errors[0])+ self.assertIn("Cleanup incomplete", errors[1])++ def test_shared_tag_failure_still_removes_other_tags(self):+ self.state["tags"]["2.0.0"]["status"] = "500"+ self.assert_fails_but_handles_other_tags("2.0.0")++ def test_published_version_without_digest_performs_no_deletions(self):+ self.state["release_status"] = "200"+ result, deleted = self.run_cleanup(digest="")+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertEqual(deleted, [])++ def test_retains_artifacts_that_other_version_tags_may_still_use(self):+ # Historical release tags are not in the rollback set. Their image+ # manifests can share child digests with this failed build.+ self.state["tags"]["1.10.7"] = {"digest": PREVIOUS}+ self.state["tags"]["latest"] = {"digest": PREVIOUS}+ result, deleted = self.run_cleanup()+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertEqual(deleted, ["2.0.0", "2.0", "prerelease", *BUILD_TAGS])++ def test_docker_authentication_failure_performs_no_deletions(self):+ self.state["login_exit"] = 1+ result, deleted = self.run_cleanup()+ self.assertNotEqual(result.returncode, 0)+ self.assertEqual(deleted, [])++ def test_rerun_preserves_an_already_published_version(self):+ self.state["release_status"] = "200"+ result, deleted = self.run_cleanup()+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertEqual(deleted, [])++ def test_uncertain_release_lookup_performs_no_deletions(self):+ for status in ("401", "403", "429", "500", "000ERR"):+ with self.subTest(status=status):+ self.state["release_status"] = status+ result, deleted = self.run_cleanup()+ self.assertNotEqual(result.returncode, 0)+ self.assertEqual(deleted, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/ci/test_release_queue_contract.py b/tests/ci/test_release_queue_contract.pynew file mode 100644index 0000000000..c8771efb5e--- /dev/null+++ b/tests/ci/test_release_queue_contract.py@@ -0,0 +1,61 @@+"""Keep pending release and release-gate runs from displacing each other."""++import importlib.util+from pathlib import Path++import yaml+++WORKFLOWS = Path(__file__).resolve().parents[2] / ".github" / "workflows"+++def test_release_and_gate_retain_pending_runs_without_deadlocking() -> None:+ release = yaml.safe_load((WORKFLOWS / "release.yml").read_text())+ gate = yaml.safe_load((WORKFLOWS / "release-gate.yml").read_text())++ release_concurrency = release["concurrency"]+ gate_concurrency = gate["concurrency"]+ for concurrency in (release_concurrency, gate_concurrency):+ assert concurrency["cancel-in-progress"] is False+ assert concurrency["queue"] == "max"++ # The called gate cannot acquire the parent's group while the parent waits+ # for it. Keeping the groups distinct avoids a reusable-workflow deadlock.+ assert release_concurrency["group"] != gate_concurrency["group"]+ assert "github.workflow" not in gate_concurrency["group"]+++def test_checkov_scans_workflows_with_queue_after_blanking_it() -> None:+ """Checkov 3.2.499's schema rejects concurrency.queue and then silently+ skips the whole workflow, so the gate must blank it before scanning."""+ root = WORKFLOWS.parents[1]+ checkov = yaml.safe_load((WORKFLOWS / "checkov.yml").read_text())+ steps = checkov["jobs"]["checkov"]["steps"]+ commands = [step.get("run", "") for step in steps]+ blank = next(+ i+ for i, run in enumerate(commands)+ if "strip-concurrency-queue.py .github/workflows/*.yml" in run+ )+ scan = next(+ i+ for i, run in enumerate(commands)+ if "checkov -d .github/workflows" in run+ )+ assert blank < scan++ script = root / ".github" / "scripts" / "strip-concurrency-queue.py"+ spec = importlib.util.spec_from_file_location("strip_queue", script)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ adapter_spec = importlib.util.spec_from_file_location(+ "adapter", module.HOOK+ )+ adapter = importlib.util.module_from_spec(adapter_spec)+ adapter_spec.loader.exec_module(adapter)+ for name in ("release.yml", "release-gate.yml"):+ source = (WORKFLOWS / name).read_text()+ stripped = adapter.strip_concurrency_queue(source)+ assert stripped.count("\n") == source.count("\n")+ parsed = yaml.safe_load(stripped)+ assert set(parsed["concurrency"]) == {"group", "cancel-in-progress"}diff --git a/tests/hooks/test_actionlint_self_repository.py b/tests/hooks/test_actionlint_self_repository.pyindex e88f9e1823..fb106f2c09 100644--- a/tests/hooks/test_actionlint_self_repository.py+++ b/tests/hooks/test_actionlint_self_repository.py@@ -4,6 +4,7 @@ Run directly with python3 to avoid importing the application. The dedicatedpre-commit hook supplies the same pinned actionlint used for workflow linting."""+import importlib.utilimport shutilimport subprocessimport sys@@ -11,6 +12,8 @@ import tempfileimport unittestfrom pathlib import Path+import yaml+WRAPPER = (Path(__file__).resolve().parents[2]/ ".pre-commit-hooks"@@ -88,6 +91,223 @@ jobs:name: example"""+LATE_CONCURRENCY = """\+on: workflow_dispatch+jobs:+ call:+ uses: {uses}+ with:+ query: example+ enabled: true+ secrets:+ TOKEN: ${{{{ secrets.TOKEN }}}}+concurrency:+ group: release+ queue: max+ cancel-in-progress: false+"""++REF = "$/.github/workflows/callee.yml"+++def load_wrapper():+ spec = importlib.util.spec_from_file_location("actionlint_wrapper", WRAPPER)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++class TestNormalizeEditOrder(unittest.TestCase):+ """Pure checks that need no actionlint binary."""++ def test_duplicate_queue_key_is_rejected(self):+ wrapper = load_wrapper()+ for source in (+ "concurrency:\n group: g\n queue: max\n queue: single\n"+ + CALLER,+ "concurrency:\n group: g\n queue: single\n"+ " cancel-in-progress: true\n queue: single\n" + CALLER,+ "jobs:\n a:\n runs-on: x\n concurrency:\n"+ " group: g\n queue: max\n queue: max\n",+ ):+ with self.subTest(source=source):+ for fn in (+ wrapper.strip_concurrency_queue,+ wrapper.normalize_workflow_calls,+ ):+ with self.assertRaisesRegex(ValueError, "duplicated"):+ fn(source)++ def test_concurrency_after_jobs_with_length_changing_uses(self):+ normalize = load_wrapper().normalize_workflow_calls+ cases = {+ "block scalar": ">-\n " + REF,+ "escaped quotes": '"\\u0024/.github/workflows/callee.yml"',+ }+ for name, uses in cases.items():+ with self.subTest(name):+ source = LATE_CONCURRENCY.format(uses=uses)+ expected = LATE_CONCURRENCY.format(+ uses=(+ '"./.github/workflows/callee.yml"'+ + ("\n" if "\n" in uses else "")+ )+ ).replace("queue: max", " " * len("queue: max"))+ result = normalize(source)+ self.assertEqual(result, expected)+ self.assertEqual(+ len(result.splitlines()), len(source.splitlines())+ )+ parsed = yaml.safe_load(result)+ self.assertEqual(+ parsed["concurrency"],+ {"group": "release", "cancel-in-progress": False},+ )+ self.assertEqual(+ parsed["jobs"]["call"]["uses"],+ "./.github/workflows/callee.yml",+ )++ def test_job_level_queue_is_blanked_like_workflow_level(self):+ normalize = load_wrapper().normalize_workflow_calls+ source = (+ "on: push\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " concurrency:\n"+ " group: build\n"+ " queue: max\n"+ " cancel-in-progress: false\n"+ " steps:\n"+ " - run: echo ok\n"+ )+ result = normalize(source)+ self.assertEqual(+ result, source.replace("queue: max", " " * len("queue: max"))+ )+ self.assertNotIn("queue", result)+ yaml.safe_load(result)+ with self.assertRaisesRegex(ValueError, "single or max"):+ normalize(source.replace("queue: max", "queue: unlimited"))++ def test_queue_max_with_cancel_in_progress_is_rejected(self):+ normalize = load_wrapper().normalize_workflow_calls+ for cancel in ("true", "${{ github.event_name == 'push' }}"):+ for template in (+ "concurrency:\n group: g\n queue: max\n"+ " cancel-in-progress: CANCEL\njobs: {}\n",+ "jobs:\n a:\n runs-on: x\n concurrency:\n"+ " cancel-in-progress: CANCEL\n queue: max\n",+ ):+ with self.subTest(cancel=cancel, template=template[:20]):+ with self.assertRaisesRegex(+ ValueError, "requires cancel-in-progress: false"+ ):+ normalize(template.replace("CANCEL", cancel))+ # queue: single and an omitted cancel-in-progress stay allowed.+ normalize(+ "concurrency: {group: g, cancel-in-progress: true, queue: single}\njobs: {}\n"+ )+ normalize("concurrency: {group: g, queue: max}\njobs: {}\n")++ def test_shared_concurrency_mapping_is_edited_once(self):+ wrapper = load_wrapper()+ cases = {+ "anchored concurrency reused by a job": (+ "on: push\n"+ "concurrency: &c\n group: g\n queue: max\n"+ "jobs:\n a:\n runs-on: x\n concurrency: *c\n"+ ),+ "aliased job": (+ "on: push\n"+ "jobs:\n a: &j\n runs-on: x\n concurrency:\n"+ " group: g\n queue: max\n b: *j\n"+ ),+ }+ for name, source in cases.items():+ with self.subTest(name):+ for convert in (+ wrapper.normalize_workflow_calls,+ wrapper.strip_concurrency_queue,+ ):+ result = convert(source)+ self.assertEqual(+ result,+ source.replace("queue: max", " " * len("queue: max")),+ )+ yaml.safe_load(result)++ def test_genuine_overlap_is_a_clean_failure(self):+ wrapper = load_wrapper()+ with self.assertRaisesRegex(RuntimeError, "must not overlap"):+ wrapper.apply_edits("abcdef", [(0, 4, ""), (2, 5, "")])+ self.assertEqual(+ wrapper.apply_edits("abcdef", [(1, 2, "X"), (1, 2, "X")]),+ "aXcdef",+ )++ def test_queue_key_shapes_that_widen_the_blanked_span_fail_closed(self):+ wrapper = load_wrapper()+ cases = {+ "alias key": (+ "jobs: {a: {runs-on: x, env: {Z: &k queue}},"+ " b: {runs-on: x, concurrency: {group: g, *k : max}}}\n"+ ),+ "anchored key": (+ "concurrency: {group: g, &k queue: max}\njobs: {}\n"+ ),+ "anchored key in block mapping": (+ "concurrency:\n group: g\n &k queue: max\njobs: {}\n"+ ),+ }+ for name, source in cases.items():+ with self.subTest(name):+ yaml.safe_load(source)+ for convert in (+ wrapper.normalize_workflow_calls,+ wrapper.strip_concurrency_queue,+ ):+ with self.assertRaisesRegex(+ ValueError, "plain, unanchored"+ ):+ convert(source)++ def test_plain_quoted_and_value_anchored_queue_pairs_are_blanked(self):+ wrapper = load_wrapper()+ for pair in ("queue: max", '"queue": "max"', "queue : &q max"):+ with self.subTest(pair):+ source = f"concurrency:\n group: g\n {pair}\njobs: {{}}\n"+ result = wrapper.strip_concurrency_queue(source)+ self.assertEqual(result, source.replace(pair, " " * len(pair)))+ yaml.safe_load(result)++ def test_flow_mapping_blanking_must_leave_valid_yaml(self):+ wrapper = load_wrapper()+ for convert in (+ wrapper.normalize_workflow_calls,+ wrapper.strip_concurrency_queue,+ ):+ with self.subTest(convert.__name__):+ last = "concurrency: {group: g, queue: max}\njobs: {}\n"+ yaml.safe_load(convert(last))+ for first in (+ "concurrency: {queue: max, group: g}\njobs: {}\n",+ "concurrency: {group: g, queue: max, cancel-in-progress: false}\njobs: {}\n",+ ):+ with self.assertRaisesRegex(ValueError, "invalid YAML"):+ convert(first)++ def test_queue_alias_is_rejected(self):+ normalize = load_wrapper().normalize_workflow_calls+ source = (+ "env: {X: &q max}\n"+ "concurrency: {group: release, queue: *q}\n"+ "jobs: {}\n"+ )+ with self.assertRaisesRegex(ValueError, "must not be an alias"):+ normalize(source)+@unittest.skipUnless(shutil.which("actionlint"), "actionlint is not installed")class TestActionlintSelfRepository(unittest.TestCase):@@ -132,6 +352,52 @@ class TestActionlintSelfRepository(unittest.TestCase):result = self.lint()self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ def test_current_queue_setting_preserves_actionlint_checks(self):+ concurrency = (+ "concurrency:\n"+ " group: release\n"+ " cancel-in-progress: false\n"+ " queue: max\n"+ )+ result = self.lint(concurrency + CALLER)+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)++ invalid_call = (concurrency + CALLER).replace(+ "query: example", "qurey: example"+ )+ result = self.lint(invalid_call)+ self.assertEqual(result.returncode, 1, result.stdout + result.stderr)+ self.assertIn('input "qurey" is not defined', result.stdout)+ line = next(+ i+ for i, text in enumerate(invalid_call.splitlines(), 1)+ if "qurey: example" in text+ )+ self.assertIn(f"caller.yml:{line}:", result.stdout)++ def test_queue_after_jobs_with_length_changing_uses(self):+ for uses in (+ ">-\n " + REF,+ '"\\u0024/.github/workflows/callee.yml"',+ ):+ with self.subTest(uses=uses):+ result = self.lint(LATE_CONCURRENCY.format(uses=uses))+ self.assertEqual(+ result.returncode, 0, result.stdout + result.stderr+ )++ def test_invalid_queue_setting_is_rejected(self):+ for value in ("unlimited", "[max]"):+ with self.subTest(value=value):+ source = (+ "concurrency:\n"+ " group: release\n"+ f" queue: {value}\n" + CALLER+ )+ self.assert_rejected(+ source, "concurrency.queue must be single or max"+ )+def write_local_action(self):action = self.root / ".github" / "actions" / "greet"action.mkdir(parents=True)