Skip to content

The agent that grows with you

fix(release): move artifact handoffs to r2

ethernet5874b11ec6fb
diff --git a/.github/workflows/desktop-bundled-release.yml b/.github/workflows/desktop-bundled-release.yml
index b62b989c0f5..b4f214371ad 100644
--- a/.github/workflows/desktop-bundled-release.yml
+++ b/.github/workflows/desktop-bundled-release.yml
@@ -4,15 +4,15 @@ name: Desktop Bundled Release
#
# tag admission (shape + pyproject lockstep + ancestry on origin/main,
# resolved to an IMMUTABLE full SHA) → per-OS builder jobs → stage
-# artifacts to R2 (releases/tag/<tag>/) → per-OS publish jobs write the
-# feeds → builds table.
+# files + receipts to R2 (releases/tag/<tag>/) → gated publish jobs write
+# feeds → builds table. Stable candidates stop before feed publication.
#
# Per-OS topology (MSIX work is gated on the WINDOWS build only — mac/linux
# legs never block the win32 feed or Store submission):
#
-# build-win32 (win32-x64 + win32-arm64) → stage to R2 + upload *.msix
+# build-win32 (win32-x64 + win32-arm64) → stage packages + receipts to R2
# build-darwin (darwin-arm64 + darwin-x64) → sign + notarize + stage
-# dmg/zip/blockmap to R2; per-arch feed ymls as artifacts
+# dmg/zip/blockmap + per-arch feed inputs to the R2 tag archive
# build-linux → DISABLED for now (dummy skips)
# publish-win32-updater → App Installer feed
# (needs build-win32): releases/win32/<stable|canary>/*.appinstaller +
@@ -36,7 +36,10 @@ name: Desktop Bundled Release
# (dmg/zip live once in releases/tag/<tag>/; the merged feed points at
# them with absolute object keys)
# The publish jobs write the feeds ONCE after their whole build matrix is
-# green, so a failed leg can never publish a partial channel.
+# green, so a failed leg can never publish a partial channel. Stable candidate
+# jobs only stage tag-scoped objects; stable-release.yml gates feed promotion
+# on package acceptance and artifact publication. No GitHub job artifacts
+# carry release files. Non-publishing builds leave output on the runner only.
#
# Payload staging is `hermes pm bundle` on the native runner. There is
# no cross-target staging. The darwin legs sign (CSC_LINK) and notarize
@@ -99,8 +102,8 @@ on:
required: false
type: boolean
default: false
- termux_upgrade_from_run:
- description: 'Successful Termux run whose package must upgrade to this build'
+ termux_upgrade_from_tag:
+ description: 'Published release tag whose R2 Termux package must upgrade to this build'
required: false
type: string
default: ''
@@ -265,7 +268,8 @@ jobs:
uses: ./.github/actions/setup-pm
with:
toolchain: all
- cache-python: false
+ # The payload tools cache does not include uv's built wheels.
+ cache-python: true
- name: Resolve toolchain cache key
id: toolchain
@@ -454,62 +458,25 @@ jobs:
node apps/desktop/scripts/audit-bundle-arch.mjs \
--arch="${MATRIX_LABEL##*-}" --root=apps/desktop/release
- - name: Record stable Windows candidate
- if: inputs.release-phase == 'candidate'
+ - name: Stage Windows packages to R2
+ if: inputs.upload_release == true || inputs.release-phase == 'candidate'
shell: bash
env:
TARGET: ${{ matrix.target.label }}
+ RELEASE_PHASE: ${{ inputs.release-phase }}
+ RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}
+ # The tag archive is the handoff, never an update feed. The receipt
+ # appears only after both normal and Store packages are uploaded.
run: |
- python -m scripts.bundles.release_artifacts record --platform windows --arch "${TARGET##*-}" \
- --root apps/desktop/release --tag "$HERMES_PAYLOAD_TAG" --out "$RUNNER_TEMP/$TARGET.tar"
- - name: Retain stable Windows candidate
- if: inputs.release-phase == 'candidate'
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
- with:
- name: stable-candidate-${{ matrix.target.label }}
- path: ${{ runner.temp }}/${{ matrix.target.label }}.tar
- if-no-files-found: error
-
- - name: Upload artifacts
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
- with:
- # The win32 legs' actual .msix binaries: publish-win32-updater bundles
- # the per-arch .msix for the App Installer feed.
- name: hermes-bundled-${{ matrix.target.label }}-${{ inputs.tag }}
- path: |
- apps/desktop/release/*.msix
- retention-days: 30
- if-no-files-found: error
-
- - name: Stage to Cloudflare R2
- if: inputs.upload_release == true
- shell: bash
- # Every artifact goes to releases/tag/<tag>/ (immutable staging).
- # publish-win32-updater consumes the per-arch .msix to build the App
- # Installer feed; publish-win32-store bundles the Store-*.msix — never
- # from a leg, so a failed leg cannot publish a partial feed.
- run: |
- shopt -s nullglob
- # Store-*.msix are archived by the dedicated loop below — exclude
- # them here so they are not uploaded twice.
- files=(apps/desktop/release/*.msix)
- if [ ${#files[@]} -eq 0 ]; then
- echo "::error::no release artifacts found"; exit 1
+ args=(--include '*.msix')
+ if [ "$RELEASE_PHASE" = candidate ]; then
+ python -m scripts.bundles.release_artifacts record --platform windows --arch "${TARGET##*-}" \
+ --root apps/desktop/release --tag "$HERMES_PAYLOAD_TAG" --commit "$RELEASE_COMMIT" \
+ --out "apps/desktop/release/metadata-windows-${TARGET##*-}.json"
+ args+=(--include 'metadata-*.json')
fi
- for f in "${files[@]}"; do
- case "$f" in
- */Store-*) continue ;; # archived by the Store loop below
- esac
- python -m scripts.releases.r2 put \
- --tag "$HERMES_PAYLOAD_TAG" --key "$(basename "$f")" --file "$f"
- done
- # The Store-submission MSIX (built by the win legs) goes to the tag
- # archive too — hidden from the builds table and never a feed dir.
- for f in apps/desktop/release/Store-*.msix; do
- [ -f "$f" ] || continue
- python -m scripts.releases.r2 put \
- --tag "$HERMES_PAYLOAD_TAG" --key "$(basename "$f")" --file "$f"
- done
+ python -m scripts.releases.handoff stage --tag "$HERMES_PAYLOAD_TAG" --commit "$RELEASE_COMMIT" \
+ --name "$TARGET" --root apps/desktop/release "${args[@]}"
# ── macOS builders (REAL) ──────────────────────────────────────────────────
# Native per-arch darwin builds via scripts/bundles/desktop.py (the
@@ -570,7 +537,8 @@ jobs:
uses: ./.github/actions/setup-pm
with:
toolchain: all
- cache-python: false
+ # The payload tools cache does not include uv's built wheels.
+ cache-python: true
- name: Resolve toolchain cache key
id: toolchain
@@ -761,8 +729,8 @@ jobs:
if: inputs.upload_release == true || inputs.release-phase == 'candidate'
# electron-builder writes the channel feed yml (stable-mac.yml /
# canary-mac.yml) with the SAME name on both legs; prefix the arch
- # so the publish job's merge-multiple download keeps both and
- # r2-release finalize can merge them into <channel>-mac.yml. The
+ # so the R2 tag archive keeps both and finalize can merge them
+ # into <channel>-mac.yml after both native legs pass. The
# channel token is preserved verbatim in the staged name
# (arm64-stable-mac.yml / x64-canary-mac.yml …).
shell: bash
@@ -775,61 +743,24 @@ jobs:
test -s "$f"
mv "$f" "apps/desktop/release/${arch}-${channel}-mac.yml"
- - name: Record stable macOS candidate
- if: inputs.release-phase == 'candidate'
- env:
- TARGET: ${{ matrix.target.label }}
- run: |
- python3 -m scripts.bundles.release_artifacts record --platform macos --arch "${TARGET##*-}" \
- --root apps/desktop/release --tag "$HERMES_PAYLOAD_TAG" --out "$RUNNER_TEMP/$TARGET.tar"
- - name: Retain stable macOS candidate
- if: inputs.release-phase == 'candidate'
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
- with:
- name: stable-candidate-${{ matrix.target.label }}
- path: ${{ runner.temp }}/${{ matrix.target.label }}.tar
- if-no-files-found: error
-
- - name: Upload feed metadata
+ - name: Stage macOS packages and feed inputs to R2
if: inputs.upload_release == true || inputs.release-phase == 'candidate'
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
- with:
- name: hermes-bundled-${{ matrix.target.label }}-${{ inputs.tag }}
- path: |
- apps/desktop/release/*-mac.yml
- retention-days: 30
- if-no-files-found: error
-
- - name: Retain non-publishing build artifacts
- if: inputs.upload_release != true && inputs.release-phase != 'candidate'
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
- with:
- name: hermes-bundled-${{ matrix.target.label }}-${{ inputs.tag }}
- path: |
- apps/desktop/release/*.dmg
- apps/desktop/release/*.zip
- apps/desktop/release/*.blockmap
- retention-days: 30
- if-no-files-found: error
-
- - name: Stage to Cloudflare R2
- if: inputs.upload_release == true
shell: bash
- # Every artifact goes to releases/tag/<tag>/ (immutable staging).
- # publish-darwin-updater merges the per-arch ymls into the channel
- # feed AFTER both legs are green — never from a leg, so a failed
- # leg cannot publish a partial channel.
+ env:
+ TARGET: ${{ matrix.target.label }}
+ RELEASE_PHASE: ${{ inputs.release-phase }}
+ RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}
+ # Per-arch feed inputs stay in the tag archive until both legs pass.
run: |
- shopt -s nullglob
- files=(apps/desktop/release/*.dmg apps/desktop/release/*.zip \
- apps/desktop/release/*.blockmap)
- if [ ${#files[@]} -eq 0 ]; then
- echo "::error::no darwin release artifacts found"; exit 1
+ args=(--include '*.dmg' --include '*.zip' --include '*.blockmap' --include '*-mac.yml')
+ if [ "$RELEASE_PHASE" = candidate ]; then
+ python -m scripts.bundles.release_artifacts record --platform macos --arch "${TARGET##*-}" \
+ --root apps/desktop/release --tag "$HERMES_PAYLOAD_TAG" --commit "$RELEASE_COMMIT" \
+ --out "apps/desktop/release/metadata-macos-${TARGET##*-}.json"
+ args+=(--include 'metadata-*.json')
fi
- for f in "${files[@]}"; do
- python -m scripts.releases.r2 put \
- --tag "$HERMES_PAYLOAD_TAG" --key "$(basename "$f")" --file "$f"
- done
+ python -m scripts.releases.handoff stage --tag "$HERMES_PAYLOAD_TAG" --commit "$RELEASE_COMMIT" \
+ --name "$TARGET" --root apps/desktop/release "${args[@]}"
# ── Linux builders (DISABLED for now) ─────────────────────────────────────
build-linux:
@@ -927,12 +858,13 @@ jobs:
restore-keys: |
eb2-${{ runner.os }}-${{ runner.arch }}-
- - name: Download win legs' MSIX
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
- with:
- pattern: hermes-bundled-win32-*-${{ inputs.tag }}
- path: apps/desktop/release
- merge-multiple: true
+ - name: Retrieve Windows packages from R2
+ shell: bash
+ env:
+ RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}
+ run: |
+ python -m scripts.releases.handoff fetch --tag "$HERMES_PAYLOAD_TAG" --commit "$RELEASE_COMMIT" \
+ --name win32-x64 --name win32-arm64 --root apps/desktop/release --include '*.msix'
- name: Azure login (OIDC)
uses: azure/login@f5d393ae46f8fde4be8b75f32e3fc50e654ad0ca # v3.0.1
@@ -962,9 +894,8 @@ jobs:
AZURE_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }}
AZURE_TENANT_ID: ${{ vars.AZURE_TENANT_ID }}
run: |
- # Out-of-store feed (bundled variant): universal .msixbundle +
- # .appinstaller per channel; plus re-upload the Store-submission
- # .msix to the tag archive (never a feed dir).
+ # Candidate mode builds the bundles without writing a feed.
+ # Canary mode publishes the App Installer bundle and pointer.
args=()
if [ "$RELEASE_PHASE" = candidate ]; then args+=(--candidate); fi
node scripts/stage-msixbundle.mjs --tag "$HERMES_PAYLOAD_TAG" --variant bundled "${args[@]}"
@@ -972,13 +903,14 @@ jobs:
node scripts/bundle-store-msixbundle.mjs --tag "$HERMES_PAYLOAD_TAG"
fi
- - name: Retain stable universal bundles
+ - name: Stage stable universal bundles to R2
if: inputs.release-phase == 'candidate'
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
- with:
- name: stable-candidate-universal
- path: apps/desktop/release/*.msixbundle
- if-no-files-found: error
+ shell: bash
+ env:
+ RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}
+ run: |
+ python -m scripts.releases.handoff stage --tag "$HERMES_PAYLOAD_TAG" --commit "$RELEASE_COMMIT" \
+ --name windows-universal --root apps/desktop/release --include '*.msixbundle'
# ── Windows Store submission (REAL — PARALLEL with publish-win32-updater) ─
# Bundles the two Store-*.msix into one universal Store .msixbundle and
@@ -1072,12 +1004,13 @@ jobs:
restore-keys: |
eb2-${{ runner.os }}-${{ runner.arch }}-
- - name: Download win legs' MSIX (incl. Store-*.msix)
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
- with:
- pattern: hermes-bundled-win32-*-${{ inputs.tag }}
- path: apps/desktop/release
- merge-multiple: true
+ - name: Retrieve Store packages from R2
+ shell: bash
+ env:
+ RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}
+ run: |
+ python -m scripts.releases.handoff fetch --tag "$HERMES_PAYLOAD_TAG" --commit "$RELEASE_COMMIT" \
+ --name win32-x64 --name win32-arm64 --root apps/desktop/release --include 'Store-*.msix'
- name: Bundle the Store submission MSIX
id: storebundle
@@ -1176,12 +1109,13 @@ jobs:
with:
cache-python: false
- - name: Download both darwin legs' feed ymls
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
- with:
- pattern: hermes-bundled-darwin-*-${{ inputs.tag }}
- path: staged
- merge-multiple: true
+ - name: Retrieve macOS feed inputs from R2
+ shell: bash
+ env:
+ RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}
+ run: |
+ python -m scripts.releases.handoff fetch --tag "$HERMES_PAYLOAD_TAG" --commit "$RELEASE_COMMIT" \
+ --name darwin-x64 --name darwin-arm64 --root staged --include '*-mac.yml'
- name: Assert the per-arch feeds are present
shell: bash
@@ -1418,39 +1352,28 @@ jobs:
--payload termux-build/payload \
--out termux-build/deb
- - name: Upload the .deb as a workflow artifact
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
- with:
- # Matches the publish jobs' download pattern hermes-bundled-* so
- # the release leg's artifact sweep sees it.
- name: hermes-bundled-termux-${{ inputs.tag }}
- path: termux-build/deb/*.deb
- retention-days: 30
- if-no-files-found: error
-
- - name: Verify the previous Termux run
- if: inputs.termux_upgrade_from_run != ''
+ - name: Retrieve the previous published Termux package from R2
+ if: inputs.termux_upgrade_from_tag != ''
env:
- PREVIOUS_RUN: ${{ inputs.termux_upgrade_from_run }}
+ PREVIOUS_TAG: ${{ inputs.termux_upgrade_from_tag }}
run: |
- [[ "$PREVIOUS_RUN" =~ ^[0-9]+$ ]]
- gh api "repos/$GITHUB_REPOSITORY/actions/runs/$PREVIOUS_RUN" > "$RUNNER_TEMP/termux-previous-run.json"
- python3 - "$RUNNER_TEMP/termux-previous-run.json" <<'PY'
- import json, subprocess, sys
- run = json.load(open(sys.argv[1], encoding="utf-8"))
- assert run["conclusion"] == "success", "previous run did not succeed"
- assert run["path"] == ".github/workflows/desktop-bundled-release.yml", "wrong artifact producer"
- subprocess.run(["git", "merge-base", "--is-ancestor", run["head_sha"], "origin/main"], check=True)
+ python - <<'PY'
+ import json, os, subprocess
+ from pathlib import Path
+ from scripts.releases.handoff import fetch
+ from scripts.releases.semver import is_valid_version
+ tag = os.environ['PREVIOUS_TAG']
+ if not tag.startswith('v') or not is_valid_version(tag[1:]):
+ raise ValueError('Invalid previous release tag')
+ release = json.loads(subprocess.check_output([
+ 'gh', 'release', 'view', tag, '--repo', os.environ['GITHUB_REPOSITORY'],
+ '--json', 'tagName,isDraft'], text=True))
+ if release['tagName'] != tag or release['isDraft']:
+ raise ValueError('Previous package must come from a published release')
+ commit = subprocess.check_output(['git', 'rev-parse', '--verify', f'refs/tags/{tag}^{{commit}}'], text=True).strip()
+ subprocess.run(['git', 'merge-base', '--is-ancestor', commit, 'origin/main'], check=True)
+ fetch(tag, commit, ['termux'], Path('termux-build/previous'), ['deb/*.deb'])
PY
- - name: Download the previous Termux package
- if: inputs.termux_upgrade_from_run != ''
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
- with:
- github-token: ${{ github.token }}
- run-id: ${{ inputs.termux_upgrade_from_run }}
- pattern: hermes-bundled-termux-*
- merge-multiple: true
- path: termux-build/previous
- name: Write the APT signing key
shell: bash
@@ -1467,8 +1390,9 @@ jobs:
shell: bash
env:
CHANNEL: ${{ steps.channel.outputs.channel }}
- PREVIOUS_RUN: ${{ inputs.termux_upgrade_from_run }}
+ PREVIOUS_TAG: ${{ inputs.termux_upgrade_from_tag }}
RELEASE_PHASE: ${{ inputs.release-phase }}
+ RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}
# Passphrase-protected signing keys only; unset for bare keys.
TERMUX_APT_GPG_PASSPHRASE: ${{ secrets.TERMUX_APT_GPG_PASSPHRASE }}
run: |
@@ -1490,8 +1414,8 @@ jobs:
-v "$PWD/scripts/termux/check_apt.sh:/tmp/check-apt.sh:ro" \
-v "$PWD/scripts/termux/validate_installed.py:/tmp/validate_installed.py:ro" \
"termux/termux-docker@$digest" bash /tmp/check-apt.sh "hermes-$CHANNEL" "$version"
- if [ -n "$PREVIOUS_RUN" ]; then
- previous=(termux-build/previous/*.deb)
+ if [ -n "$PREVIOUS_TAG" ]; then
+ previous=(termux-build/previous/deb/*.deb)
test "${#previous[@]}" -eq 1
docker run --rm --platform linux/arm64 --user 1000:1000 --network none \
-v "$PWD/termux-build/apt:/apt:ro" \
@@ -1501,11 +1425,16 @@ jobs:
"termux/termux-docker@$digest" bash /tmp/check-apt.sh "hermes-$CHANNEL" "$version"
fi
+ args=(--include 'deb/*.deb' --include 'apt/**/*')
if [ "$RELEASE_PHASE" = candidate ]; then
- python3 -m scripts.bundles.release_artifacts record --platform termux --arch aarch64 \
- --root termux-build --tag "$HERMES_PAYLOAD_TAG" --out "$RUNNER_TEMP/termux.tar"
- exit 0
+ python -m scripts.bundles.release_artifacts record --platform termux --arch aarch64 \
+ --root termux-build --tag "$HERMES_PAYLOAD_TAG" --commit "$RELEASE_COMMIT" \
+ --out termux-build/metadata-termux-aarch64.json
+ args+=(--include 'metadata-*.json')
fi
+ python -m scripts.releases.handoff stage --tag "$HERMES_PAYLOAD_TAG" --commit "$RELEASE_COMMIT" \
+ --name termux --root termux-build "${args[@]}"
+ if [ "$RELEASE_PHASE" = candidate ]; then exit 0; fi
# --key-is-full is MANDATORY on every feed-dir upload: without it
# scripts.releases.r2 re-prefixes the key into the tag archive
# (releases/tag/<tag>/) and the APT feed never lands at
@@ -1542,13 +1471,6 @@ jobs:
-v "$GITHUB_WORKSPACE/scripts/termux/check_apt.sh:/tmp/check-apt.sh:ro" \
-v "$GITHUB_WORKSPACE/scripts/termux/validate_installed.py:/tmp/validate_installed.py:ro" \
"termux/termux-docker@$digest" bash /tmp/check-apt.sh "hermes-$CHANNEL" "$version" "$public_repo"
- - name: Retain stable Termux candidate
- if: inputs.release-phase == 'candidate'
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
- with:
- name: stable-candidate-termux
- path: ${{ runner.temp }}/termux.tar
- if-no-files-found: error
builds-pending:
name: Mark the builds table as in progress
@@ -1623,17 +1545,16 @@ jobs:
- uses: ./.github/actions/setup-pm
with:
cache-python: false
- - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
- with:
- pattern: stable-candidate-*
- path: candidates
+ - name: Retrieve candidate receipts and native metadata from R2
+ env:
+ RELEASE_COMMIT: ${{ needs.validate.outputs.sha }}
+ run: |
+ python -m scripts.releases.handoff fetch --tag "$RELEASE_TAG" --commit "$RELEASE_COMMIT" \
+ --name win32-x64 --name win32-arm64 --name darwin-x64 --name darwin-arm64 \
+ --name termux --name windows-universal --root candidates \
+ --include 'metadata-*.json' --include '*.msixbundle'
- id: manifest
- run: python -m scripts.bundles.release_artifacts assemble --root candidates --bundle-dir candidates/stable-candidate-universal --out release-candidates.json
- - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
- with:
- name: stable-release-candidates
- path: release-candidates.json
- if-no-files-found: error
+ run: python -m scripts.bundles.release_artifacts assemble --root candidates --out release-candidates.json
stable-publish:
name: Verify published candidate files
@@ -1657,10 +1578,7 @@ jobs:
- uses: ./.github/actions/setup-pm
with:
cache-python: false
- - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
- with:
- name: stable-release-candidates
- - run: python -m scripts.bundles.release_artifacts publish --manifest release-candidates.json --root verified
+ - run: python -m scripts.bundles.release_artifacts publish --root verified
stable-store:
name: Submit the verified Store package
@@ -1685,12 +1603,9 @@ jobs:
- uses: ./.github/actions/setup-pm
with:
cache-python: false
- - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
- with:
- name: stable-release-candidates
- name: Retrieve the exact Store candidate
shell: bash
- run: python -m scripts.bundles.release_artifacts materialize --manifest release-candidates.json --root verified --store-only
+ run: python -m scripts.bundles.release_artifacts materialize --root verified --store-only
- uses: microsoft/microsoft-store-apppublisher@cc9910a8d59f2eb55cbb83df0a3800cf3b5300e0 # v1.4
- name: Submit without rebuilding
shell: bash
@@ -1725,10 +1640,7 @@ jobs:
- uses: ./.github/actions/setup-pm
with:
cache-python: false
- - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
- with:
- name: stable-release-candidates
- - run: uv run --no-project --with PyYAML==6.0.3 python -m scripts.bundles.release_artifacts promote --manifest release-candidates.json --root verified
+ - run: uv run --no-project --with PyYAML==6.0.3 python -m scripts.bundles.release_artifacts promote --root verified
- run: python scripts/render-builds-table.py --tag "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY"
stable-phase-result:
diff --git a/docs/stable-releases.md b/docs/stable-releases.md
index 7d7c81724a6..406afa2f2b4 100644
--- a/docs/stable-releases.md
+++ b/docs/stable-releases.md
@@ -42,13 +42,30 @@ The local workflow calls and their checkouts use the tag's commit, not moving
main.
For a failed publication or promotion, retry the failed jobs in the original
-run while its candidate artifacts remain available. Cross-phase artifact
-handoff is scoped to that run. Immutable uploads accept an existing object
-only after verifying that its bytes match; different bytes fail. Do not delete
-archive objects or rebuild signed candidates under the same tag to bypass a
-conflict. A fresh dispatch starts the build phases again and is not a
-promotion-only retry. If the original artifacts are unavailable, stop recovery
-rather than replace the accepted candidate.
+run. Desktop and Termux handoffs live in the immutable R2 tag archive, not
+expiring GitHub job artifacts. Each producer uploads its files, then writes a
+`handoff-<target>.json` receipt containing the tag, commit, paths, sizes and
+SHA256 digests. Consumers validate that identity and verify streamed downloads
+before using them. Candidate assembly publishes only `release-candidates.json`;
+it does not upload the packages again.
+
+Windows, macOS and Termux candidate jobs stage packages, native metadata and
+APT inputs under `releases/tag/<tag>/` before acceptance. No stable feed is
+written at this stage. Publication and promotion read the candidate manifest
+from R2 and require the digest passed by the accepted candidate job. The
+existing acceptance and publication gates still control every stable channel.
+
+Immutable uploads accept an existing object only after verifying that its bytes
+match; different bytes fail. Do not delete archive objects or rebuild signed
+candidates under the same tag to bypass a conflict. A fresh dispatch starts the
+build phases again and is not a promotion-only retry. If the original objects
+are unavailable, stop recovery rather than replace the accepted candidate.
+
+The desktop workflow's optional Termux upgrade input is
+`termux_upgrade_from_tag`: an exact published release tag with a Termux R2
+handoff. It no longer selects packages by a GitHub workflow run. Explicit
+non-publishing desktop builds retain no downloadable job artifacts. Unrelated
+CI diagnostics and tested Docker image handoffs keep their existing storage.
## Signed-package baseline
diff --git a/scripts/bundles/release_artifacts.py b/scripts/bundles/release_artifacts.py
index 82f71c0ed32..01588c0960f 100644
--- a/scripts/bundles/release_artifacts.py
+++ b/scripts/bundles/release_artifacts.py
@@ -8,14 +8,13 @@ import os
import plistlib
import re
import subprocess
-import tarfile
import tempfile
import urllib.request
import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path
-from scripts.releases.stable import validate_candidates
+from scripts.releases.stable import read_manifest, require_stable_identity, validate_candidates
def sha256_file(file: Path) -> str:
@@ -50,7 +49,6 @@ def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Pat
raise ValueError("MSIX architecture differs from release target")
row.update(identity=identity.attrib["Name"], publisher=identity.attrib["Publisher"],
applicationId=application.attrib["Id"], version=identity.attrib["Version"])
- files = list(root.glob(f"*-win-{arch}.msix"))
elif platform == "macos":
package = single(root.glob(f"*-mac-{arch}.zip"))
app = single(root.glob("mac*/*.app"))
@@ -66,12 +64,11 @@ def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Pat
row.update(identity=info["CFBundleIdentifier"], teamId=team.group(1), version=info["CFBundleShortVersionString"], filename=package.name)
if row["version"] != tag[1:]:
raise ValueError("App version differs from release tag")
- files = [p for p in root.iterdir() if p.is_file() and (f"-mac-{arch}." in p.name or p.name == f"{arch}-stable-mac.yml")]
elif platform == "termux":
package = single((root / "deb").glob("*.deb"))
fields = subprocess.check_output(["dpkg-deb", "--field", str(package), "Package", "Version", "Architecture"], text=True, encoding="utf-8")
parsed = dict(line.split(": ", 1) for line in fields.splitlines())
- row.update(identity=parsed["Package"], version=parsed["Version"], filename=package.name)
+ row.update(identity=parsed["Package"], version=parsed["Version"], filename=package.relative_to(root).as_posix())
if parsed["Architecture"] != "aarch64":
raise ValueError("Wrong Termux package architecture")
with tempfile.TemporaryDirectory() as temp:
@@ -79,75 +76,67 @@ def record(platform: str, arch: str, root: Path, tag: str, commit: str, out: Pat
stamps = list(Path(temp).rglob("install-stamp.json"))
if not any((data := json.loads(p.read_text(encoding="utf-8"))).get("commit") == commit and data.get("tag") == tag for p in stamps):
raise ValueError("Termux package has no matching provenance")
- files = [package]
else:
raise ValueError("Unknown platform")
out.parent.mkdir(parents=True, exist_ok=True)
- with tarfile.open(out, "w") as archive:
- for file in files:
- archive.add(file, arcname=file.name)
- if platform == "termux":
- archive.add(root / "apt", arcname="apt")
- with tempfile.TemporaryDirectory() as temp:
- metadata = Path(temp) / f"metadata-{platform}-{arch}.json"
- metadata.write_text(json.dumps(row), encoding="utf-8")
- archive.add(metadata, arcname=metadata.name)
-
-
-def unpack(directory: Path, target: Path) -> None:
- target.mkdir(parents=True, exist_ok=True)
- for file in directory.rglob("*.tar"):
- with tarfile.open(file) as archive:
- archive.extractall(target, filter="data")
-
-
-def assemble(directory: Path, bundle: Path, tag: str, commit: str, public_base: str, out: Path) -> dict:
- """Collect native outputs and retain hashes of every file publication will use."""
- from scripts.releases.r2 import put
-
- with tempfile.TemporaryDirectory() as temp:
- root = Path(temp)
- unpack(directory, root)
- rows = [json.loads(p.read_text(encoding="utf-8")) for p in root.glob("metadata-*.json")]
- for item in bundle.iterdir():
- if item.is_file() and item.suffix == ".msixbundle":
- import shutil
- shutil.copy2(item, root / item.name)
- universal = single(p for p in root.glob("*.msixbundle") if not p.name.startswith("Store-"))
- windows = [r for r in rows if r["platform"] == "windows"]
- if sorted(r["arch"] for r in windows) != ["arm64", "x64"]:
- raise ValueError("Windows metadata must include both architectures")
- for field in ("identity", "publisher", "version", "applicationId"):
- if len({r[field] for r in windows}) != 1:
- raise ValueError(f"Windows packages disagree on {field}")
- with zipfile.ZipFile(universal) as archive:
- manifest = ET.fromstring(archive.read("AppxMetadata/AppxBundleManifest.xml"))
- identity = manifest.find("{*}Identity")
- for attr, field in (("Name", "identity"), ("Publisher", "publisher"), ("Version", "version")):
- if identity.attrib[attr] != windows[0][field]:
- raise ValueError("Universal bundle identity does not match its packages")
- files = []
- for file in sorted(root.rglob("*")):
- if not file.is_file() or file.name.startswith("metadata-"):
- continue
- relative = file.relative_to(root).as_posix()
- key = f"releases/tag/{tag}/{relative}"
- put(tag=tag, key=key, file=file, key_is_full=True, immutable=True)
- files.append({"path": relative, "sha256": sha256_file(file), "url": f"{public_base.rstrip('/')}/{key}"})
- by_name = {item["path"]: item for item in files}
- packages = []
- for row in rows:
- stamp_matches(row, tag, commit)
- filename = universal.name if row["platform"] == "windows" else row["filename"]
- item = by_name[filename]
- packages.append({k: v for k, v in {**row, "artifact": {"url": item["url"], "sha256": item["sha256"]}}.items() if k != "filename"})
- result = {"schema": 1, "tag": tag, "commit": commit, "packages": packages, "files": files}
- validate_candidates(result, tag, commit, public_base)
- if not any(row["platform"] == "termux" for row in packages):
- raise ValueError("Missing Termux candidate")
- out.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
- put(tag=tag, key="release-candidates.json", file=out, immutable=True)
- return result
+ out.write_text(json.dumps(row, sort_keys=True, indent=2) + "\n", encoding="utf-8")
+
+
+def assemble(root: Path, tag: str, commit: str, public_base: str, out: Path) -> dict:
+ """Bind the native metadata to files already staged by their build jobs."""
+ from scripts.releases.handoff import receipt_name, validate_receipt
+ from scripts.releases.r2 import put, staging_key_for
+
+ expected = ("win32-x64", "win32-arm64", "darwin-x64", "darwin-arm64", "termux", "windows-universal")
+ by_name = {}
+ for name in expected:
+ file = root / receipt_name(name)
+ if not file.is_file():
+ raise ValueError(f"Missing candidate handoff: {name}")
+ receipt = json.loads(file.read_text(encoding="utf-8"))
+ for row in validate_receipt(receipt, tag, commit, name):
+ prior = by_name.get(row["path"])
+ if prior is not None and prior != row:
+ raise ValueError("Candidate handoffs disagree on file receipts")
+ by_name[row["path"]] = row
+ rows = []
+ for name, receipt in sorted(by_name.items()):
+ if name.startswith("metadata-") or name.endswith(".msixbundle"):
+ file = root / name
+ if not file.is_file() or sha256_file(file) != receipt["sha256"]:
+ raise ValueError(f"Candidate local digest mismatch: {name}")
+ if name.startswith("metadata-"):
+ rows.append(json.loads(file.read_text(encoding="utf-8")))
+ universal_name = single(name for name in by_name if name.endswith(".msixbundle") and not name.startswith("Store-"))
+ single(name for name in by_name if name.endswith(".msixbundle") and name.startswith("Store-"))
+ windows = [r for r in rows if r["platform"] == "windows"]
+ if sorted(r["arch"] for r in windows) != ["arm64", "x64"]:
+ raise ValueError("Windows metadata must include both architectures")
+ for field in ("identity", "publisher", "version", "applicationId"):
+ if len({r[field] for r in windows}) != 1:
+ raise ValueError(f"Windows packages disagree on {field}")
+ with zipfile.ZipFile(root / universal_name) as archive:
+ manifest = ET.fromstring(archive.read("AppxMetadata/AppxBundleManifest.xml"))
+ identity = manifest.find("{*}Identity")
+ for attr, field in (("Name", "identity"), ("Publisher", "publisher"), ("Version", "version")):
+ if identity.attrib[attr] != windows[0][field]:
+ raise ValueError("Universal bundle identity does not match its packages")
+ files = [{**row, "url": f"{public_base.rstrip('/')}/{staging_key_for(tag, name)}"}
+ for name, row in sorted(by_name.items()) if not name.startswith("metadata-")]
+ by_name = {item["path"]: item for item in files}
+ packages = []
+ for row in rows:
+ stamp_matches(row, tag, commit)
+ filename = universal_name if row["platform"] == "windows" else row["filename"]
+ item = by_name[filename]
+ packages.append({k: v for k, v in {**row, "artifact": {"url": item["url"], "sha256": item["sha256"]}}.items() if k != "filename"})
+ result = {"schema": 1, "tag": tag, "commit": commit, "packages": packages, "files": files}
+ validate_candidates(result, tag, commit, public_base)
+ if not any(row["platform"] == "termux" for row in packages):
+ raise ValueError("Missing Termux candidate")
+ out.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
+ put(tag=tag, key="release-candidates.json", file=out, immutable=True)
+ return result
def materialize(manifest: dict, root: Path, *, public_base: str, store_only: bool = False) -> None:
@@ -227,32 +216,34 @@ def promote(manifest: dict, root: Path, public_base: str) -> None:
publish_pointer(f"releases/termux/stable/{file.relative_to(apt).as_posix()}", file)
-def main() -> None:
+def main(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["record", "assemble", "publish", "promote", "materialize"])
parser.add_argument("--platform", choices=["windows", "macos", "termux"])
parser.add_argument("--arch")
parser.add_argument("--root", type=Path, required=True)
- parser.add_argument("--bundle-dir", type=Path)
parser.add_argument("--out", type=Path)
parser.add_argument("--tag", default=os.environ.get("RELEASE_TAG"))
parser.add_argument("--commit", default=os.environ.get("GITHUB_SHA"))
parser.add_argument("--public-base", default=os.environ.get("CLOUDFLARE_R2_PUBLIC_URL"))
- parser.add_argument("--manifest", type=Path)
parser.add_argument("--store-only", action="store_true")
- args = parser.parse_args()
+ args = parser.parse_args(argv)
if args.command == "record":
record(args.platform, args.arch, args.root, args.tag, args.commit, args.out)
elif args.command == "assemble":
- assemble(args.root, args.bundle_dir, args.tag, args.commit, args.public_base, args.out)
+ assemble(args.root, args.tag, args.commit, args.public_base, args.out)
if os.environ.get("GITHUB_OUTPUT"):
with Path(os.environ["GITHUB_OUTPUT"]).open("a", encoding="utf-8") as file:
file.write(f"manifest-url={args.public_base.rstrip('/')}/releases/tag/{args.tag}/release-candidates.json\nmanifest-sha256={sha256_file(args.out)}\n")
else:
expected_digest = os.environ.get("CANDIDATE_MANIFEST_SHA256", "")
- if not re.fullmatch(r"[a-f0-9]{64}", expected_digest) or sha256_file(args.manifest) != expected_digest:
- raise ValueError("Candidate manifest differs from accepted candidate")
- manifest = json.loads(args.manifest.read_text(encoding="utf-8"))
+ if not re.fullmatch(r"[a-f0-9]{64}", expected_digest):
+ raise ValueError("Pinned candidate manifest digest is required")
+ require_stable_identity(args.tag, args.commit, f"refs/tags/{args.tag}")
+ manifest = read_manifest(
+ f"{args.public_base.rstrip('/')}/releases/tag/{args.tag}/release-candidates.json",
+ expected_digest, expected_origin=args.public_base,
+ )
validate_candidates(manifest, args.tag, args.commit, args.public_base)
if args.command == "materialize":
materialize(manifest, args.root, public_base=args.public_base, store_only=args.store_only)
diff --git a/scripts/releases/handoff.py b/scripts/releases/handoff.py
new file mode 100644
index 00000000000..559a64e42c9
--- /dev/null
+++ b/scripts/releases/handoff.py
@@ -0,0 +1,144 @@
+"""Transfer immutable release files through R2 without publishing a feed."""
+from __future__ import annotations
+
+import argparse
+import fnmatch
+import json
+import ntpath
+import os
+import re
+import tempfile
+from pathlib import Path, PurePosixPath
+
+from scripts.releases import r2
+from scripts.releases.semver import is_valid_version
+
+
+def validate_identity(tag: str, commit: str, name: str) -> None:
+ if (not isinstance(tag, str) or not tag.startswith("v") or not is_valid_version(tag[1:])
+ or not re.fullmatch(r"[a-f0-9]{40}", commit or "")
+ or not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", name or "")):
+ raise ValueError("Invalid release handoff identity")
+
+
+def receipt_name(name: str) -> str:
+ return f"handoff-{name}.json"
+
+
+def relative_path(value: str) -> str:
+ if (not isinstance(value, str) or not value or value.startswith("/")
+ or any(part in ("", ".", "..") for part in value.split("/"))
+ or any(c in value for c in "\\:%?#") or any(ord(c) < 32 for c in value)
+ or ntpath.isreserved(value)):
+ raise ValueError("Invalid release artifact path")
+ return value
+
+
+def validate_receipt(receipt: dict, tag: str, commit: str, name: str) -> list[dict]:
+ validate_identity(tag, commit, name)
+ if (not isinstance(receipt, dict) or receipt.get("schema") != 1
+ or receipt.get("tag") != tag or receipt.get("commit") != commit or receipt.get("name") != name):
+ raise ValueError("Release handoff identity mismatch")
+ files = receipt.get("files")
+ if not isinstance(files, list) or not files:
+ raise ValueError("No files in release handoff")
+ seen = set()
+ for row in files:
+ if not isinstance(row, dict):
+ raise ValueError("Invalid release file receipt")
+ path = relative_path(row.get("path"))
+ if path.casefold() in seen:
+ raise ValueError("Duplicate release artifact path")
+ seen.add(path.casefold())
+ if (type(row.get("size")) is not int or row["size"] < 0
+ or not re.fullmatch(r"[a-f0-9]{64}", row.get("sha256", ""))):
+ raise ValueError("Invalid release file size or digest")
+ return files
+
+
+def stage(tag: str, commit: str, name: str, root: Path, includes: list[str]) -> dict:
+ validate_identity(tag, commit, name)
+ root = root.resolve()
+ selected = {}
+ for pattern in includes:
+ matched = [p for p in root.glob(pattern) if p.is_file()]
+ if not matched:
+ raise ValueError(f"No files match release handoff pattern: {pattern}")
+ for file in matched:
+ if file.is_symlink() or not file.resolve().is_relative_to(root):
+ raise ValueError("Release artifact path escapes its build root")
+ selected[file.relative_to(root).as_posix()] = file
+ files = [{"path": relative_path(path), "size": file.stat().st_size, "sha256": r2.file_sha256(file)}
+ for path, file in sorted(selected.items())]
+ receipt = {"schema": 1, "tag": tag, "commit": commit, "name": name, "files": files}
+ validate_receipt(receipt, tag, commit, name)
+ for row in files:
+ r2.put(tag=tag, key=row["path"], file=selected[row["path"]], immutable=True)
+ # The receipt is the completion marker. An interrupted upload cannot publish it.
+ with tempfile.TemporaryDirectory() as directory:
+ file = Path(directory) / receipt_name(name)
+ file.write_text(json.dumps(receipt, sort_keys=True, indent=2) + "\n", encoding="utf-8")
+ r2.put(tag=tag, key=file.name, file=file, immutable=True)
+ return receipt
+
+
+def read_receipt(tag: str, commit: str, name: str) -> dict:
+ validate_identity(tag, commit, name)
+ creds, base, bucket = r2.credentials()
+ key = r2.staging_key_for(tag, receipt_name(name))
+ text = r2.get_object(creds, base, bucket, key, r2.amz_timestamp())
+ if text is None:
+ raise ValueError(f"Missing release handoff: {name}")
+ receipt = json.loads(text)
+ validate_receipt(receipt, tag, commit, name)
+ return receipt
+
+
+def fetch(tag: str, commit: str, names: list[str], root: Path,
+ includes: list[str] | None = None) -> list[dict]:
+ receipts = [read_receipt(tag, commit, name) for name in names]
+ root = root.resolve()
+ selected = {}
+ for receipt in receipts:
+ for row in receipt["files"]:
+ if includes and not any(fnmatch.fnmatchcase(row["path"], pattern) for pattern in includes):
+ continue
+ prior = selected.get(row["path"].casefold())
+ if prior is not None and prior != row:
+ raise ValueError("Conflicting release file receipts")
+ target = root / PurePosixPath(row["path"])
+ if not target.resolve().is_relative_to(root):
+ raise ValueError("Release artifact path escapes its download root")
+ selected[row["path"].casefold()] = row
+ if not selected:
+ raise ValueError("No files selected from release handoff")
+ root.mkdir(parents=True, exist_ok=True)
+ creds, base, bucket = r2.credentials()
+ for row in selected.values():
+ r2.download_object(creds, base, bucket, r2.staging_key_for(tag, row["path"]),
+ root / row["path"], r2.amz_timestamp(),
+ expected_size=row["size"], expected_sha256=row["sha256"])
+ for receipt in receipts:
+ (root / receipt_name(receipt["name"])).write_text(json.dumps(receipt, sort_keys=True, indent=2) + "\n", encoding="utf-8")
+ return receipts
+
+
+def main(argv: list[str] | None = None) -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("command", choices=["stage", "fetch"])
+ parser.add_argument("--tag", default=os.environ.get("HERMES_PAYLOAD_TAG") or os.environ.get("RELEASE_TAG"), required=False)
+ parser.add_argument("--commit", default=os.environ.get("GITHUB_SHA"))
+ parser.add_argument("--name", action="append", required=True)
+ parser.add_argument("--root", type=Path, required=True)
+ parser.add_argument("--include", action="append")
+ args = parser.parse_args(argv)
+ if args.command == "stage":
+ if len(args.name) != 1 or not args.include:
+ parser.error("stage needs one name and at least one include pattern")
+ stage(args.tag, args.commit, args.name[0], args.root, args.include)
+ else:
+ fetch(args.tag, args.commit, args.name, args.root, args.include)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/releases/r2.py b/scripts/releases/r2.py
index 399183b673a..bd5b3f4adf7 100644
--- a/scripts/releases/r2.py
+++ b/scripts/releases/r2.py
@@ -318,6 +318,53 @@ def verify_remote_artifact(
raise ValueError(f"Artifact checksum mismatch: {urlparse(url).path}")
+def download_object(
+ creds: dict[str, str], base: str, bucket: str, key: str, file: Path, now: str,
+ *, expected_size: int, expected_sha256: str,
+) -> None:
+ """Publish a download locally only after its exact receipt matches."""
+ import tempfile
+
+ if type(expected_size) is not int or expected_size < 0 or not re.fullmatch(r"[a-f0-9]{64}", expected_sha256):
+ raise ValueError("Invalid artifact size or SHA256")
+ file = Path(file)
+ file.parent.mkdir(parents=True, exist_ok=True)
+ url = f"{base}/{bucket}/{encode_key_path(key)}"
+ parsed = urlparse(url)
+ for attempt in range(1, 4):
+ headers = r2_headers("GET", parsed.netloc, parsed.path, "", EMPTY_SHA,
+ now if attempt == 1 else amz_timestamp(), creds)
+ conn = _connection(url, timeout=600.0)
+ temporary = None
+ try:
+ conn.request("GET", parsed.path, headers=headers)
+ response = conn.getresponse()
+ if response.status != 200:
+ raise R2RequestError("GET", parsed.path, response.status)
+ digest, size = hashlib.sha256(), 0
+ with tempfile.NamedTemporaryFile(dir=file.parent, prefix=f".{file.name}.", delete=False) as output:
+ temporary = Path(output.name)
+ while chunk := response.read(1024 * 1024):
+ digest.update(chunk)
+ size += len(chunk)
+ output.write(chunk)
+ if size != expected_size or digest.hexdigest() != expected_sha256:
+ raise ValueError(f"Artifact checksum mismatch: {key}")
+ temporary.replace(file)
+ return
+ except R2RequestError as error:
+ if error.status not in _RETRYABLE_STATUSES or attempt == 3:
+ raise
+ except (OSError, http.client.HTTPException):
+ if attempt == 3:
+ raise
+ finally:
+ conn.close()
+ if temporary is not None:
+ temporary.unlink(missing_ok=True)
+ time.sleep(float(attempt))
+
+
def _stream_and_hash(url: str, creds: dict[str, str], now: str, algorithm: str):
"""True streaming GET: hash + count bytes as chunks arrive off the
socket, never materializing the body in memory."""
diff --git a/tests/scripts/test_release_artifacts.py b/tests/scripts/test_release_artifacts.py
index bcdef41f00f..8dc1427411e 100644
--- a/tests/scripts/test_release_artifacts.py
+++ b/tests/scripts/test_release_artifacts.py
@@ -2,13 +2,13 @@
import hashlib
import io
import json
-import tarfile
import zipfile
from pathlib import Path
import pytest
from scripts.bundles.release_artifacts import materialize, record, stamp_matches
+from tests.scripts.test_release_r2 import r2_server # noqa: F401
def test_windows_metadata_is_read_from_package_and_stale_stamp_is_rejected(tmp_path):
@@ -24,22 +24,77 @@ def test_windows_metadata_is_read_from_package_and_stale_stamp_is_rejected(tmp_p
archive.writestr('app/resources/install-stamp.json', json.dumps({'tag': tag, 'commit': sha}))
write_package(commit)
- out = tmp_path / 'record.tar'
+ out = root / 'metadata-windows-x64.json'
+ original = package.read_bytes()
record('windows', 'x64', root, tag, commit, out)
- with tarfile.open(out) as archive:
- metadata = json.load(archive.extractfile('metadata-windows-x64.json'))
- assert metadata['identity'] == 'Product'
- assert metadata['version'] == '1.2.3.0'
- assert metadata['publisher'] == 'CN=Test'
- assert metadata['applicationId'] == 'App'
- assert archive.extractfile(package.name).read() == package.read_bytes()
+ metadata = json.loads(out.read_text(encoding='utf-8'))
+ assert metadata['identity'] == 'Product'
+ assert metadata['version'] == '1.2.3.0'
+ assert metadata['publisher'] == 'CN=Test'
+ assert metadata['applicationId'] == 'App'
+ assert package.read_bytes() == original
write_package('b' * 40)
with pytest.raises(ValueError, match='provenance'):
- record('windows', 'x64', root, tag, commit, tmp_path / 'bad.tar')
+ record('windows', 'x64', root, tag, commit, tmp_path / 'bad.json')
with pytest.raises(ValueError, match='provenance'):
stamp_matches({}, tag, commit)
+def test_assemble_uses_staged_receipts_and_only_publishes_the_manifest(tmp_path, monkeypatch, r2_server):
+ from scripts.bundles.release_artifacts import assemble
+ from scripts.releases import handoff
+
+ tag, commit, base = 'v1.2.3', 'a' * 40, 'https://releases.example'
+ built = tmp_path / 'built'
+ built.mkdir()
+ for platform, arches in [('windows', ('x64', 'arm64')), ('macos', ('x64', 'arm64')), ('termux', ('aarch64',))]:
+ for arch in arches:
+ row = {'platform': platform, 'arch': arch, 'tag': tag, 'commit': commit, 'identity': 'Product'}
+ if platform == 'windows':
+ row.update(version='1.2.3.0', publisher='CN=Test', applicationId='App')
+ package = f'Product-win-{arch}.msix'
+ handoff_name = f'win32-{arch}'
+ elif platform == 'macos':
+ package = f'Product-mac-{arch}.zip'
+ row.update(version='1.2.3', teamId='ABCDEFGHIJ', filename=package)
+ handoff_name = f'darwin-{arch}'
+ else:
+ package = 'deb/product.deb'
+ row.update(version='1.2.3-1', filename=package)
+ handoff_name = 'termux'
+ file = built / package
+ file.parent.mkdir(parents=True, exist_ok=True)
+ file.write_bytes(b'package transport fixture')
+ metadata = built / f'metadata-{platform}-{arch}.json'
+ metadata.write_text(json.dumps(row), encoding='utf-8')
+ handoff.stage(tag, commit, handoff_name, built, [package, metadata.name])
+ bundle = built / 'Product-win.msixbundle'
+ with zipfile.ZipFile(bundle, 'w') as archive:
+ archive.writestr('AppxMetadata/AppxBundleManifest.xml', '<Bundle><Identity Name="Product" Publisher="CN=Test" Version="1.2.3.0"/></Bundle>')
+ (built / 'Store-Product-win.msixbundle').write_bytes(b'Store bundle transport fixture')
+ handoff.stage(tag, commit, 'windows-universal', built, ['*.msixbundle'])
+ fetched = tmp_path / 'fetched'
+ names = ['win32-x64', 'win32-arm64', 'darwin-x64', 'darwin-arm64', 'termux', 'windows-universal']
+ handoff.fetch(tag, commit, names, fetched, ['metadata-*.json', '*.msixbundle'])
+ r2_server.requests.clear()
+ manifest = assemble(fetched, tag, commit, base, tmp_path / 'release-candidates.json')
+ assert {row['platform'] + '/' + row['arch'] for row in manifest['packages']} == {
+ 'windows/x64', 'windows/arm64', 'macos/x64', 'macos/arm64', 'termux/aarch64'}
+ assert all(not file['path'].startswith(('handoff-', 'metadata-')) for file in manifest['files'])
+ puts = [path for method, path, _ in r2_server.requests if method == 'PUT']
+ assert puts == [f'/hermes-releases/releases/tag/{tag}/release-candidates.json']
+ assert all(key.startswith(f'releases/tag/{tag}/') for key in r2_server.store)
+ receipt = fetched / 'handoff-darwin-arm64.json'
+ original = receipt.read_bytes()
+ receipt.unlink()
+ with pytest.raises(ValueError, match='handoff'):
+ assemble(fetched, tag, commit, base, tmp_path / 'missing.json')
+ receipt.write_bytes(original)
+ (fetched / 'metadata-windows-x64.json').write_text('{}', encoding='utf-8')
+ with pytest.raises(ValueError, match='digest'):
+ assemble(fetched, tag, commit, base, tmp_path / 'changed.json')
+
+
def test_materialize_validates_the_published_file_receipt_before_using_bytes(tmp_path, monkeypatch):
base, tag, commit = 'https://releases.example', 'v1.2.3', 'a' * 40
data = b'package transport fixture, not native signing proof'
@@ -68,6 +123,29 @@ def test_materialize_validates_the_published_file_receipt_before_using_bytes(tmp
files.append(store)
materialize(manifest, tmp_path / 'store', public_base=base, store_only=True)
assert [p.name for p in (tmp_path / 'store').iterdir()] == [store['path']]
+
+ from scripts.bundles import release_artifacts
+ from scripts.releases import stable
+ raw_manifest = json.dumps(manifest).encode()
+ seen = []
+
+ def read_remote(url, expected_hash, *, expected_origin):
+ seen.append((url, expected_hash, expected_origin))
+ return stable.read_manifest(url, expected_hash, expected_origin=expected_origin,
+ opener=lambda *args, **kwargs: Response(raw_manifest))
+
+ monkeypatch.setattr(release_artifacts, 'read_manifest', read_remote)
+ monkeypatch.setenv('CANDIDATE_MANIFEST_SHA256', hashlib.sha256(raw_manifest).hexdigest())
+ release_artifacts.main(['materialize', '--tag', tag, '--commit', commit, '--public-base', base,
+ '--root', str(tmp_path / 'remote-store'), '--store-only'])
+ assert (tmp_path / 'remote-store' / store['path']).read_bytes() == data
+ assert seen[0][0] == f'{base}/releases/tag/{tag}/release-candidates.json'
+ assert seen[0][2] == base
+ monkeypatch.setenv('CANDIDATE_MANIFEST_SHA256', 'f' * 64)
+ with pytest.raises(ValueError, match='digest mismatch'):
+ release_artifacts.main(['materialize', '--tag', tag, '--commit', commit, '--public-base', base,
+ '--root', str(tmp_path / 'wrong-manifest'), '--store-only'])
+ assert not (tmp_path / 'wrong-manifest').exists()
files[0]['sha256'] = 'b' * 64
with pytest.raises(ValueError, match='receipts differ'):
materialize(manifest, tmp_path / 'bad', public_base=base)
diff --git a/tests/scripts/test_release_handoff.py b/tests/scripts/test_release_handoff.py
new file mode 100644
index 00000000000..827fd2cc256
--- /dev/null
+++ b/tests/scripts/test_release_handoff.py
@@ -0,0 +1,87 @@
+"""Release handoffs use exact R2 bytes without advancing a channel."""
+import copy
+import json
+
+import pytest
+
+from scripts.releases import r2
+from tests.scripts.test_release_r2 import r2_server # noqa: F401
+
+
[email protected]('tag', ['v1.2.3', 'v1.2.3-canary.20260908232538'])
+def test_stage_and_fetch_bind_tag_commit_and_files_without_feed_writes(tmp_path, r2_server, tag):
+ from scripts.releases import handoff
+
+ commit = "a" * 40
+ root = tmp_path / "built"
+ root.mkdir()
+ data = b"multi-chunk package transport fixture\n" * 90000
+ (root / "app.msix").write_bytes(data)
+ (root / "Store-app.msix").write_bytes(b"store transport fixture")
+ (root / "metadata-windows-x64.json").write_text("{}", encoding="utf-8")
+ nested = root / "apt" / "dists" / "hermes-stable" / "InRelease"
+ nested.parent.mkdir(parents=True)
+ nested.write_bytes(b"APT index transport fixture")
+ handoff.main(["stage", "--tag", tag, "--commit", commit, "--name", "win32-x64",
+ "--root", str(root), "--include", "*.msix", "--include", "metadata-*.json", "--include", "apt/**/*"])
+ receipt_key = f"releases/tag/{tag}/handoff-win32-x64.json"
+ receipt = json.loads(r2_server.store[receipt_key][0])
+ assert receipt["tag"] == tag and receipt["commit"] == commit
+ assert {row["path"] for row in receipt["files"]} == {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()}
+ assert all(key.startswith(f"releases/tag/{tag}/") for key in r2_server.store)
+ puts = [path for method, path, _ in r2_server.requests if method == "PUT"]
+ assert puts[-1].endswith(receipt_key)
+ assert all(headers.get("If-None-Match") == "*" for method, _, headers in r2_server.requests if method == "PUT")
+
+ downloaded = tmp_path / "downloaded"
+ handoff.main(["fetch", "--tag", tag, "--commit", commit, "--name", "win32-x64",
+ "--root", str(downloaded), "--include", "*.msix"])
+ assert (downloaded / "app.msix").read_bytes() == data
+ assert (downloaded / "Store-app.msix").read_bytes() == b"store transport fixture"
+ assert not (downloaded / "metadata-windows-x64.json").exists()
+ handoff.stage(tag, commit, "win32-x64", root, ["*.msix", "metadata-*.json", "apt/**/*"])
+ handoff.fetch(tag, commit, ["win32-x64"], downloaded, ["apt/*"])
+ assert (downloaded / nested.relative_to(root)).read_bytes() == nested.read_bytes()
+
+ with pytest.raises(ValueError, match="identity"):
+ handoff.fetch(tag, "b" * 40, ["win32-x64"], tmp_path / "wrong")
+
+ for bad_path in ("../outside", "C:/outside", "dir\\outside", "a//b", "./a", "a%2fb", "a:b", "a?b", "a#b"):
+ bad = copy.deepcopy(receipt)
+ bad["files"][0]["path"] = bad_path
+ r2_server.store[receipt_key] = (json.dumps(bad).encode(), '"e"')
+ r2_server.requests.clear()
+ with pytest.raises(ValueError, match="path"):
+ handoff.fetch(tag, commit, ["win32-x64"], tmp_path / "unsafe")
+ assert len(r2_server.requests) == 1
+ r2_server.store[receipt_key] = (json.dumps(receipt).encode(), '"e"')
+ r2_server.store[f"releases/tag/{tag}/app.msix"] = (b"different bytes", '"e"')
+ with pytest.raises(ValueError, match="checksum mismatch"):
+ handoff.fetch(tag, commit, ["win32-x64"], downloaded)
+ assert (downloaded / "app.msix").read_bytes() == data
+
+
+def test_failed_stage_never_publishes_a_receipt_or_channel(tmp_path, monkeypatch, r2_server):
+ from scripts.releases import handoff
+
+ tag, commit = "v1.2.3", "a" * 40
+ (tmp_path / "one.msix").write_bytes(b"first")
+ (tmp_path / "two.msix").write_bytes(b"second")
+ real_put = r2.put
+
+ def fail_second(**kwargs):
+ if kwargs["key"] == "two.msix":
+ raise RuntimeError("upload interrupted")
+ real_put(**kwargs)
+
+ monkeypatch.setattr(r2, "put", fail_second)
+ with pytest.raises(RuntimeError, match="interrupted"):
+ handoff.stage(tag, commit, "win32-x64", tmp_path, ["*.msix"])
+ assert set(r2_server.store) == {f"releases/tag/{tag}/one.msix"}
+ r2_server.requests.clear()
+ with pytest.raises(ValueError, match="No files"):
+ handoff.stage(tag, commit, "win32-x64", tmp_path, ["*.zip"])
+ assert r2_server.requests == []
+ with pytest.raises(ValueError, match="identity"):
+ handoff.stage("../bad", commit, "win32-x64", tmp_path, ["*.msix"])
+ assert r2_server.requests == []
diff --git a/tests/scripts/test_release_r2.py b/tests/scripts/test_release_r2.py
index cdda83bbe8a..9f9b0c1163b 100644
--- a/tests/scripts/test_release_r2.py
+++ b/tests/scripts/test_release_r2.py
@@ -673,6 +673,64 @@ def test_verify_remote_artifact_streams_without_buffering(r2_server):
)
+def test_download_streams_verified_bytes_and_preserves_destination_on_failure(r2_server, tmp_path, monkeypatch):
+ import hashlib
+ import http.client
+
+ payload = os.urandom(3 * 1024 * 1024 + 7)
+ key = "releases/tag/v1.2.3/package.msix"
+ r2_server.store[key] = (payload, '"e"')
+ target = tmp_path / "downloads" / "package.msix"
+ target.parent.mkdir()
+ target.write_bytes(b"previous complete file")
+ real_read = http.client.HTTPResponse.read
+ reads = []
+
+ def bounded_read(response, amount=None):
+ assert amount is not None and amount <= 1024 * 1024
+ reads.append(amount)
+ return real_read(response, amount)
+
+ monkeypatch.setattr(http.client.HTTPResponse, "read", bounded_read)
+ args = dict(creds={"access_key_id": AKID, "secret_key": SECRET},
+ base=f"http://127.0.0.1:{r2_server.server_port}", bucket="hermes-releases",
+ key=key, file=target, now=NOW, expected_size=len(payload),
+ expected_sha256=hashlib.sha256(payload).hexdigest())
+ r2.download_object(**args)
+ assert target.read_bytes() == payload
+ assert len(reads) > 1
+ assert all("authorization" in headers for _, _, headers in r2_server.requests)
+
+ original_get = _R2StubHandler.do_GET
+ request_times = []
+ refreshed = "20150830T125600Z"
+
+ def transient_get(handler):
+ request_times.append(handler.headers['x-amz-date'])
+ if len(request_times) == 1:
+ handler._send(503, b"retry")
+ else:
+ original_get(handler)
+
+ monkeypatch.setattr(_R2StubHandler, 'do_GET', transient_get)
+ monkeypatch.setattr(r2, 'amz_timestamp', lambda: refreshed)
+ monkeypatch.setattr(r2.time, 'sleep', lambda _: None)
+ r2.download_object(**args)
+ assert request_times == [NOW, refreshed]
+ monkeypatch.setattr(_R2StubHandler, 'do_GET', original_get)
+
+ r2_server.store[key] = (b"corrupt replacement", '"e"')
+ with pytest.raises(ValueError, match="checksum mismatch"):
+ r2.download_object(**args)
+ assert target.read_bytes() == payload
+ assert list(target.parent.iterdir()) == [target]
+ del r2_server.store[key]
+ with pytest.raises(r2.R2RequestError):
+ r2.download_object(**args)
+ assert target.read_bytes() == payload
+ assert list(target.parent.iterdir()) == [target]
+
+
def test_put_accepts_pathlib_paths(r2_server):
import pathlib
import tempfile