An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:zap: Build and verify Docker release platforms on separate runners
Danieldf1a53aa9e61
diff --git a/.github/workflows/dockerimage.yml b/.github/workflows/dockerimage.ymlindex 84e253eefc..b8cf168521 100644--- a/.github/workflows/dockerimage.yml+++ b/.github/workflows/dockerimage.yml@@ -15,7 +15,7 @@ on:required: truetype: stringverify_cache:- description: 'Run cold and warm ONNX cache acceptance (slow)'+ description: 'Run separate per-platform ONNX cache acceptance (slow)'default: falsetype: boolean@@ -25,32 +25,28 @@ concurrency:queue: maxenv:- package_json: "app/package.json"- docker_hub_owner: "b3log"- docker_hub_repo: "siyuan"+ IMAGE_REPOSITORY: b3log/siyuan++permissions:+ contents: readjobs:- build:+ prepare:if: ${{ github.repository_owner == 'siyuan-note' }}- name: buildruns-on: ubuntu-24.04- permissions:- packages: write- contents: read- defaults:- run:- working-directory: source-+ outputs:+ version: ${{ steps.release.outputs.version }}+ source_commit: ${{ steps.release.outputs.source_commit }}steps:- - name: Checkout repository and submodules+ - name: Checkout release sourceuses: actions/checkout@v6with:# 手动重建使用正式版标签的源码,避免混入工作流分支上的后续开发内容。ref: ${{ github.event_name == 'workflow_dispatch' && format('refs/tags/v{0}', inputs.version) || github.sha }}path: source- submodules: recursive+ persist-credentials: false- - name: Checkout Docker build configuration+ - name: Checkout Docker build configuration and testsuses: actions/checkout@v6with:ref: ${{ github.sha }}@@ -65,17 +61,12 @@ jobs:sparse-checkout-cone-mode: falsepersist-credentials: false- - name: Extract version from package.json- id: version- run: |- echo "value=$(jq .version ${{ env.package_json }} -r)" >> $GITHUB_OUTPUT-- - name: Verify release version matches package.json- # 标签触发时校验标签,手动触发时校验指定版本,两种方式均只发布正式版。+ - name: Verify and pin release version and source+ id: release+ working-directory: sourceenv:EVENT_NAME: ${{ github.event_name }}REQUESTED_VERSION: ${{ inputs.version }}- PACKAGE_VERSION: ${{ steps.version.outputs.value }}run: |if [ "$EVENT_NAME" = "workflow_dispatch" ]; thenVERSION="$REQUESTED_VERSION"@@ -86,36 +77,86 @@ jobs:echo "Expected a stable version without a v prefix, stopping"exit 1fi+ PACKAGE_VERSION=$(jq -er .version app/package.json)if [ "$VERSION" != "$PACKAGE_VERSION" ]; thenecho "Requested version ($VERSION) does not match package.json ($PACKAGE_VERSION), stopping"exit 1fi- echo "Release version matches package.json: $VERSION"+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"+ echo "source_commit=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"+ echo "Release version: $VERSION; source: $(git rev-parse HEAD)"- - name: Apply Docker build configuration- if: ${{ github.event_name == 'workflow_dispatch' }}- # 只更新工作流提交中的构建配置,应用源码和资源保持正式版标签的内容。+ - name: Test Docker release verification+ run: python3 -m unittest discover -s docker-config/scripts -p test_docker_release.py++ build:+ needs: prepare+ name: Build and verify ${{ matrix.id }}+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 360+ strategy:+ # 一个平台失败时保留其他平台的构建结果,支持只重试失败任务。+ fail-fast: false+ matrix:+ include:+ - id: amd64+ platform: linux/amd64+ runner: ubuntu-24.04+ emulate: false+ - id: arm64+ platform: linux/arm64+ runner: ubuntu-24.04-arm+ emulate: false+ - id: armv7+ platform: linux/arm/v7+ runner: ubuntu-24.04+ emulate: true+ - id: armv8+ platform: linux/arm/v8+ runner: ubuntu-24.04+ emulate: true+ defaults:+ run:+ working-directory: source+ steps:+ - name: Checkout pinned release source and submodules+ uses: actions/checkout@v6+ with:+ ref: ${{ needs.prepare.outputs.source_commit }}+ path: source+ submodules: recursive+ persist-credentials: false++ - name: Checkout pinned Docker build configuration+ uses: actions/checkout@v6+ with:+ ref: ${{ github.sha }}+ path: docker-config+ sparse-checkout: |+ Dockerfile+ .dockerignore+ scripts/verify-docker-release.py+ scripts/testdata/docker-ocr+ sparse-checkout-cone-mode: false+ persist-credentials: false++ - name: Apply and record build configuration+ env:+ SOURCE_COMMIT: ${{ needs.prepare.outputs.source_commit }}+ CONFIGURATION_COMMIT: ${{ github.sha }}+ RELEASE_VERSION: ${{ needs.prepare.outputs.version }}run: |+ test "$(git rev-parse HEAD)" = "$SOURCE_COMMIT"+ test "$(jq -er .version app/package.json)" = "$RELEASE_VERSION"cp ../docker-config/Dockerfile Dockerfilecp ../docker-config/.dockerignore .dockerignore-- - name: Record source and build configuration- run: |- echo "Source commit: $(git rev-parse HEAD)"+ echo "Source commit: $SOURCE_COMMIT; configuration commit: $CONFIGURATION_COMMIT"sha256sum Dockerfile .dockerignore- - name: Test Docker release verification- run: python3 -m unittest discover -s ../docker-config/scripts -p test_docker_release.py-- name: Free Disk Space (Ubuntu)uses: jlumbroso/free-disk-space@mainwith:- # this might remove tools that are actually needed,- # if set to "true" but frees about 6 GBtool-cache: false-- # all of these default to true, but feel free to set to- # "false" if necessary for your workflowandroid: truedotnet: truehaskell: true@@ -123,8 +164,11 @@ jobs:docker-images: trueswap-storage: true- - name: Set up QEMU+ - name: Set up QEMU for ARM32+ if: ${{ matrix.emulate }}uses: docker/setup-qemu-action@v4+ with:+ platforms: arm- name: Setup Docker buildxuses: docker/setup-buildx-action@v4@@ -135,61 +179,188 @@ jobs:username: ${{ secrets.DOCKER_HUB_USER }}password: ${{ secrets.DOCKER_HUB_PWD }}- - name: Build candidate image and export cache+ - name: Build platform candidate and export its cacheid: buildshell: bashenv:- IMAGE_REPOSITORY: ${{ env.docker_hub_owner }}/${{ env.docker_hub_repo }}- CACHE_IMAGE: ${{ env.docker_hub_owner }}/${{ env.docker_hub_repo }}:buildcache-release-v1+ PLATFORM: ${{ matrix.platform }}+ PLATFORM_ID: ${{ matrix.id }}+ CACHE_IMAGE: ${{ env.IMAGE_REPOSITORY }}:buildcache-release-v2-${{ matrix.id }}run: |- docker buildx build --push --platform linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v8 \+ docker buildx build --push --platform "$PLATFORM" --provenance=mode=min \--cache-from "type=registry,ref=$CACHE_IMAGE" \--cache-to "type=registry,ref=$CACHE_IMAGE,mode=max" \--metadata-file "$RUNNER_TEMP/docker-metadata.json" --progress plain \- -t "$IMAGE_REPOSITORY:build-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" . \+ -t "$IMAGE_REPOSITORY:build-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT-$PLATFORM_ID" . \2>&1 | tee "$RUNNER_TEMP/docker-build.log"DIGEST=$(jq -r '."containerimage.digest"' "$RUNNER_TEMP/docker-metadata.json")if [[ ! "$DIGEST" =~ ^sha256:[0-9a-f]{64}$ ]]; then- echo "Missing candidate image digest"+ echo "Missing platform candidate image digest"exit 1fiecho "image=$IMAGE_REPOSITORY@$DIGEST" >> "$GITHUB_OUTPUT"- - name: Verify all release platforms and OCR+ - name: Verify platform kernel and real OCRenv:RELEASE_IMAGE: ${{ steps.build.outputs.image }}- RELEASE_VERSION: ${{ steps.version.outputs.value }}+ RELEASE_VERSION: ${{ needs.prepare.outputs.version }}+ SOURCE_COMMIT: ${{ needs.prepare.outputs.source_commit }}+ CONFIGURATION_COMMIT: ${{ github.sha }}+ PLATFORM: ${{ matrix.platform }}run: |python3 ../docker-config/scripts/verify-docker-release.py verify \- --image "$RELEASE_IMAGE" --version "$RELEASE_VERSION" \- --report "$RUNNER_TEMP/docker-verification.json"+ --image "$RELEASE_IMAGE" --version "$RELEASE_VERSION" --platform "$PLATFORM" \+ --source-commit "$SOURCE_COMMIT" --configuration-commit "$CONFIGURATION_COMMIT" \+ --run-id "$GITHUB_RUN_ID" --report "$RUNNER_TEMP/docker-verification/report.json"++ - name: Save successful platform verification+ uses: actions/upload-artifact@v7+ with:+ # 同次运行重试时只替换对应平台的报告,其他成功平台的报告继续保留。+ name: docker-verification-${{ matrix.id }}+ path: ${{ runner.temp }}/docker-verification/report.json+ if-no-files-found: error+ overwrite: true++ - name: Preserve platform build and verification records+ if: ${{ always() }}+ uses: actions/upload-artifact@v7+ with:+ name: docker-build-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.id }}+ path: |+ ${{ runner.temp }}/docker-build.log+ ${{ runner.temp }}/docker-metadata.json+ ${{ runner.temp }}/docker-verification/report.json+ if-no-files-found: ignore++ cache:+ name: Optional cache acceptance ${{ matrix.id }}+ needs: prepare+ if: ${{ github.event_name == 'workflow_dispatch' && inputs.verify_cache }}+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 360+ strategy:+ fail-fast: false+ matrix:+ include:+ - id: amd64+ platform: linux/amd64+ runner: ubuntu-24.04+ emulate: false+ - id: arm64+ platform: linux/arm64+ runner: ubuntu-24.04-arm+ emulate: false+ - id: armv7+ platform: linux/arm/v7+ runner: ubuntu-24.04+ emulate: true+ - id: armv8+ platform: linux/arm/v8+ runner: ubuntu-24.04+ emulate: true+ steps:+ - name: Checkout pinned cache verification configuration+ uses: actions/checkout@v6+ with:+ ref: ${{ github.sha }}+ sparse-checkout: |+ Dockerfile+ scripts/check-docker-cache.py+ sparse-checkout-cone-mode: false+ persist-credentials: false- - name: Verify ONNX cache reuse and invalidation- if: ${{ github.event_name == 'workflow_dispatch' && inputs.verify_cache }}+ - name: Free Disk Space (Ubuntu)+ uses: jlumbroso/free-disk-space@main+ with:+ tool-cache: false++ - name: Set up QEMU for ARM32+ if: ${{ matrix.emulate }}+ uses: docker/setup-qemu-action@v4+ with:+ platforms: arm++ - name: Setup Docker buildx+ uses: docker/setup-buildx-action@v4++ - name: Log in to Docker Hub+ uses: docker/login-action@v4+ with:+ username: ${{ secrets.DOCKER_HUB_USER }}+ password: ${{ secrets.DOCKER_HUB_PWD }}++ - name: Verify platform ONNX cache reuse and invalidationenv:- CACHE_REPOSITORY: ${{ env.docker_hub_owner }}/${{ env.docker_hub_repo }}+ PLATFORM: ${{ matrix.platform }}run: |- python3 ../docker-config/scripts/check-docker-cache.py \- --dockerfile Dockerfile --cache-repository "$CACHE_REPOSITORY" \+ python3 scripts/check-docker-cache.py --platform "$PLATFORM" \+ --dockerfile Dockerfile --cache-repository "$IMAGE_REPOSITORY" \--records "$RUNNER_TEMP/docker-cache-acceptance"+ - name: Preserve cache acceptance records+ if: ${{ always() }}+ uses: actions/upload-artifact@v7+ with:+ name: docker-cache-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.id }}+ path: ${{ runner.temp }}/docker-cache-acceptance+ if-no-files-found: ignore++ publish:+ name: Assemble and publish verified release+ needs: [prepare, build, cache]+ # 未启用额外缓存验收时允许其跳过,所有平台的成品验收始终必须成功。+ if: ${{ !cancelled() && needs.prepare.result == 'success' && needs.build.result == 'success' && (needs.cache.result == 'success' || needs.cache.result == 'skipped') }}+ runs-on: ubuntu-24.04+ steps:+ - name: Checkout pinned release verification+ uses: actions/checkout@v6+ with:+ ref: ${{ github.sha }}+ sparse-checkout: scripts/verify-docker-release.py+ sparse-checkout-cone-mode: false+ persist-credentials: false++ - name: Download successful platform reports from this run+ uses: actions/download-artifact@v8+ with:+ pattern: docker-verification-*+ path: ${{ runner.temp }}/platform-reports++ - name: Setup Docker buildx+ uses: docker/setup-buildx-action@v4++ - name: Log in to Docker Hub+ uses: docker/login-action@v4+ with:+ username: ${{ secrets.DOCKER_HUB_USER }}+ password: ${{ secrets.DOCKER_HUB_PWD }}++ - name: Assemble verified platform digests+ env:+ RELEASE_VERSION: ${{ needs.prepare.outputs.version }}+ SOURCE_COMMIT: ${{ needs.prepare.outputs.source_commit }}+ CONFIGURATION_COMMIT: ${{ github.sha }}+ run: |+ python3 scripts/verify-docker-release.py assemble \+ --repository "$IMAGE_REPOSITORY" --candidate-tag "build-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT-verified" \+ --version "$RELEASE_VERSION" --source-commit "$SOURCE_COMMIT" \+ --configuration-commit "$CONFIGURATION_COMMIT" --run-id "$GITHUB_RUN_ID" \+ --reports "$RUNNER_TEMP/platform-reports" --report "$RUNNER_TEMP/docker-verification.json"+- name: Publish verified release imageenv:- RELEASE_IMAGE: ${{ steps.build.outputs.image }}- RELEASE_VERSION: ${{ steps.version.outputs.value }}+ RELEASE_VERSION: ${{ needs.prepare.outputs.version }}run: |- python3 ../docker-config/scripts/verify-docker-release.py promote \+ RELEASE_IMAGE=$(jq -er .image "$RUNNER_TEMP/docker-verification.json")+ python3 scripts/verify-docker-release.py promote \--image "$RELEASE_IMAGE" --version "$RELEASE_VERSION" \--report "$RUNNER_TEMP/docker-verification.json"- - name: Preserve build and verification records+ - name: Preserve assembled release verificationif: ${{ always() }}uses: actions/upload-artifact@v7with:name: docker-release-${{ github.run_id }}-${{ github.run_attempt }}- path: |- ${{ runner.temp }}/docker-build.log- ${{ runner.temp }}/docker-metadata.json- ${{ runner.temp }}/docker-verification.json- ${{ runner.temp }}/docker-cache-acceptance+ path: ${{ runner.temp }}/docker-verification.jsonif-no-files-found: ignorediff --git a/scripts/check-docker-cache.py b/scripts/check-docker-cache.pyindex ecf24b2a32..068df9f2e9 100644--- a/scripts/check-docker-cache.py+++ b/scripts/check-docker-cache.py@@ -32,7 +32,7 @@ def cache_bytes(manifest):return sum(sizes.values())-def onnx_steps(log):+def onnx_steps(log, expected=PLATFORMS):steps, result = {}, {}for line in log.splitlines():match = re.match(r"^#(\d+) \[(linux/[a-z0-9/]+) onnx-build \d+/\d+\] RUN python3 /onnxruntime/tools/ci_build/build.py", line)@@ -42,12 +42,12 @@ def onnx_steps(log):if status and status[1] in steps:platform = steps[status[1]]result[platform] = result.get(platform, False) or status[2] == "CACHED"- if set(result) != PLATFORMS:+ if set(result) != set(expected):raise ValueError(f"Incomplete ONNX build log: {tuple(result)}")return result-def build_case(context, cache, directory, name, *, import_cache, revision=None):+def build_case(context, cache, directory, name, *, import_cache, revision=None, platforms=PLATFORMS):builder = "siyuan-cache-check-" + uuid.uuid4().hexstarted = time.monotonic()log_path = directory / (name + ".log")@@ -78,7 +78,7 @@ def build_case(context, cache, directory, name, *, import_cache, revision=None):subprocess.run(["docker", "buildx", "create", "--name", builder, "--driver", "docker-container"], check=True)monitor.start()command = ["docker", "buildx", "build", "--builder", builder, "--target", "onnx-build",- "--platform", ",".join(sorted(PLATFORMS)), "--progress", "plain", "--output", "type=cacheonly",+ "--platform", ",".join(sorted(platforms)), "--progress", "plain", "--output", "type=cacheonly","--cache-to", "type=registry,ref=" + cache + ",mode=max"]if import_cache:command += ["--cache-from", "type=registry,ref=" + cache]@@ -88,7 +88,7 @@ def build_case(context, cache, directory, name, *, import_cache, revision=None):# 将完整日志留在验收目录,终端只显示当前轮次和最后的缓存命中结果。with log_path.open("w", encoding="utf-8") as log:subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True)- hits = onnx_steps(log_path.read_text(encoding="utf-8"))+ hits = onnx_steps(log_path.read_text(encoding="utf-8"), platforms)exported = subprocess.run(["docker", "buildx", "imagetools", "inspect", cache, "--raw"],capture_output=True, text=True, check=True)return {"case": name, "cached": hits, "seconds": round(time.monotonic() - started, 3),@@ -105,12 +105,14 @@ def main():parser.add_argument("--dockerfile", type=Path, required=True)parser.add_argument("--cache-repository", required=True)parser.add_argument("--records", type=Path, required=True)+ parser.add_argument("--platform", choices=sorted(PLATFORMS))args = parser.parse_args()if not re.fullmatch(r"[a-z0-9][a-z0-9./_-]*", args.cache_repository):parser.error("Expected a registry repository without a tag or digest")args.records.mkdir(parents=True, exist_ok=False)+ platforms = {args.platform} if args.platform else PLATFORMScache = args.cache_repository + ":buildcache-check-" + uuid.uuid4().hex- report = {"cache": cache, "status": "running", "cases": [],+ report = {"cache": cache, "platforms": sorted(platforms), "status": "running", "cases": [],"dockerfile_sha256": hashlib.sha256(args.dockerfile.read_bytes()).hexdigest()}try:with tempfile.TemporaryDirectory(prefix="siyuan-onnx-cache-") as directory:@@ -123,7 +125,8 @@ def main():if changed:(context / "app/cache-probe.txt").write_text("changed application source\n", encoding="utf-8")revision = uuid.uuid4().hex if name == "onnx-input-change" else None- result = build_case(context, cache, args.records, name, import_cache=imported, revision=revision)+ result = build_case(context, cache, args.records, name, import_cache=imported, revision=revision,+ platforms=platforms)report["cases"].append(result)expected = name in ("warm", "application-change")if any(cached != expected for cached in result["cached"].values()):diff --git a/scripts/test_docker_release.py b/scripts/test_docker_release.pyindex 66e23d4557..97ce2a0c2b 100644--- a/scripts/test_docker_release.py+++ b/scripts/test_docker_release.py@@ -107,20 +107,33 @@ class PublishTests(unittest.TestCase):response = subprocess.CompletedProcess([], 0, json.dumps(manifest()), "")with patch.object(release, "run", return_value=response) as run:release.promote(IMAGE, "3.8.7", self.path)- command = run.call_args_list[0].args[0]+ command = run.call_args_list[1].args[0]self.assertEqual(command[-1], IMAGE)self.assertIn("b3log/siyuan:v3.8.7", command)self.assertIn("b3log/siyuan:latest", command)- self.assertEqual(run.call_count, 3)+ self.assertEqual(run.call_count, 4)def test_remote_manifest_difference_is_reported(self):self.save(report())changed = manifest()changed["manifests"][0]["digest"] = "sha256:" + "f" * 64- with patch.object(release, "run", return_value=subprocess.CompletedProcess([], 0, json.dumps(changed), "")):+ responses = [subprocess.CompletedProcess([], 0, json.dumps(manifest()), ""),+ subprocess.CompletedProcess([], 0, "", ""),+ subprocess.CompletedProcess([], 0, json.dumps(changed), "")]+ with patch.object(release, "run", side_effect=responses):with self.assertRaisesRegex(ValueError, "differs"):release.promote(IMAGE, "3.8.7", self.path)+ def test_candidate_mismatch_blocks_all_release_tag_writes(self):+ self.save(report())+ changed = manifest()+ changed["manifests"][0]["digest"] = "sha256:" + "f" * 64+ with patch.object(release, "run", return_value=subprocess.CompletedProcess([], 0, json.dumps(changed), "")) as run:+ with self.assertRaisesRegex(ValueError, "differs"):+ release.promote(IMAGE, "3.8.7", self.path)+ self.assertEqual(run.call_count, 1)+ self.assertEqual(run.call_args.args[0][3], "inspect")+def test_smoke_failure_preserves_failed_report_and_blocks_promotion(self):fixtures = Path(self.temp.name) / "fixtures"fixtures.mkdir()@@ -153,6 +166,125 @@ class PublishTests(unittest.TestCase):self.assertEqual(commands.call_args_list[-1].args[0][-1], cleanup[0][-1] + "-workspace")+class PlatformReleaseTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.root = Path(self.temp.name)+ self.reports = self.root / "reports"+ self.reports.mkdir()+ self.output = self.root / "assembled.json"+ self.provenance = {"source_commit": "b" * 40, "configuration_commit": "c" * 40, "run_id": "123"}+ self.sources = {}+ self.paths = []+ for index, entry in enumerate(report()["platforms"]):+ image = "b3log/siyuan@sha256:" + str(index + 5) * 64+ value = {**report(), **self.provenance, "image": image, "platforms": [entry]}+ directory = self.reports / str(index)+ directory.mkdir()+ path = directory / "report.json"+ path.write_text(json.dumps(value), encoding="utf-8")+ self.paths.append(path)+ self.sources[image] = {"manifests": [manifest()["manifests"][index]]}++ def command(self, arguments, **kwargs):+ if arguments[3] == "create":+ return subprocess.CompletedProcess(arguments, 0, "", "")+ if "--format" in arguments:+ value = {"digest": IMAGE.partition("@")[2]}+ else:+ value = self.sources.get(arguments[4], manifest())+ return subprocess.CompletedProcess(arguments, 0, json.dumps(value), "")++ def assemble(self):+ release.assemble("b3log/siyuan", "build-123-2-verified", "3.8.7", self.reports, self.output, self.provenance)++ def test_only_four_verified_current_run_candidates_are_assembled(self):+ with patch.object(release, "run", side_effect=self.command) as run:+ self.assemble()+ commands = [call.args[0] for call in run.call_args_list if call.args[0][3] == "create"]+ self.assertEqual(len(commands), 1)+ self.assertEqual(commands[0][5], "b3log/siyuan:build-123-2-verified")+ self.assertEqual(set(commands[0][6:]), set(self.sources))+ value = json.loads(self.output.read_text(encoding="utf-8"))+ self.assertEqual(value["status"], "passed")+ self.assertEqual(value["image"], IMAGE)+ self.assertEqual(release.verified_platforms(value, IMAGE, "3.8.7"), release.manifests(manifest()))+ self.assertEqual(value["run_id"], "123")++ def test_old_source_configuration_run_failed_or_incomplete_reports_block_assembly(self):+ original = json.loads(self.paths[0].read_text(encoding="utf-8"))+ changes = [lambda value: value.update(source_commit="d" * 40),+ lambda value: value.update(configuration_commit="d" * 40),+ lambda value: value.update(run_id="122"), lambda value: value.update(status="failed"),+ lambda value: value.update(version="3.8.8"),+ lambda value: value["platforms"][0]["checks"].remove("chinese"),+ lambda value: value["platforms"][0].update(platform="linux/arm64"),+ lambda value: value.update(image=value["image"].replace("b3log/siyuan", "other/repo"))]+ for change in changes:+ value = copy.deepcopy(original)+ change(value)+ self.paths[0].write_text(json.dumps(value), encoding="utf-8")+ with self.subTest(change=change), patch.object(release, "run", side_effect=self.command) as run:+ with self.assertRaises(ValueError):+ self.assemble()+ self.assertFalse(any(call.args[0][3] == "create" for call in run.call_args_list))+ self.assertFalse(self.output.exists())++ def test_missing_platform_report_blocks_assembly(self):+ self.paths[-1].unlink()+ with patch.object(release, "run") as run:+ with self.assertRaisesRegex(ValueError, "four"):+ self.assemble()+ run.assert_not_called()++ def test_report_digest_must_match_its_platform_candidate(self):+ source = next(iter(self.sources.values()))+ source["manifests"][0]["digest"] = "sha256:" + "f" * 64+ with patch.object(release, "run", side_effect=self.command) as run:+ with self.assertRaisesRegex(ValueError, "digest differs"):+ self.assemble()+ self.assertFalse(any(call.args[0][3] == "create" for call in run.call_args_list))++ def test_assembled_digest_mismatch_never_creates_successful_report(self):+ def mismatched(arguments, **kwargs):+ response = self.command(arguments, **kwargs)+ if arguments[3] == "inspect" and arguments[4] == IMAGE:+ value = manifest()+ value["manifests"].pop()+ response.stdout = json.dumps(value)+ return response+ with patch.object(release, "run", side_effect=mismatched) as run:+ with self.assertRaises(ValueError):+ self.assemble()+ self.assertFalse(self.output.exists())+ for call in run.call_args_list:+ self.assertNotIn("b3log/siyuan:latest", call.args[0])+ self.assertNotIn("b3log/siyuan:v3.8.7", call.args[0])++ def test_single_platform_verification_keeps_every_smoke_check_and_provenance(self):+ fixtures = self.root / "fixtures"+ fixtures.mkdir()+ for name in ("chinese", "latin", "blank"):+ (fixtures / (name + ".png")).write_bytes(b"fixture")+ entry = report()["platforms"][3]+ response = subprocess.CompletedProcess([], 0, json.dumps({"manifests": [manifest()["manifests"][3]]}), "")+ with patch.object(release, "run", return_value=response), \+ patch.object(release, "verify_platform", return_value=entry) as verify:+ release.verify(IMAGE, "3.8.7", fixtures, self.output, 240,+ platform="linux/arm/v8", provenance=self.provenance)+ self.assertEqual(verify.call_count, 1)+ self.assertEqual(verify.call_args.args[2], "linux/arm/v8")+ value = json.loads(self.output.read_text(encoding="utf-8"))+ self.assertEqual(value["source_commit"], self.provenance["source_commit"])+ self.assertEqual(set(value["platforms"][0]["checks"]), release.CHECKS)++ def test_wrong_or_extra_platform_in_single_candidate_is_rejected(self):+ for value in (manifest(), {"manifests": [manifest()["manifests"][0]]}):+ with self.subTest(value=value), self.assertRaises(ValueError):+ release.manifests(value, ("linux/arm/v8",))++class CacheTests(unittest.TestCase):def test_resource_measurements_use_binary_units_and_deduplicate_cache_layers(self):self.assertEqual(cache.memory_bytes("1.5GiB"), 1610612736)@@ -176,6 +308,29 @@ class CacheTests(unittest.TestCase):with self.assertRaises(ValueError):cache.onnx_steps(log)+ def test_per_platform_cache_acceptance_does_not_accept_other_arm_variants(self):+ line = "#1 [linux/arm/v8 onnx-build 5/5] RUN python3 /onnxruntime/tools/ci_build/build.py --build\n#1 CACHED"+ self.assertEqual(cache.onnx_steps(line, {"linux/arm/v8"}), {"linux/arm/v8": True})+ with self.assertRaises(ValueError):+ cache.onnx_steps(line, {"linux/arm64"})++ def test_selected_platform_is_used_for_all_four_cache_acceptance_cases(self):+ def build(context, cache_ref, directory, name, *, platforms, **kwargs):+ self.assertEqual(platforms, {"linux/arm64"})+ return {"cached": {"linux/arm64": name in ("warm", "application-change")}}+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ dockerfile = root / "Dockerfile"+ dockerfile.write_text("FROM alpine AS onnx-build\n", encoding="utf-8")+ with patch("sys.argv", ["check-docker-cache.py", "--dockerfile", str(dockerfile),+ "--cache-repository", "b3log/siyuan", "--records", str(root / "records"),+ "--platform", "linux/arm64"]), patch.object(cache, "build_case", side_effect=build) as run:+ cache.main()+ self.assertEqual(run.call_count, 4)+ value = json.loads(root.joinpath("records/report.json").read_text(encoding="utf-8"))+ self.assertEqual(value["status"], "passed")+ self.assertEqual(value["platforms"], ["linux/arm64"])+class SourceDownloadTests(unittest.TestCase):def execute(self, fetch_failures=0, submodule_failures=0, actual_commit=None):diff --git a/scripts/verify-docker-release.py b/scripts/verify-docker-release.pyindex 7fed8ec460..bfbfbf4c38 100644--- a/scripts/verify-docker-release.py+++ b/scripts/verify-docker-release.py@@ -33,7 +33,7 @@ def platform_name(platform):return name-def manifests(index):+def manifests(index, expected=PLATFORMS):result = {}for entry in index.get("manifests", []):if entry.get("annotations", {}).get("vnd.docker.reference.type") == "attestation-manifest":@@ -43,8 +43,8 @@ def manifests(index):if name in result or not DIGEST.fullmatch(digest):raise ValueError(f"Invalid or duplicate image manifest: {name}")result[name] = digest- if set(result) != set(PLATFORMS):- raise ValueError(f"Expected {PLATFORMS}, found {tuple(result)}")+ if set(result) != set(expected):+ raise ValueError(f"Expected {expected}, found {tuple(result)}")return result@@ -161,18 +161,19 @@ def verify_platform(repository, digest, platform, version, fixtures, timeout):return {"platform": platform, "digest": digest, "checks": checks, "seconds": round(time.monotonic() - started, 3)}-def verify(image, version, fixtures, report_path, timeout):+def verify(image, version, fixtures, report_path, timeout, *, platform=None, provenance=None):repository, separator, digest = image.partition("@")if not separator or not DIGEST.fullmatch(digest):raise ValueError("Verification requires an immutable image digest")for name in ("chinese", "latin", "blank"):if not (fixtures / f"{name}.png").is_file():raise ValueError(f"Missing OCR fixture: {name}")- index = manifests(json.loads(run(["docker", "buildx", "imagetools", "inspect", image, "--raw"]).stdout))- report = {"image": image, "version": version, "status": "running", "platforms": []}+ expected = (platform,) if platform else PLATFORMS+ index = manifests(json.loads(run(["docker", "buildx", "imagetools", "inspect", image, "--raw"]).stdout), expected)+ report = {"image": image, "version": version, "status": "running", "platforms": [], **(provenance or {})}try:- for platform in PLATFORMS:- print(f"Verifying {platform} under Docker/QEMU", flush=True)+ for platform in expected:+ print(f"Verifying {platform} in Docker", flush=True)report["platforms"].append(verify_platform(repository, index[platform], platform, version, fixtures, timeout))report["status"] = "passed"except Exception as error:@@ -183,12 +184,11 @@ def verify(image, version, fixtures, report_path, timeout):report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")-def promote(image, version, report_path):- report = json.loads(report_path.read_text(encoding="utf-8"))+def verified_platforms(report, image, version, expected=PLATFORMS):if report.get("image") != image or report.get("version") != version or report.get("status") != "passed":raise ValueError("Image promotion requires a matching successful verification report")platforms = report.get("platforms", [])- if len(platforms) != len(PLATFORMS) or {value.get("platform") for value in platforms} != set(PLATFORMS):+ if len(platforms) != len(expected) or {value.get("platform") for value in platforms} != set(expected):raise ValueError("Verification did not cover every release platform")for value in platforms:if set(value.get("checks", [])) != CHECKS or not DIGEST.fullmatch(value.get("digest", "")):@@ -196,28 +196,100 @@ def promote(image, version, report_path):repository, separator, digest = image.partition("@")if not separator or not DIGEST.fullmatch(digest):raise ValueError("Image promotion requires an immutable digest")+ return {value["platform"]: value["digest"] for value in platforms}+++def assemble(repository, tag, version, reports_path, report_path, provenance):+ # 重试失败任务时可复用同次运行中已通过的报告,但不接受其他运行或其他提交的产物。+ reports = sorted(reports_path.rglob("report.json"))+ if len(reports) != len(PLATFORMS):+ raise ValueError("Assembly requires exactly four platform reports")+ expected, sources, entries = {}, [], []+ for path in reports:+ report = json.loads(path.read_text(encoding="utf-8"))+ if any(report.get(key) != value for key, value in provenance.items()):+ raise ValueError("Platform report belongs to another source, configuration or workflow run")+ platform_entries = report.get("platforms", [])+ if len(platform_entries) != 1 or platform_entries[0].get("platform") not in PLATFORMS:+ raise ValueError("Expected one supported platform per report")+ platform = platform_entries[0]["platform"]+ image = report.get("image", "")+ if image.partition("@")[0] != repository or platform in expected:+ raise ValueError("Unexpected repository or duplicate platform report")+ verified = verified_platforms(report, image, version, (platform,))+ actual = manifests(json.loads(run(["docker", "buildx", "imagetools", "inspect", image, "--raw"]).stdout), (platform,))+ if actual != verified:+ raise ValueError("Platform report digest differs from candidate image")+ expected.update(verified)+ sources.append(image)+ entries.extend(platform_entries)+ if set(expected) != set(PLATFORMS):+ raise ValueError("Assembly is missing a release platform")+ candidate = repository + ":" + tag+ run(["docker", "buildx", "imagetools", "create", "--tag", candidate, *sources], timeout=900)+ descriptor = json.loads(run(["docker", "buildx", "imagetools", "inspect", candidate,+ "--format", "{{json .Manifest}}"]).stdout)+ digest = descriptor.get("digest", "")+ if not DIGEST.fullmatch(digest):+ raise ValueError("Missing assembled image digest")+ image = repository + "@" + digest+ actual = manifests(json.loads(run(["docker", "buildx", "imagetools", "inspect", image, "--raw"]).stdout))+ if actual != expected:+ raise ValueError("Assembled manifest differs from the verified platform images")+ report = {"image": image, "version": version, "status": "passed", "platforms": entries, **provenance}+ report_path.parent.mkdir(parents=True, exist_ok=True)+ report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")+++def promote(image, version, report_path):+ report = json.loads(report_path.read_text(encoding="utf-8"))+ expected = verified_platforms(report, image, version)+ repository = image.partition("@")[0]+ actual = manifests(json.loads(run(["docker", "buildx", "imagetools", "inspect", image, "--raw"]).stdout))+ if actual != expected:+ raise ValueError("Candidate manifest differs from the verified image")run(["docker", "buildx", "imagetools", "create", "--tag", repository + ":v" + version,"--tag", repository + ":latest", image], timeout=900)for tag in (":v" + version, ":latest"):published = manifests(json.loads(run(["docker", "buildx", "imagetools", "inspect", repository + tag, "--raw"]).stdout))- expected = {value["platform"]: value["digest"] for value in platforms}if published != expected:raise ValueError(f"Published manifest differs from the verified image: {tag}")def main():parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("command", choices=("verify", "promote"))- parser.add_argument("--image", required=True)+ parser.add_argument("command", choices=("verify", "assemble", "promote"))+ parser.add_argument("--image")parser.add_argument("--version", required=True)parser.add_argument("--report", type=Path, required=True)parser.add_argument("--fixtures", type=Path, default=Path(__file__).parent / "testdata/docker-ocr")parser.add_argument("--timeout", type=int, default=240)+ parser.add_argument("--platform", choices=PLATFORMS)+ parser.add_argument("--repository")+ parser.add_argument("--candidate-tag")+ parser.add_argument("--reports", type=Path)+ parser.add_argument("--source-commit")+ parser.add_argument("--configuration-commit")+ parser.add_argument("--run-id")args = parser.parse_args()if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", args.version) or args.timeout <= 0:parser.error("Expected a stable release version and positive timeout")+ provenance = {"source_commit": args.source_commit, "configuration_commit": args.configuration_commit,+ "run_id": args.run_id}+ if args.command == "assemble" or args.platform:+ if not all(re.fullmatch(r"[0-9a-f]{40}", value or "")+ for value in (args.source_commit, args.configuration_commit)) or not re.fullmatch(r"[0-9]+", args.run_id or ""):+ parser.error("Platform verification requires pinned source/configuration commits and a workflow run ID")+ if args.command != "assemble" and not args.image:+ parser.error("Expected an immutable --image")if args.command == "verify":- verify(args.image, args.version, args.fixtures, args.report, args.timeout)+ verify(args.image, args.version, args.fixtures, args.report, args.timeout,+ platform=args.platform, provenance=provenance if args.platform else None)+ elif args.command == "assemble":+ if not re.fullmatch(r"[a-z0-9][a-z0-9./_-]*", args.repository or "") \+ or not re.fullmatch(r"build-[0-9]+-[0-9]+-verified", args.candidate_tag or "") or not args.reports:+ parser.error("Expected a repository, reports directory and temporary build candidate tag")+ assemble(args.repository, args.candidate_tag, args.version, args.reports, args.report, provenance)else:promote(args.image, args.version, args.report)