Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:zap: Cache ONNX Docker builds and verify release images

Daniel5d837dad3f66
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000000..ca99ce8c5c
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,6 @@
+.git
+.cache
+**/node_modules
+**/__pycache__
+app/build
+app/stage/build
diff --git a/.github/workflows/dockerimage.yml b/.github/workflows/dockerimage.yml
index 573bdaf88e..574cdacacb 100644
--- a/.github/workflows/dockerimage.yml
+++ b/.github/workflows/dockerimage.yml
@@ -13,6 +13,15 @@ on:
description: 'Stable version to build, without the v prefix'
required: true
type: string
+ verify_cache:
+ description: 'Run cold and warm ONNX cache acceptance (slow)'
+ default: false
+ type: boolean
+
+concurrency:
+ group: siyuan-docker-release
+ cancel-in-progress: false
+ queue: max
env:
package_json: "app/package.json"
@@ -41,12 +50,17 @@ jobs:
submodules: recursive
- name: Checkout Docker build configuration
- if: ${{ github.event_name == 'workflow_dispatch' }}
uses: actions/checkout@v6
with:
ref: ${{ github.sha }}
path: docker-config
- sparse-checkout: Dockerfile
+ sparse-checkout: |
+ Dockerfile
+ .dockerignore
+ scripts/verify-docker-release.py
+ scripts/check-docker-cache.py
+ scripts/test_docker_release.py
+ scripts/testdata/docker-ocr
sparse-checkout-cone-mode: false
persist-credentials: false
@@ -79,13 +93,18 @@ jobs:
- name: Apply Docker build configuration
if: ${{ github.event_name == 'workflow_dispatch' }}
- # 只复制工作流提交中的 Dockerfile,应用源码和资源保持正式版标签的内容。
- run: cp ../docker-config/Dockerfile Dockerfile
+ # 只更新工作流提交中的构建配置,应用源码和资源保持正式版标签的内容。
+ run: |
+ cp ../docker-config/Dockerfile Dockerfile
+ cp ../docker-config/.dockerignore .dockerignore
- name: Record source and build configuration
run: |
echo "Source commit: $(git rev-parse HEAD)"
- sha256sum Dockerfile
+ 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@main
@@ -115,7 +134,61 @@ jobs:
username: ${{ secrets.DOCKER_HUB_USER }}
password: ${{ secrets.DOCKER_HUB_PWD }}
- - name: Build and push Docker image
- # 走到这里的一定是 stable 版本,直接同时打 :latest 和具体版本号标签
+ - name: Build candidate image and export cache
+ id: build
+ shell: bash
+ env:
+ IMAGE_REPOSITORY: ${{ env.docker_hub_owner }}/${{ env.docker_hub_repo }}
+ CACHE_IMAGE: ${{ env.docker_hub_owner }}/${{ env.docker_hub_repo }}:buildcache-release-v1
+ run: |
+ docker buildx build --push --platform linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v8 \
+ --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" . \
+ 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"
+ exit 1
+ fi
+ echo "image=$IMAGE_REPOSITORY@$DIGEST" >> "$GITHUB_OUTPUT"
+
+ - name: Verify all release platforms and OCR
+ env:
+ RELEASE_IMAGE: ${{ steps.build.outputs.image }}
+ RELEASE_VERSION: ${{ steps.version.outputs.value }}
run: |
- docker buildx build --push --platform linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v8 -t ${{ env.docker_hub_owner }}/${{ env.docker_hub_repo }}:latest -t ${{ env.docker_hub_owner }}/${{ env.docker_hub_repo }}:v${{ steps.version.outputs.value }} .
+ python3 ../docker-config/scripts/verify-docker-release.py verify \
+ --image "$RELEASE_IMAGE" --version "$RELEASE_VERSION" \
+ --report "$RUNNER_TEMP/docker-verification.json"
+
+ - name: Verify ONNX cache reuse and invalidation
+ if: ${{ github.event_name == 'workflow_dispatch' && inputs.verify_cache }}
+ env:
+ CACHE_REPOSITORY: ${{ env.docker_hub_owner }}/${{ env.docker_hub_repo }}
+ run: |
+ python3 ../docker-config/scripts/check-docker-cache.py \
+ --dockerfile Dockerfile --cache-repository "$CACHE_REPOSITORY" \
+ --records "$RUNNER_TEMP/docker-cache-acceptance"
+
+ - name: Publish verified release image
+ env:
+ RELEASE_IMAGE: ${{ steps.build.outputs.image }}
+ RELEASE_VERSION: ${{ steps.version.outputs.value }}
+ run: |
+ python3 ../docker-config/scripts/verify-docker-release.py promote \
+ --image "$RELEASE_IMAGE" --version "$RELEASE_VERSION" \
+ --report "$RUNNER_TEMP/docker-verification.json"
+
+ - name: Preserve build and verification records
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v7
+ with:
+ 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
+ if-no-files-found: ignore
diff --git a/Dockerfile b/Dockerfile
index 6148669ca8..d98685d589 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,4 +1,7 @@
-FROM --platform=$BUILDPLATFORM node:22 AS node-build
+ARG ALPINE_IMAGE=alpine:3.24@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6
+ARG GO_IMAGE=golang:1.26-alpine@sha256:3082400e369fa24d5fc60bca20edab3f6d604e0c5a690ec66b295eff4dd87ade
+
+FROM --platform=$BUILDPLATFORM node:22@sha256:0e5f906573693feaa1e21057ebdcfdb5bd5021f050b2dc7c9deceb629c7da2a8 AS node-build
ARG NPM_REGISTRY=
@@ -28,7 +31,7 @@ mv appearance stage guide /artifacts/
if [ -d changelogs ]; then mv changelogs /artifacts/; fi
EORUN
-FROM golang:1.26-alpine AS go-build
+FROM ${GO_IMAGE} AS go-source
RUN <<EORUN
#!/bin/sh -e
@@ -39,20 +42,26 @@ EORUN
WORKDIR /kernel
ADD kernel/go.* .
-RUN --mount=type=cache,target=/root/.cache/go-build --mount=type=cache,target=/go/pkg \
- go mod download
+RUN go mod download
ADD kernel/ .
-RUN --mount=type=cache,target=/root/.cache/go-build --mount=type=cache,target=/go/pkg \
+FROM go-source AS go-build
+RUN --mount=type=cache,target=/root/.cache/go-build \
go build -tags "fts5 sqlcipher" -ldflags "-s -w"
-FROM go-build AS ocr-build
+FROM ${ALPINE_IMAGE} AS onnx-build
ARG TARGETARCH
-# 容器保留 Alpine 基础镜像,使用 musl 构建原生运行时和识别辅助进程。
-RUN apk add --no-cache bash cmake make g++ git patch python3 py3-pip py3-packaging linux-headers
+ARG TARGETPLATFORM
+ARG ONNX_COMMIT=3a728b75062256951b6e19ce718907cf1a1d4cf0
+ARG ONNX_VERSION=1.24.3
+ARG ONNX_TOOLCHAIN_REV=1
+# ONNX 阶段只依赖 C++ 工具链和固定源码;更新工具链时递增修订号以刷新安装层。
+RUN echo "${TARGETPLATFORM} toolchain revision ${ONNX_TOOLCHAIN_REV}" \
+ && apk add --no-cache bash cmake make g++ git patch python3 py3-pip py3-packaging linux-headers \
+ && apk info -v | sort > /onnx-toolchain.txt
RUN git clone --no-checkout https://github.com/microsoft/onnxruntime /onnxruntime \
&& cd /onnxruntime \
- && git checkout 3a728b75062256951b6e19ce718907cf1a1d4cf0 \
+ && git checkout "${ONNX_COMMIT}" \
&& git submodule update --init --recursive
# Release 构建不生成栈回溯,将 execinfo.h 限定为 Debug 构建所需的头文件。
RUN <<EORUN
@@ -71,13 +80,22 @@ EOPATCH
EORUN
RUN python3 /onnxruntime/tools/ci_build/build.py --build_dir /onnxruntime/build \
--config Release --update --build --parallel 2 --build_shared_lib \
- --skip_tests --allow_running_as_root --compile_no_warning_as_error
-RUN mkdir -p /ocr/linux-${TARGETARCH} \
- && cp /onnxruntime/build/Release/libonnxruntime.so.1.24.3 /ocr/linux-${TARGETARCH}/libonnxruntime.so \
- && cp /onnxruntime/LICENSE /onnxruntime/ThirdPartyNotices.txt /ocr/linux-${TARGETARCH}/ \
+ --skip_tests --allow_running_as_root --compile_no_warning_as_error \
+ --cmake_extra_defines onnxruntime_BUILD_UNIT_TESTS=OFF \
+ && grep -q '^onnxruntime_BUILD_UNIT_TESTS:BOOL=OFF$' /onnxruntime/build/Release/CMakeCache.txt \
+ && mkdir -p /onnx-artifacts \
+ && cp "/onnxruntime/build/Release/libonnxruntime.so.${ONNX_VERSION}" /onnx-artifacts/libonnxruntime.so \
+ && cp /onnxruntime/LICENSE /onnxruntime/ThirdPartyNotices.txt /onnx-toolchain.txt /onnx-artifacts/ \
+ && rm -rf /onnxruntime/build
+
+FROM go-source AS ocr-build
+ARG TARGETARCH
+RUN --mount=type=cache,target=/root/.cache/go-build \
+ mkdir -p /ocr/linux-${TARGETARCH} \
&& go build -trimpath -ldflags "-s -w" -o /ocr/linux-${TARGETARCH}/siyuan-ocr ./ocr/cmd/ocr-worker
+COPY --from=onnx-build /onnx-artifacts/ /ocr/linux-${TARGETARCH}/
-FROM alpine:latest
+FROM ${ALPINE_IMAGE}
LABEL maintainer="Liang Ding<[email protected]>"
RUN apk add --no-cache ca-certificates tzdata su-exec libstdc++
diff --git a/scripts/check-docker-cache.py b/scripts/check-docker-cache.py
new file mode 100644
index 0000000000..ecf24b2a32
--- /dev/null
+++ b/scripts/check-docker-cache.py
@@ -0,0 +1,141 @@
+"""用独立缓存和全新 builder 验收 ONNX 的冷构建、热构建及失效行为。"""
+
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import tempfile
+import threading
+import time
+import uuid
+
+
+PLATFORMS = {"linux/amd64", "linux/arm64", "linux/arm/v7", "linux/arm/v8"}
+
+
+def memory_bytes(value):
+ match = re.match(r"([0-9.]+)\s*(B|KiB|MiB|GiB|TiB)\b", value)
+ if not match:
+ raise ValueError(f"Unknown Docker memory measurement: {value}")
+ return int(float(match[1]) * 1024 ** ("B", "KiB", "MiB", "GiB", "TiB").index(match[2]))
+
+
+def cache_bytes(manifest):
+ # 当前 registry 导出使用 OCI image manifest,统计其引用的压缩层和配置大小。
+ if "layers" not in manifest:
+ return None
+ entries = [*manifest["layers"], manifest.get("config", {})]
+ sizes = {entry["digest"]: entry["size"] for entry in entries if "digest" in entry and "size" in entry}
+ return sum(sizes.values())
+
+
+def onnx_steps(log):
+ 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)
+ if match:
+ steps[match[1]] = match[2]
+ status = re.match(r"^#(\d+) (CACHED|DONE)(?:\s|$)", line)
+ 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:
+ raise ValueError(f"Incomplete ONNX build log: {tuple(result)}")
+ return result
+
+
+def build_case(context, cache, directory, name, *, import_cache, revision=None):
+ builder = "siyuan-cache-check-" + uuid.uuid4().hex
+ started = time.monotonic()
+ log_path = directory / (name + ".log")
+ stopped = threading.Event()
+ measurements = {"peak_builder_memory_bytes": None, "minimum_host_free_disk_bytes": shutil.disk_usage(directory).free}
+
+ def sample():
+ last_progress = started
+ while not stopped.is_set():
+ measurements["minimum_host_free_disk_bytes"] = min(
+ measurements["minimum_host_free_disk_bytes"], shutil.disk_usage(directory).free)
+ try:
+ stats = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{json .}}",
+ "buildx_buildkit_" + builder + "0"], capture_output=True, text=True, timeout=5)
+ if stats.returncode == 0 and stats.stdout.strip():
+ used = memory_bytes(json.loads(stats.stdout)["MemUsage"].split("/")[0].strip())
+ measurements["peak_builder_memory_bytes"] = max(measurements["peak_builder_memory_bytes"] or 0, used)
+ except (subprocess.TimeoutExpired, ValueError, KeyError):
+ pass
+ now = time.monotonic()
+ if now - last_progress >= 60:
+ print(f"{name}: {int(now - started)}s elapsed, measurements={measurements}", flush=True)
+ last_progress = now
+ stopped.wait(5)
+
+ monitor = threading.Thread(target=sample, daemon=True)
+ try:
+ 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",
+ "--cache-to", "type=registry,ref=" + cache + ",mode=max"]
+ if import_cache:
+ command += ["--cache-from", "type=registry,ref=" + cache]
+ if revision is not None:
+ command += ["--build-arg", "ONNX_TOOLCHAIN_REV=" + revision]
+ command.append(str(context))
+ # 将完整日志留在验收目录,终端只显示当前轮次和最后的缓存命中结果。
+ 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"))
+ 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),
+ "cache_referenced_bytes": cache_bytes(json.loads(exported.stdout)), **measurements}
+ finally:
+ stopped.set()
+ if monitor.is_alive():
+ monitor.join(timeout=10)
+ subprocess.run(["docker", "buildx", "rm", "--force", builder], check=False)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--dockerfile", type=Path, required=True)
+ parser.add_argument("--cache-repository", required=True)
+ parser.add_argument("--records", type=Path, required=True)
+ 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)
+ cache = args.cache_repository + ":buildcache-check-" + uuid.uuid4().hex
+ report = {"cache": cache, "status": "running", "cases": [],
+ "dockerfile_sha256": hashlib.sha256(args.dockerfile.read_bytes()).hexdigest()}
+ try:
+ with tempfile.TemporaryDirectory(prefix="siyuan-onnx-cache-") as directory:
+ context = Path(directory)
+ (context / "Dockerfile").write_bytes(args.dockerfile.read_bytes())
+ (context / "app").mkdir()
+ for name, imported, changed in (("cold", False, False), ("warm", True, False),
+ ("application-change", True, True), ("onnx-input-change", True, False)):
+ print(f"ONNX cache acceptance: {name}", flush=True)
+ 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)
+ report["cases"].append(result)
+ expected = name in ("warm", "application-change")
+ if any(cached != expected for cached in result["cached"].values()):
+ raise ValueError(f"Unexpected cache reuse for {name}: {result['cached']}")
+ print(json.dumps(result), flush=True)
+ report["status"] = "passed"
+ except Exception as error:
+ report.update(status="failed", error=str(error))
+ raise
+ finally:
+ (args.records / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test_docker_release.py b/scripts/test_docker_release.py
new file mode 100644
index 0000000000..507939bcb0
--- /dev/null
+++ b/scripts/test_docker_release.py
@@ -0,0 +1,179 @@
+"""Docker 发布验收、manifest 校验和缓存日志的回归测试,不构建镜像。"""
+
+import copy
+import importlib.util
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+from unittest.mock import patch
+
+
+def module(name, file):
+ spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(file))
+ result = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(result)
+ return result
+
+
+release = module("docker_release", "verify-docker-release.py")
+cache = module("docker_cache", "check-docker-cache.py")
+IMAGE = "b3log/siyuan@sha256:" + "a" * 64
+
+
+def manifest():
+ entries = []
+ for index, platform in enumerate(release.PLATFORMS):
+ parts = platform.split("/")
+ target = {"os": parts[0], "architecture": parts[1]}
+ if len(parts) == 3:
+ target["variant"] = parts[2]
+ elif parts[1] == "arm64":
+ target["variant"] = "v8"
+ entries.append({"platform": target, "digest": "sha256:" + str(index + 1) * 64})
+ return {"manifests": entries}
+
+
+def report():
+ return {"image": IMAGE, "version": "3.8.7", "status": "passed", "platforms": [
+ {"platform": platform, "digest": digest, "checks": sorted(release.CHECKS)}
+ for platform, digest in release.manifests(manifest()).items()]}
+
+
+class ManifestTests(unittest.TestCase):
+ def test_keeps_arm32_variants_separate_and_normalizes_arm64(self):
+ self.assertEqual(set(release.manifests(manifest())), set(release.PLATFORMS))
+
+ def test_accepts_attestations_but_rejects_unknown_executable_platform(self):
+ index = manifest()
+ index["manifests"].append({"platform": {"os": "unknown", "architecture": "unknown"},
+ "annotations": {"vnd.docker.reference.type": "attestation-manifest"}})
+ self.assertEqual(len(release.manifests(index)), 4)
+ index["manifests"][-1].pop("annotations")
+ with self.assertRaises(ValueError):
+ release.manifests(index)
+
+ def test_missing_duplicate_and_invalid_digest_are_rejected(self):
+ for change in (lambda value: value["manifests"].pop(),
+ lambda value: value["manifests"].append(copy.deepcopy(value["manifests"][0])),
+ lambda value: value["manifests"][0].update(digest="latest")):
+ with self.subTest(change=change):
+ index = manifest()
+ change(index)
+ with self.assertRaises(ValueError):
+ release.manifests(index)
+
+
+class OCRTests(unittest.TestCase):
+ def test_recognition_tolerates_layout_whitespace_and_latin_case(self):
+ release.validate_rows('[{"text":"SiYuan"},{"text":" OCR123"}]', "siyuan ocr 123")
+ release.validate_rows('[{"text":"思源"},{"text":"笔记"}]', "思源笔记")
+ release.validate_rows("[]", None)
+
+ def test_blank_false_positive_wrong_text_and_invalid_response_are_rejected(self):
+ for output, expected in (("{}", None), ('[{"text":5}]', None), ('[{"text":"noise"}]', None),
+ ('[{"text":"思源笔计"}]', "思源笔记")):
+ with self.subTest(output=output), self.assertRaises(ValueError):
+ release.validate_rows(output, expected)
+
+
+class PublishTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.path = Path(self.temp.name) / "report.json"
+
+ def save(self, value):
+ self.path.write_text(json.dumps(value), encoding="utf-8")
+
+ def test_failed_partial_or_mismatched_verification_never_publishes(self):
+ for mutate in (lambda value: value.update(status="failed"), lambda value: value["platforms"].pop(),
+ lambda value: value.update(image=IMAGE.replace("a", "b")),
+ lambda value: value.update(version="3.8.8"),
+ lambda value: value["platforms"][0]["checks"].remove("chinese")):
+ value = report()
+ mutate(value)
+ self.save(value)
+ with self.subTest(mutate=mutate), patch.object(release, "run") as run:
+ with self.assertRaises(ValueError):
+ release.promote(IMAGE, "3.8.7", self.path)
+ run.assert_not_called()
+
+ def test_publishes_verified_digest_then_checks_both_tags(self):
+ self.save(report())
+ 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]
+ 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)
+
+ 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), "")):
+ with self.assertRaisesRegex(ValueError, "differs"):
+ release.promote(IMAGE, "3.8.7", self.path)
+
+ def test_smoke_failure_preserves_failed_report_and_blocks_promotion(self):
+ fixtures = Path(self.temp.name) / "fixtures"
+ fixtures.mkdir()
+ for name in ("chinese", "latin", "blank"):
+ (fixtures / (name + ".png")).write_bytes(b"fixture")
+ with patch.object(release, "run", return_value=subprocess.CompletedProcess([], 0, json.dumps(manifest()), "")), \
+ patch.object(release, "verify_platform", side_effect=RuntimeError("OCR failed")):
+ with self.assertRaisesRegex(RuntimeError, "OCR failed"):
+ release.verify(IMAGE, "3.8.7", fixtures, self.path, 240)
+ self.assertEqual(json.loads(self.path.read_text())["status"], "failed")
+ with patch.object(release, "run") as run:
+ with self.assertRaises(ValueError):
+ release.promote(IMAGE, "3.8.7", self.path)
+ run.assert_not_called()
+
+ def test_notebook_failure_removes_only_owned_test_resources(self):
+ def run(command, **kwargs):
+ if command[:2] == ["docker", "inspect"]:
+ return subprocess.CompletedProcess([], 0, json.dumps([{"NetworkSettings": {"Ports": {
+ "6806/tcp": [{"HostPort": "12345"}]}}}]), "")
+ return subprocess.CompletedProcess([], 0, "", "")
+ with patch.object(release, "run", side_effect=run) as commands, \
+ patch.object(release, "request", side_effect=[{"progress": 100}, "3.8.7"]):
+ with self.assertRaisesRegex(RuntimeError, "worker failed"):
+ release.verify_notebook(IMAGE, "linux/amd64", "3.8.7", 240,
+ lambda: (_ for _ in ()).throw(RuntimeError("worker failed")))
+ cleanup = [entry.args[0] for entry in commands.call_args_list if entry.args[0][:2] == ["docker", "rm"]]
+ self.assertEqual(len(cleanup), 1)
+ self.assertTrue(cleanup[0][-1].startswith("siyuan-docker-smoke-"))
+ self.assertEqual(commands.call_args_list[-1].args[0][-1], cleanup[0][-1] + "-workspace")
+
+
+class CacheTests(unittest.TestCase):
+ def test_resource_measurements_use_binary_units_and_deduplicate_cache_layers(self):
+ self.assertEqual(cache.memory_bytes("1.5GiB"), 1610612736)
+ self.assertEqual(cache.memory_bytes("512MiB"), 536870912)
+ self.assertEqual(cache.cache_bytes({"layers": [{"digest": "one", "size": 100}, {"digest": "one", "size": 100}],
+ "config": {"digest": "two", "size": 12}}), 112)
+ self.assertIsNone(cache.cache_bytes({"manifests": []}))
+
+ def log(self, cached):
+ return "\n".join(f"#{index} [{platform} onnx-build 5/5] RUN python3 /onnxruntime/tools/ci_build/build.py --build\n"
+ f"#{index} {'CACHED' if cached else 'DONE 12.3s'}"
+ for index, platform in enumerate(release.PLATFORMS))
+
+ def test_distinguishes_real_compilation_from_cached_steps(self):
+ self.assertTrue(all(cache.onnx_steps(self.log(True)).values()))
+ self.assertFalse(any(cache.onnx_steps(self.log(False)).values()))
+
+ def test_missing_architecture_or_only_dependency_cache_is_not_accepted(self):
+ for log in (self.log(True).replace("linux/arm/v8", "linux/arm/v7"),
+ self.log(True).replace("RUN python3 /onnxruntime/tools/ci_build/build.py", "RUN apk add cmake")):
+ with self.assertRaises(ValueError):
+ cache.onnx_steps(log)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/testdata/docker-ocr/README.md b/scripts/testdata/docker-ocr/README.md
new file mode 100644
index 0000000000..d810f8dc55
--- /dev/null
+++ b/scripts/testdata/docker-ocr/README.md
@@ -0,0 +1,3 @@
+测试图片由仓库内置霞鹜文楷 GB Lite 和 Liberation Sans 字体生成,只用于 Docker 镜像的真实 OCR 验收。字体许可证分别位于 `app/appearance/fonts/LxgwWenKaiGB-Lite-1.521/LICENSE` 和 PDF 标准字体的上游许可证中。
+
+`chinese.png` 应识别出「思源笔记」,`latin.png` 应识别出「SiYuan OCR 123」,`blank.png` 应返回空结果。验收忽略空白和拉丁字母大小写,不忽略汉字差异。
diff --git a/scripts/testdata/docker-ocr/blank.png b/scripts/testdata/docker-ocr/blank.png
new file mode 100644
index 0000000000..f9671acfa6
Binary files /dev/null and b/scripts/testdata/docker-ocr/blank.png differ
diff --git a/scripts/testdata/docker-ocr/chinese.png b/scripts/testdata/docker-ocr/chinese.png
new file mode 100644
index 0000000000..99dfdb3285
Binary files /dev/null and b/scripts/testdata/docker-ocr/chinese.png differ
diff --git a/scripts/testdata/docker-ocr/latin.png b/scripts/testdata/docker-ocr/latin.png
new file mode 100644
index 0000000000..2bc84f2591
Binary files /dev/null and b/scripts/testdata/docker-ocr/latin.png differ
diff --git a/scripts/verify-docker-release.py b/scripts/verify-docker-release.py
new file mode 100644
index 0000000000..7fed8ec460
--- /dev/null
+++ b/scripts/verify-docker-release.py
@@ -0,0 +1,226 @@
+"""逐架构验证临时 Docker 镜像,并在验收通过后按 digest 发布。"""
+
+import argparse
+import json
+from pathlib import Path
+import re
+import subprocess
+import time
+import unicodedata
+import urllib.error
+import urllib.request
+import uuid
+
+
+PLATFORMS = ("linux/amd64", "linux/arm64", "linux/arm/v7", "linux/arm/v8")
+CHECKS = {"licenses", "version", "model-load", "chinese", "latin", "blank", "worker-failure", "notebook"}
+DIGEST = re.compile(r"sha256:[0-9a-f]{64}")
+
+
+def run(arguments, *, input=None, timeout=300, check=True):
+ result = subprocess.run(arguments, input=input, text=True, encoding="utf-8", errors="replace",
+ capture_output=True, timeout=timeout)
+ if check and result.returncode:
+ raise RuntimeError(f"Command failed ({result.returncode}): {arguments[0]}\n{result.stderr}")
+ return result
+
+
+def platform_name(platform):
+ name = platform.get("os", "") + "/" + platform.get("architecture", "")
+ variant = platform.get("variant", "")
+ if variant and not (name == "linux/arm64" and variant == "v8"):
+ name += "/" + variant
+ return name
+
+
+def manifests(index):
+ result = {}
+ for entry in index.get("manifests", []):
+ if entry.get("annotations", {}).get("vnd.docker.reference.type") == "attestation-manifest":
+ continue
+ name = platform_name(entry.get("platform", {}))
+ digest = entry.get("digest", "")
+ 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)}")
+ return result
+
+
+def normalized(text):
+ return "".join(unicodedata.normalize("NFKC", text).split()).casefold()
+
+
+def validate_rows(output, expected):
+ rows = json.loads(output)
+ if not isinstance(rows, list) or any(not isinstance(row, dict) or not isinstance(row.get("text"), str) for row in rows):
+ raise ValueError("Invalid OCR response")
+ if expected is None:
+ if rows:
+ raise ValueError("Blank image produced OCR text")
+ elif normalized(expected) not in normalized("".join(row["text"] for row in rows)):
+ raise ValueError(f"Expected OCR text {expected!r}, received {rows!r}")
+
+
+def request(base, endpoint, token, payload=None):
+ data = None if payload is None else json.dumps(payload).encode("utf-8")
+ req = urllib.request.Request(base + endpoint, data=data,
+ headers={"Content-Type": "application/json", "Authorization": "Token " + token})
+ with urllib.request.urlopen(req, timeout=10) as response:
+ result = json.load(response)
+ if result.get("code") != 0:
+ raise ValueError(f"Kernel API failed: {endpoint}: {result}")
+ return result["data"]
+
+
+def verify_notebook(image, platform, version, timeout, fail_ocr):
+ # 只使用本次测试创建的容器和卷,所有读写均发生在临时工作空间。
+ name = "siyuan-docker-smoke-" + uuid.uuid4().hex
+ volume, token = name + "-workspace", uuid.uuid4().hex
+ run(["docker", "volume", "create", volume])
+ try:
+ run(["docker", "run", "--rm", "-i", "--platform", platform, "--entrypoint", "/bin/sh",
+ "--mount", f"type=volume,src={volume},dst=/siyuan/workspace", image, "-ec",
+ "mkdir -p /siyuan/workspace/conf; cat > /siyuan/workspace/conf/conf.json"],
+ input=json.dumps({"api": {"token": token}, "ocr": {"auto": False}}))
+ run(["docker", "run", "-d", "--name", name, "--platform", platform,
+ "--mount", f"type=volume,src={volume},dst=/siyuan/workspace",
+ "-p", "127.0.0.1::6806", image, "serve", "--port=6806", "--safe-mode",
+ "--accessAuthCode=" + token])
+ bindings = json.loads(run(["docker", "inspect", name]).stdout)[0]["NetworkSettings"]["Ports"]["6806/tcp"]
+ base = "http://127.0.0.1:" + bindings[0]["HostPort"]
+ deadline = time.monotonic() + timeout
+ while True:
+ try:
+ progress = request(base, "/api/system/bootProgress", token)
+ if progress["progress"] == 100:
+ break
+ except (urllib.error.URLError, TimeoutError, ValueError):
+ pass
+ if time.monotonic() >= deadline:
+ raise TimeoutError(f"Kernel did not boot: {platform}\n" + run(["docker", "logs", name]).stdout)
+ if run(["docker", "inspect", "--format", "{{.State.Running}}", name]).stdout.strip() != "true":
+ raise RuntimeError("Kernel stopped before booting\n" + run(["docker", "logs", name]).stdout)
+ time.sleep(2)
+ if request(base, "/api/system/version", token) != version:
+ raise ValueError("HTTP kernel version differs from release version")
+ fail_ocr()
+ notebook = request(base, "/api/notebook/createNotebook", token, {"name": "Docker OCR smoke"})
+ block = request(base, "/api/filetree/createDocWithMd", token,
+ {"notebook": notebook["notebook"]["id"], "path": "/Docker smoke", "markdown": "Docker OCR smoke 123"})
+ data = request(base, "/api/block/getBlockKramdown", token, {"id": block})
+ if "Docker OCR smoke 123" not in data["kramdown"]:
+ raise ValueError("Notebook write/read verification failed")
+ finally:
+ run(["docker", "rm", "-f", name], check=False)
+ run(["docker", "volume", "rm", volume], check=False)
+
+
+def verify_platform(repository, digest, platform, version, fixtures, timeout):
+ started = time.monotonic()
+ image = repository + "@" + digest
+ architecture = platform.split("/")[1]
+ runtime = "/opt/siyuan/stage/ocr/runtime/linux-" + architecture
+ worker = runtime + "/siyuan-ocr"
+ prefix = ["docker", "run", "--rm", "--platform", platform]
+ checks = []
+ run(["docker", "pull", "--platform", platform, image], timeout=900)
+ shell = f"test -s LICENSE && test -s THIRD_PARTY_NOTICES.md && test -s {runtime}/LICENSE " \
+ f"&& test -s {runtime}/ThirdPartyNotices.txt && test -s {runtime}/onnx-toolchain.txt " \
+ f"&& ldd {worker} && ldd {runtime}/libonnxruntime.so"
+ run(prefix + ["--entrypoint", "/bin/sh", image, "-ec", shell])
+ checks.append("licenses")
+ output = run(prefix + ["--entrypoint", "/opt/siyuan/kernel", image, "--version"]).stdout
+ if not re.search(r"\bversion\s+" + re.escape(version) + r"(?![\w.-])", output):
+ raise ValueError(f"Unexpected kernel version: {output}")
+ checks.append("version")
+ worker_name = "siyuan-docker-ocr-" + uuid.uuid4().hex
+ prefix += ["--name", worker_name, "-i", "--mount", f"type=bind,src={fixtures.resolve()},dst=/fixtures,readonly",
+ "--entrypoint", worker, image]
+ config = {"library": runtime + "/libonnxruntime.so", "directory": "/opt/siyuan/stage/ocr/models/tiny"}
+ try:
+ for name, expected in (("model-load", None), ("chinese", "思源笔记"), ("latin", "SiYuan OCR 123"), ("blank", None)):
+ payload = {"config": config, "image": "" if name == "model-load" else f"/fixtures/{name}.png"}
+ result = run(prefix, input=json.dumps(payload), timeout=timeout)
+ validate_rows(result.stdout, expected)
+ checks.append(name)
+
+ # 模拟辅助进程加载失败,再验证已启动的内核仍可读写普通文档。
+ def fail_ocr():
+ bad = {"config": {**config, "library": runtime + "/missing-onnxruntime.so"}, "image": ""}
+ failure = run(prefix, input=json.dumps(bad), timeout=timeout, check=False)
+ if not failure.returncode or "missing-onnxruntime.so" not in failure.stderr:
+ raise ValueError("Missing OCR runtime did not produce the expected failure")
+ checks.append("worker-failure")
+
+ verify_notebook(image, platform, version, timeout, fail_ocr)
+ checks.append("notebook")
+ finally:
+ run(["docker", "rm", "-f", worker_name], check=False)
+ return {"platform": platform, "digest": digest, "checks": checks, "seconds": round(time.monotonic() - started, 3)}
+
+
+def verify(image, version, fixtures, report_path, timeout):
+ 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": []}
+ try:
+ for platform in PLATFORMS:
+ print(f"Verifying {platform} under Docker/QEMU", flush=True)
+ report["platforms"].append(verify_platform(repository, index[platform], platform, version, fixtures, timeout))
+ report["status"] = "passed"
+ except Exception as error:
+ report.update(status="failed", error=str(error))
+ raise
+ finally:
+ 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"))
+ 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):
+ 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", "")):
+ raise ValueError("Incomplete platform verification")
+ repository, separator, digest = image.partition("@")
+ if not separator or not DIGEST.fullmatch(digest):
+ raise ValueError("Image promotion requires an immutable digest")
+ 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("--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)
+ 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")
+ if args.command == "verify":
+ verify(args.image, args.version, args.fixtures, args.report, args.timeout)
+ else:
+ promote(args.image, args.version, args.report)
+
+
+if __name__ == "__main__":
+ main()