Skip to content

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

:zap: Reuse verified staged OCR runtimes https://github.com/siyuan-note/siyuan/issues/20328

Daniel3a722fd77b42
diff --git a/scripts/prepare-ocr.py b/scripts/prepare-ocr.py
index 9dcf2787b7..5e718f7111 100644
--- a/scripts/prepare-ocr.py
+++ b/scripts/prepare-ocr.py
@@ -22,6 +22,7 @@ import zipfile
ROOT = Path(__file__).resolve().parents[1]
MANIFEST = json.loads(Path(__file__).with_name("ocr-assets.json").read_text(encoding="utf-8"))
STAGE = ROOT / "app/stage/ocr"
+RUNTIME_STAMP = "onnxruntime-files.json"
class WindowsDLL:
@@ -260,15 +261,47 @@ def download_ranges(entry, destination):
future.result()
-def prepare_runtime(target, build_worker, prerequisites=None):
- if prerequisites is None:
- prerequisites = runtime_prerequisites(target, build_worker)
- entry = MANIFEST["runtime"][target]
- cache = Path(tempfile.gettempdir()) / "siyuan-ocr-assets" / entry["url"].rsplit("/", 1)[1]
- download(entry, cache)
- directory = STAGE / "runtime" / target
- directory.mkdir(parents=True, exist_ok=True)
+def runtime_source(entry):
+ """记录已校验归档的来源摘要和主库名称,镜像地址不参与复用判断。"""
+ algorithm = "sha256" if "sha256" in entry else "sha512"
+ return {"algorithm": algorithm, "digest": entry[algorithm], "size": entry.get("size"), "library": entry["library"]}
+
+
+def record_runtime(entry, directory, names):
+ """解包成功后原子写入归档来源和产物摘要。"""
+ stamp = {"version": 1, "archive": runtime_source(entry),
+ "files": {name: digest(directory / name) for name in sorted(names)}}
+ handle, name = tempfile.mkstemp(prefix=RUNTIME_STAMP + "-", suffix=".tmp", dir=directory)
+ os.close(handle)
+ temporary = Path(name)
+ try:
+ temporary.write_text(json.dumps(stamp, indent=2) + "\n", encoding="utf-8")
+ os.replace(temporary, directory / RUNTIME_STAMP)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def runtime_is_verified(entry, directory):
+ """来源匹配且归档产物完整时允许复用,异常标记回退到归档校验和解包。"""
+ try:
+ stamp = json.loads((directory / RUNTIME_STAMP).read_text(encoding="utf-8"))
+ if not isinstance(stamp, dict) or stamp.get("version") != 1 or stamp.get("archive") != runtime_source(entry):
+ return False
+ files = stamp.get("files")
+ allowed = {entry["library"], "LICENSE", "ThirdPartyNotices.txt", "onnxruntime_providers_shared.dll"}
+ if not isinstance(files, dict) or entry["library"] not in files or not set(files).issubset(allowed):
+ return False
+ return all(isinstance(value, str) and (directory / name).is_file() and
+ not (directory / name).is_symlink() and digest(directory / name) == value
+ for name, value in files.items())
+ except (OSError, ValueError, TypeError):
+ return False
+
+
+def extract_runtime(entry, cache, directory):
+ """仅解包主库、共享库和许可证,返回本次归档产出的文件名。"""
library = entry["library"]
+ written = {library}
# 仅复制固定名称的库和许可证,归档路径不参与目标路径拼接。
if zipfile.is_zipfile(cache):
with zipfile.ZipFile(cache) as archive:
@@ -278,6 +311,7 @@ def prepare_runtime(target, build_worker, prerequisites=None):
for name in files:
if name.rsplit("/", 1)[-1] in ("LICENSE", "ThirdPartyNotices.txt", "onnxruntime_providers_shared.dll"):
(directory / name.rsplit("/", 1)[-1]).write_bytes(archive.read(name))
+ written.add(name.rsplit("/", 1)[-1])
else:
with tarfile.open(cache, "r:gz") as archive:
files = [member for member in archive.getmembers() if member.isfile()]
@@ -291,6 +325,23 @@ def prepare_runtime(target, build_worker, prerequisites=None):
if member.name.rsplit("/", 1)[-1] in ("LICENSE", "ThirdPartyNotices.txt"):
with archive.extractfile(member) as source, (directory / member.name.rsplit("/", 1)[-1]).open("wb") as destination:
shutil.copyfileobj(source, destination)
+ written.add(member.name.rsplit("/", 1)[-1])
+ return written
+
+
+def prepare_runtime(target, build_worker, prerequisites=None):
+ if prerequisites is None:
+ prerequisites = runtime_prerequisites(target, build_worker)
+ entry = MANIFEST["runtime"][target]
+ directory = STAGE / "runtime" / target
+ directory.mkdir(parents=True, exist_ok=True)
+ if runtime_is_verified(entry, directory):
+ print(f"Reusing verified OCR runtime: {target}")
+ else:
+ cache = Path(tempfile.gettempdir()) / "siyuan-ocr-assets" / entry["url"].rsplit("/", 1)[1]
+ download(entry, cache)
+ record_runtime(entry, directory, extract_runtime(entry, cache, directory))
+ # 本地依赖每次重新准备,复用归档产物不跳过 CRT 校验或工作进程构建。
if target.startswith("windows-"):
prepare_windows_crt(target, directory, prerequisites)
if target.startswith("linux-") and build_worker:
diff --git a/scripts/test_prepare_ocr.py b/scripts/test_prepare_ocr.py
index 38b0b60e78..fbe7d0f4a1 100644
--- a/scripts/test_prepare_ocr.py
+++ b/scripts/test_prepare_ocr.py
@@ -258,6 +258,109 @@ class ResourceTests(unittest.TestCase):
with patch.object(prepare, "STAGE", self.root / "stage"), patch.object(prepare, "MANIFEST", {"runtime": {target: entry}}), patch.object(prepare.tempfile, "gettempdir", return_value=str(self.root / "cache")):
prepare.prepare_runtime(target, False)
+ def runtime_archive(self):
+ archive = self.root / "runtime.tgz"
+ with tarfile.open(archive, "w:gz") as output:
+ for name, content in {"ort/lib/libonnxruntime.so.1": b"native", "ort/LICENSE": b"license"}.items():
+ member = tarfile.TarInfo(name)
+ member.size = len(content)
+ output.addfile(member, io.BytesIO(content))
+ return archive
+
+ def test_verified_runtime_reuses_artifacts_without_archive_cache(self):
+ archive = self.runtime_archive()
+ entry = {**self.entry(archive), "library": "libonnxruntime.so"}
+ with patch.object(prepare, "STAGE", self.root / "stage"), \
+ patch.object(prepare, "MANIFEST", {"runtime": {"linux-amd64": entry}}), \
+ patch.object(prepare.tempfile, "gettempdir", return_value=str(self.root / "cache")):
+ prepare.prepare_runtime("linux-amd64", False)
+ archive.unlink()
+ (self.root / "cache/siyuan-ocr-assets/runtime.tgz").unlink()
+ with patch.object(prepare, "download") as download:
+ prepare.prepare_runtime("linux-amd64", False)
+ download.assert_not_called()
+ directory = self.root / "stage/runtime/linux-amd64"
+ self.assertEqual((directory / "libonnxruntime.so").read_bytes(), b"native")
+ self.assertEqual((directory / "LICENSE").read_bytes(), b"license")
+
+ def test_runtime_reuse_rejects_changed_source_or_damaged_artifacts(self):
+ directory = self.root / "runtime"
+ directory.mkdir()
+ (directory / "library").write_bytes(b"native")
+ (directory / "LICENSE").write_bytes(b"license")
+ for algorithm in ("sha256", "sha512"):
+ entry = {"library": "library", algorithm: "a" * (64 if algorithm == "sha256" else 128), "size": 6}
+ prepare.record_runtime(entry, directory, {"library", "LICENSE"})
+ self.assertTrue(prepare.runtime_is_verified(entry, directory))
+ self.assertTrue(prepare.runtime_is_verified({**entry, "url": "https://mirror.invalid/archive"}, directory))
+ for changed in ({algorithm: "b" * len(entry[algorithm])}, {"size": 7}, {"library": "other"}):
+ self.assertFalse(prepare.runtime_is_verified({**entry, **changed}, directory))
+ (directory / "LICENSE").write_bytes(b"tampered")
+ self.assertFalse(prepare.runtime_is_verified(entry, directory))
+ (directory / "LICENSE").unlink()
+ self.assertFalse(prepare.runtime_is_verified(entry, directory))
+
+ def test_runtime_reuse_rejects_malformed_or_incomplete_stamps(self):
+ directory = self.root / "runtime"
+ directory.mkdir()
+ (directory / "library").write_bytes(b"native")
+ entry = {"library": "library", "sha256": "a" * 64}
+ self.assertFalse(prepare.runtime_is_verified(entry, directory))
+ for value in ("not json", "null", "[]", "{}"):
+ (directory / prepare.RUNTIME_STAMP).write_text(value, encoding="utf-8")
+ self.assertFalse(prepare.runtime_is_verified(entry, directory))
+ prepare.record_runtime(entry, directory, {"library"})
+ valid = json.loads((directory / prepare.RUNTIME_STAMP).read_text(encoding="utf-8"))
+ for files in (None, [], {}, {"LICENSE": "a" * 64}, {"library": None},
+ {"library": prepare.digest(directory / "library"), "../outside": "a" * 64}):
+ with self.subTest(files=files):
+ stamp = {**valid, "files": files}
+ (directory / prepare.RUNTIME_STAMP).write_text(json.dumps(stamp), encoding="utf-8")
+ self.assertFalse(prepare.runtime_is_verified(entry, directory))
+
+ def test_damaged_runtime_is_restored_from_verified_archive(self):
+ archive = self.runtime_archive()
+ entry = {**self.entry(archive), "library": "libonnxruntime.so"}
+ with patch.object(prepare, "STAGE", self.root / "stage"), \
+ patch.object(prepare, "MANIFEST", {"runtime": {"linux-amd64": entry}}), \
+ patch.object(prepare.tempfile, "gettempdir", return_value=str(self.root / "cache")):
+ prepare.prepare_runtime("linux-amd64", False)
+ library = self.root / "stage/runtime/linux-amd64/libonnxruntime.so"
+ library.write_bytes(b"damaged")
+ prepare.prepare_runtime("linux-amd64", False)
+ self.assertEqual(library.read_bytes(), b"native")
+
+ def test_reused_windows_runtime_refreshes_crt(self):
+ source = self.crt_source()
+ archive = self.root / "runtime.zip"
+ with zipfile.ZipFile(archive, "w") as output:
+ output.writestr("ort/lib/onnxruntime.dll", windows_dll(imports={"MSVCP140.dll": ["cpp"]}))
+ entry = {**self.entry(archive), "library": "onnxruntime.dll"}
+ with patch.dict(os.environ, {"SIYUAN_OCR_VC_REDIST_DIR": str(source)}), \
+ patch.object(prepare, "STAGE", self.root / "stage"), \
+ patch.object(prepare, "MANIFEST", {"runtime": {"windows-amd64": entry}}), \
+ patch.object(prepare.tempfile, "gettempdir", return_value=str(self.root / "cache")):
+ prepare.prepare_runtime("windows-amd64", False)
+ dependency = self.root / "stage/runtime/windows-amd64/msvcp140.dll"
+ dependency.unlink()
+ with patch.object(prepare, "download") as download:
+ prepare.prepare_runtime("windows-amd64", False)
+ download.assert_not_called()
+ self.assertEqual(dependency.read_bytes(), (source / "msvcp140.dll").read_bytes())
+
+ def test_reused_linux_runtime_still_builds_worker(self):
+ archive = self.runtime_archive()
+ entry = {**self.entry(archive), "library": "libonnxruntime.so"}
+ with patch.object(prepare, "STAGE", self.root / "stage"), \
+ patch.object(prepare, "MANIFEST", {"runtime": {"linux-amd64": entry}}), \
+ patch.object(prepare.tempfile, "gettempdir", return_value=str(self.root / "cache")):
+ prepare.prepare_runtime("linux-amd64", False)
+ with patch.object(prepare, "download") as download, patch.object(prepare.subprocess, "run") as build:
+ prepare.prepare_runtime("linux-amd64", True, {"CC": "gcc"})
+ download.assert_not_called()
+ build.assert_called_once()
+ self.assertEqual(build.call_args.kwargs["env"], {"CC": "gcc"})
+
class CompilerTests(unittest.TestCase):
def test_selects_native_and_cross_compilers_without_inheriting_kernel_cc(self):