Peach: Local-first video metadata scraper and media manager.
perf(ci): 晋级已验收制品并复用媒体构建
longmeidao5133d8b9a47e
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 67541bd0a..fb830d6cd 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -47,6 +47,7 @@ jobs:name: Windows FFmpeg 与对应源码runs-on: ubuntu-latestneeds: validate+ if: github.ref_type != 'tag'timeout-minutes: 40steps:- uses: actions/checkout@v7@@ -92,6 +93,7 @@ jobs:name: Windows x64 独立测试包runs-on: windows-latestneeds: ffmpeg+ if: github.ref_type != 'tag'timeout-minutes: 40outputs:version: ${{ steps.version.outputs.version }}@@ -257,6 +259,7 @@ jobs:macos:name: macOS ${{ matrix.arch }} 独立测试包needs: validate+ if: github.ref_type != 'tag'strategy:fail-fast: falsematrix:@@ -353,38 +356,41 @@ jobs:release:name: GitHub 预发布if: github.ref_type == 'tag'- needs: [windows, desktop-smoke, macos-smoke, docker]+ needs: validateruns-on: ubuntu-latesttimeout-minutes: 10permissions:contents: write+ actions: readsteps:- - uses: actions/download-artifact@v8- with:- name: desktop-candidate- path: release- - uses: actions/download-artifact@v8+ - uses: actions/checkout@v7+ - uses: actions/setup-python@v7with:- pattern: macos-candidate-*- merge-multiple: true- path: macos-candidates+ python-version: '3.14'+ - name: 核对并取得同提交演练产物+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ python scripts/github_release_candidate.py desktop --destination release+ python scripts/github_release_candidate.py macos --destination macos-candidates- name: 创建预发布env:GH_TOKEN: ${{ github.token }}GH_REPO: ${{ github.repository }}- VERSION: ${{ needs.windows.outputs.version }}+ VERSION: ${{ github.ref_name }}run: |cd releasecp ../macos-candidates/release/*.dmg .tail -n +4 ../macos-candidates/scripts/MACOS_DOWNLOADS.md >> RELEASE_NOTES.mdsha256sum ./*.zip ./*-setup.exe ./*.dmg > SHA256SUMS.txt- gh release create "$GITHUB_REF_NAME" ./*.zip ./*-setup.exe ./*.dmg SHA256SUMS.txt --verify-tag --prerelease --title "Peach $VERSION · Windows / macOS 测试版" --notes-file RELEASE_NOTES.md+ gh release create "$GITHUB_REF_NAME" ./*.zip ./*-setup.exe ./*.dmg SHA256SUMS.txt --verify-tag --prerelease --title "Peach ${VERSION#v} · Windows / macOS 测试版" --notes-file RELEASE_NOTES.md- # 镜像先构建、验收(演练与标签都跑),发布排在 GitHub Release 成功之后:+ # 镜像在演练中构建和验收,标签核对相同 image ID 后发布;发布排在 GitHub Release 成功之后:# 桌面包任何一步没发出去,Docker Hub 的版本号与 edge 都不动(ADR-0121)。docker:name: Linux amd64 镜像构建与验收needs: validate+ if: github.ref_type != 'tag'runs-on: ubuntu-latesttimeout-minutes: 25steps:@@ -393,21 +399,40 @@ jobs:with:python-version: '3.14'- uses: docker/setup-buildx-action@v4+ - name: 读取镜像版本+ id: version+ run: echo "version=$(PYTHONPATH=src python -c 'from peach import __version__; print(__version__)')" >> "$GITHUB_OUTPUT"- name: 构建候选镜像uses: docker/build-push-action@v7with:context: .load: truetags: longmeidao/peach:candidate+ labels: |+ org.opencontainers.image.version=${{ steps.version.outputs.version }}+ org.opencontainers.image.revision=${{ github.sha }}cache-from: type=ghacache-to: type=gha,mode=max- name: 验收临时容器run: python3 scripts/smoke_docker.py longmeidao/peach:candidate+ - name: 保存已验收镜像与摘要+ run: |+ python scripts/github_release_candidate.py image-record --version '${{ steps.version.outputs.version }}' --destination docker-image.json+ docker image save longmeidao/peach:candidate | gzip > docker-image.tar.gz+ - uses: actions/upload-artifact@v7+ with:+ name: docker-candidate+ if-no-files-found: error+ retention-days: 7+ compression-level: 0+ path: |+ docker-image.json+ docker-image.tar.gzdocker-publish:name: 发布已验收镜像if: github.ref_type == 'tag' && vars.DOCKERHUB_USERNAME != ''- needs: [release, docker]+ needs: [release, validate]runs-on: ubuntu-latesttimeout-minutes: 25steps:@@ -415,17 +440,13 @@ jobs:- uses: actions/setup-python@v7with:python-version: '3.14'- - uses: docker/setup-buildx-action@v4- # 作业之间不共享 Docker 守护进程:按同一提交、同一缓存重建,再验收一次才推送。- - name: 构建镜像- uses: docker/build-push-action@v7- with:- context: .- load: true- tags: longmeidao/peach:candidate- cache-from: type=gha- - name: 验收临时容器- run: python3 scripts/smoke_docker.py longmeidao/peach:candidate+ - name: 取得并核对已验收镜像+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ python scripts/github_release_candidate.py docker --destination docker-candidate+ docker image load --input docker-candidate/docker-image.tar.gz+ python scripts/github_release_candidate.py image-verify --version "${GITHUB_REF_NAME#v}" --destination docker-candidate/docker-image.json- uses: docker/login-action@v4with:username: ${{ vars.DOCKERHUB_USERNAME }}diff --git a/.gitlab-ci.yml b/.gitlab-ci.ymlindex 17cbc32eb..d1e611292 100644--- a/.gitlab-ci.yml+++ b/.gitlab-ci.yml@@ -6,7 +6,7 @@ workflow:when: never- if: '$CI_COMMIT_BRANCH'-stages: [verify, package, validate, media, build, smoke, publish]+stages: [prepare, verify, package, validate, media, build, smoke, publish]default:tags: [docker]@@ -26,7 +26,7 @@ variables:PEACH_R2_PUBLIC_BASE: https://downloads.peach.video# 回归口径(ADR-0119):分支与合并请求验证改动域及平台敏感用例,必要时使用全量范围。-# 版本提交的演练使用三平台全量范围;标签流水线复核同提交的演练结果后构建与发布。+# 版本提交的演练使用三平台全量范围;标签流水线复核同提交的演练结果后晋级产物并发布。# 正式验证使用有效证明续跑;缓存缺失或证明失效时执行必要测试。# 改动域随时可能退成全量,所以两种作业的时限都按全量定。.verify-linux:@@ -68,10 +68,10 @@ variables:- build/agent-verification/browser/setup-serve.log- build/test-history/-# 三平台验收在版本提交上由演练规则改成全量(规则变量 PEACH_CI_COVERAGE=full 覆盖作业变量),-# 每个平台只跑一次全量;标签流水线由 validate-release 核对同一提交的演练已通过,不再重跑。+# 三平台验收在版本提交上由演练规则改成全量;标签核对成功演练和不可变产物清单后发布。verify-linux:extends: .verify-linux+ needs: [{job: release-preflight, optional: true}]rules:- !reference [.release-rehearsal, rules]- if: '$CI_COMMIT_BRANCH || $CI_PIPELINE_SOURCE == "merge_request_event"'@@ -97,6 +97,7 @@ verify-linux:verify-windows:extends: .verify-windows+ needs: [{job: release-preflight, optional: true}]rules:- !reference [.release-rehearsal, rules]- if: '$CI_COMMIT_BRANCH == "master"'@@ -121,6 +122,7 @@ verify-windows:verify-macos:extends: .verify-macos+ needs: [{job: release-preflight, optional: true}]rules:- !reference [.release-rehearsal, rules]- if: '$CI_COMMIT_BRANCH == "master"'@@ -152,7 +154,7 @@ wheel-smoke:# 发版分两步(ADR-0121):版本提交 `chore(release): 版本 X` 推上 master 时演练整条发布链,三平台验收# 改跑全量,媒体、构建、冒烟与镜像都跑,只是不发布;`release_tag.py --ship` 等这条流水线转绿才打标签。-# 标签流水线核对同一提交的演练已通过,重新构建后发布,不再重跑全量;任何一步没过都不发布任何东西。+# 标签流水线晋级演练中已验收的相同产物;任何必需验证失败都不发布(ADR-0127)。.release-rehearsal:rules:- if: '$CI_COMMIT_BRANCH == "master" && $CI_COMMIT_REF_PROTECTED == "true" && $CI_COMMIT_MESSAGE =~ /^chore\(release\): 版本 /'@@ -167,7 +169,6 @@ wheel-smoke:.release-linux:image: ghcr.io/astral-sh/uv:0.13.3-python3.14-trixie-slimrules:- - !reference [.release-publish, rules]- !reference [.release-rehearsal, rules]before_script:- apt-get update@@ -180,19 +181,41 @@ wheel-smoke:- export PATH="$CI_PROJECT_DIR/build/release-tools:$PATH"- export GLAB_ENABLE_CI_AUTOLOGIN=true+release-preflight:+ extends: .release-linux+ stage: prepare+ environment:+ name: release+ action: prepare+ script:+ - python3 scripts/release_candidate.py preflight+validate-release:extends: .release-linuxstage: validate# 核对这个提交的主线流水线(含演练)已经成功:演练里正在跑的就是它自己,所以只在标签上跑。rules: !reference [.release-publish, rules]+ environment:+ name: release+ action: verifyscript:- python3 scripts/release_tag.py --gitlab-host "$CI_SERVER_HOST" --repo "$CI_PROJECT_PATH" --verify-sha "$CI_COMMIT_SHA"- python3 -c 'import os; from pathlib import Path; from scripts.version_bump import read_version; assert os.environ["CI_COMMIT_TAG"] == "v" + read_version(Path.cwd())'- python3 scripts/changelog.py --notes "${CI_COMMIT_TAG#v}" --to build/release-notes.md+ - python3 scripts/release_candidate.py validate+ artifacts:+ expire_in: 14 days+ paths: [build/ci-artifacts/release-candidate.json]windows-media:extends: .release-linuxstage: media+ needs: [release-preflight]+ cache:+ key:+ prefix: windows-media-v2+ files: [scripts/ffmpeg-sources.json, scripts/untrunc-sources.json]+ paths: [build/media-cache/]variables:PEACH_SOURCE_CACHE_BASE: "${PEACH_R2_PUBLIC_BASE}/_sources"environment:@@ -200,8 +223,7 @@ windows-media:action: preparescript:- apt-get install -y build-essential gcc-mingw-w64-x86-64-posix g++-mingw-w64-x86-64-posix mingw-w64-x86-64-dev nasm pkg-config clang meson ninja-build cmake curl xz-utils- - bash scripts/build_ffmpeg_windows.sh build/ffmpeg-windows- - bash scripts/build_untrunc_windows.sh build/untrunc-windows+ - python3 scripts/media_build_cache.py windows- python3 scripts/ci_r2_artifacts.py push windows-mediaartifacts:expire_in: 14 days@@ -219,15 +241,17 @@ build-windows:before_script:- python scripts/fetch_release_tools.py --rclone-only- if ($LASTEXITCODE -ne 0) { throw 'R2 传输工具校验失败' }- - python scripts/ci_r2_artifacts.py pull windows-media+ - python scripts/ci_r2_artifacts.py restore windows-release+ - if ($LASTEXITCODE -ne 0) { throw 'Windows 产物恢复检查失败' }+ - if (-not (Get-Content build/ci-artifacts/windows-release-resume.json -Raw | ConvertFrom-Json).restored) { python scripts/ci_r2_artifacts.py pull windows-media }- if ($LASTEXITCODE -ne 0) { throw '媒体构建产物校验失败' }script:# 本机 Windows runner 就是开发机:构建、冒烟与镜像作业和本机测试排同一把整机重负载锁# (scripts/machine_lock.py)。runner 的系统 Python 没有 filelock,用 uv 起一个只带它的临时环境,# 不碰作业里会被 uv sync 改写的 .venv。验证作业经测试入口,入口自己拿这把锁。- - uv run --no-project --with filelock==4.2.4 --python 3.14 python -X utf8 scripts/machine_lock.py -- pwsh -NoProfile -File ./scripts/ci_windows.ps1 build+ - if (-not (Get-Content build/ci-artifacts/windows-release-resume.json -Raw | ConvertFrom-Json).restored) { uv run --no-project --with filelock==4.2.4 --python 3.14 python -X utf8 scripts/machine_lock.py -- pwsh -NoProfile -File ./scripts/ci_windows.ps1 build }- if ($LASTEXITCODE -ne 0) { throw 'Windows 构建失败' }- - python scripts/ci_r2_artifacts.py push windows-release+ - if (-not (Get-Content build/ci-artifacts/windows-release-resume.json -Raw | ConvertFrom-Json).uploaded) { python scripts/ci_r2_artifacts.py push windows-release }- if ($LASTEXITCODE -ne 0) { throw 'Windows 产物暂存失败' }artifacts:expire_in: 14 days@@ -236,19 +260,32 @@ build-windows:build-macos:stage: buildtags: [peach-macos]- # 两个架构各自从源码编译 x264、ffmpeg 与 untrunc,不走缓存;windows-media 单架构交叉编译 ffmpeg 与 untrunc 约 17 分钟。+ # 两个架构分别核对工具缓存与对应源码;缓存缺失或构建输入变化时从源码编译。timeout: 2hrules: !reference [.release-linux, rules]needs: [{job: validate-release, optional: true}, {job: verify-macos, artifacts: false, optional: true}]environment:name: releaseaction: prepare+ cache:+ key:+ prefix: macos-media-v2+ files: [scripts/ffmpeg-sources.json, scripts/untrunc-sources.json]+ paths: [build/media-cache/]before_script:- python3 scripts/fetch_release_tools.py --rclone-onlyscript:- - bash scripts/ci_macos.sh build arm64- - bash scripts/ci_macos.sh build x86_64- - python3 scripts/ci_r2_artifacts.py push macos-release+ - python3 scripts/ci_r2_artifacts.py restore macos-release+ - |+ restored="$(python3 -c 'import json; print(int(json.load(open("build/ci-artifacts/macos-release-resume.json"))["restored"]))')"+ if [ "$restored" = 0 ]; then+ bash scripts/ci_macos.sh build arm64+ bash scripts/ci_macos.sh build x86_64+ fi+ uploaded="$(python3 -c 'import json; print(int(json.load(open("build/ci-artifacts/macos-release-resume.json"))["uploaded"]))')"+ if [ "$uploaded" = 0 ]; then+ python3 scripts/ci_r2_artifacts.py push macos-release+ fiartifacts:expire_in: 14 dayspaths: [build/ci-artifacts/macos-release.json]@@ -257,7 +294,7 @@ smoke-windows:stage: smoketags: [peach-windows]rules: !reference [.release-linux, rules]- needs: [build-windows]+ needs: [build-windows, candidate-capacity]environment:name: releaseaction: verify@@ -280,15 +317,32 @@ docker-build:environment:name: releaseaction: prepare+ before_script:+ - python scripts/fetch_release_tools.py --rclone-only+ - if ($LASTEXITCODE -ne 0) { throw 'R2 传输工具校验失败' }+ - python scripts/ci_r2_artifacts.py restore docker-release+ - if ($LASTEXITCODE -ne 0) { throw '镜像回执恢复检查失败' }script:- uv run --no-project --with filelock==4.2.4 --python 3.14 python -X utf8 scripts/machine_lock.py -- pwsh -NoProfile -File ./scripts/ci_windows.ps1 docker-build- if ($LASTEXITCODE -ne 0) { throw 'Docker 镜像构建或验收失败' }+ - if (-not (Get-Content build/ci-artifacts/docker-release-resume.json -Raw | ConvertFrom-Json).uploaded) { python scripts/ci_r2_artifacts.py push docker-release }+ - if ($LASTEXITCODE -ne 0) { throw '镜像验收回执上传失败' }++candidate-capacity:+ extends: .release-linux+ stage: smoke+ needs: [build-windows, build-macos, docker-build]+ environment:+ name: release+ action: verify+ script:+ - python3 scripts/release_candidate.py check-capacitypublish-docker:stage: publishtags: [peach-windows]rules: !reference [.release-publish, rules]- needs: [publish-release, docker-build]+ needs: [publish-release, validate-release]resource_group: peach-docker-publicationenvironment:name: release@@ -297,32 +351,33 @@ publish-docker:- pwsh -NoProfile -File ./scripts/ci_windows.ps1 docker-push- if ($LASTEXITCODE -ne 0) { throw 'Docker 镜像发布失败' }-# 演练不发布:暂存在 R2 的本流水线产物删掉,不占容量预算。演练失败也照样回收(when: always),-# 回收本身失败不挡发版(allow_failure,不在 REHEARSAL_JOBS 里)。-release-rehearsal-cleanup:+# 候选登记是演练必需任务;保留暂存,直到桌面包和镜像都成功发布。+seal-release:extends: .release-linuxstage: publishrules:- if: '$CI_COMMIT_BRANCH == "master" && $CI_COMMIT_REF_PROTECTED == "true" && $CI_COMMIT_MESSAGE =~ /^chore\(release\): 版本 /'- when: always- allow_failure: truevariables:PEACH_RELEASE_REHEARSAL: "1"needs:- {job: smoke-windows, artifacts: false}- {job: build-macos, artifacts: false}- {job: docker-build, artifacts: false}+ - {job: verify-linux, artifacts: false}+ - {job: verify-windows, artifacts: false}+ - {job: verify-macos, artifacts: false}+ - {job: wheel-smoke, artifacts: false}environment:name: releaseaction: preparescript:- - python3 scripts/ci_r2_artifacts.py cleanup+ - python3 scripts/release_candidate.py sealpublish-release:extends: .release-linuxstage: publishrules: !reference [.release-publish, rules]- needs: [validate-release, build-windows, smoke-windows, build-macos, docker-build]+ needs: [validate-release]resource_group: peach-release-publicationenvironment:name: release@@ -331,9 +386,18 @@ publish-release:PEACH_R2_BUCKET: peach-releasesPEACH_R2_PUBLIC_BASE: https://downloads.peach.videoscript:- - python3 scripts/ci_r2_artifacts.py pull windows-release- - python3 scripts/ci_r2_artifacts.py pull macos-release+ - python3 scripts/release_candidate.py pull- cp dist/macos.noindex/arm64/*.dmg dist/macos.noindex/x86_64/*.dmg release/- cp dist/macos.noindex/arm64/*-corresponding-source.zip dist/macos.noindex/x86_64/*-corresponding-source.zip release/- python3 scripts/publish_gitlab_release.py- - python3 scripts/ci_r2_artifacts.py cleanup++publication-cleanup:+ extends: .release-linux+ rules: !reference [.release-publish, rules]+ stage: publish+ needs: [validate-release, publish-release, publish-docker]+ environment:+ name: release+ action: prepare+ script:+ - python3 scripts/release_candidate.py cleanupdiff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex 87f470a79..116ff5485 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -81,7 +81,9 @@ Windows 原生 Runner 在深目录中检出项目时,需为 Git 启用 `core.l计划任务的「失败后重启」(`RestartCount`、`RestartInterval`)只在任务启动失败时生效,`gitlab-runner` 进程自己退出后不会被拉起,主线的 Windows 作业就一直排着没人接。所以任务的动作是 runner 目录里的入口脚本 `run-runner.ps1`:它按可执行文件路径查找本目录的 `gitlab-runner.exe`,已经在跑就直接退出,没在跑才拉起,这样不会让同一个 token 跑两个 runner。触发器保留「登录时」,另加一个每 5 分钟重复、不设结束时间的时间触发器,`MultipleInstances` 设为 `IgnoreNew`。runner 退出后最多 5 分钟就会被拉回来。-版本标签须受保护。标签流水线重新核对提交与版本,构建固定来源的媒体工具、Windows 完整包与拆分包、macOS 双架构 DMG,并进行独立制品验收。发布全有或全无:`publish-release` 要等全部构建、冒烟与 `docker-build` 通过才上传 R2 并创建 GitLab Release,`publish-docker` 排在它成功之后才推送镜像。任何一步没过,安装包、R2、Release、Docker Hub 一个都不动;发布作业自身失败时,重试同一个作业即可,标签不动。项目流水线使用 `PEACH_DOWNLOAD_BACKEND=both`,将同一份制品分别保存到 R2 与 GitGud Generic Package Registry;不把会过期的 job artifacts 当作永久下载地址。独立部署可明确选用 `r2` 或 `gitgud` 单后端。+计划任务使用 `pythonw.exe` 调用 `scripts/run_gitlab_runner.py --root <runner目录>`,由启动器通过 `CREATE_NO_WINDOW` 运行原有 `run-runner.ps1`。PowerShell 的 `-WindowStyle Hidden` 不能保证不触发 Windows Terminal 托管,后台入口不直接以控制台程序作为计划任务动作。启动器日志保存在 runner 目录的 `runner-launcher.log`,runner 输出仍沿用 `runner.log`。++版本标签须受保护。版本提交的演练完成三平台回归、固定来源媒体工具、Windows 完整包与拆分包、macOS 双架构 DMG、安装升级和镜像验收,再登记候选。标签核对相同提交、验证任务与文件摘要后发布已验收产物,不重新构建。`publish-release` 上传 R2 并创建 GitLab Release,`publish-docker` 排在它成功之后推送同一 image ID 的镜像;最终回收演练暂存。发布作业失败时重试同一作业,标签不动。项目流水线使用 `PEACH_DOWNLOAD_BACKEND=both`,同一份制品分别保存在 R2 与 GitGud Generic Package Registry;不把会过期的 job artifacts 当作永久下载地址。独立部署可明确选择 `r2` 或 `gitgud` 单后端。候选和发布顺序见 [ADR-0127](adr/0127-verified-release-artifact-promotion.md)。Linux 发布任务使用官方 uv Python 3.14 容器,并在获取制品工具前核对解释器版本;源码归档使用 `tarfile` 的 `data` 过滤器解压。CI 的 `.npm/` 与 `.uv-cache/` 属于生成缓存,不计入源码工作区变化。@@ -93,9 +95,11 @@ GitGud 的 Linux 平台 Runner 不提供 Docker 守护进程,Docker 镜像由可选的 `r2` 后端使用独立 Standard 桶与 HTTPS 自定义域名。`PEACH_R2_ACCESS_KEY_ID`、`PEACH_R2_SECRET_ACCESS_KEY`、`PEACH_R2_ENDPOINT` 放入受保护且隐藏的 CI 变量,环境作用域为 `release`;`PEACH_R2_BUCKET` 和 `PEACH_R2_PUBLIC_BASE` 指定发布目标。S3 传输复用 rclone,版本文件禁止覆盖;每份文件必须从公开入口完整下载并核对大小及 SHA-256 后,才更新公开版本索引和 Release 链接。-GitLab 标签流水线通过 R2 暂存传递媒体工具、Windows 发行目录与 macOS 镜像,job artifacts 只保存 JSON 清单。中转需要上述 R2 变量;构建与验收任务使用 `release` 环境的 `prepare` 或 `verify` 动作,只有受保护的版本标签与受保护 master 上的版本提交演练能取得凭据,普通分支回归不使用这些变量。演练的暂存产物由 `release-rehearsal-cleanup` 在验收后回收。构建期 rclone 按当前操作系统和 CPU 架构从官方固定版本归档安装并核对 SHA-256。+GitLab 演练通过 R2 暂存传递媒体工具、Windows 发行目录、macOS 镜像和 Docker 验收回执,job artifacts 保存 JSON 清单。中转需要上述 R2 变量;构建与验收任务使用 `release` 环境的 `prepare` 或 `verify` 动作,只有受保护版本标签与受保护 master 上的版本提交演练能取得凭据。候选保留到桌面与镜像都发布成功,由 `publication-cleanup` 回收;失败时保留供重试。构建期 rclone 按当前操作系统和 CPU 架构从官方固定版本归档安装并核对 SHA-256。++暂存对象位于 `_ci/<项目 ID>/<流水线 ID>/<提交 SHA>/<产物组>/<作业 ID>/`,纳入同一桶预算。完整上传后在同一前缀的 `completed/` 登记不可变完成清单;重试优先恢复已经完成的同流水线产物,传输失败不当作未构建。`seal-release` 登记版本、提交、成功任务与文件摘要。标签通过 GitLab API 核对同一提交的成功主线演练,再下载其相同文件;路径限定在对应输出目录,不接收软链接或路径穿越。macOS 仅传两种架构的 DMG、对应源码、`build-info.json` 与 `SHA256SUMS.txt`,不传展开应用。所有构建和独立制品验收成功后才写正式版本目录和公开索引;桌面与镜像都发布成功后只回收该演练前缀。失败候选保留供重试,不覆盖已有公开版本。-暂存对象位于 `_ci/<项目 ID>/<流水线 ID>/<提交 SHA>/<产物组>/<作业 ID>/`,纳入同一桶的容量预算。每次重试使用自己的作业 ID,构建时间等元数据变化不会覆盖其他尝试的文件。下载任务先核对清单的版本、提交和流水线身份,再校验每份文件的大小与 SHA-256;产物路径限定在对应构建输出目录,不接收软链接或路径穿越。macOS 仅上传两种架构的 DMG、`build-info.json` 与 `SHA256SUMS.txt`,不传递展开应用。所有构建与独立制品验收成功后,发布任务才写入正式版本目录和公开版本索引;GitLab Release 创建成功后,只回收当前流水线的暂存前缀。失败流水线保留暂存以便排障和重试,不覆盖已有公开版本。+上传期间的完成构建保存在 `CI_BUILDS_DIR/.peach-upload-resume/` 的独立身份目录。R2 部分上传失败后,同机重试核对备份大小与 SHA-256,继续传到原作业前缀;完整上传清单登记后回收本组备份。机器更换且没有完整远端清单时需重新构建,不拼接未知来源文件。Windows 轻量安装器缺少本地工具包时,先从 R2 下载当前版本的工具;连接失败或内容校验失败时,尝试 GitHub 的同版本文件。两个来源均须匹配安装器内置清单的大小与 SHA-256,不能混用其他版本。发布完成后,用 `scripts/smoke_split_update.py` 的 `--prepare-with-app --online` 在空缓存中运行实际制品,核对联网取得的工具能否重建完整程序。GitLab Release 的下载表使用 R2,资产区另列 GitGud 副本,文档链接指向对应版本标签。@@ -105,7 +109,7 @@ Windows 轻量安装器缺少本地工具包时,先从 R2 下载当前版本R2 公网下载流量免费,存储与请求按账户共享额度计费。预算告警只通知,不会停止服务;R2 后端不提供零费用硬封顶。要求绝不产生按量费用的部署应使用不绑定按量计费的下载服务,不启用 R2 自动发布。-上传前列举本桶现有文件并计算新增制品的总容量;默认超过 8 GB 时停止上传,保留已有文件。`PEACH_R2_MAX_BYTES` 可明确调整该桶预算;此检查不能限制同账户其他桶,也不代替请求量计费保护。版本文件设置长期缓存,公开版本索引只缓存一分钟。+演练入口读取本桶真实占用和暂存范围,构建清单齐备后、安装冒烟前计算暂存与公开副本的精确峰值,候选登记和上传时仍复查;默认超过 8 GB 时停止,保留已有文件。未知新版体积在构建前不视为已知容量。`PEACH_R2_MAX_BYTES` 可明确调整该桶预算;此检查不能限制同账户其他桶,也不代替请求量计费保护。版本文件设置长期缓存,公开版本索引只缓存一分钟。Mac 与 Windows 托盘的首层只显示简短状态与提醒数量,展开状态子菜单按行查看服务和媒体来源。长地址与路径会缩略,子菜单中的「查看完整配置」保留完整设置入口;提醒消失后会随下一轮健康检查更新。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 22cbf3cf4..f0e496c10 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -106,6 +106,8 @@ Windows 构建路径解析复用 PowerShell 7 的原生 [`GetUnresolvedProviderPGitLab API、CI 认证和 Release 创建复用官方 [glab 1.124.0](https://gitlab.com/gitlab-org/cli)(MIT,维护中);GitLab CI 的发布写入使用短期 `CI_JOB_TOKEN` 与官方 CI 自动登录。R2 的 S3 上传复用 [rclone 1.75.2](https://rclone.org/)(MIT,维护中),使用单桶对象读写凭据;版本文件不可覆盖,并由独立 HTTPS 下载校验 SHA-256。两者都是构建期 CLI,不进入应用运行时依赖。+演练产物晋级复用上述传输和 GitLab 作业 API;GitHub 通过官方 [Artifacts REST API](https://docs.github.com/en/rest/actions/artifacts)读取服务端摘要,再由标准库 `urllib.request`、`hashlib` 和 `zipfile` 下载、核验与展开。Peach 负责同一提交、版本、平台和验证任务的身份契约,以及已验收镜像的 image ID。媒体缓存沿用固定源码构建器,缓存二进制与对应源码,按实际构建输入和工具链核对,不新增缓存 SDK。协议与回收边界见 [ADR-0127](adr/0127-verified-release-artifact-promotion.md)。+GitGud 双存储副本复用同一版 glab 的原生 `packages upload` 与官方 [Packages API](https://docs.gitlab.com/api/packages/),不另写认证或上传协议。Peach 只核对版本、文件名、大小与 `file_sha256`,复用相同内容并拒绝覆盖冲突;登记未完成最多检查三次。R2 下载表与 GitGud 备用资产链接使用不同的 Release 路径。未新增运行时依赖,离线回归覆盖首次上传、重复执行、内容冲突、未登记终止与双来源链接。轻量安装器的 R2 优先与 GitHub 同版本回退复用 `standalone_update.download`、既有 HTTPX 和内置工具清单;每个来源分别验证大小与 SHA-256。发布后空缓存验收复用 `smoke_split_update.py` 与实际冻结程序的 `--installer-tools` 入口,不新增下载器或依赖。diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 4dafdd9aa..197144036 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -98,9 +98,9 @@ PR 计划按改动选择前端、vendor、wheel 与浏览器任务,文档 PRPython 分片上传完整测试输出;浏览器分片上传 TAP、服务日志及已脱敏网络日志,保留 14 天。npm 审计遇到 high 或 critical 漏洞直接失败;只有临时网络错误最多请求三次,在前两次失败后分别等待 15 与 30 秒,未知响应不当成通过。-GitGud 流水线(`.gitlab-ci.yml`)的 `verify-linux`、`verify-windows`、`verify-macos` 在分支与合并请求上跑改动域加本平台的平台敏感用例:基线是最近一条成功的主线流水线里、作为本提交祖先的那个提交,由 `scripts/ci_scope.py` 判定;先用正式入口跑 `auto --base <基线>`,选域与退回全量的规则同本机 `auto`,再用 `-Focus` 跑 `PLATFORM_TESTS` 里本平台的用例。取不到基线(首次推送、强推、接口不可达)、改了 `.gitlab-ci.yml` 本身,或改动落到必须全量的面时只跑一次全量。版本提交(`chore(release): 版本 X`)的主线流水线是发布演练:演练规则把三个平台的验收改成全量,媒体、构建、冒烟与镜像也都跑,只是不发布;`--ship` 等它全部通过才打标签,标签流水线只构建和发布([ADR-0121](adr/0121-release-rehearsal-and-atomic-publication.md))。口径与平台集合的理由见 [ADR-0119](adr/0119-mainline-changed-scope-release-full-suite.md)。+GitGud 流水线(`.gitlab-ci.yml`)的 `verify-linux`、`verify-windows`、`verify-macos` 在分支与合并请求上跑改动域加本平台的平台敏感用例:基线是最近一条成功的主线流水线里、作为本提交祖先的那个提交,由 `scripts/ci_scope.py` 判定;先用正式入口跑 `auto --base <基线>`,选域与退回全量的规则同本机 `auto`,再用 `-Focus` 跑 `PLATFORM_TESTS` 里本平台的用例。取不到基线(首次推送、强推、接口不可达)、改了 `.gitlab-ci.yml` 本身,或改动落到必须全量的面时只跑一次全量。版本提交(`chore(release): 版本 X`)的主线流水线是发布演练:三平台全量、媒体构建、桌面安装升级与镜像验收都成功后登记候选;`--ship` 等演练成功才打标签。标签核对同一提交、验证任务和产物 SHA-256,发布已验收的相同文件与镜像,不重新构建。候选身份、保留与回收见 [ADR-0127](adr/0127-verified-release-artifact-promotion.md),全量范围见 [ADR-0119](adr/0119-mainline-changed-scope-release-full-suite.md)。-Release 在媒体工具编译前核对同 SHA 主线 CI,缓存键绑定媒体工具源码清单与构建脚本,缓存内容同时含二进制和对应源码包;制品与独立开箱验收仍是发布前置。Docker 只在镜像相关主线改动、匹配 PR、版本标签或手动请求时运行,验收后推送同一个本地镜像。版本发布与覆盖升级验收不取消进行中的同目标运行;覆盖升级需明确选择目标版本及完整构建提交。+演练先读取发布桶真实占用,媒体编译可与正式回归并行;构建清单齐备后在安装冒烟前核对包含暂存与公开副本的精确峰值,候选登记与正式上传仍复查。媒体缓存身份绑定固定源码、构建脚本、工具链、平台与架构,二进制和对应源码均逐文件校验;缓存不代替独立制品验收。Docker 发布核对演练记录的 image ID、提交与版本,在桌面包和 Release 就绪后推送。版本发布与覆盖升级验收不取消进行中的同目标运行;覆盖升级需明确选择目标版本及完整构建提交。浏览器用例覆盖 `frontend/e2e` 下全部 `*.test.ts`,包括子目录。`setup.test.ts` 由 `SetupE2ETests` 在首次设置服务上执行,其余文件在已配置的演示库服务上按文件并发、文件内串行。并发数取 `PEACH_E2E_CONCURRENCY`;未设时本机取逻辑核数的四分之一、上限 4,CI(`GITHUB_ACTIONS=true`)为 1。每个文件单独起一次 Node,限时 600 秒,取得自己的完整 TAP;空出的通道马上领下一个文件,没有批与批之间的等待。并发时文件按 `scripts/ci-browser-timings.json` 的实测秒数先长后短排队(没测过的按 30 秒算),测量动画、密度切换与等待态替换的文件(`tests/test_web_e2e.py` 的 `TIMING_SENSITIVE_SUITES`)在并发文件全部结束后逐个串行;并发为 1 时按设计决定、交互回归和路由冒烟的顺序逐个执行。任一文件失败或超时,整轮验证失败。并发的文件共用一个服务和演示库:用例触发的写请求只能落在别的用例不断言的状态上,否则用 `page.route` 拦下或归进时序敏感的串行文件。控制台在每个文件结束时输出成败与耗时;每个文件的 TAP 日志 `e2e-<文件名>.tap`、首启的 `setup.tap` 与服务访问日志 `serve.log` 保存在 `build/agent-verification/browser/`,CI 在测试结束后上传其中的 TAP 日志。diff --git a/docs/adr/0121-release-rehearsal-and-atomic-publication.md b/docs/adr/0121-release-rehearsal-and-atomic-publication.mdindex 7ad47bffc..4b6056adb 100644--- a/docs/adr/0121-release-rehearsal-and-atomic-publication.md+++ b/docs/adr/0121-release-rehearsal-and-atomic-publication.md@@ -1,6 +1,7 @@# ADR-0121:版本提交先演练,标签只负责发布且全有或全无- 状态:已采纳+- 后续决策:产物晋级、传输续跑与回收方式见 [ADR-0127](0127-verified-release-artifact-promotion.md)。- 日期:2026-10-24- 关系:修订 [ADR-0119](0119-mainline-changed-scope-release-full-suite.md) 第四条「版本标签流水线:三平台全量是发布门槛」;补充 [ADR-0012](0012-version-and-update-boundary.md) 的发布边界diff --git a/docs/adr/0127-verified-release-artifact-promotion.md b/docs/adr/0127-verified-release-artifact-promotion.mdnew file mode 100644index 000000000..10a1614db--- /dev/null+++ b/docs/adr/0127-verified-release-artifact-promotion.md@@ -0,0 +1,35 @@+# ADR-0127:从成功演练晋级发行产物++- 状态:已采纳+- 日期:2026-10-26+- 关系:修订 [ADR-0121](0121-release-rehearsal-and-atomic-publication.md) 的标签重新构建与演练回收方式++## 背景++演练和标签分别构建时,标签仍会遇到源码下载与上传故障。已经构建成功的文件也可能因最后的清单上传失败而需要重建。重复媒体编译、打包和安装验收增加发布时间,两个流水线分别暂存还会增加发布桶峰值。++## 决策++版本提交仍执行三平台正式回归、媒体编译、桌面制品安装与升级验收、Docker 冒烟。演练全部成功才允许创建标签。标签核对同一提交后晋级已验收产物,不重新构建,也不删减演练中的验证。++GitLab 的产物按项目、流水线、完整提交、版本和生成作业隔离。每组文件完整上传后,在同一暂存前缀登记不可变完成清单;文件大小、SHA-256、路径与来源身份同时受检。作业重试可以恢复该流水线已经完整上传的文件,网络失败与尚无完成清单分别处理。`seal-release` 在全部必需任务成功后登记候选清单。标签必须核对最新成功演练的任务标识、候选来源和文件摘要,缺失、过期或身份不符时停止。++R2 上传前,把完成构建的字节和清单保存在 `CI_BUILDS_DIR/.peach-upload-resume/` 的同项目、流水线、提交与产物组目录。传输失败后优先核对这份备份并续传到原生成作业前缀,不重新构建;远端完成清单登记成功后删除本组备份。备份缺失、机器已更换或文件校验失败时分别报告,不把网络失败当作没有构建结果。++GitHub 从相同提交、主线推送触发的成功 Release 演练读取产物。必需的构建和制品验收任务须成功,产物须未过期且具有服务端 SHA-256;下载后核对摘要再展开。镜像保存为演练产物,发布前核对加载后的 image ID、版本与提交。REST 请求使用 CI 提供的短期令牌,跨主机下载重定向移除认证头。++GitLab 的 Docker 候选镜像保留在完成演练的 Windows runner,清单记录 image ID。发布必须取得同一个镜像及对应提交、版本,镜像丢失或被替换时停止,重新执行演练。桌面文件与 GitGud Release 就绪后才推版本镜像和 `edge`,发布顺序沿用 ADR-0121。++## 容量、缓存与回收++构建前读取发布桶真实占用并列出暂存范围;构建清单齐备后、Windows 安装冒烟前计算包含暂存和公开版本副本的精确峰值。候选登记与正式上传仍复查预算,不把尚未构建的版本大小当作已知值。清理历史暂存和调整预算仍需独立审阅,不自动删除既有公开版本。++演练候选保留到桌面与镜像发布全部成功。最终回收任务核对公开版本索引和同一成功演练,只删除该演练暂存前缀。发布失败保留候选,以便重试传输阶段。++媒体工具缓存包含二进制、许可证和对应源码包。缓存身份覆盖固定源码清单、构建脚本、平台、架构、部署目标和工具链,命中后逐文件核对 SHA-256;缺文件、内容损坏或输入改变时重建。缓存不是发布成功证明,应用和镜像的独立验收照常执行。++## 边界++本决策不改变终端用户数据库、数据目录、更新清单或安装协议。现有安装通过原有升级路径取得发行文件。网络出口和账号托管不在本决策中更改。++演练产物过期、受保护凭据不可用或候选镜像丢失时,不临时拼接其他流水线文件,也不放宽摘要检查。应重新完成同一版本提交的演练,再发布其完整产物。diff --git a/scripts/ci_macos.sh b/scripts/ci_macos.shindex 160ad3d5d..8ffe0c269 100644--- a/scripts/ci_macos.sh+++ b/scripts/ci_macos.sh@@ -92,8 +92,7 @@ output="${PEACH_MACOS_OUTPUT_DIR:-$root/dist/macos.noindex/$architecture}""$python" scripts/setup_macos_media_tools.py --root "$root/build/macos-media-toolchain"export PATH="$root/build/macos-media-toolchain/env/bin:$PATH"for tool in ffmpeg untrunc; do- "$python" scripts/build_macos_media.py --tool "$tool" --arch "$architecture" \- --output "$root/build/media-macos/$architecture/$tool"+ "$python" scripts/media_build_cache.py macos --tool "$tool" --arch "$architecture"done"$python" scripts/fetch_cloudflared_macos.py --arch "$architecture" \--destination "$root/build/media-macos/$architecture/cloudflared"diff --git a/scripts/ci_r2_artifacts.py b/scripts/ci_r2_artifacts.pyindex 668076a81..fbcde0e23 100644--- a/scripts/ci_r2_artifacts.py+++ b/scripts/ci_r2_artifacts.py@@ -1,4 +1,4 @@-"""通过 R2 传递同一流水线的大产物,GitLab 只保存带 SHA-256 的清单。"""+"""通过 R2 传递演练大产物并晋级至标签,GitLab 只保存带 SHA-256 的清单。"""from __future__ import annotationsimport argparse@@ -22,6 +22,7 @@ GROUPS = {"build/untrunc-windows/untrunc", "build/untrunc-windows/untrunc-corresponding-source.zip"),"windows-release": ("release",),"macos-release": ("dist/macos.noindex/arm64", "dist/macos.noindex/x86_64"),+ "docker-release": ("build/ci-artifacts/docker-image.json",),}@@ -69,6 +70,8 @@ def allowed_path(name: str, group: str) -> bool:or parts[-1] in {"ffmpeg-corresponding-source.zip", "untrunc-corresponding-source.zip","RELEASE_NOTES.md", "DOWNLOADS.md", "version.txt", "ci_windows.ps1","smoke_desktop.py", "smoke_update_tasks.py", "smoke_split_update.py"})+ if group == "docker-release":+ return name == "build/ci-artifacts/docker-image.json"return any(name == base or name.startswith(base + "/") for base in GROUPS[group])@@ -156,14 +159,122 @@ def validate_manifest(manifest: dict, group: str, build: dict) -> list[dict]:return items-def transfer(root: Path, group: str, mode: str) -> dict:- root = root.resolve(strict=True)+def checkpoint(build: dict, group: str) -> str:+ if group not in GROUPS:+ raise ValueError("未知的产物组")+ return prefix(build) + "/completed/" + group + ".json"+++def upload_backup(root: Path, build: dict, group: str) -> Path | None:+ value = os.environ.get("CI_BUILDS_DIR")+ if not value:+ return None+ if group not in GROUPS or any(not re.fullmatch(r"[1-9][0-9]*", build[key]) for key in ("project", "pipeline")):+ raise ValueError("无效的构建续传身份")+ base = Path(value).resolve() / ".peach-upload-resume"+ path = base / build["project"] / build["pipeline"] / build["commit"] / group+ if not path.resolve().is_relative_to(base.resolve()) or path.resolve().is_relative_to(root.resolve()):+ raise ValueError("续传目录必须位于 CI 构建根的独立命名空间")+ if path.is_symlink() or any(parent.is_symlink() for parent in path.parents if parent.is_relative_to(base)):+ raise ValueError("续传目录不能包含软链接")+ return path+++def preserve_upload(root: Path, manifest: dict) -> None:+ group, build = manifest["group"], manifest["identity"]+ destination = upload_backup(root, build, group)+ if destination is None:+ return+ destination.mkdir(parents=True, exist_ok=True)+ for item in manifest["files"]:+ source = local_path(root, item["path"], group)+ target = local_path(destination, item["path"], group)+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(source, target)+ temporary = destination / "upload.json.tmp"+ temporary.write_text(json.dumps(manifest, sort_keys=True, indent=2) + "\n", encoding="utf-8")+ temporary.replace(destination / "upload.json")+++def discard_upload(root: Path, build: dict, group: str) -> None:+ path = upload_backup(root, build, group)+ if path is not None and path.exists():+ shutil.rmtree(path)+++def remote_json(root: Path, key: str, payload: dict | None = None) -> dict | None:+ """只在受保护 CI 的暂存命名空间读取或登记完整对象;网络失败不当作不存在。"""+ if not re.fullmatch(r"_ci/[1-9][0-9]*/[1-9][0-9]*/[0-9a-f]{40}/(?:completed/[a-z-]+|release-candidate)\.json", key):+ raise ValueError("无效的 CI 元数据路径")+ environment = rclone_environment()+ executable = rclone_executable(root.resolve(strict=True))+ bucket = f"peach:{environment['PEACH_R2_BUCKET']}"+ with tempfile.TemporaryDirectory(prefix="peach-ci-metadata-") as directory:+ temporary = Path(directory)+ configuration = temporary / "rclone.conf"+ configuration.touch()+ common = {"env": environment, "text": True, "encoding": "utf-8"}+ if payload is None:+ listing = json.loads(subprocess.check_output([executable, "lsjson", bucket, "--recursive", "--files-only",+ "--config", str(configuration)], **common))+ if not any(row["Path"] == key for row in listing):+ return None+ return json.loads(subprocess.check_output([executable, "cat", bucket + "/" + key,+ "--config", str(configuration)], **common))+ source = temporary / "metadata.json"+ source.write_text(json.dumps(payload, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8")+ subprocess.run([executable, "copyto", str(source), bucket + "/" + key,+ "--checksum", "--immutable", "--config", str(configuration)], env=environment, check=True)+ return payload+++def restore(root: Path, group: str) -> dict:+ """恢复同一受保护提交与流水线已完整上传的构建,供失败作业重试复用。"""build = identity()+ manifest = remote_json(root, checkpoint(build, group))+ result = {"restored": manifest is not None, "uploaded": manifest is not None, "group": group}+ destination = root / "build/ci-artifacts"+ destination.mkdir(parents=True, exist_ok=True)+ if manifest is not None:+ validate_manifest(manifest, group, build)+ (destination / (group + ".json")).write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")+ result.update(transfer(root, group, "pull"))+ discard_upload(root, build, group)+ else:+ backup = upload_backup(root, build, group)+ if backup is not None and (backup / "upload.json").is_file():+ manifest = json.loads((backup / "upload.json").read_text(encoding="utf-8"))+ items = validate_manifest(manifest, group, build)+ for item in items:+ path = local_path(backup, item["path"], group)+ if not path.is_file() or path.stat().st_size != item["size"] or checksum(path) != item["sha256"]:+ raise ValueError("本机续传文件的大小或 SHA-256 不符")+ for item in items:+ target = local_path(root, item["path"], group)+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(local_path(backup, item["path"], group), target)+ (destination / (group + ".json")).write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")+ result["restored"] = True+ (destination / (group + "-resume.json")).write_text(json.dumps(result) + "\n", encoding="utf-8")+ return result+++def transfer(root: Path, group: str, mode: str, *, source: dict | None = None) -> dict:+ root = root.resolve(strict=True)+ current = identity()+ build = current if source is None else source+ if source is not None and (mode != "pull" or any(build[key] != current[key] for key in ("project", "commit", "tag"))):+ raise ValueError("晋级产物必须属于同一项目、版本与提交")environment = rclone_environment()executable = rclone_executable(root)manifest_path = root / "build/ci-artifacts" / (group + ".json")if mode == "push":producer_job = os.environ.get("CI_JOB_ID", "")+ if manifest_path.exists():+ previous = json.loads(manifest_path.read_text(encoding="utf-8"))+ validate_manifest(previous, group, build)+ if previous["files"] == inventory(root, group):+ producer_job = previous["producer_job"]else:manifest = json.loads(manifest_path.read_text(encoding="utf-8"))items = validate_manifest(manifest, group, build)@@ -187,15 +298,18 @@ def transfer(root: Path, group: str, mode: str) -> dict:if actual != build["commit"] or dirty:raise ValueError("暂存需要当前提交的干净构建目录")items = inventory(root, group)+ manifest = {"format": 1, "identity": build, "group": group, "producer_job": producer_job, "files": items}+ preserve_upload(root, manifest)existing = json.loads(command("lsjson", f"peach:{environment['PEACH_R2_BUCKET']}", "--recursive", "--files-only", read=True))require_capacity(existing, [{"name": item["path"], "size": item["size"]} for item in items],storage_prefix, int(environment.get("PEACH_R2_MAX_BYTES", "8000000000")))listing = temporary / "files.txt"listing.write_text("".join(item["path"] + "\n" for item in items), encoding="utf-8")command("copy", str(root), remote, "--files-from-raw", str(listing), "--checksum", "--immutable")- manifest = {"format": 1, "identity": build, "group": group, "producer_job": producer_job, "files": items}manifest_path.parent.mkdir(parents=True, exist_ok=True)manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")+ remote_json(root, checkpoint(build, group), manifest)+ discard_upload(root, build, group)else:for item in items:local_path(root, item["path"], group)@@ -213,12 +327,12 @@ def transfer(root: Path, group: str, mode: str) -> dict:return {"group": group, "mode": mode, "files": len(items), "bytes": sum(item["size"] for item in items), "commit": build["commit"]}-def cleanup(root: Path) -> dict:- """公开发布成功后只回收当前流水线的暂存前缀。-- 发布演练(ADR-0121)从不发布,暂存只是验收用的草稿,演练跑完直接回收。- """- build = identity()+def cleanup(root: Path, *, source: dict | None = None) -> dict:+ """回收指定流水线的暂存前缀;晋级入口在全部发布成功后选择来源演练。"""+ current = identity()+ build = current if source is None else source+ if source is not None and any(build[key] != current[key] for key in ("project", "commit", "tag")):+ raise ValueError("回收范围必须属于同一项目、版本与提交")rehearsal = os.environ.get("PEACH_RELEASE_REHEARSAL") == "1" and not os.environ.get("CI_COMMIT_TAG")environment = rclone_environment()executable = rclone_executable(root.resolve(strict=True))@@ -239,12 +353,13 @@ def cleanup(root: Path) -> dict:def main() -> None:parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("mode", choices=("push", "pull", "cleanup"))+ parser.add_argument("mode", choices=("push", "pull", "restore", "cleanup"))parser.add_argument("group", nargs="?", choices=tuple(GROUPS))args = parser.parse_args()if args.mode != "cleanup" and not args.group:parser.error("上传和下载须指定产物组")- result = cleanup(Path.cwd()) if args.mode == "cleanup" else transfer(Path.cwd(), args.group, args.mode)+ result = (cleanup(Path.cwd()) if args.mode == "cleanup" else restore(Path.cwd(), args.group)+ if args.mode == "restore" else transfer(Path.cwd(), args.group, args.mode))print(json.dumps(result, ensure_ascii=False))diff --git a/scripts/ci_windows.ps1 b/scripts/ci_windows.ps1index 184a3c2c4..b66afb2d6 100644--- a/scripts/ci_windows.ps1+++ b/scripts/ci_windows.ps1@@ -82,12 +82,25 @@ if ($Mode -eq 'docker-build' -or $Mode -eq 'docker-push') {Assert-ReleaseRef $Version$Endpoint = (docker context inspect --format '{{.Endpoints.docker.Host}}')Assert-Exit '需要运行 Docker Desktop'- $Candidate = "peach-ci:$Version-$env:CI_PIPELINE_ID"+ $SourcePipeline = $env:CI_PIPELINE_ID+ if ($Mode -eq 'docker-push') {+ $CandidateReceipt = Get-Content -LiteralPath build/ci-artifacts/release-candidate.json -Raw -Encoding utf8 | ConvertFrom-Json+ if ($CandidateReceipt.target.pipeline -ne $env:CI_PIPELINE_ID -or $CandidateReceipt.target.commit -ne $env:CI_COMMIT_SHA) { throw '镜像晋级回执不属于当前发布' }+ $SourcePipeline = $CandidateReceipt.candidate.identity.pipeline+ }+ $Candidate = "peach-ci:$Version-$SourcePipeline"}if ($Mode -eq 'docker-build') {$Revision = (git rev-parse HEAD).Trim()Assert-Exit '无法读取提交'+ if ((Test-Path -LiteralPath build/ci-artifacts/docker-release-resume.json) -and (Get-Content -LiteralPath build/ci-artifacts/docker-release-resume.json -Raw | ConvertFrom-Json).restored) {+ $Verified = Get-Content -LiteralPath build/ci-artifacts/docker-image.json -Raw -Encoding utf8 | ConvertFrom-Json+ $Existing = docker image inspect --format '{{json .}}' $Candidate | ConvertFrom-Json+ Assert-Exit '已登记的候选镜像不在本机,请重新执行演练'+ if ($Existing.Id -ne $Verified.image_id -or $Existing.Config.Labels.'org.opencontainers.image.revision' -ne $Revision -or $Existing.Config.Labels.'org.opencontainers.image.version' -ne $Version) { throw '本机候选镜像与验收回执不一致' }+ exit 0+ }docker build --pull --label "org.opencontainers.image.version=$Version" --label "org.opencontainers.image.revision=$Revision" `--build-arg PEACH_SENTRY_DSN --build-arg PEACH_LIBRARY_SENTRY_DSN --build-arg PEACH_REQUIRE_REPORTING=1 -t $Candidate .Assert-Exit '镜像构建失败'@@ -100,8 +113,10 @@ if ($Mode -eq 'docker-build') {docker image rm $Candidate | Out-Nullthrow}- # 演练不推送,验收完就删;标签流水线留给 publish-docker 推送后再删。- if ($env:PEACH_RELEASE_REHEARSAL -eq '1') { docker image rm $Candidate | Out-Null }+ $ImageId = (docker image inspect --format '{{.Id}}' $Candidate).Trim()+ Assert-Exit '无法读取已验收镜像摘要'+ New-Item -ItemType Directory -Path build/ci-artifacts -Force | Out-Null+ @{image=$Candidate; image_id=$ImageId; version=$Version; commit=$Revision; pipeline=$env:CI_PIPELINE_ID} | ConvertTo-Json | Set-Content -LiteralPath build/ci-artifacts/docker-image.json -Encoding utf8exit 0}@@ -109,6 +124,9 @@ if ($Mode -eq 'docker-push') {if (-not $env:DOCKERHUB_USERNAME -or -not $env:DOCKERHUB_TOKEN) { throw '缺少 Docker Hub 发布变量' }docker image inspect $Candidate | Out-NullAssert-Exit "本机没有 docker-build 验收过的 $Candidate;重试 docker-build 后再推送"+ $ActualImage = (docker image inspect --format '{{json .}}' $Candidate | ConvertFrom-Json)+ Assert-Exit '无法读取候选镜像身份'+ if ($ActualImage.Id -ne $CandidateReceipt.candidate.docker.image_id -or $ActualImage.Config.Labels.'org.opencontainers.image.revision' -ne $env:CI_COMMIT_SHA -or $ActualImage.Config.Labels.'org.opencontainers.image.version' -ne $Version) { throw '候选镜像与已验收的摘要、提交或版本不一致' }# 登录写进作业专用配置目录,不改动宿主用户的 Docker 登录。$SavedConfig, $SavedHost = $env:DOCKER_CONFIG, $env:DOCKER_HOST$env:DOCKER_HOST = $Endpoint@@ -127,8 +145,8 @@ if ($Mode -eq 'docker-push') {docker logout | Out-NullRemove-Item -LiteralPath $env:DOCKER_CONFIG -Recurse -Force -ErrorAction SilentlyContinue$env:DOCKER_CONFIG, $env:DOCKER_HOST = $SavedConfig, $SavedHost- docker image rm $Candidate | Out-Null}+ docker image rm $Candidate | Out-Nullexit 0}diff --git a/scripts/github_release_candidate.py b/scripts/github_release_candidate.pynew file mode 100644index 000000000..87773832d--- /dev/null+++ b/scripts/github_release_candidate.py@@ -0,0 +1,141 @@+"""GitHub CI 通过官方 REST 接口晋级同一提交的已验收产物,不调用 CLI。"""+from __future__ import annotations++import argparse+import hashlib+import json+import os+from pathlib import Path, PurePosixPath+import re+import shutil+import subprocess+import tempfile+from urllib.parse import urlsplit+from urllib.request import HTTPRedirectHandler, Request, build_opener+import zipfile++REQUIRED_ARTIFACTS = {"desktop-candidate", "macos-candidate-arm64", "macos-candidate-x86_64", "docker-candidate"}+REQUIRED_JOBS = {"Windows x64 独立测试包", "仅下载制品验收", "Linux amd64 镜像构建与验收",+ "macOS arm64 独立测试包", "macOS x86_64 独立测试包",+ "macOS arm64 仅下载制品验收", "macOS x86_64 仅下载制品验收"}+++class ArtifactRedirect(HTTPRedirectHandler):+ def redirect_request(self, request, file, code, message, headers, url):+ if urlsplit(url).scheme != "https":+ raise ValueError("GitHub 产物重定向必须使用 HTTPS")+ redirected = super().redirect_request(request, file, code, message, headers, url)+ if redirected is not None and urlsplit(url).hostname != "api.github.com":+ redirected.remove_header("Authorization")+ return redirected+++def request(repo: str, endpoint: str):+ headers = {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "Peach-release"}+ token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")+ if os.environ.get("GITHUB_ACTIONS") == "true" and token:+ headers["Authorization"] = "Bearer " + token+ return build_opener(ArtifactRedirect()).open(Request(f"https://api.github.com/repos/{repo}/{endpoint}", headers=headers), timeout=60)+++def api(repo: str, endpoint: str):+ with request(repo, endpoint) as response:+ return json.load(response)+++def select(repo: str, sha: str) -> dict:+ if not re.fullmatch(r"[0-9a-f]{40}", sha) or not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repo):+ raise ValueError("GitHub 晋级需要明确仓库与完整提交")+ runs = api(repo, f"actions/workflows/release.yml/runs?head_sha={sha}&event=push&per_page=100")["workflow_runs"]+ matching = [row for row in runs if row["head_sha"] == sha and row["head_branch"] == "master" and row["event"] == "push"]+ if not matching:+ raise ValueError("未取得同一提交的主线发布演练")+ run = max(matching, key=lambda row: (row["id"], row.get("run_attempt", 1)))+ if run["status"] != "completed" or run["conclusion"] != "success":+ raise ValueError("主线发布演练尚未成功")+ jobs = api(repo, f"actions/runs/{run['id']}/jobs?per_page=100")["jobs"]+ passed = {row["name"] for row in jobs if row["conclusion"] == "success"}+ if not REQUIRED_JOBS <= passed:+ raise ValueError("演练缺少必需的构建或独立制品验收")+ artifacts = api(repo, f"actions/runs/{run['id']}/artifacts?per_page=100")["artifacts"]+ selected = {row["name"]: row for row in artifacts if row["name"] in REQUIRED_ARTIFACTS and not row["expired"]}+ if set(selected) != REQUIRED_ARTIFACTS or any(not re.fullmatch(r"sha256:[0-9a-f]{64}", str(row.get("digest", ""))) for row in selected.values()):+ raise ValueError("候选产物已过期、缺失或缺少摘要;重新执行演练")+ return {"run_id": run["id"], "commit": sha, "artifacts": selected}+++def extract(package: Path, destination: Path) -> None:+ with zipfile.ZipFile(package) as archive:+ for info in archive.infolist():+ parts = PurePosixPath(info.filename).parts+ if (not parts or ".." in parts or "\\" in info.filename or ":" in info.filename+ or PurePosixPath(info.filename).is_absolute() or (info.external_attr >> 16) & 0o170000 == 0o120000):+ raise ValueError("候选 ZIP 包含无效路径")+ target = destination.joinpath(*parts)+ if not target.resolve().is_relative_to(destination.resolve()):+ raise ValueError("候选 ZIP 路径越出目标")+ if info.is_dir():+ target.mkdir(parents=True, exist_ok=True)+ continue+ target.parent.mkdir(parents=True, exist_ok=True)+ if target.exists():+ with archive.open(info) as source, target.open("rb") as current:+ if hashlib.file_digest(source, "sha256").digest() != hashlib.file_digest(current, "sha256").digest():+ raise ValueError("候选文件同名但内容不同")+ continue+ with archive.open(info) as source, target.open("xb") as stream:+ shutil.copyfileobj(source, stream)+++def download(repo: str, sha: str, group: str, destination: Path) -> dict:+ receipt = select(repo, sha)+ names = {"desktop": {"desktop-candidate"}, "macos": {"macos-candidate-arm64", "macos-candidate-x86_64"},+ "docker": {"docker-candidate"}}[group]+ destination.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(prefix="peach-candidate-") as directory:+ for name in sorted(names):+ row = receipt["artifacts"][name]+ package = Path(directory) / (name + ".zip")+ with request(repo, f"actions/artifacts/{row['id']}/zip") as response, package.open("wb") as stream:+ shutil.copyfileobj(response, stream)+ with package.open("rb") as stream:+ actual = "sha256:" + hashlib.file_digest(stream, "sha256").hexdigest()+ if actual != row["digest"]:+ raise ValueError("下载产物与演练的 SHA-256 不一致")+ extract(package, destination)+ return {"promoted": True, "run_id": receipt["run_id"], "commit": sha, "group": group}+++def image_receipt(destination: Path, version: str, *, verify: bool) -> dict:+ actual = json.loads(subprocess.check_output(["docker", "image", "inspect", "--format", "{{json .}}",+ "longmeidao/peach:candidate"], text=True, encoding="utf-8"))+ labels = actual.get("Config", {}).get("Labels", {})+ sha = os.environ["GITHUB_SHA"]+ if labels.get("org.opencontainers.image.revision") != sha or labels.get("org.opencontainers.image.version") != version:+ raise ValueError("镜像标签与发布提交或版本不一致")+ expected = {"image_id": actual["Id"], "commit": sha, "version": version}+ if verify:+ if json.loads(destination.read_text(encoding="utf-8")) != expected:+ raise ValueError("镜像与演练验收的摘要不一致")+ else:+ destination.write_text(json.dumps(expected, indent=2) + "\n", encoding="utf-8")+ return expected+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("group", choices=("desktop", "macos", "docker", "image-record", "image-verify"))+ parser.add_argument("--destination", required=True, type=Path)+ parser.add_argument("--version")+ args = parser.parse_args()+ if args.group.startswith("image-"):+ if not args.version:+ parser.error("镜像核验需要版本")+ result = image_receipt(args.destination, args.version, verify=args.group == "image-verify")+ else:+ result = download(os.environ["GITHUB_REPOSITORY"], os.environ["GITHUB_SHA"], args.group, args.destination)+ print(json.dumps(result))+++if __name__ == "__main__":+ main()diff --git a/scripts/media_build_cache.py b/scripts/media_build_cache.pynew file mode 100644index 000000000..dc61ae26d--- /dev/null+++ b/scripts/media_build_cache.py@@ -0,0 +1,129 @@+"""按源码、构建脚本、平台和工具链核对媒体工具缓存,包含对应源码包。"""+from __future__ import annotations++import argparse+import hashlib+import json+import os+from pathlib import Path, PurePosixPath+import platform+import shutil+import subprocess+import sys++INPUTS = ("scripts/ffmpeg-sources.json", "scripts/untrunc-sources.json", "scripts/build_ffmpeg_windows.sh",+ "scripts/build_untrunc_windows.sh", "scripts/dav1d-mingw64.ini", "scripts/build_macos_media.py",+ "scripts/fetch_ffmpeg_sources.py", "scripts/fetch_untrunc_sources.py", "scripts/setup_macos_media_tools.py",+ "scripts/media_build_cache.py", "src/peach/user_agent.py", "LICENSE")+++def digest(path: Path) -> str:+ with path.open("rb") as stream:+ return hashlib.file_digest(stream, "sha256").hexdigest()+++def input_identity(root: Path, target: str, arch: str, *, toolchain: dict | None = None) -> dict:+ if toolchain is None:+ commands = {"compiler": ["x86_64-w64-mingw32-gcc", "--version"], "cxx": ["x86_64-w64-mingw32-g++", "--version"]} if target == "windows" else {+ "compiler": ["clang", "--version"], "sdk": ["xcrun", "--show-sdk-version"]}+ commands.update({name: [name, "--version"] for name in ("meson", "ninja", "cmake", "make")})+ commands["nasm"] = ["nasm", "-v"]+ commands["clang"] = ["clang", "--version"]+ toolchain = {name: subprocess.check_output(command, text=True, encoding="utf-8").strip()+ for name, command in commands.items()}+ return {"format": 1, "target": target, "arch": arch, "host": platform.system(),+ "deployment_target": os.environ.get("MACOSX_DEPLOYMENT_TARGET", "11.0") if target == "macos" else "",+ "toolchain": toolchain, "inputs": {name: digest(root / name) for name in INPUTS}}+++def remove_owned(root: Path, path: Path) -> None:+ base = (root / "build").resolve()+ if not base.is_relative_to(root.resolve()) or path.is_symlink() or not path.resolve().is_relative_to(base) or path.resolve() == base:+ raise ValueError("媒体缓存清理路径越出构建目录")+ for parent in path.parents:+ if parent == root:+ break+ if parent.is_symlink():+ raise ValueError("媒体缓存路径包含软链接")+ if path.exists():+ shutil.rmtree(path)+++def valid(cache: Path, identity: dict, tool: str, archive: str) -> bool:+ receipt = cache / "cache.json"+ if not receipt.is_file() or receipt.is_symlink():+ return False+ try:+ data = json.loads(receipt.read_text(encoding="utf-8"))+ if data.get("identity") != identity or not isinstance(data.get("files"), dict):+ return False+ files = data["files"]+ if archive not in files or f"{tool}/manifest.json" not in files:+ return False+ actual = {path.relative_to(cache).as_posix() for path in cache.rglob("*") if path.is_file() and path != receipt}+ if actual != set(files):+ return False+ for name, checksum in files.items():+ parts = PurePosixPath(name).parts+ if (not parts or name != archive and parts[0] != tool or ".." in parts or "\\" in name+ or PurePosixPath(name).is_absolute()):+ return False+ path = cache / name+ if path.is_symlink() or any(parent.is_symlink() for parent in path.parents if parent != cache and parent.is_relative_to(cache)):+ raise ValueError("媒体缓存包含软链接")+ if digest(path) != checksum:+ return False+ return True+ except (OSError, ValueError, TypeError):+ return False+++def build(root: Path, target: str, arch: str = "x86_64", tool: str | None = None) -> dict:+ root = root.resolve(strict=True)+ identity = input_identity(root, target, arch)+ tools = ("ffmpeg", "untrunc") if tool is None else (tool,)+ hits = []+ for item in tools:+ output = root / "build" / (f"{item}-windows" if target == "windows" else f"media-macos/{arch}/{item}")+ archive = f"{item}-corresponding-source.zip" if target == "windows" else f"{item}-macos-{arch}-corresponding-source.zip"+ cache = root / f"build/media-cache/{target}-{arch}/{item}"+ if cache.is_symlink() or not cache.resolve().is_relative_to((root / "build").resolve()):+ raise ValueError("媒体缓存位置越出构建目录")+ if valid(cache, identity, item, archive):+ remove_owned(root, output)+ output.mkdir(parents=True)+ shutil.copytree(cache / item, output / item)+ shutil.copyfile(cache / archive, output / archive)+ hits.append(item)+ continue+ remove_owned(root, output)+ if target == "windows":+ command = ["bash", str(root / f"scripts/build_{item}_windows.sh"), str(output)]+ else:+ command = [sys.executable, str(root / "scripts/build_macos_media.py"), "--tool", item,+ "--arch", arch, "--output", str(output)]+ subprocess.run(command, cwd=root, check=True)+ if not (output / item / "manifest.json").is_file() or not (output / archive).is_file():+ raise ValueError("媒体构建缺少已核验工具或对应源码包")+ remove_owned(root, cache)+ cache.mkdir(parents=True)+ shutil.copytree(output / item, cache / item)+ shutil.copyfile(output / archive, cache / archive)+ files = {path.relative_to(cache).as_posix(): digest(path) for path in cache.rglob("*") if path.is_file()}+ (cache / "cache.json").write_text(json.dumps({"identity": identity, "files": files}, sort_keys=True, indent=2) + "\n", encoding="utf-8")+ return {"target": target, "arch": arch, "cache_hits": hits, "tools": list(tools)}+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("target", choices=("windows", "macos"))+ parser.add_argument("--arch", choices=("arm64", "x86_64"), default="x86_64")+ parser.add_argument("--tool", choices=("ffmpeg", "untrunc"))+ args = parser.parse_args()+ if args.target == "windows" and args.arch != "x86_64":+ parser.error("Windows 媒体工具只构建 x86_64")+ print(json.dumps(build(Path.cwd(), args.target, args.arch, args.tool)))+++if __name__ == "__main__":+ main()diff --git a/scripts/release_candidate.py b/scripts/release_candidate.pynew file mode 100644index 000000000..a0225607b--- /dev/null+++ b/scripts/release_candidate.py@@ -0,0 +1,197 @@+"""核对受保护演练的产物清单;标签发布同一份已验收字节。"""+from __future__ import annotations++import argparse+import json+import os+from pathlib import Path, PurePosixPath+import subprocess+import re+import sys+import tempfile++if not __package__:+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+ __package__ = "scripts"+from . import ci_r2_artifacts as artifacts+from .release_forge import GitLabForge, REQUIRED_TEST_JOBS, REHEARSAL_JOBS+from .release_r2 import require_capacity++GROUPS = ("windows-release", "macos-release", "docker-release")+RECEIPT = Path("build/ci-artifacts/release-candidate.json")+++def forge() -> GitLabForge:+ def command(*args):+ return subprocess.check_output(args, text=True, encoding="utf-8", stderr=subprocess.PIPE)+ return GitLabForge(os.environ["CI_SERVER_HOST"], command)+++def verified_jobs(client, repo: str, build: dict) -> dict[str, int]:+ selected = client.jobs(repo, int(build["pipeline"]))+ required = (REQUIRED_TEST_JOBS | REHEARSAL_JOBS) - {"seal-release"}+ bad = [name for name in sorted(required) if name not in selected+ or selected[name]["status"] != "success" or selected[name].get("allow_failure")+ or selected[name].get("commit", {}).get("id") != build["commit"]]+ if bad:+ raise ValueError("演练缺少同一提交的成功验证:" + "、".join(bad))+ return {name: selected[name]["id"] for name in sorted(required)}+++def listing(root: Path) -> list[dict]:+ environment = artifacts.rclone_environment()+ with tempfile.TemporaryDirectory(prefix="peach-release-capacity-") as directory:+ config = Path(directory) / "rclone.conf"+ config.touch()+ return json.loads(subprocess.check_output([artifacts.rclone_executable(root), "lsjson",+ f"peach:{environment['PEACH_R2_BUCKET']}", "--recursive", "--files-only", "--config", str(config)],+ env=environment, text=True, encoding="utf-8"))+++def manifests(root: Path, build: dict) -> dict:+ result = {}+ for group in GROUPS:+ manifest = artifacts.remote_json(root, artifacts.checkpoint(build, group))+ if manifest is None:+ raise ValueError("缺少完整上传的演练产物:" + group)+ artifacts.validate_manifest(manifest, group, build)+ result[group] = manifest+ return result+++def publication_items(groups: dict) -> list[dict]:+ result = {}+ for group in ("windows-release", "macos-release"):+ for item in groups[group]["files"]:+ path = PurePosixPath(item["path"])+ if path.suffix not in {".zip", ".exe", ".dmg"}:+ continue+ row = {"name": path.name, "size": item["size"], "sha256": item["sha256"]}+ if path.name in result and result[path.name] != row:+ raise ValueError("发行文件同名但内容不一致")+ result[path.name] = row+ return list(result.values())+++def check_capacity(root: Path, build: dict | None = None, groups: dict | None = None) -> dict:+ build = build or artifacts.identity()+ groups = groups or manifests(root, build)+ rows = listing(root)+ limit = int(os.environ.get("PEACH_R2_MAX_BYTES", "8000000000"))+ projected = require_capacity(rows, publication_items(groups), build["tag"], limit)+ return {"current_bytes": sum(row["Size"] for row in rows if not row.get("IsDir")),+ "projected_bytes": projected, "limit_bytes": limit}+++def preflight(root: Path) -> dict:+ """构建前取得真实桶占用;精确发行峰值在清单齐备后、安装冒烟前核对。"""+ artifacts.identity()+ rows = listing(root)+ limit = int(os.environ.get("PEACH_R2_MAX_BYTES", "8000000000"))+ current = sum(row["Size"] for row in rows if not row.get("IsDir"))+ if limit <= 0 or current >= limit:+ raise ValueError(f"发布桶当前占用 {current} 字节,预算 {limit};先审阅暂存清理方案")+ scopes = {}+ for row in rows:+ parts = row["Path"].split("/")+ if len(parts) >= 4 and parts[0] == "_ci":+ scope = "/".join(parts[:4])+ scopes[scope] = scopes.get(scope, 0) + row["Size"]+ return {"current_bytes": current, "limit_bytes": limit, "staging_bytes": scopes,+ "publication_peak": "构建清单齐备后精确核对;不按未知新版体积伪造剩余容量"}+++def seal(root: Path) -> dict:+ build = artifacts.identity()+ if os.environ.get("CI_COMMIT_BRANCH") != "master" or os.environ.get("CI_COMMIT_TAG"):+ raise ValueError("只有受保护主线的发布演练可以登记候选")+ client = forge()+ jobs = verified_jobs(client, os.environ["CI_PROJECT_PATH"], build)+ groups = manifests(root, build)+ capacity = check_capacity(root, build, groups)+ path = root / "build/ci-artifacts/docker-image.json"+ (root / "build/ci-artifacts").mkdir(parents=True, exist_ok=True)+ (root / "build/ci-artifacts/docker-release.json").write_text(json.dumps(groups["docker-release"]), encoding="utf-8")+ artifacts.transfer(root, "docker-release", "pull")+ docker = json.loads(path.read_text(encoding="utf-8-sig"))+ validate_docker(docker, build)+ candidate = {"format": 1, "identity": build, "jobs": jobs, "groups": groups, "docker": docker}+ artifacts.remote_json(root, artifacts.prefix(build) + "/release-candidate.json", candidate)+ return {"sealed": True, "identity": build, "capacity": capacity}+++def validate_docker(docker: dict, build: dict) -> None:+ if (docker.get("commit") != build["commit"] or docker.get("pipeline") != build["pipeline"]+ or docker.get("version") != build["tag"][1:]+ or docker.get("image") != f"peach-ci:{build['tag'][1:]}-{build['pipeline']}"+ or not re.fullmatch(r"sha256:[0-9a-f]{64}", str(docker.get("image_id", "")))):+ raise ValueError("Docker 候选镜像不属于同一提交与演练")+++def validate(root: Path) -> dict:+ target = artifacts.identity()+ if os.environ.get("CI_COMMIT_TAG") != target["tag"]:+ raise ValueError("候选晋级只接受受保护版本标签")+ client, repo = forge(), os.environ["CI_PROJECT_PATH"]+ runs = client.test_runs(repo, target["commit"])+ if not runs or runs[0]["status"] != "completed" or runs[0]["conclusion"] != "success":+ raise ValueError("同一提交的主线发布演练尚未成功")+ source = {**target, "pipeline": str(runs[0]["id"])}+ client.require_rehearsal(repo, int(source["pipeline"]))+ candidate = artifacts.remote_json(root, artifacts.prefix(source) + "/release-candidate.json")+ if not isinstance(candidate, dict) or candidate.get("format") != 1 or candidate.get("identity") != source:+ raise ValueError("候选清单不属于当前项目、提交、版本与演练")+ if candidate.get("jobs") != verified_jobs(client, repo, source) or set(candidate.get("groups", {})) != set(GROUPS):+ raise ValueError("候选的验证记录与演练最新成功任务不一致")+ for group, manifest in candidate["groups"].items():+ artifacts.validate_manifest(manifest, group, source)+ validate_docker(candidate.get("docker", {}), source)+ receipt = {"target": target, "candidate": candidate}+ path = root / RECEIPT+ if path.exists() and json.loads(path.read_text(encoding="utf-8")) != receipt:+ raise ValueError("本标签已选择另一份候选,保留原回执并停止")+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")+ return receipt+++def pull(root: Path) -> dict:+ receipt = validate(root)+ candidate = receipt["candidate"]+ for group in GROUPS:+ manifest = candidate["groups"][group]+ path = root / "build/ci-artifacts" / (group + ".json")+ path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")+ artifacts.transfer(root, group, "pull", source=candidate["identity"])+ return {"promoted": True, "source_pipeline": candidate["identity"]["pipeline"], "commit": candidate["identity"]["commit"]}+++def cleanup(root: Path) -> dict:+ receipt = json.loads((root / RECEIPT).read_text(encoding="utf-8"))+ target = artifacts.identity()+ if receipt.get("target") != target:+ raise ValueError("回收回执不属于当前标签流水线")+ client, repo = forge(), os.environ["CI_PROJECT_PATH"]+ runs = client.test_runs(repo, target["commit"])+ if not runs or runs[0]["status"] != "completed" or runs[0]["conclusion"] != "success":+ raise ValueError("回收前未取得成功演练")+ source = {**target, "pipeline": str(runs[0]["id"])}+ if (receipt["candidate"].get("identity") != source+ or receipt["candidate"].get("jobs") != verified_jobs(client, repo, source)):+ raise ValueError("回收回执与成功演练不一致")+ client.require_rehearsal(repo, int(source["pipeline"]))+ return artifacts.cleanup(root, source=source)+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("mode", choices=("preflight", "check-capacity", "seal", "validate", "pull", "cleanup"))+ args = parser.parse_args()+ functions = {"preflight": preflight, "check-capacity": check_capacity,+ "seal": seal, "validate": validate, "pull": pull, "cleanup": cleanup}+ result = functions[args.mode](Path.cwd().resolve())+ print(json.dumps(result, ensure_ascii=False))+++if __name__ == "__main__":+ main()diff --git a/scripts/release_forge.py b/scripts/release_forge.pyindex 40af632cc..c381875fa 100644--- a/scripts/release_forge.py+++ b/scripts/release_forge.py@@ -19,7 +19,7 @@ from peach.peach_proxy import read_urlREQUIRED_TEST_JOBS = frozenset({"verify-linux", "verify-windows", "verify-macos", "wheel-smoke"})#: 版本提交的主线流水线里演练的标签作业(ADR-0121):全部成功才打标签。规则没匹配上、演练没跑,#: 也不能当作通过。三平台验收是必需任务,演练规则在版本提交上把它们改成全量。-REHEARSAL_JOBS = frozenset({"windows-media", "build-windows", "build-macos", "smoke-windows", "docker-build"})+REHEARSAL_JOBS = frozenset({"windows-media", "build-windows", "build-macos", "smoke-windows", "docker-build", "seal-release"})TERMINAL_STATUSES = frozenset({"success", "failed", "canceled", "skipped"})#: 必需任务落在这些状态时,整条流水线等多久都不会转绿;重试会生成同名的新任务。RED_JOB_STATUSES = frozenset({"failed", "canceled"})diff --git a/scripts/run_gitlab_runner.py b/scripts/run_gitlab_runner.pynew file mode 100644index 000000000..b8dc8407e--- /dev/null+++ b/scripts/run_gitlab_runner.py@@ -0,0 +1,37 @@+"""以无控制台进程运行现有 Windows runner 入口,避免创建终端窗口。"""+from __future__ import annotations++import argparse+import os+from pathlib import Path+import shutil+import subprocess+++def run(root: Path) -> int:+ root = root.resolve(strict=True)+ for name in ("run-runner.ps1", "gitlab-runner.exe", "config.toml"):+ path = root / name+ if path.is_symlink() or not path.is_file():+ raise ValueError("runner 目录缺少普通入口文件:" + name)+ powershell = shutil.which("pwsh.exe")+ if not powershell:+ raise ValueError("未找到 PowerShell 7")+ with (root / "runner-launcher.log").open("ab") as log:+ process = subprocess.run([powershell, "-NoProfile", "-NonInteractive", "-File", str(root / "run-runner.ps1")],+ cwd=root, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT,+ creationflags=subprocess.CREATE_NO_WINDOW, check=False)+ return process.returncode+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--root", required=True, type=Path)+ args = parser.parse_args()+ if os.name != "nt":+ parser.error("无控制台 runner 启动器仅用于 Windows")+ return run(args.root)+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 4694f0a66..a4c1e5a61 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -111,7 +111,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"tooling": ("test_scripts.py", "test_trash_junk.py", "test_auth.py", "test_access.py", "test_cli.py", "test_server.py", "test_diagnostics.py", "test_error_reporting.py", "test_remote_reporting.py", "test_reporting_*.py", "test_library_sharing.py", "test_library_diagnostics.py", "test_script_policy.py","test_scan.py", "test_record_rehome.py", "test_wants.py", "test_push_discovery.py", "test_media_probe.py", "test_subtitles.py", "test_onboarding.py", "test_configuration_sources.py", "test_clouddrive_proxy.py", "test_folder_picker.py", "test_ledger_backups.py", "test_clear_camera_filename_codes.py","test_agent_worktree.py", "test_test_evidence.py", "test_test_history.py", "test_test_environment.py", "test_dependency_policy.py",- "test_version_bump.py", "test_changelog.py", "test_release_due.py",+ "test_version_bump.py", "test_changelog.py", "test_release_due.py", "test_release_candidate.py", "test_media_build_cache.py", "test_runner_launcher.py","test_restart_windows_tray.py", "test_deploy_windows_tray.py", "test_runtime_prepare.py","test_buildinfo.py", "test_versioning.py", "test_macos_standalone.py","test_windows_update.py", "test_release_updates.py", "test_automatic_updates.py", "test_standalone_update.py", "test_upgrade_repairs.py", "test_certs.py", "test_config.py",@@ -155,7 +155,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_cli.py", "test_server.py", "test_versioning.py", "test_frontend_build.py", "test_frontend_preflight.py","test_cloudflared_packaging.py", "test_desktop_installer.py","test_ffmpeg_build.py", "test_ffmpeg_bundle.py", "test_untrunc_build.py", "test_macos_media.py",- "test_face_models_bundle.py", "test_metadata_amane_bridge.py"),+ "test_face_models_bundle.py", "test_metadata_amane_bridge.py", "test_release_candidate.py", "test_media_build_cache.py"),}SCOPE_TEST_IDS: dict[str, tuple[str, ...]] = {@@ -174,6 +174,7 @@ SCOPE_TEST_IDS: dict[str, tuple[str, ...]] = {# 一个文件可以落到多个域:读它的测试登记在哪个域,改它就得跑到哪个域。# `tests/test_test_planning.py` 按测试源码里真实读到的路径反查这两张表,漏一条本地就红。AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {+ "scripts/run_gitlab_runner.py": ("tooling",),"frontend/e2e/jav-userscript-contract.mjs": ("catalog", "web"),"web/integrations/peach-jav.user.js": ("catalog", "web"),"scripts/build_macos_media.py": ("tooling", "packaging"),diff --git a/tests/test_media_build_cache.py b/tests/test_media_build_cache.pynew file mode 100644index 000000000..503a1b811--- /dev/null+++ b/tests/test_media_build_cache.py@@ -0,0 +1,70 @@+from pathlib import Path+import tempfile+import unittest+from unittest import mock++from scripts import media_build_cache as cache+++class MediaBuildCacheTests(unittest.TestCase):+ def compiler(self, command, **_kwargs):+ output = Path(command[-1])+ tool = "ffmpeg" if "build_ffmpeg" in command[1] else "untrunc"+ (output / tool).mkdir(parents=True)+ (output / tool / "manifest.json").write_text('{"compiled": true}')+ (output / tool / "program.exe").write_bytes(b"compiled program")+ (output / f"{tool}-corresponding-source.zip").write_bytes(b"matching source")++ def test_cached_binaries_and_corresponding_sources_restore_without_compiling(self):+ with tempfile.TemporaryDirectory() as directory, mock.patch.object(cache, "input_identity", return_value={"input": "locked"}), \+ mock.patch.object(cache.subprocess, "run", side_effect=self.compiler) as compiler:+ root = Path(directory).resolve()+ first = cache.build(root, "windows")+ second = cache.build(root, "windows")+ self.assertEqual(first["cache_hits"], [])+ self.assertEqual(second["cache_hits"], ["ffmpeg", "untrunc"])+ self.assertEqual(compiler.call_count, 2)+ self.assertEqual((root / "build/ffmpeg-windows/ffmpeg-corresponding-source.zip").read_bytes(), b"matching source")++ def test_changed_inputs_or_corrupt_bytes_require_compilation(self):+ with tempfile.TemporaryDirectory() as directory, mock.patch.object(cache, "input_identity", return_value={"input": "one"}) as identity, \+ mock.patch.object(cache.subprocess, "run", side_effect=self.compiler) as compiler:+ root = Path(directory).resolve()+ cache.build(root, "windows", tool="ffmpeg")+ binary = root / "build/media-cache/windows-x86_64/ffmpeg/ffmpeg/program.exe"+ binary.write_bytes(b"corrupt")+ self.assertEqual(cache.build(root, "windows", tool="ffmpeg")["cache_hits"], [])+ identity.return_value = {"input": "two"}+ self.assertEqual(cache.build(root, "windows", tool="ffmpeg")["cache_hits"], [])+ self.assertEqual(compiler.call_count, 3)++ def test_missing_source_archive_is_not_a_cache_hit(self):+ with tempfile.TemporaryDirectory() as directory, mock.patch.object(cache, "input_identity", return_value={"input": "locked"}), \+ mock.patch.object(cache.subprocess, "run", side_effect=self.compiler) as compiler:+ root = Path(directory).resolve()+ cache.build(root, "windows", tool="ffmpeg")+ (root / "build/media-cache/windows-x86_64/ffmpeg/ffmpeg-corresponding-source.zip").unlink()+ self.assertEqual(cache.build(root, "windows", tool="ffmpeg")["cache_hits"], [])+ self.assertEqual(compiler.call_count, 2)++ def test_cache_paths_cannot_delete_outside_the_build_directory(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ protected = root / "media"+ protected.mkdir()+ with self.assertRaises(ValueError):+ cache.remove_owned(root, protected)+ self.assertTrue(protected.is_dir())++ def test_input_identity_distinguishes_architecture_and_sdk(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ for name in cache.INPUTS:+ path = root / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("input")+ first = cache.input_identity(root, "macos", "arm64", toolchain={"sdk": "one"})+ self.assertNotEqual(first, cache.input_identity(root, "macos", "x86_64", toolchain={"sdk": "one"}))+ self.assertNotEqual(first, cache.input_identity(root, "macos", "arm64", toolchain={"sdk": "two"}))+ (root / cache.INPUTS[0]).write_text("different source revision")+ self.assertNotEqual(first, cache.input_identity(root, "macos", "arm64", toolchain={"sdk": "one"}))diff --git a/tests/test_release_candidate.py b/tests/test_release_candidate.pynew file mode 100644index 000000000..aa99442fb--- /dev/null+++ b/tests/test_release_candidate.py@@ -0,0 +1,275 @@+import copy+import hashlib+import json+import os+import io+from pathlib import Path+import subprocess+import shutil+import tempfile+import unittest+from urllib.request import Request+import zipfile+from unittest import mock++from scripts import ci_r2_artifacts as artifacts+from scripts import release_candidate as candidate+from scripts import github_release_candidate as github+from scripts.release_forge import REQUIRED_TEST_JOBS, REHEARSAL_JOBS+++class ReleaseCandidateTests(unittest.TestCase):+ def setUp(self):+ self.build = {"project": "123", "pipeline": "7", "commit": "a" * 40, "tag": "v1.2.3"}+ self.environment = {"CI_PROJECT_ID": "123", "CI_PIPELINE_ID": "8", "CI_COMMIT_SHA": "a" * 40,+ "CI_COMMIT_TAG": "v1.2.3", "CI_COMMIT_REF_PROTECTED": "true", "CI_SERVER_HOST": "forge.example",+ "CI_PROJECT_PATH": "owner/repo"}+ self.names = sorted((REQUIRED_TEST_JOBS | REHEARSAL_JOBS) - {"seal-release"})+ self.jobs = {name: {"id": index + 10, "status": "success", "commit": {"id": "a" * 40}}+ for index, name in enumerate(self.names)}+ self.docker = {"commit": "a" * 40, "pipeline": "7", "version": "1.2.3",+ "image": "peach-ci:1.2.3-7", "image_id": "sha256:" + "b" * 64}+ self.paths = {"windows-release": "release/Peach-1.2.3-windows-x64.zip",+ "macos-release": "dist/macos.noindex/arm64/Peach-1.2.3-macos-arm64.dmg",+ "docker-release": "build/ci-artifacts/docker-image.json"}+ self.groups = {group: {"format": 1, "identity": self.build, "producer_job": "99", "group": group,+ "files": [{"path": path, "size": 4, "sha256": hashlib.sha256(b"file").hexdigest()}]}+ for group, path in self.paths.items()}+ self.sealed = {"format": 1, "identity": self.build, "jobs": {name: row["id"] for name, row in self.jobs.items()},+ "groups": self.groups, "docker": self.docker}+ self.forge = mock.Mock()+ self.forge.test_runs.return_value = [{"id": 7, "status": "completed", "conclusion": "success"}]+ self.forge.jobs.return_value = self.jobs++ def test_tag_validation_binds_successful_jobs_and_same_commit_candidate(self):+ with tempfile.TemporaryDirectory() as directory, mock.patch.dict(os.environ, self.environment, clear=True), \+ mock.patch.object(candidate, "forge", return_value=self.forge), \+ mock.patch.object(artifacts, "remote_json", return_value=self.sealed):+ root = Path(directory).resolve()+ receipt = candidate.validate(root)+ self.assertEqual(receipt["candidate"]["identity"]["pipeline"], "7")+ self.assertEqual(receipt["target"]["pipeline"], "8")+ self.assertTrue((root / candidate.RECEIPT).is_file())+ self.forge.require_rehearsal.assert_called_once_with("owner/repo", 7)++ def test_changed_commit_failed_checks_or_replaced_mirror_are_rejected(self):+ mutations = (lambda data: data["identity"].update(commit="c" * 40),+ lambda data: data["jobs"].update({self.names[0]: 999}),+ lambda data: data["docker"].update(image="unrelated:latest"))+ for mutate in mutations:+ with self.subTest(mutate=mutate), tempfile.TemporaryDirectory() as directory, \+ mock.patch.dict(os.environ, self.environment, clear=True), \+ mock.patch.object(candidate, "forge", return_value=self.forge):+ data = copy.deepcopy(self.sealed)+ mutate(data)+ with mock.patch.object(artifacts, "remote_json", return_value=data), self.assertRaises(ValueError):+ candidate.validate(Path(directory).resolve())+ self.jobs[self.names[0]]["status"] = "failed"+ with self.assertRaises(ValueError):+ candidate.verified_jobs(self.forge, "owner/repo", self.build)++ def test_missing_candidate_is_not_a_successful_promotion(self):+ with tempfile.TemporaryDirectory() as directory, mock.patch.dict(os.environ, self.environment, clear=True), \+ mock.patch.object(candidate, "forge", return_value=self.forge), \+ mock.patch.object(artifacts, "remote_json", return_value=None), self.assertRaises(ValueError):+ candidate.validate(Path(directory).resolve())++ def test_pull_keeps_source_pipeline_identity_and_group_file_checksums(self):+ with tempfile.TemporaryDirectory() as directory, mock.patch.dict(os.environ, self.environment, clear=True), \+ mock.patch.object(candidate, "forge", return_value=self.forge), \+ mock.patch.object(artifacts, "remote_json", return_value=self.sealed), \+ mock.patch.object(artifacts, "transfer", return_value={"files": 1}) as transfer:+ root = Path(directory).resolve()+ result = candidate.pull(root)+ self.assertTrue(result["promoted"])+ self.assertEqual(transfer.call_count, 3)+ self.assertTrue(all(call.kwargs["source"] == self.build for call in transfer.call_args_list))+ manifest = json.loads((root / "build/ci-artifacts/windows-release.json").read_text())+ self.assertEqual(manifest["files"], self.groups["windows-release"]["files"])++ def test_peak_capacity_includes_staging_and_new_public_files(self):+ with tempfile.TemporaryDirectory() as directory, \+ mock.patch.object(candidate, "listing", return_value=[{"Path": "_ci/current", "Size": 7999999995}]), \+ self.assertRaisesRegex(ValueError, "超过上限"):+ candidate.check_capacity(Path(directory), self.build, self.groups)++ def test_unprotected_tags_and_foreign_source_identity_cannot_read_artifacts(self):+ with mock.patch.dict(os.environ, {**self.environment, "CI_COMMIT_REF_PROTECTED": "false"}, clear=True), \+ self.assertRaises(ValueError):+ candidate.validate(Path.cwd())+ with mock.patch.dict(os.environ, self.environment, clear=True), self.assertRaises(ValueError):+ artifacts.transfer(Path.cwd(), "windows-release", "pull", source={**self.build, "project": "other"})++ def test_restore_distinguishes_absence_from_failed_reads(self):+ with tempfile.TemporaryDirectory() as directory, mock.patch.dict(os.environ, self.environment, clear=True), \+ mock.patch.object(artifacts, "remote_json", return_value=None) as read:+ root = Path(directory).resolve()+ self.assertFalse(artifacts.restore(root, "windows-release")["restored"])+ read.side_effect = subprocess.CalledProcessError(1, "rclone")+ with self.assertRaises(subprocess.CalledProcessError):+ artifacts.restore(root, "windows-release")++ def test_checkpoint_restore_downloads_without_publishing_new_build(self):+ build = {**self.build, "pipeline": "8"}+ manifest = {**self.groups["windows-release"], "identity": build}+ with tempfile.TemporaryDirectory() as directory, mock.patch.dict(os.environ, self.environment, clear=True), \+ mock.patch.object(artifacts, "remote_json", return_value=manifest), \+ mock.patch.object(artifacts, "transfer", return_value={"files": 1}) as transfer:+ root = Path(directory).resolve()+ self.assertTrue(artifacts.restore(root, "windows-release")["restored"])+ transfer.assert_called_once_with(root, "windows-release", "pull")++ def test_sealed_rehearsal_and_tag_transfer_keep_identical_bytes(self):+ metadata, objects = {}, {}+ for group, path in self.paths.items():+ data = json.dumps(self.docker).encode() if group == "docker-release" else b"verified " + group.encode()+ item = self.groups[group]["files"][0]+ item.update(size=len(data), sha256=hashlib.sha256(data).hexdigest())+ metadata[artifacts.checkpoint(self.build, group)] = self.groups[group]+ remote = f"peach:peach-releases/{artifacts.prefix(self.build, group, '99')}/{path}"+ objects[remote] = data+ def remote_json(_root, key, payload=None):+ if payload is not None:+ metadata[key] = copy.deepcopy(payload)+ return copy.deepcopy(metadata.get(key))+ def transfer(command, **_kwargs):+ self.assertEqual(command[1], "copy")+ source, destination = command[2:4]+ names = Path(command[command.index("--files-from-raw") + 1]).read_text().splitlines()+ for name in names:+ path = Path(destination) / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(objects[source + "/" + name])+ with tempfile.TemporaryDirectory() as directory, mock.patch.object(candidate, "forge", return_value=self.forge), \+ mock.patch.object(candidate, "listing", return_value=[]), \+ mock.patch.object(artifacts, "remote_json", side_effect=remote_json), \+ mock.patch.object(artifacts, "rclone_environment", return_value={"PEACH_R2_BUCKET": "peach-releases"}), \+ mock.patch.object(artifacts, "rclone_executable", return_value="rclone"), \+ mock.patch.object(artifacts.subprocess, "run", side_effect=transfer):+ root = Path(directory).resolve()+ source = root / "rehearsal"+ source.mkdir()+ rehearsal = {**self.environment, "CI_PIPELINE_ID": "7", "CI_COMMIT_BRANCH": "master",+ "CI_COMMIT_TAG": "", "PEACH_RELEASE_REHEARSAL": "1"}+ with mock.patch.dict(os.environ, rehearsal, clear=True), mock.patch.object(artifacts, "rehearsal_tag", return_value="v1.2.3"):+ self.assertTrue(candidate.seal(source)["sealed"])+ target = root / "tag"+ target.mkdir()+ with mock.patch.dict(os.environ, self.environment, clear=True):+ self.assertTrue(candidate.pull(target)["promoted"])+ self.assertEqual((target / self.paths["windows-release"]).read_bytes(), b"verified windows-release")+ self.assertEqual(json.loads((target / self.paths["docker-release"]).read_text()), self.docker)++[email protected](shutil.which("pwsh"), "需要 PowerShell 7 执行 Windows 发布入口")+class DockerPublicationTests(unittest.TestCase):+ def test_failed_push_retains_verified_image_and_success_removes_it(self):+ entry = Path(__file__).resolve().parents[1] / "scripts/ci_windows.ps1"+ image = {"Id": "sha256:" + "b" * 64, "Config": {"Labels": {+ "org.opencontainers.image.revision": "a" * 40, "org.opencontainers.image.version": "1.2.3"}}}+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ (root / "src/peach").mkdir(parents=True)+ (root / "src/peach/__init__.py").write_text('__version__ = "1.2.3"')+ (root / "build/ci-artifacts").mkdir(parents=True)+ receipt = {"target": {"pipeline": "8", "commit": "a" * 40},+ "candidate": {"identity": {"pipeline": "7"}, "docker": {"image_id": image["Id"]}}}+ (root / "build/ci-artifacts/release-candidate.json").write_text(json.dumps(receipt))+ driver = root / "driver.ps1"+ driver.write_text('''function docker {+ param([Parameter(Position=0, ValueFromRemainingArguments=$true)][string[]]$DockerArgs,+ [Parameter(ValueFromPipeline=$true)][string]$LoginInput)+ Add-Content -LiteralPath calls.log -Value ($DockerArgs -join ' ')+ $global:LASTEXITCODE = 0+ if ($DockerArgs[0] -eq 'context') { return 'fixture-endpoint' }+ if ($DockerArgs[0] -eq 'image' -and $DockerArgs[1] -eq 'inspect') { return $env:TEST_IMAGE }+ if ($DockerArgs[0] -eq 'push' -and $env:TEST_FAIL_PUSH -eq '1') { $global:LASTEXITCODE = 1 }+}+try { & $env:TEST_CI_ENTRY docker-push } catch { Write-Output $_; exit 3 }+''', encoding="utf-8")+ environment = {**os.environ, "TEST_CI_ENTRY": str(entry), "TEST_IMAGE": json.dumps(image),+ "CI_PIPELINE_ID": "8", "CI_COMMIT_SHA": "a" * 40, "CI_COMMIT_TAG": "v1.2.3",+ "PEACH_RELEASE_REHEARSAL": "", "DOCKERHUB_USERNAME": "fixture", "DOCKERHUB_TOKEN": "fixture"}+ for fail in (True, False):+ with self.subTest(failed=fail):+ log = root / "calls.log"+ log.unlink(missing_ok=True)+ result = subprocess.run([shutil.which("pwsh"), "-NoProfile", "-NonInteractive", "-File", str(driver)],+ cwd=root, env={**environment, "TEST_FAIL_PUSH": str(int(fail))}, text=True, encoding="utf-8", capture_output=True)+ calls = log.read_text(encoding="utf-8-sig")+ self.assertEqual(result.returncode == 0, not fail, (result.stdout or "") + (result.stderr or ""))+ self.assertEqual("image rm peach-ci:1.2.3-7" in calls, not fail)+ self.assertIn("logout", calls)+++class GitHubCandidateTests(unittest.TestCase):+ def payload(self, name="program.exe"):+ stream = io.BytesIO()+ with zipfile.ZipFile(stream, "w") as package:+ package.writestr(name, b"verified bytes")+ return stream.getvalue()++ def test_download_checks_server_digest_before_extracting(self):+ payload = self.payload()+ record = {"run_id": 7, "artifacts": {"desktop-candidate": {"id": 9,+ "digest": "sha256:" + hashlib.sha256(payload).hexdigest()}}}+ with tempfile.TemporaryDirectory() as directory, mock.patch.object(github, "select", return_value=record), \+ mock.patch.object(github, "request", side_effect=lambda *_: io.BytesIO(payload)):+ root = Path(directory)+ self.assertTrue(github.download("owner/repo", "a" * 40, "desktop", root)["promoted"])+ self.assertEqual((root / "program.exe").read_bytes(), b"verified bytes")+ record["artifacts"]["desktop-candidate"]["digest"] = "sha256:" + "0" * 64+ with self.assertRaisesRegex(ValueError, "SHA-256"):+ github.download("owner/repo", "a" * 40, "desktop", root / "second")+ self.assertFalse((root / "second/program.exe").exists())++ def test_verified_zip_cannot_escape_or_replace_an_existing_file(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ path = root / "artifact.zip"+ path.write_bytes(self.payload("../outside"))+ with self.assertRaises(ValueError):+ github.extract(path, root / "target")+ self.assertFalse((root / "outside").exists())+ path.write_bytes(self.payload())+ (root / "program.exe").write_bytes(b"keep original")+ with self.assertRaises(ValueError):+ github.extract(path, root)+ self.assertEqual((root / "program.exe").read_bytes(), b"keep original")++ def test_cross_host_redirect_drops_ci_authorization(self):+ original = Request("https://api.github.com/repos/owner/repo/actions/artifacts/9/zip",+ headers={"Authorization": "Bearer test-value"})+ redirected = github.ArtifactRedirect().redirect_request(original, None, 302, "Found", {}, "https://artifacts.example/package")+ self.assertIsNone(redirected.get_header("Authorization"))+ with self.assertRaises(ValueError):+ github.ArtifactRedirect().redirect_request(original, None, 302, "Found", {}, "http://artifacts.example/package")++ def test_expired_artifacts_and_skipped_smoke_are_not_successful_candidates(self):+ run = {"id": 7, "head_sha": "a" * 40, "head_branch": "master", "event": "push", "status": "completed", "conclusion": "success"}+ jobs = [{"name": name, "conclusion": "success"} for name in github.REQUIRED_JOBS]+ artifacts = [{"name": name, "id": index, "expired": False, "digest": "sha256:" + "b" * 64}+ for index, name in enumerate(sorted(github.REQUIRED_ARTIFACTS))]+ def api(_repo, endpoint):+ return {"workflow_runs": [run]} if "workflows/" in endpoint else {"jobs": jobs} if "/jobs?" in endpoint else {"artifacts": artifacts}+ with mock.patch.object(github, "api", side_effect=api):+ self.assertEqual(github.select("owner/repo", "a" * 40)["run_id"], 7)+ artifacts[0]["expired"] = True+ with self.assertRaises(ValueError):+ github.select("owner/repo", "a" * 40)+ artifacts[0]["expired"] = False+ jobs[0]["conclusion"] = "skipped"+ with self.assertRaises(ValueError):+ github.select("owner/repo", "a" * 40)++ def test_loaded_docker_image_must_match_the_recorded_image_id(self):+ image = {"Id": "sha256:" + "b" * 64, "Config": {"Labels": {+ "org.opencontainers.image.version": "1.2.3", "org.opencontainers.image.revision": "a" * 40}}}+ with tempfile.TemporaryDirectory() as directory, mock.patch.dict(os.environ, {"GITHUB_SHA": "a" * 40}), \+ mock.patch.object(github.subprocess, "check_output", side_effect=lambda *_a, **_kw: json.dumps(image)):+ receipt = Path(directory) / "image.json"+ github.image_receipt(receipt, "1.2.3", verify=False)+ github.image_receipt(receipt, "1.2.3", verify=True)+ image["Id"] = "sha256:" + "c" * 64+ with self.assertRaises(ValueError):+ github.image_receipt(receipt, "1.2.3", verify=True)diff --git a/tests/test_runner_launcher.py b/tests/test_runner_launcher.pynew file mode 100644index 000000000..642814876--- /dev/null+++ b/tests/test_runner_launcher.py@@ -0,0 +1,28 @@+from pathlib import Path+from types import SimpleNamespace+import tempfile+import unittest+from unittest import mock++from scripts import run_gitlab_runner as launcher+++class RunnerLauncherTests(unittest.TestCase):+ def test_child_has_no_console_and_preserves_existing_runner_entry(self):+ with tempfile.TemporaryDirectory() as directory, \+ mock.patch.object(launcher.shutil, "which", return_value="pwsh.exe"), \+ mock.patch.object(launcher.subprocess, "CREATE_NO_WINDOW", 0x08000000, create=True), \+ mock.patch.object(launcher.subprocess, "run", return_value=SimpleNamespace(returncode=7)) as run:+ root = Path(directory).resolve()+ for name in ("run-runner.ps1", "gitlab-runner.exe", "config.toml"):+ (root / name).write_bytes(b"fixture")+ self.assertEqual(launcher.run(root), 7)+ self.assertEqual(run.call_args.kwargs["creationflags"], 0x08000000)+ self.assertEqual(run.call_args.kwargs["stdin"], launcher.subprocess.DEVNULL)+ self.assertEqual(run.call_args.args[0][-1], str(root / "run-runner.ps1"))++ def test_missing_runner_files_prevent_launch(self):+ with tempfile.TemporaryDirectory() as directory, mock.patch.object(launcher.subprocess, "run") as run:+ with self.assertRaises(ValueError):+ launcher.run(Path(directory))+ run.assert_not_called()diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex 8df7e15d6..477ca000f 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -4813,6 +4813,9 @@ class R2ArtifactTransferTests(unittest.TestCase):objects = {}def run(command, **_kwargs):+ if command[1] == "copyto":+ objects[command[3]] = Path(command[2]).read_bytes()+ returnself.assertEqual(command[1], "copy")names = Path(command[command.index("--files-from-raw") + 1]).read_text().splitlines()source, destination = command[2:4]@@ -4828,6 +4831,8 @@ class R2ArtifactTransferTests(unittest.TestCase):def read(command, **_kwargs):if command[0] == "git":return "a" * 40 if "rev-parse" in command else ""+ if command[1] == "cat":+ return objects[command[2]].decode()return json.dumps([{"Path": key.split("peach:peach-releases/", 1)[1], "Size": len(value)}for key, value in objects.items()])@@ -4847,7 +4852,12 @@ class R2ArtifactTransferTests(unittest.TestCase):artifact.unlink()module.transfer(root, "windows-release", "pull")self.assertEqual(artifact.read_bytes(), b"verified executable archive")- key, = objects+ artifact.unlink()+ manifest_path.unlink()+ with mock.patch.dict(os.environ, {"CI_JOB_ID": "790"}):+ self.assertTrue(module.restore(root, "windows-release")["restored"])+ self.assertEqual(artifact.read_bytes(), b"verified executable archive")+ key, = [name for name in objects if name.endswith("/release/Peach-1.2.3-windows-x64.zip")]self.assertTrue(key.startswith("peach:peach-releases/_ci/123/456/" + "a" * 40 + "/"))objects[key] = b"corrupted"with self.assertRaisesRegex(ValueError, "SHA-256"):@@ -4875,6 +4885,80 @@ class R2ArtifactTransferTests(unittest.TestCase):module.validate_manifest({**manifest, "files": [item, {**item, "path": "release/VERSION.txt"}]},"windows-release", build)+ def test_partial_upload_retry_recovers_built_bytes_and_original_remote_prefix(self):+ module = load_script("ci_r2_artifacts")+ objects, fail = {}, [True]+ def run(command, **_kwargs):+ if command[1] == "copyto":+ objects[command[3]] = Path(command[2]).read_bytes()+ return+ names = Path(command[command.index("--files-from-raw") + 1]).read_text().splitlines()+ source, destination = command[2:4]+ for name in names:+ if destination.startswith("peach:"):+ objects[destination + "/" + name] = (Path(source) / name).read_bytes()+ else:+ path = Path(destination) / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(objects[source + "/" + name])+ if destination.startswith("peach:") and fail[0]:+ fail[0] = False+ raise subprocess.CalledProcessError(1, command)+ def read(command, **_kwargs):+ if command[0] == "git":+ return "a" * 40 if "rev-parse" in command else ""+ if command[1] == "cat":+ return objects[command[2]].decode()+ return json.dumps([{"Path": key.split("peach:peach-releases/", 1)[1], "Size": len(value)}+ for key, value in objects.items()])+ with tempfile.TemporaryDirectory() as directory, \+ mock.patch.object(module, "rclone_environment", side_effect=self.rclone_environment), \+ mock.patch.object(module.subprocess, "check_output", side_effect=read), \+ mock.patch.object(module.subprocess, "run", side_effect=run):+ root = Path(directory).resolve() / "checkout"+ root.mkdir()+ environment = {**self.environment(), "CI_BUILDS_DIR": str(Path(directory).resolve() / "builds")}+ with mock.patch.dict(os.environ, environment, clear=True):+ self.tools(root)+ artifact = root / "release/Peach-1.2.3-windows-x64.zip"+ artifact.parent.mkdir()+ artifact.write_bytes(b"same built archive")+ with self.assertRaises(subprocess.CalledProcessError):+ module.transfer(root, "windows-release", "push")+ backup = module.upload_backup(root, module.identity(), "windows-release")+ self.assertTrue((backup / "upload.json").is_file())+ artifact.unlink()+ with mock.patch.dict(os.environ, {"CI_JOB_ID": "790"}):+ result = module.restore(root, "windows-release")+ self.assertTrue(result["restored"])+ self.assertFalse(result["uploaded"])+ module.transfer(root, "windows-release", "push")+ self.assertEqual(artifact.read_bytes(), b"same built archive")+ self.assertFalse(backup.exists())+ self.assertFalse(any("/windows-release/790/" in key for key in objects))++ def test_capacity_failure_preserves_completed_build_for_retry(self):+ module = load_script("ci_r2_artifacts")+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve() / "checkout"+ root.mkdir()+ environment = {**self.environment(), "CI_BUILDS_DIR": str(Path(directory).resolve() / "builds")}+ with mock.patch.dict(os.environ, environment, clear=True), \+ mock.patch.object(module, "rclone_environment", side_effect=self.rclone_environment), \+ mock.patch.object(module.subprocess, "check_output", side_effect=["a" * 40, "", "[]"]), \+ mock.patch.object(module, "require_capacity", side_effect=ValueError("capacity")), \+ mock.patch.object(module.subprocess, "run") as upload:+ self.tools(root)+ artifact = root / "release/Peach-1.2.3-windows-x64.zip"+ artifact.parent.mkdir()+ artifact.write_bytes(b"completed build")+ with self.assertRaisesRegex(ValueError, "capacity"):+ module.transfer(root, "windows-release", "push")+ backup = module.upload_backup(root, module.identity(), "windows-release")+ self.assertEqual((backup / artifact.relative_to(root)).read_bytes(), b"completed build")+ self.assertTrue((backup / "upload.json").is_file())+ upload.assert_not_called()+def test_macos_inventory_keeps_signed_images_and_checks_build_identity(self):module = load_script("ci_r2_artifacts")with tempfile.TemporaryDirectory() as temporary, mock.patch.dict(os.environ, self.environment(), clear=True):