Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Build once by build-input key: reuse any green main/staging Packages run of the same inputs
islandmed8f5b44b21c1a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 81033837..9139ac49 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -342,6 +342,7 @@ jobs:run: python -m pip install "bpy==${{ matrix.bpy }}" numpy- name: Build sculptforge-clirun: |+ ccache -z # (ccache -s below: this run's hits, not the restored cache's lifetime)cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DSCULPTFORGE_USE_SYSTEM_SDL=OFF -DSCULPTFORGE_BUILD_APP=OFF \-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccachecmake --build build --target sculptforge-cli --parallel 4diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.ymlindex d929d26d..7e206204 100644--- a/.github/workflows/packages.yml+++ b/.github/workflows/packages.yml@@ -1,13 +1,19 @@name: Packages# The release packages (.deb, AppImage, .tar.gz, Flatpak, .rpm and VFX Reference Platform tarballs, .dmg, Windows-# installer and .zip), each built and tested exactly as a release ships them. It runs on every push to staging and main-# that changes the app, so a tagged release promotes the staging run's packages of the commit it tags instead of-# building them again (.github/workflows/release.yml); release.yml also calls it to build from the tag (--rebuild).+# installer and .zip), each built and tested exactly as a release ships them. It runs on every push to staging and main,+# so a tagged release promotes those packages instead of building them again (.github/workflows/release.yml);+# release.yml also calls it to build from the tag (--rebuild).+#+# Build once: job reuse computes the push's build-input key (tools/release/build_key.py: a hash of every file that goes+# into the packages, tools/release/build_inputs.txt) and, when an earlier green run of THIS workflow on a maintainer's+# push to main or staging built the same key (tools/release/staged_run.py, the same rule the release uses), skips every+# build and says which run it reuses. A website or release-paperwork change never builds again; there is no `paths:`+# filter (it skipped staging's push of 0.11.14 and the release rebuilt from the tag).## Integrity: the release promotes only artifacts of a successful run of THIS workflow triggered by a maintainer's push-# to `staging` (scripts/merge-queue.sh staging) for exactly the tagged commit (tools/release/staged_run.py, in-# release.yml and scripts/release.sh); main's push then reuses the staging run (job reuse). Every package gets a GitHub+# to `staging` or `main` for the tagged commit or one with the same key (tools/release/staged_run.py, in release.yml and+# scripts/release.sh; release.yml recomputes both keys from git). Every package gets a GitHub# artifact attestation (job permissions id-token/attestations: write, nothing else) and job sums records their SHA-256;# release.yml checks both before publishing (tools/release/verify_staged.py). Artifacts are kept 14 days.# Compiler caches are restored here but saved only by branch runs (pushes to main or staging, maintainers' own@@ -19,16 +25,7 @@ name: Packageson:push:branches: [main, staging] # staging: the merge queue's batch, the release's packages (built once, promoted unchanged)- paths: # everything but the website (its phone page, website/link, is built into the app) and release paperwork- - '**'- - '!website/**'- - website/link/**- - '!.github/workflows/pages.yml'- - '!.github/workflows/download-stats.yml'- - '!packaging/arch/**'- - '!tools/publish/**'- - '!scripts/release.sh'- - '!docs/releasing.md'+ # No paths: job reuse skips the builds when nothing that goes into the packages changed (tools/release/build_inputs.txt).workflow_dispatch:workflow_call:inputs:@@ -46,7 +43,10 @@ permissions:concurrency:group: packages-${{ inputs.ref || github.ref }}- cancel-in-progress: true # a newer push to main supersedes; a tag of the older commit then builds its own+ # main never cancels a build in progress: with no paths: filter every push runs, and a website push (the queue page+ # merges often) would cancel the build of the app change before it; the newer run waits, then reuses that build.+ # (Waiting runs still replace each other: the newest push is the one checked.) A newer staging batch supersedes.+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}env:REF: ${{ inputs.ref || github.sha }}@@ -62,11 +62,12 @@ env:jobs:reuse:- # A batch that went through `staging` (scripts/merge-queue.sh staging) ran this workflow there on the push, for the- # same commit; main's push then reuses that run instead of building it all again, and the release promotes the- # staging run's packages (release.yml, job locate). In progress: wait for it. Failed, cancelled or none: build.- name: Reuse the staging run- if: github.event_name == 'push' && github.ref == 'refs/heads/main'+ # The packages of an earlier green run on a maintainer's push to main or staging whose build inputs are byte for+ # byte this commit's (tools/release/staged_run.py: the same SHA, or the same tools/release/build_key.py key): reused,+ # not rebuilt, and the release promotes that run. Only runs older than this one count, so two runs never wait for+ # each other; one in progress is waited for. Failed, cancelled, expired or none: build. Dispatches and tags build.+ name: Reuse an earlier build of the same inputs+ if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/staging')runs-on: ubuntu-24.04timeout-minutes: 50permissions:@@ -75,23 +76,27 @@ jobs:outputs:run-id: ${{ steps.find.outputs.run-id }}steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ # trees only (the key hashes git objects, never file contents): earlier runs' commits are fetched the same way+ with: { persist-credentials: false, filter: 'blob:none', sparse-checkout: tools/release }- id: findenv:GH_TOKEN: ${{ github.token }}REPO: ${{ github.repository }}SHA: ${{ github.sha }}+ RUN: ${{ github.run_id }}run: |- id=$(gh api "repos/$REPO/actions/workflows/packages.yml/runs?head_sha=$SHA&event=push&branch=staging&per_page=5" \- --jq '[.workflow_runs[] | select(.head_sha == "'"$SHA"'" and .head_branch == "staging"- and .path == ".github/workflows/packages.yml" and .head_repository.full_name == "'"$REPO"'")][0].id // empty')- [ -n "$id" ] || { echo "No Packages run on staging for $SHA: building here"; exit 0; }- while [ "$(gh api "repos/$REPO/actions/runs/$id" --jq .status)" != completed ]; do sleep 30; done- conclusion=$(gh api "repos/$REPO/actions/runs/$id" --jq .conclusion)- if [ "$conclusion" = success ]; then- echo "::notice::$SHA's packages were built and tested on staging (run $id, https://github.com/$REPO/actions/runs/$id): reused, not rebuilt"+ key=$(python3 tools/release/build_key.py "$SHA" | cut -d' ' -f1)+ echo "Build-input key of $SHA: \`$key\`" >> "$GITHUB_STEP_SUMMARY"+ rc=0+ found=$(python3 tools/release/staged_run.py --repo "$REPO" --sha "$SHA" --before-run "$RUN" --wait --wait-minutes 45 --full) || rc=$?+ if [ $rc = 0 ]; then+ read -r id built ref <<<"$found"+ echo "::notice::reuses run $id ($ref, $built): the same build inputs, built and tested there (https://github.com/$REPO/actions/runs/$id)"+ echo "Reuses run [$id](https://github.com/$REPO/actions/runs/$id) ($ref, $built): nothing rebuilt." >> "$GITHUB_STEP_SUMMARY"echo "run-id=$id" >> "$GITHUB_OUTPUT"else- echo "Packages run $id on staging: $conclusion: building here"+ echo "No earlier green build of these inputs (exit $rc, above): building here" | tee -a "$GITHUB_STEP_SUMMARY"filinux:@@ -133,6 +138,7 @@ jobs:restore-keys: ccache-pkg-linux-${{ matrix.arch }}.- name: Buildrun: |+ ccache -z # (ccache -s below: this run's hits, not the restored cache's lifetime)cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DSCULPTFORGE_USE_SYSTEM_SDL=OFF \-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DSCULPTFORGE_MOLD=OFFcmake --build build --parallel 4@@ -248,9 +254,9 @@ jobs:matrix:include:# CY2026: EL8 / glibc 2.28 also gives the .rpm for RHEL 8, 9, 10 and Fedora.- - { label: 'RPM + VFX CY2026', suffix: vfx2026, cy: CY2026, generators: 'RPM;TGZ', image: 'rockylinux:8', arch: x86_64, ccarch: x86_64, os: "${{ vars.SF_RUNNER_LINUX || 'ubuntu-24.04' }}" }+ - { label: 'RPM + VFX CY2026', suffix: vfx2026, cy: CY2026, generators: 'RPM;TGZ', image: 'rockylinux:8', arch: x86_64, ccarch: x86_64, ci: 'ccache-ci-CY2026.', os: "${{ vars.SF_RUNNER_LINUX || 'ubuntu-24.04' }}" }- { label: 'RPM + VFX CY2026', suffix: vfx2026, cy: CY2026, generators: 'RPM;TGZ', image: 'rockylinux:8', arch: arm64, ccarch: aarch64, os: "${{ vars.SF_RUNNER_LINUX_ARM || 'ubuntu-24.04-arm' }}" }- - { label: 'VFX CY2027', suffix: vfx2027, cy: CY2027, generators: 'TGZ', image: 'rockylinux:9', arch: x86_64, ccarch: x86_64, os: "${{ vars.SF_RUNNER_LINUX || 'ubuntu-24.04' }}" }+ - { label: 'VFX CY2027', suffix: vfx2027, cy: CY2027, generators: 'TGZ', image: 'rockylinux:9', arch: x86_64, ccarch: x86_64, ci: 'ccache-ci-CY2027.', os: "${{ vars.SF_RUNNER_LINUX || 'ubuntu-24.04' }}" }- { label: 'VFX CY2027', suffix: vfx2027, cy: CY2027, generators: 'TGZ', image: 'rockylinux:9', arch: arm64, ccarch: aarch64, os: "${{ vars.SF_RUNNER_LINUX_ARM || 'ubuntu-24.04-arm' }}" }steps:- run: dnf -y install git tar gzip zstd@@ -281,10 +287,10 @@ jobs:with:path: .ccachekey: ccache-pkg-${{ matrix.suffix }}-${{ matrix.arch }}.${{ github.sha }}- # CI's job for the same image and compiler (x86_64) shares most object files.+ # CI's job for the same image and compiler (x86_64 only: CI builds no arm64 VFX image) shares most object files.restore-keys: |ccache-pkg-${{ matrix.suffix }}-${{ matrix.arch }}.- ccache-ci-${{ matrix.cy }}.+ ${{ matrix.ci }}- name: Python 3.13 (python-build-standalone, pinned by hash)run: |case $(uname -m) in@@ -299,6 +305,7 @@ jobs:- name: Build with GCC 14run: |source /opt/rh/gcc-toolset-14/enable+ ccache -zcmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DSCULPTFORGE_USE_SYSTEM_SDL=OFF \-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DSCULPTFORGE_MOLD=OFF \-DSCULPTFORGE_BUILD_PYTHON=ON -DPython_EXECUTABLE="$PYTHON313" -DSCULPTFORGE_PYTHON_INSTALL_DIR=lib/sculptforge/python@@ -361,6 +368,7 @@ jobs:restore-keys: ccache-pkg-macos.- name: Buildrun: |+ ccache -zcmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DSCULPTFORGE_USE_SYSTEM_SDL=OFF \-DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0 \-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache@@ -443,6 +451,7 @@ jobs:ccache-ci-windows.- name: Build (Visual Studio generator; ccache as cl.exe, one compiler per file)run: |+ ccache -zcmake -S . -B build -DSCULPTFORGE_USE_SYSTEM_SDL=OFF `-DCMAKE_VS_GLOBALS="CLToolExe=cl.exe;CLToolPath=${{ env.SF_CCACHE_CL }};TrackFileAccess=false;UseMultiToolTask=true;EnforceProcessCountAcrossBuilds=true"cmake --build build --config Release --parallel 4@@ -479,7 +488,7 @@ jobs:sums:name: Record checksumsneeds: [linux, flatpak, vfx, macos, windows]- # Explicit: job reuse is skipped outside a push to main, and a skipped ancestor would skip this job too.+ # Explicit: job reuse is skipped outside a push to main or staging, and a skipped ancestor would skip this job too.if: ${{ !cancelled() && needs.linux.result == 'success' && needs.flatpak.result == 'success' && needs.vfx.result == 'success' && needs.macos.result == 'success' && needs.windows.result == 'success' }}runs-on: ubuntu-24.04steps:diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex e7b3e5e8..3b80eae6 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -4,14 +4,15 @@ name: Release## locate the tagged commit must carry the version the tag names (CMakeLists.txt's version, plus its# SCULPTFORGE_PRERELEASE for a beta: v0.11.0-beta.1 tags 0.11.0 with "beta.1"). When the Packages workflow-# (packages.yml) ran on a maintainer's push to `staging` for exactly this commit (scripts/release.sh --stage),-# the release promotes that run's packages unchanged: built and tested once. tools/release/staged_run.py-# picks it (push event, branch, actor, success, at most 7 days old, artifacts present) and refuses the-# release if no such run qualifies; CI must have passed on main for the commit. With no staging run at all:+# (packages.yml) ran on a maintainer's push to `staging` or `main` for this commit, or for one with the same+# build-input key (tools/release/build_key.py: every file that goes into the packages identical), the release+# promotes that run's packages unchanged: built and tested once. tools/release/staged_run.py picks it (push+# event, branch, actor, success, at most 7 days old, artifacts present, the key recomputed from git) and+# refuses the release if no such run qualifies; CI must have passed on main for the commit. With none at all:# build the Packages workflow runs here, from the tag (compiler cache restored from main, never saved): the# --rebuild path.# verify every package's SHA-256 is the one its run recorded (packages.yml job sums) and its GitHub artifact-# attestation names packages.yml, this commit and that run (and, promoted, a push to staging):+# attestation names packages.yml, the commit that run built and that run (and, promoted, its push):# tools/release/verify_staged.py. Any mismatch refuses the release.# smoke every package installed or unpacked on a fresh runner: the app opens a model and sculpts# (tests/ui/release_smoke.sfui), sculptforge-cli opens, sculpts, saves and reopens and its MCP server answers@@ -64,6 +65,8 @@ jobs:outputs:run-id: ${{ steps.find.outputs.run-id }}sha: ${{ steps.find.outputs.sha }}+ built-sha: ${{ steps.find.outputs.built-sha }}+ built-ref: ${{ steps.find.outputs.built-ref }}tag: ${{ steps.find.outputs.tag }}staged: ${{ steps.find.outputs.staged }}steps:@@ -106,17 +109,24 @@ jobs:--jq '.workflow_runs[] | select(.head_sha == "'"$sha"'" and .head_branch == "main" and .event == "push"and .path == ".github/workflows/'"$1"'" and .head_repository.full_name == "'"$REPO"'") | .id' | head -1}- # The packages: only the Packages run of a maintainer's push to `staging` for exactly this commit (exit 3:- # there is none, build here; exit 1: there are runs, none may be promoted: refuse).+ # The packages: only the Packages run of a maintainer's push to `staging` or `main` for this commit or one with+ # the same build-input key (exit 3: there is none, build here; exit 1: there are runs, none may be promoted: refuse).rc=0- pkg=$(python3 tools/release/staged_run.py --repo "$REPO" --sha "$sha") || rc=$?+ found=$(python3 tools/release/staged_run.py --repo "$REPO" --sha "$sha" --full) || rc=$?if [ $rc = 3 ]; then- echo "No Packages run on staging for $sha: building the packages here (the --rebuild path)"+ echo "No Packages run on staging or main for $sha or its build inputs: building the packages here (the --rebuild path)"exit 0elif [ $rc != 0 ]; then- echo "::error::$sha has Packages runs on staging but none may be promoted (above). Fix: stage the release again (scripts/release.sh X.Y.Z --stage), or delete the tag and use scripts/release.sh X.Y.Z --rebuild."+ echo "::error::$sha has Packages runs but none may be promoted (above). Fix: stage the release again (scripts/release.sh X.Y.Z --stage), or delete the tag and use scripts/release.sh X.Y.Z --rebuild."exit 1fi+ read -r pkg built ref <<<"$found"+ case "$ref" in main|staging) ;; *) echo "::error::run $pkg is from '$ref', not main or staging"; exit 1 ;; esac+ if [ "$built" != "$sha" ]; then # (staged_run.py checked it; checked again here, from git, where it is logged)+ keys=$(python3 tools/release/build_key.py "$sha" "$built" | cut -d' ' -f1 | sort -u | wc -l)+ [ "$keys" = 1 ] || { echo "::error::run $pkg built $built, whose build inputs differ from $sha's"; exit 1; }+ echo "Run $pkg built $built ($ref), whose build inputs are byte for byte $sha's: $(python3 tools/release/build_key.py "$sha")"+ fici=$(runs ci.yml || true)if [ -z "$ci" ]; then# The bump commit adds only release paperwork (tools/release/paperwork_only.py: version lines, CHANGELOG,@@ -128,8 +138,10 @@ jobs:donefi[ -n "$ci" ] || { echo "::error::no successful CI run on main for $sha: a staged commit lands on main only after CI passed"; exit 1; }- echo "Promoting the packages of staging's Packages run $pkg (CI run $ci passed for $sha)"+ echo "Promoting the packages of $ref's Packages run $pkg (CI run $ci passed for $sha)"echo "run-id=$pkg" >> "$GITHUB_OUTPUT"+ echo "built-sha=$built" >> "$GITHUB_OUTPUT"+ echo "built-ref=refs/heads/$ref" >> "$GITHUB_OUTPUT"echo "staged=true" >> "$GITHUB_OUTPUT"build:@@ -176,9 +188,10 @@ jobs:- env:GH_TOKEN: ${{ github.token }}RUN: ${{ needs.locate.outputs.run-id || github.run_id }}- SHA: ${{ needs.locate.outputs.sha }}+ SHA: ${{ needs.locate.outputs.built-sha || needs.locate.outputs.sha }}STAGED: ${{ needs.locate.outputs.staged }}- run: python3 tools/release/verify_staged.py dist sums/SHA256SUMS.staged.txt --repo "$GITHUB_REPOSITORY" --run "$RUN" --sha "$SHA" ${STAGED:+--staged}+ REF: ${{ needs.locate.outputs.built-ref }}+ run: python3 tools/release/verify_staged.py dist sums/SHA256SUMS.staged.txt --repo "$GITHUB_REPOSITORY" --run "$RUN" --sha "$SHA" ${STAGED:+--staged --ref "$REF"}smoke:name: Smoke test ${{ matrix.name }}diff --git a/changes/ci-build-once.md b/changes/ci-build-once.mdnew file mode 100644index 00000000..0b94ff21--- /dev/null+++ b/changes/ci-build-once.md@@ -0,0 +1,14 @@+---+changed: Release packages are built once per set of build inputs: a commit whose packaged files are byte for byte an+ earlier green build's (a website or release-paperwork change) reuses that build's packages, verified and attested as+ before, instead of building them again (docs/releasing.md, "Build once, promote").+---+For reviewers (ci/build-once):+- tools/release/build_key.py + build_inputs.txt: the build-input key (git ls-tree -r over the inputs, SHA-256).+- tools/release/staged_run.py: a run for the exact SHA or the same key, main or staging pushes, every old check kept;+ --before-run (no mutual waits), --full (id, built SHA, branch). Self-test: key match/mismatch, fork, dispatch by+ another actor, expired artifacts, reuse runs skipped for their builder, the 0.11.14 case.+- packages.yml: no `paths:` (check_workflows.py forbids it), job reuse keyed, main no longer cancels a build in progress+ (a website push would have); `ccache -z` per build, VFX arm64 no longer+ restores CI's x86_64 cache. ci.yml: Blender job `ccache -z` (its 29-43% "hits" were lifetime counters).+- release.yml: locate passes the built SHA/branch on, re-checks both keys from git; verify attests against them.diff --git a/docs/releasing.md b/docs/releasing.mdindex 6ba8ef98..455d81c5 100644--- a/docs/releasing.md+++ b/docs/releasing.md@@ -42,7 +42,7 @@ the gates, what each step does, and how to recover.commit. For the bump commit, step `ci` and release.yml reuse the CI result of the commit before it when the bumponly added release paperwork (`tools/release/paperwork_only.py`: exact files and lines, fails safe). Step `check` hasalready run the bump's own tests (What's New, the guide, notes) on the bumped tree. Packages still has to pass for the- bump commit itself:+ bump commit itself, or for one with the same build inputs (below):- **CI** (ci.yml) runs every test on Linux x86_64 and ARM64, macOS, Windows, the VFX platforms and Blender.- **Packages** (packages.yml) builds every release package the way it ships, with its tests.4. **Packaged-artifact smoke tests** (release.yml `smoke`): every package is installed or unpacked on a fresh runner.@@ -68,10 +68,22 @@ packages and T1 go ahead, and only main's fast-forward waits for the lock (`SF_PIf the promote pushed release paperwork to main meanwhile (site, feed, What's New: `tools/release/paperwork_only.py`),the batch lands as a merge on top of it; anything else on main stops as before. A dead holder's lock doesn't count.-What makes a run promotable (tools/release/staged_run.py, used by release.sh steps ci and tag and by release.yml-`locate`; refused otherwise, nothing is rebuilt silently):-- packages.yml of this repository, triggered by a **push** to `staging` for exactly the tagged commit: never a- pull_request, a workflow_dispatch or a fork's run;+**Build inputs, built once.** A commit's build-input key (tools/release/build_key.py) is a SHA-256 of `git ls-tree -r`+over the files that go into the packages: every file except those tools/release/build_inputs.txt lists (the website but+website/link/ and website/founding.json, release paperwork). Version files are inputs. Same key = every input file byte+for byte the same, so the packages are the same build. packages.yml runs on every push to main and staging (no+`paths:` filter: one skipped 0.11.14's staging push and the release rebuilt from the tag for a queue.html edit); its+job `reuse` looks for an earlier green run with the same key (staged_run.py --before-run: only older runs, so two never+wait for each other; one in progress is waited for) and then skips every build ("reuses run N" in the summary). The+binaries carry the commit they were built from (proof mode's `SF_GIT_COMMIT`), which for a reused run is that run's+commit: same inputs, another SHA.++What makes a run promotable (tools/release/staged_run.py, used by release.sh steps ci and tag, release.yml+`locate` and packages.yml `reuse`; refused otherwise, nothing is rebuilt silently):+- packages.yml of this repository, triggered by a **push** to `staging` or `main` for the tagged commit, or for a+ commit with the same build-input key, computed from git there (never read from the run; release.yml `locate`+ checks it again and logs both): never a pull_request, a workflow_dispatch or a fork's run. The exact commit wins,+ then the newest;- pushed and (re)run by islandmed (`actor` and `triggering_actor`);- concluded `success`, at most 7 days old (`SF_STAGED_MAX_DAYS`; artifacts are kept 14), every package artifact and`staged-sums` still there;@@ -79,8 +91,8 @@ What makes a run promotable (tools/release/staged_run.py, used by release.sh steBefore anything is published (release.yml `verify`, tools/release/verify_staged.py): the downloaded files are exactlythose packages.yml's job `sums` recorded, each with the recorded SHA-256, and each has a GitHub artifact attestation-(actions/attest-build-provenance in every build job) that `gh attestation verify` accepts for packages.yml, this-commit, that run and, promoted, `refs/heads/staging` and a push. `publish` re-checks the checksums of the files it+(actions/attest-build-provenance in every build job) that `gh attestation verify` accepts for packages.yml, the+commit that run built, that run and, promoted, its branch (`refs/heads/staging` or `refs/heads/main`) and a push. `publish` re-checks the checksums of the files ituploads. Any mismatch stops the release.Signing happens only at promotion: `UPDATE_SIGNING_KEY` is a secret of the environments `release` (job `publish`,@@ -92,7 +104,7 @@ that run's Actions artifacts (14 days). In this public repository signed-in GitHartifacts, as they always could for main's Packages runs; the attestations (public, in Sigstore's log) carry onlychecksums and the commit.-**--rebuild** (fallback): bump pushed to main, no staging run for that commit, so release.yml builds the packages from+**--rebuild** (fallback): bump pushed to main, no main or staging run for that commit's build inputs, so release.yml builds the packages fromthe tag (about 40 minutes), attests and verifies them the same way, then smoke-tests and publishes.Compiler caches: release builds restore main's caches, and nothing run from a tag or a pull request ever saves one.diff --git a/scripts/release.sh b/scripts/release.shindex c67aaa12..666f69e8 100755--- a/scripts/release.sh+++ b/scripts/release.sh@@ -244,9 +244,10 @@ bumped() {grep -q "^project(SculptForge VERSION ${BASE//./\\.}[ )]" CMakeLists.txt && prerelease_is "$PRE" &&{ [ -n "$PRE" ] || grep -q "^## \[${V//./\\.}\]" CHANGELOG.md; }}-# staged_run SHA [--wait]: the id of staging's Packages run that this release may promote (tools/release/staged_run.py:-# a push to staging by islandmed for exactly SHA, successful, at most SF_STAGED_MAX_DAYS (7) days old, artifacts-# present). Its exit status: 0 found, 3 there is no staging run for SHA, 1 none may be promoted (why in $work/staged.err).+# staged_run SHA [--wait]: the id of the Packages run that this release may promote (tools/release/staged_run.py:+# a push to staging or main by islandmed for SHA or a commit with the same build-input key (tools/release/build_key.py),+# successful, at most SF_STAGED_MAX_DAYS (7) days old, artifacts present). Its exit status: 0 found, 3 there is no+# such run, 1 none may be promoted (why in $work/staged.err).staged_run() {python3 tools/release/staged_run.py --repo "$REPO" --sha "$1" --actors "$AUTHOR_NAME" --max-days "${SF_STAGED_MAX_DAYS:-7}" \${2:+"$2"} 2>"$work/staged.err"@@ -600,12 +601,13 @@ step_ci() {returnfilocal run rc=0- echo " staging's Packages run for ${sha:0:8} (waits while it runs) ..."+ echo " the Packages run that built ${sha:0:8}'s build inputs (waits while it runs) ..."run=$(staged_run "$sha" --wait) || rc=$?case $rc in- 0) ok "staging's Packages run $run built and tested $V for ${sha:0:8}: the release promotes exactly its packages" ;;- 3) die "no Packages run on staging for ${sha:0:8}" "$(stage_fix)" ;;- *) die "staging's Packages runs for ${sha:0:8} can't be promoted: $(tail -1 "$work/staged.err")" \+ 0) ok "Packages run $run built and tested $V for ${sha:0:8}: the release promotes exactly its packages"+ sed 's/^ *//' "$work/staged.err" | grep '^run .* built ' | sed 's/^/ /' || true ;;+ 3) die "no Packages run on staging or main for ${sha:0:8} or its build inputs" "$(stage_fix)" ;;+ *) die "the Packages runs for ${sha:0:8} can't be promoted: $(tail -1 "$work/staged.err")" \"a failed run that was a runner hiccup: gh run rerun <id> --failed -R $REPO, then $(resume ci); otherwise $(stage_fix)" ;;esac}@@ -617,7 +619,7 @@ step_tag() {if [ $MODE = promote ]; then # the tag goes on exactly the staged commit, which main isgit fetch -q origin main[ "$sha" = "$(git rev-parse origin/main)" ] || die "HEAD ${sha:0:8} is not origin/main $(git rev-parse --short origin/main)" "git switch main && git merge --ff-only origin/main; if main moved past the staged commit, stage again: $(stage_fix)"- staged_run "$sha" >/dev/null || die "${sha:0:8} has no promotable staging Packages run: $(tail -1 "$work/staged.err")" "$(stage_fix)"+ staged_run "$sha" >/dev/null || die "${sha:0:8} has no promotable Packages run: $(tail -1 "$work/staged.err")" "$(stage_fix)"ficonfirm "Tag $T at $(git log -1 --format='%h %s' "$sha") and push it? This publishes SculptForge $V${PRE:+ for members, in $INSIDERS_REPO}." ||die "not confirmed" "run again and answer y (or YES=1) once the owner has said ship it for $V"diff --git a/tests/release_beta_test.sh b/tests/release_beta_test.shindex 63cd8751..405b25af 100755--- a/tests/release_beta_test.sh+++ b/tests/release_beta_test.sh@@ -62,8 +62,10 @@ touch "$S/build/CTestTestfile.cmake"cat > "$S/bin/gh" <<EOF#!/usr/bin/env bash# staging's Packages run for the asked commit (tools/release/staged_run.py): STAGED_EVENT, STAGED_ACTOR vary it.+# Listings by branch (runs of other commits with the same build-input key) are empty here.runs() {sha=\$(sed -n 's/.*head_sha=\([0-9a-f]*\).*/\1/p' <<<"\$1")+ [ -n "\$sha" ] || { echo '{"workflow_runs": []}'; return; } # (the branch listings: no other commit's run)printf '{"workflow_runs": [{"id": 77, "path": ".github/workflows/packages.yml", "head_sha": "%s", "head_branch": "staging","event": "%s", "status": "completed", "conclusion": "success", "created_at": "%s","head_repository": {"full_name": "islandmed/SculptForge"}, "repository": {"full_name": "islandmed/SculptForge"},diff --git a/tools/release/build_inputs.txt b/tools/release/build_inputs.txtnew file mode 100644index 00000000..b0c92a28--- /dev/null+++ b/tools/release/build_inputs.txt@@ -0,0 +1,17 @@+# Build inputs: the files that go into the release packages (tools/release/build_key.py, docs/releasing.md "Build once").+# Every file of a commit is a build input unless a line below matches its path (extended regexes, one per line, '#' lines+# ignored); a line starting with '!' makes a matching path an input again (the last matching line decides). Two commits+# whose inputs are byte for byte the same build the same packages, so packages.yml and tools/release/staged_run.py reuse+# one green run for both. When in doubt, leave a file an input: a needless build costs minutes, a missed input ships+# a package that wasn't built from what it claims. Version files (CMakeLists.txt and the rest) are inputs: the version+# is baked in.+# The website and the release's own paperwork (built from main, never compiled into the app):+^website/+^\.github/workflows/(pages|download-stats)\.yml$+^packaging/arch/+^tools/publish/+^scripts/release\.sh$+^docs/releasing\.md$+# ...except what the app compiles in (CMakeLists.txt: the phone page, Help > About's Founding Members; tools/ci/site_lane.txt):+!^website/link/+!^website/founding\.json$diff --git a/tools/release/build_key.py b/tools/release/build_key.pynew file mode 100644index 00000000..41011645--- /dev/null+++ b/tools/release/build_key.py@@ -0,0 +1,140 @@+#!/usr/bin/env python3+# SculptForge - open source digital sculpting+# SPDX-License-Identifier: GPL-3.0-or-later+"""The build-input key of a commit: one SHA-256 of exactly what goes into its release packages (docs/releasing.md,+"Build once, promote").++ build_key.py [SHA ...] prints "KEY SHA" per commit (default HEAD); exit 1 if a commit isn't in the repository+ build_key.py --self-test++The key hashes `git ls-tree -r` of the commit restricted to the build inputs (tools/release/build_inputs.txt): each+input file's mode, object id and path, so two commits get the same key exactly when every input file is byte for+byte the same (and none was added, removed or renamed). It reads git objects only, never the working tree.+packages.yml (job reuse) and tools/release/staged_run.py use it to promote one green Packages run for every commit+with the same key: a change to the website or the release paperwork never builds the packages again.+"""+import hashlib+import os+import re+import subprocess+import sys++RULES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "build_inputs.txt")+SCHEMA = b"sculptforge build inputs v1\n"+++def load_rules(path=RULES):+ """[(is_input, regex)] in file order; a missing or empty file means every file is an input (fail safe)."""+ with open(path, encoding="utf-8") as f:+ lines = [l.strip() for l in f if l.strip() and not l.lstrip().startswith("#")]+ return [(l.startswith("!"), re.compile(l[1:] if l.startswith("!") else l)) for l in lines]+++def is_input(path, rules):+ keep = True+ for again, rx in rules:+ if rx.search(path):+ keep = again+ return keep+++def key_of_tree(entries, rules):+ """entries: [(mode, type, object id, path)] as git ls-tree -r lists them (sorted by path)."""+ h = hashlib.sha256(SCHEMA)+ for mode, kind, oid, path in entries:+ if is_input(path, rules):+ h.update(f"{mode} {kind} {oid}\t{path}\0".encode())+ return h.hexdigest()+++def ls_tree(sha, cwd=None):+ """The commit's files, or None when the commit isn't here."""+ p = subprocess.run(["git", "ls-tree", "-r", "-z", "--full-tree", f"{sha}^{{commit}}"], cwd=cwd, capture_output=True)+ if p.returncode != 0:+ return None+ out = []+ for rec in p.stdout.decode("utf-8", "surrogateescape").split("\0"):+ if rec:+ meta, path = rec.split("\t", 1)+ mode, kind, oid = meta.split(" ")+ out.append((mode, kind, oid, path))+ return out+++def key(sha, rules=None, cwd=None):+ entries = ls_tree(sha, cwd)+ return None if entries is None else key_of_tree(entries, rules if rules is not None else load_rules())+++def self_test():+ import tempfile+ bad = []+ rules = load_rules()+ expect = {"src/app/Main.cpp": True, "CMakeLists.txt": True, "website/queue.html": False, "website/link/index.html": True,+ "website/founding.json": True, "website/founding.json.bak": False, "packaging/arch/PKGBUILD": False,+ "packaging/flatpak/x.yml": True, "scripts/release.sh": False, "scripts/merge-queue.sh": True,+ ".github/workflows/packages.yml": True, ".github/workflows/pages.yml": False, "docs/releasing.md": False,+ "docs/guide/index.md": True, "docs/supporters.txt": True, "tools/release/build_inputs.txt": True}+ bad += [f"is_input {p}: want {w}" for p, w in expect.items() if is_input(p, rules) != w]+ base = [("100644", "blob", "a" * 40, "CMakeLists.txt"), ("100644", "blob", "b" * 40, "website/queue.html")]+ k = key_of_tree(base, rules)+ variants = {+ "site edit": ([base[0], ("100644", "blob", "c" * 40, "website/queue.html")], True),+ "site file added": (base + [("100644", "blob", "c" * 40, "website/x.html")], True),+ "input edit": ([("100644", "blob", "c" * 40, "CMakeLists.txt"), base[1]], False),+ "input mode": ([("100755", "blob", "a" * 40, "CMakeLists.txt"), base[1]], False),+ "input added": (base + [("100644", "blob", "c" * 40, "src/x.cpp")], False),+ "input removed": (base[1:], False),+ "input renamed": ([("100644", "blob", "a" * 40, "CMakeList.txt"), base[1]], False),+ "app input in site": (base + [("100644", "blob", "c" * 40, "website/founding.json")], False),+ }+ bad += [f"key {n}: same={key_of_tree(e, rules) == k}" for n, (e, same) in variants.items() if (key_of_tree(e, rules) == k) != same]+ if load_rules(os.devnull) != [] or not is_input("website/x", []):+ bad.append("no rules: every file must be an input")+ with tempfile.TemporaryDirectory() as d:+ env = {**os.environ, "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t", "GIT_COMMITTER_NAME": "t",+ "GIT_COMMITTER_EMAIL": "t@t", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}+ g = lambda *a: subprocess.run(["git", *a], cwd=d, env=env, check=True, capture_output=True, text=True).stdout.strip()+ g("init", "-q")+ os.makedirs(os.path.join(d, "website"))+ for name, text in {"CMakeLists.txt": "v1", "website/queue.html": "q1", "a b.txt": "x"}.items():+ with open(os.path.join(d, name), "w") as f:+ f.write(text)+ g("add", "-A")+ g("commit", "-qm", "one")+ one = g("rev-parse", "HEAD")+ with open(os.path.join(d, "website/queue.html"), "w") as f:+ f.write("q2")+ g("commit", "-qam", "site")+ two = g("rev-parse", "HEAD")+ with open(os.path.join(d, "CMakeLists.txt"), "w") as f:+ f.write("v2")+ g("commit", "-qam", "app")+ three = g("rev-parse", "HEAD")+ k1, k2, k3 = (key(s, rules, d) for s in (one, two, three))+ if not (k1 and k1 == k2 and k2 != k3):+ bad.append(f"git: site-only commit must keep the key, an app commit change it ({k1} {k2} {k3})")+ if key("f" * 40, rules, d) is not None:+ bad.append("git: a missing commit must give None")+ for b in bad:+ print("self-test FAIL", b)+ print("self-test", "failed" if bad else "ok")+ return 1 if bad else 0+++def main():+ if "--self-test" in sys.argv:+ return self_test()+ rules, rc = load_rules(), 0+ for sha in sys.argv[1:] or ["HEAD"]:+ k = key(sha, rules)+ if k is None:+ print(f"build_key.py: {sha}: no such commit here", file=sys.stderr)+ rc = 1+ else:+ print(k, subprocess.run(["git", "rev-parse", f"{sha}^{{commit}}"], capture_output=True, text=True).stdout.strip())+ return rc+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/release/check_workflows.py b/tools/release/check_workflows.pyindex fc911a2e..a5c8d838 100755--- a/tools/release/check_workflows.py+++ b/tools/release/check_workflows.py@@ -15,6 +15,9 @@tools/release/staged_run.py; a publisher doesn't need job verify or re-check the checksums(tools/release/verify_staged.py); packages.yml reads any secret, or a job of it uploads packages without apinned actions/attest-build-provenance step.+ - build once by key: packages.yml filters its pushes by `paths:` (tools/release/build_inputs.txt is the one list of+ build inputs; a filter skipped 0.11.14's staging push), or has no job reuse picking the earlier run with+ tools/release/staged_run.py --before-run (only older runs, so two runs never wait for each other).- integrations.yml (the Blender/Maya lanes) runs on anything but tag pushes, has an unpinned `uses:` or shelltracing, reads a secret other than UPDATE_SIGNING_KEY (in `environment: release`, by a job that can't write), orpublishes without re-checking SHA256SUMS.txt.sig against the app's key (openssl pkeyutl -verify).@@ -94,6 +97,10 @@ def check(files):if pk is not None:if "secrets." in pk:errs.append("packages.yml: reads a secret (staging builds must never see one; signing happens at promotion)")+ if re.search(r"^\s+paths(-ignore)?:", pk.split("\njobs:")[0], re.M):+ errs.append("packages.yml: a paths: filter (job reuse skips unchanged build inputs: tools/release/build_inputs.txt)")+ if not re.search(r"staged_run\.py\b.*--before-run", "\n".join(jobs(pk).get("reuse", []))):+ errs.append("packages.yml: no job reuse running tools/release/staged_run.py --before-run")for job, lines in jobs(pk).items():body = "\n".join(lines)if job != "sums" and "upload-artifact" in body and not ATTEST.search(body):@@ -202,6 +209,9 @@ PACKAGES = """on:push:branches: [main, staging]jobs:+ reuse:+ steps:+ - run: python3 tools/release/staged_run.py --sha "$SHA" --before-run "$RUN" --wait --fulllinux:permissions:id-token: write@@ -260,6 +270,10 @@ def self_test():"packages attest unpinned": ({"release.yml": GOOD, "packages.yml": PACKAGES.replace("@4d101475d8b20a2381f78447822ac1eab6504dd8", "@v4")}, 1),"packages attests less": ({"release.yml": GOOD, "packages.yml": PACKAGES.replace(" build/*.mcpb\n sums:", " sums:")}, 1),"packages secret": ({"release.yml": GOOD, "packages.yml": PACKAGES + " env: { K: '${{ secrets.X }}' }\n"}, 1),+ "packages paths filter": ({"release.yml": GOOD, "packages.yml": PACKAGES.replace("[main, staging]\n", "[main, staging]\n paths: ['**', '!website/**']\n")}, 1),+ "packages paths-ignore": ({"release.yml": GOOD, "packages.yml": PACKAGES.replace("[main, staging]\n", "[main, staging]\n paths-ignore: [website/**]\n")}, 1),+ "packages no reuse": ({"release.yml": GOOD, "packages.yml": PACKAGES.replace("staged_run.py", "x.py")}, 1),+ "packages reuse waits on newer": ({"release.yml": GOOD, "packages.yml": PACKAGES.replace(' --before-run "$RUN"', "")}, 1),"signing key outside env": ({"release.yml": GOOD.replace(" environment: release\n", "")}, 1),"signing key at repo level elsewhere": ({"release.yml": GOOD, "x.yml": f"jobs:\n a:\n env:\n K: ${{{{ {SIGNING} }}}}\n"}, 1),"no staged_run": ({"release.yml": GOOD.replace("staged_run.py", "x.py")}, 1),diff --git a/tools/release/staged_run.py b/tools/release/staged_run.pyindex daddec57..26fc2719 100755--- a/tools/release/staged_run.py+++ b/tools/release/staged_run.py@@ -3,26 +3,38 @@# SPDX-License-Identifier: GPL-3.0-or-later"""The one Packages run a release may promote for a commit (docs/releasing.md, "Build once, promote").- staged_run.py --sha SHA [--repo R] [--max-days N] [--actors a,b] [--wait]--Prints the run id and exits 0 when a run of .github/workflows/packages.yml in this repository- - was triggered by a push to the branch `staging` (scripts/merge-queue.sh staging), for exactly SHA: never a- pull_request, never a workflow_dispatch, never a fork,+ staged_run.py --sha SHA [--repo R] [--max-days N] [--actors a,b] [--wait [--wait-minutes M]] [--before-run ID] [--full]++Prints the run id (with --full: "ID BUILT_SHA BRANCH") and exits 0 when a run of .github/workflows/packages.yml in this+repository+ - was triggered by a push to `main` or `staging` (scripts/merge-queue.sh staging), for exactly SHA or for a commit+ with the same build-input key (tools/release/build_key.py: every file that goes into the packages byte for byte+ the same, computed here from git, never taken from the run): never a pull_request, never a workflow_dispatch,+ never a fork,- was pushed and (re)run by a maintainer (actor and triggering_actor in --actors),- finished with success, at most --max-days ago (default 7; artifacts are kept 14),- - still has every package artifact and the recorded checksums (staged-sums), none expired.-Exits 3 when no Packages run was pushed to staging for SHA at all (release.yml then builds from the tag: the---rebuild path), 1 when there are such runs but none may be promoted (the reasons on stderr). --wait waits for a run-in progress. scripts/release.sh (steps ci and tag) and release.yml (job locate) both use it.+ - still has every package artifact and the recorded checksums (staged-sums), none expired: a run that reused+ another one (packages.yml job reuse) has none, so the run that built them is the one picked.+A run for exactly SHA wins over one for another commit with the same key, then the newest. Exits 3 when no Packages+run was pushed for SHA or its key at all (release.yml then builds from the tag: the --rebuild path), 1 when there are+such runs but none may be promoted (the reasons on stderr). --wait waits for a run in progress. --before-run ID looks+only at runs older than run ID (packages.yml job reuse: an older run never waits for a newer one, so two never wait for+each other). scripts/release.sh (steps ci and tag), release.yml (job locate) and packages.yml (job reuse) use it."""import argparseimport json+import os+import reimport subprocessimport sysimport timefrom datetime import datetime, timedelta, timezone+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import build_key # noqa: E402+WORKFLOW = ".github/workflows/packages.yml"+BRANCHES = {"main", "staging"}ARTIFACTS = {"linux-x86_64", "linux-arm64", "flatpak-x86_64", "flatpak-aarch64", "vfx-vfx2026-x86_64", "vfx-vfx2026-arm64","vfx-vfx2027-x86_64", "vfx-vfx2027-arm64", "macos", "windows", "staged-sums",@@ -33,43 +45,57 @@ def ts(s):return datetime.fromisoformat(s.replace("Z", "+00:00"))-def candidates(runs, sha, repo):- """Runs pushed to staging for exactly sha, from this repository's own packages.yml."""- return [r for r in runs if r.get("path") == WORKFLOW and r.get("head_sha") == sha and r.get("head_branch") == "staging"- and r.get("event") == "push" and (r.get("head_repository") or {}).get("full_name") == repo- and (r.get("repository") or {}).get("full_name") == repo]---def choose(runs, artifacts, sha, repo, actors, now, max_days):- """(run id, 0) | (None, 3, why) | (None, 1, why) | (None, 2, why: in progress). artifacts: {run id: [artifact]}."""- cs = candidates(runs, sha, repo)- if not cs:- return None, 3, f"no Packages run pushed to staging for {sha[:12]}"+def candidates(runs, repo, before=None):+ """This repository's own packages.yml runs on pushes to main or staging (older than run `before`)."""+ return [r for r in runs if r.get("path") == WORKFLOW and r.get("head_branch") in BRANCHES and r.get("event") == "push"+ and (r.get("head_repository") or {}).get("full_name") == repo and (r.get("repository") or {}).get("full_name") == repo+ and (before is None or r["id"] < before)]+++def problem(r, actors, now, max_days):+ """Why run r can't be promoted, judged from the run alone; None when it may (artifacts aside)."""+ rid = r["id"]+ if r.get("status") != "completed":+ return f"run {rid} is {r.get('status')}"+ if r.get("conclusion") != "success":+ return f"run {rid} {r.get('conclusion')}"+ who = {(r.get("actor") or {}).get("login"), (r.get("triggering_actor") or {}).get("login")}+ if not who <= actors:+ return f"run {rid} was pushed or rerun by {', '.join(sorted(map(str, who - actors)))}, not a maintainer"+ age = now - ts(r["created_at"])+ if age > timedelta(days=max_days):+ return f"run {rid} is {age.days} days old (at most {max_days})"+ return None+++def choose(runs, artifacts, sha, repo, actors, now, max_days, keys, before=None):+ """(run, 0, "") | (None, 3, why) | (None, 1, why) | (None, 2, why: in progress).+ artifacts(run id) -> [artifact]; keys(shas) -> {sha: build-input key or None (commit unknown)}."""+ cs = candidates(runs, repo, before)+ exact = [r for r in cs if r.get("head_sha") == sha]+ # Another commit's run counts only when it could be promoted (or is still running) and its key is SHA's.+ others = [r for r in cs if r.get("head_sha") != sha and (problem(r, actors, now, max_days) is None or r.get("status") != "completed")]+ if others:+ k = keys({sha} | {r["head_sha"] for r in others})+ want = k.get(sha)+ others = [r for r in others if want is not None and k.get(r["head_sha"]) == want]+ if not exact and not others:+ return None, 3, f"no Packages run pushed to main or staging for {sha[:12]} or its build inputs"why = []- for r in sorted(cs, key=lambda r: r["created_at"], reverse=True):+ newest = lambda rs: sorted(rs, key=lambda r: r["created_at"], reverse=True)+ for r in newest(exact) + newest(others):rid = r["id"]- if r.get("status") != "completed":- why.append(f"run {rid} is {r.get('status')}")- continue- if r.get("conclusion") != "success":- why.append(f"run {rid} {r.get('conclusion')}")+ p = problem(r, actors, now, max_days)+ if p:+ why.append(p)continue- who = {(r.get("actor") or {}).get("login"), (r.get("triggering_actor") or {}).get("login")}- if not who <= actors:- why.append(f"run {rid} was pushed or rerun by {', '.join(sorted(map(str, who - actors)))}, not a maintainer")- continue- age = now - ts(r["created_at"])- if age > timedelta(days=max_days):- why.append(f"run {rid} is {age.days} days old (at most {max_days})")- continue- arts = artifacts.get(rid, [])- have = {a["name"] for a in arts if not a.get("expired")}+ have = {a["name"] for a in artifacts(rid) if not a.get("expired")}missing = ARTIFACTS - haveif missing:- why.append(f"run {rid} lacks artifacts {', '.join(sorted(missing))} (expired or never built)")+ why.append(f"run {rid} lacks artifacts {', '.join(sorted(missing))} (expired, never built, or it reused another run)")continue- return rid, 0, ""- pending = any(r.get("status") != "completed" for r in cs)+ return r, 0, ""+ pending = any(r.get("status") != "completed" for r in exact + others)return None, 2 if pending else 1, "; ".join(why)@@ -78,15 +104,38 @@ def gh(path):return json.loads(out)+def git_keys(shas):+ """Build-input keys from this repository's git objects; fetches commits it lacks (trees only in a partial clone)."""+ git = lambda *a: subprocess.run(["git", *a], capture_output=True, text=True)+ shas = {s for s in shas if isinstance(s, str) and re.fullmatch(r"[0-9a-f]{40}", s)}+ missing = [s for s in shas if git("cat-file", "-e", f"{s}^{{commit}}").returncode != 0]+ if missing:+ cmd = ["fetch", "-q", "--no-tags"]+ if git("rev-parse", "--is-shallow-repository").stdout.strip() == "true":+ cmd.append("--depth=1")+ if git("config", "remote.origin.promisor").stdout.strip() == "true":+ cmd.append("--filter=blob:none")+ git(*cmd, "origin", *missing) # a commit it can't fetch gets no key: never matched+ rules = build_key.load_rules()+ return {s: build_key.key(s, rules) for s in shas}++def live(sha, repo):- runs = gh(f"repos/{repo}/actions/workflows/packages.yml/runs?head_sha={sha}&branch=staging&event=push&per_page=20")["workflow_runs"]- arts = {r["id"]: gh(f"repos/{repo}/actions/runs/{r['id']}/artifacts?per_page=100")["artifacts"]- for r in candidates(runs, sha, repo) if r.get("conclusion") == "success"}- return runs, arts+ base = f"repos/{repo}/actions/workflows/packages.yml/runs?event=push&per_page="+ # (100 per branch: main's website pushes each add a run that reused another, and the builder must stay in view)+ runs = {r["id"]: r for q in (f"30&head_sha={sha}", "100&branch=main", "100&branch=staging")+ for r in gh(base + q)["workflow_runs"]}+ cache = {}++ def artifacts(rid):+ if rid not in cache:+ cache[rid] = gh(f"repos/{repo}/actions/runs/{rid}/artifacts?per_page=100")["artifacts"]+ return cache[rid]+ return list(runs.values()), artifactsdef self_test():- sha, repo, now = "a" * 40, "o/r", ts("2026-11-05T12:00:00Z")+ sha, other, repo, now = "a" * 40, "b" * 40, "o/r", ts("2026-11-05T12:00:00Z")me = {"login": "islandmed"}def run(**k):@@ -95,30 +144,54 @@ def self_test():"actor": me, "triggering_actor": me, "created_at": "2026-11-04T12:00:00Z"}r.update(k)return r- full = {1: [{"name": n} for n in ARTIFACTS]}- cases = {- "good": ([run()], full, 0),- "none": ([], {}, 3),- "dispatch": ([run(event="workflow_dispatch")], full, 3),- "pull request": ([run(event="pull_request")], full, 3),- "fork": ([run(head_repository={"full_name": "evil/r"})], full, 3),- "other branch": ([run(head_branch="main")], full, 3),- "other workflow": ([run(path=".github/workflows/ci.yml")], full, 3),- "other commit": ([run(head_sha="b" * 40)], full, 3),- "failed": ([run(conclusion="failure")], full, 1),- "in progress": ([run(status="in_progress", conclusion=None)], full, 2),- "stranger": ([run(actor={"login": "mallory"})], full, 1),- "stranger rerun": ([run(triggering_actor={"login": "mallory"})], full, 1),- "old": ([run(created_at="2026-10-20T12:00:00Z")], full, 1),- "expired": ([run()], {1: [{"name": n, "expired": n == "macos"} for n in ARTIFACTS]}, 1),- "no sums": ([run()], {1: [{"name": n} for n in ARTIFACTS - {"staged-sums"}]}, 1),- "newer failed, older ok": ([run(id=2, conclusion="failure", created_at="2026-11-05T11:00:00Z"), run()], full, 0),+ full = {n: [{"name": a} for a in ARTIFACTS] for n in (1, 2, 3)}+ same = {sha: "k1", other: "k1"}+ differ = {sha: "k1", other: "k2"}+ cases = { # name: (runs, artifacts, keys, want code, want run id)+ "good": ([run()], full, differ, 0, 1),+ "main push": ([run(head_branch="main")], full, differ, 0, 1),+ "none": ([], {}, differ, 3, None),+ "dispatch": ([run(event="workflow_dispatch")], full, differ, 3, None),+ "pull request": ([run(event="pull_request")], full, differ, 3, None),+ "fork": ([run(head_repository={"full_name": "evil/r"})], full, same, 3, None),+ "other branch": ([run(head_branch="feat/x")], full, differ, 3, None),+ "other workflow": ([run(path=".github/workflows/ci.yml")], full, differ, 3, None),+ "other commit, other key": ([run(head_sha=other)], full, differ, 3, None),+ "other commit, same key": ([run(head_sha=other)], full, same, 0, 1),+ "other commit, same key, main": ([run(head_sha=other, head_branch="main")], full, same, 0, 1),+ "other commit, unknown here": ([run(head_sha=other)], full, {sha: "k1", other: None}, 3, None),+ "this commit unknown here": ([run(head_sha=other)], full, {sha: None, other: None}, 3, None),+ "same key, fork": ([run(head_sha=other, head_repository={"full_name": "evil/r"})], full, same, 3, None),+ "same key, dispatch by another actor": ([run(head_sha=other, event="workflow_dispatch", actor={"login": "mallory"},+ triggering_actor={"login": "mallory"})], full, same, 3, None),+ "same key, pushed by another actor": ([run(head_sha=other, actor={"login": "mallory"})], full, same, 3, None),+ "same key, rerun by another actor": ([run(head_sha=other, triggering_actor={"login": "mallory"})], full, same, 3, None),+ "same key, expired": ([run(head_sha=other)], {1: [{"name": n, "expired": n == "windows"} for n in ARTIFACTS]}, same, 1, None),+ "same key, old": ([run(head_sha=other, created_at="2026-10-20T12:00:00Z")], full, same, 3, None),+ "same key, failed": ([run(head_sha=other, conclusion="failure")], full, same, 3, None),+ "same key, in progress": ([run(head_sha=other, status="in_progress", conclusion=None)], full, same, 2, None),+ "failed": ([run(conclusion="failure")], full, differ, 1, None),+ "in progress": ([run(status="in_progress", conclusion=None)], full, differ, 2, None),+ "stranger": ([run(actor={"login": "mallory"})], full, differ, 1, None),+ "stranger rerun": ([run(triggering_actor={"login": "mallory"})], full, differ, 1, None),+ "old": ([run(created_at="2026-10-20T12:00:00Z")], full, differ, 1, None),+ "expired": ([run()], {1: [{"name": n, "expired": n == "macos"} for n in ARTIFACTS]}, differ, 1, None),+ "no sums": ([run()], {1: [{"name": n} for n in ARTIFACTS - {"staged-sums"}]}, differ, 1, None),+ "newer failed, older ok": ([run(id=2, conclusion="failure", created_at="2026-11-05T11:00:00Z"), run()], full, differ, 0, 1),+ "exact wins over a newer same-key run": ([run(id=2, head_sha=other, created_at="2026-11-05T11:00:00Z"), run()], full, same, 0, 1),+ "reuse run skipped for its builder": ([run(id=2, head_branch="main", created_at="2026-11-05T11:00:00Z"),+ run(head_sha=other)], {1: full[1], 2: []}, same, 0, 1),+ "the 0.11.14 case (main built the staged commit)": ([run(id=2, head_branch="main")], {2: full[2]}, differ, 0, 2),}bad = []- for name, (runs, arts, want) in cases.items():- got = choose(runs, arts, sha, repo, {"islandmed"}, now, 7)- if got[1] != want:- bad.append(f"{name}: want {want}, got {got}")+ for name, (runs, arts, keys, want, want_id) in cases.items():+ got = choose(runs, lambda rid: arts.get(rid, []), sha, repo, {"islandmed"}, now, 7, lambda s: {x: keys.get(x) for x in s})+ if got[1] != want or (got[0] or {}).get("id") != want_id:+ bad.append(f"{name}: want {want} {want_id}, got {got[1]} {(got[0] or {}).get('id')} {got[2]}")+ # --before-run: an older run never waits for a newer one (packages.yml job reuse).+ got = choose([run(id=5, status="in_progress", conclusion=None)], lambda r: [], sha, repo, {"islandmed"}, now, 7, lambda s: {}, before=5)+ if got[1] != 3:+ bad.append(f"before-run: want 3, got {got}")for b in bad:print("self-test FAIL", b)print("self-test", "failed" if bad else "ok")@@ -131,7 +204,10 @@ def main():ap.add_argument("--repo", default="islandmed/SculptForge")ap.add_argument("--max-days", type=int, default=7)ap.add_argument("--actors", default="islandmed")- ap.add_argument("--wait", action="store_true", help="wait (up to 2 hours) for a staging run in progress")+ ap.add_argument("--wait", action="store_true", help="wait for a matching run in progress")+ ap.add_argument("--wait-minutes", type=int, default=120)+ ap.add_argument("--before-run", type=int, help="only runs older than this run id")+ ap.add_argument("--full", action="store_true", help='print "ID BUILT_SHA BRANCH"')ap.add_argument("--self-test", action="store_true")a = ap.parse_args()if a.self_test:@@ -139,17 +215,19 @@ def main():if not a.sha or len(a.sha) != 40:ap.error("--sha takes a full 40-hex commit SHA")actors = set(a.actors.split(","))- end = time.time() + 7200+ end = time.time() + 60 * a.wait_minuteswhile True:runs, arts = live(a.sha, a.repo)- rid, code, why = choose(runs, arts, a.sha, a.repo, actors, datetime.now(timezone.utc), a.max_days)+ r, code, why = choose(runs, arts, a.sha, a.repo, actors, datetime.now(timezone.utc), a.max_days, git_keys, a.before_run)if code == 2 and a.wait and time.time() < end:- print(f" waiting for the staging Packages run ({why}) ...", file=sys.stderr)+ print(f" waiting for the Packages run in progress ({why}) ...", file=sys.stderr)time.sleep(60)continuebreakif code == 0:- print(rid)+ if r["head_sha"] != a.sha:+ print(f" run {r['id']} built {r['head_sha'][:12]} ({r['head_branch']}), whose build inputs are {a.sha[:12]}'s", file=sys.stderr)+ print(f"{r['id']} {r['head_sha']} {r['head_branch']}" if a.full else r["id"])return 0print(why, file=sys.stderr)return 1 if code == 2 else codediff --git a/tools/release/verify_staged.py b/tools/release/verify_staged.pyindex edf3faa6..2366a088 100755--- a/tools/release/verify_staged.py+++ b/tools/release/verify_staged.py@@ -3,13 +3,14 @@# SPDX-License-Identifier: GPL-3.0-or-later"""Checks the packages a release is about to publish (release.yml, jobs verify and publish). Refuses on any mismatch.- verify_staged.py DIST SUMS --run ID --sha SHA [--staged] [--repo R] [--sums-only]+ verify_staged.py DIST SUMS --run ID --sha SHA [--staged [--ref REF]] [--repo R] [--sums-only]1. Checksums: DIST holds exactly the files SUMS lists (SHA256SUMS.staged.txt, written by packages.yml's job sums inthe run that built them), and each file's SHA-256, computed here, is the one listed.2. Provenance (skipped with --sums-only): each file has a GitHub artifact attestation (actions/attest-build-provenancein packages.yml), checked with `gh attestation verify`: signed by this repository's packages.yml, for exactly SHA,- in run ID; with --staged also from refs/heads/staging and a push (the merge queue's staging run).+ in run ID; with --staged also from a push to REF (default refs/heads/staging; refs/heads/main when main's run built+ it). SHA is the commit the run built: the tagged one, or one with the same build-input key (tools/release/staged_run.py)."""import argparseimport hashlib@@ -58,17 +59,17 @@ def attested(certs, run, staged):return False-def check_attestation(path, repo, run, sha, staged):+def check_attestation(path, repo, run, sha, staged, ref="refs/heads/staging"):cmd = ["gh", "attestation", "verify", str(path), "--repo", repo, "--signer-workflow", f"{repo}/.github/workflows/packages.yml","--source-digest", sha, "--format", "json"]if staged:- cmd += ["--source-ref", "refs/heads/staging"]+ cmd += ["--source-ref", ref]p = subprocess.run(cmd, capture_output=True, text=True)if p.returncode != 0:return f"{path.name}: no valid attestation ({(p.stderr or p.stdout).strip().splitlines()[-1:] or ['gh failed']})"certs = [r["verificationResult"]["signature"]["certificate"] for r in json.loads(p.stdout)]if not attested(certs, run, staged):- return f"{path.name}: attested, but not by run {run}{' on a push to staging' if staged else ''}"+ return f"{path.name}: attested, but not by run {run}{' on a push to ' + ref if staged else ''}"return None@@ -118,12 +119,13 @@ def main():ap.add_argument("--sha", required=True)ap.add_argument("--repo", default="islandmed/SculptForge")ap.add_argument("--staged", action="store_true")+ ap.add_argument("--ref", default="refs/heads/staging", choices=["refs/heads/staging", "refs/heads/main"])ap.add_argument("--sums-only", action="store_true")a = ap.parse_args()sums = read_sums(Path(a.sums).read_text(encoding="utf-8"))errs = ["no recorded checksums"] if not sums else check_sums(a.dist, sums)if not errs and not a.sums_only:- errs = [e for p in sorted(Path(a.dist).iterdir()) if (e := check_attestation(p, a.repo, a.run, a.sha, a.staged))]+ errs = [e for p in sorted(Path(a.dist).iterdir()) if (e := check_attestation(p, a.repo, a.run, a.sha, a.staged, a.ref))]for e in errs:print(f"::error::{e}")if errs: