An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Make Harmony OCR runtime builds reproducible https://github.com/siyuan-note/siyuan/issues/19984
Daniel6db65834f630
diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.ymlindex 442e4dfd4f..db1642fb76 100644--- a/.github/workflows/cd.yml+++ b/.github/workflows/cd.yml@@ -202,8 +202,8 @@ jobs:continue-on-error: truerun: pnpm testworking-directory: app- - name: Test OCR resource preparation- run: python -m unittest discover -s scripts -p "test_prepare_ocr.py"+ - name: Test OCR build and resource scripts+ run: python -m unittest discover -s scripts -p "test_*ocr*.py"build:runs-on: ${{ matrix.config.os }}diff --git a/scripts/build-ocr-harmony.py b/scripts/build-ocr-harmony.pyindex a09637e98c..6621b76040 100644--- a/scripts/build-ocr-harmony.py+++ b/scripts/build-ocr-harmony.py@@ -2,14 +2,20 @@"""使用鸿蒙 NDK 构建固定版本的 ONNX Runtime,不编译或启动思源内核。"""import argparse+from contextlib import nullcontext+import hashlib+import inspect+import jsonfrom pathlib import Pathimport reimport shutil+import structimport subprocess-import tarfileimport tempfileREVISION = "3a728b75062256951b6e19ce718907cf1a1d4cf0"+SOURCE_PATHS = ["cmake", "include", "onnxruntime/core", "onnxruntime/contrib_ops/cpu", "onnxruntime/lora",+ "onnxruntime/tool", "tools", "LICENSE", "ThirdPartyNotices.txt", "VERSION_NUMBER"]def replace_required(path, before, after):@@ -31,6 +37,15 @@ def patch_source(source):if guard in content:path.write_text(content.replace(guard, guard + " && !defined(__OHOS__)"), encoding="utf-8")replace_required(source / "onnxruntime/core/mlas/inc/mlas.h", "#if !defined(__APPLE__)", "#if !defined(__APPLE__) && !defined(__OHOS__)")+ # 鸿蒙未编译 I8MM 专用内核,量化分派和激活符号必须共同使用基础 NEON 路径。+ replace_required(+ source / "onnxruntime/core/mlas/lib/platform.cpp",+ " const bool HasI8MMInstructions = MLAS_CPUIDINFO::GetCPUIDInfo().HasArmNeon_I8MM();\n"+ " if (HasI8MMInstructions) {\n#if defined(__linux__)",+ "#if defined(__OHOS__)\n const bool HasI8MMInstructions = false;\n#else\n"+ " const bool HasI8MMInstructions = MLAS_CPUIDINFO::GetCPUIDInfo().HasArmNeon_I8MM();\n#endif\n"+ " if (HasI8MMInstructions) {\n#if defined(__linux__) && !defined(__OHOS__)",+ )replace_required(source / "cmake/onnxruntime_mlas.cmake", "if (NOT APPLE)\n set(mlas_platform_srcs", "if (NOT APPLE AND NOT SIYUAN_OHOS)\n set(mlas_platform_srcs")replace_required(source / "cmake/CMakeLists.txt", 'if (NOT APPLE AND NOT CMAKE_SYSTEM_NAME STREQUAL "Emscripten" AND onnxruntime_target_platform STREQUAL "aarch64")', 'if (NOT APPLE AND NOT SIYUAN_OHOS AND NOT CMAKE_SYSTEM_NAME STREQUAL "Emscripten" AND onnxruntime_target_platform STREQUAL "aarch64")')replace_required(source / "onnxruntime/core/platform/posix/env.cc", "#if !defined(__APPLE__) && !defined(__ANDROID__) && !defined(__wasm__) && !defined(_AIX)", "#if !defined(__APPLE__) && !defined(__ANDROID__) && !defined(__wasm__) && !defined(_AIX) && !defined(__OHOS__)")@@ -45,15 +60,79 @@ def export_source(checkout, destination):revision = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=checkout, text=True).strip()if revision != REVISION:raise ValueError(f"ONNX Runtime source must be {REVISION}, got {revision}")- with tempfile.TemporaryFile() as archive:- subprocess.run(["git", "archive", REVISION], cwd=checkout, stdout=archive, check=True)- archive.seek(0)- with tarfile.open(fileobj=archive) as source:- for member in source.getmembers():- target = (destination / member.name).resolve()- if not target.is_relative_to(destination.resolve()) or member.issym() or member.islnk():- raise ValueError("Unsafe ONNX Runtime source archive")- source.extractall(destination)+ # 直接读取指定树中的对象,避免 git archive 在精简检出中预取整仓库的测试模型和 CUDA 数据。+ tree = subprocess.check_output(["git", "ls-tree", "-rz", REVISION, "--", *SOURCE_PATHS], cwd=checkout)+ with subprocess.Popen(["git", "cat-file", "--batch"], cwd=checkout,+ stdin=subprocess.PIPE, stdout=subprocess.PIPE) as reader:+ try:+ for entry in tree.split(b"\0"):+ if not entry:+ continue+ metadata, name = entry.split(b"\t", 1)+ mode, kind, object_id = metadata.split()+ # 子模块依赖由上游 CMake 按固定版本获取,与 git archive 的导出范围一致。+ if mode == b"160000" and kind == b"commit":+ continue+ target = (destination / name.decode("utf-8")).resolve()+ if kind != b"blob" or mode not in (b"100644", b"100755") or not target.is_relative_to(destination.resolve()):+ raise ValueError("Unsupported ONNX Runtime source entry")+ reader.stdin.write(object_id + b"\n")+ reader.stdin.flush()+ header = reader.stdout.readline().split()+ if len(header) != 3 or header[:2] != [object_id, b"blob"]:+ raise ValueError(f"Cannot read ONNX Runtime source object: {object_id.decode()}")+ content = reader.stdout.read(int(header[2]))+ if len(content) != int(header[2]) or reader.stdout.read(1) != b"\n":+ raise ValueError("Incomplete ONNX Runtime source object")+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(content)+ if mode == b"100755":+ target.chmod(0o755)+ finally:+ reader.stdin.close()+ if reader.wait() != 0:+ raise RuntimeError("Cannot export ONNX Runtime source")+++def prepare_work_directory(root, args):+ # 构建参数或源码适配变化时拒绝复用,防止混入其他架构和 SDK 的产物。+ signature = {+ "revision": REVISION,+ "paths": SOURCE_PATHS,+ "patch": hashlib.sha256(inspect.getsource(patch_source).encode()).hexdigest(),+ "arch": args.arch,+ "ndk": str(args.ndk.resolve()),+ "protoc": str(args.protoc.resolve()),+ }+ marker = root / "siyuan-ocr-build.json"+ if marker.exists():+ if json.loads(marker.read_text(encoding="utf-8")) != signature:+ raise ValueError(f"Build configuration changed; choose a new --work-dir: {root}")+ return root / "source"+ root.mkdir(parents=True, exist_ok=True)+ if any(root.iterdir()):+ raise ValueError(f"Unrecognized or incomplete build directory; choose an empty --work-dir: {root}")+ source = root / "source"+ export_source(args.source, source)+ patch_source(source)+ marker.write_text(json.dumps(signature, indent=2) + "\n", encoding="utf-8")+ return source+++def validate_runtime(library, ndk, arch):+ # 复制前验证目标架构和动态加载入口,避免把宿主机库或带版本号的库打入应用。+ with library.open("rb") as binary:+ header = binary.read(20)+ machine = 183 if arch == "arm64-v8a" else 62+ if len(header) != 20 or header[:6] != b"\x7fELF\x02\x01" or struct.unpack_from("<HH", header, 16) != (3, machine):+ raise ValueError(f"Expected a 64-bit {arch} shared library: {library}")+ suffix = ".exe" if (ndk / "llvm/bin/llvm-readelf.exe").exists() else ""+ details = subprocess.check_output([str(ndk / ("llvm/bin/llvm-readelf" + suffix)),+ "--dynamic", "--dyn-syms", "--wide", str(library)], text=True)+ if not re.search(r"\(SONAME\).*\[libonnxruntime\.so\]", details):+ raise ValueError("ONNX Runtime SONAME must be libonnxruntime.so")+ if not re.search(r"\bGLOBAL\s+DEFAULT\s+\d+\s+OrtGetApiBase(?:@@\S+)?(?:\s|$)", details):+ raise ValueError("ONNX Runtime must export OrtGetApiBase")def main():@@ -64,9 +143,14 @@ def main():parser.add_argument("--output", required=True, type=Path, help="siyuan-harmony/entry/libs directory")parser.add_argument("--arch", choices=("arm64-v8a", "x86_64"), default="arm64-v8a")parser.add_argument("--jobs", type=int, default=2)+ parser.add_argument("--work-dir", type=Path, help="Retain sources, downloaded dependencies and build files for retries")+ parser.add_argument("--deps-mirror", type=Path, help="Local archive mirror arranged by upstream URL host and path")args = parser.parse_args()if not args.protoc.is_file() or args.jobs < 1:parser.error("A host protoc executable and positive job count are required")+ version = subprocess.check_output([str(args.protoc.resolve()), "--version"], text=True).strip()+ if version != "libprotoc 3.21.12":+ parser.error(f"Host protoc 3.21.12 is required, got {version}")ndk = args.ndk.resolve()suffix = ".exe" if (ndk / "llvm/bin/clang.exe").exists() else ""cmake = ndk / ("build-tools/cmake/bin/cmake" + suffix)@@ -75,17 +159,40 @@ def main():ninja = ndk / ("build-tools/cmake/bin/ninja" + suffix)if not ninja.is_file():parser.error("Harmony NDK Ninja executable was not found")- # 所有源码适配只作用于临时副本,保留原始上游检出目录。- with tempfile.TemporaryDirectory(prefix="siyuan-ocr-harmony-") as working:+ # 所有源码适配只作用于构建副本,指定工作目录后可复用失败前已完成的下载和编译。+ working_directory = nullcontext(args.work_dir.resolve()) if args.work_dir else tempfile.TemporaryDirectory(prefix="siyuan-ocr-harmony-")+ with working_directory as working:root = Path(working)- source = root / "source"- export_source(args.source, source)- patch_source(source)+ source = prepare_work_directory(root, args)toolchain = root / "toolchain.cmake"- toolchain.write_text(f'include("{(ndk / "build/cmake/ohos.toolchain.cmake").as_posix()}")\nset(CMAKE_SYSTEM_NAME Linux)\nset(CMAKE_C_FLAGS "${{CMAKE_C_FLAGS}} -D__OHOS__")\nset(CMAKE_CXX_FLAGS "${{CMAKE_CXX_FLAGS}} -D__OHOS__")\n', encoding="utf-8")+ toolchain_content = (+ f'include("{(ndk / "build/cmake/ohos.toolchain.cmake").as_posix()}")\n'+ 'set(CMAKE_SYSTEM_NAME Linux)\n'+ 'foreach(language C CXX)\n'+ ' if(NOT CMAKE_${language}_FLAGS MATCHES "(^| )-D__OHOS__( |$)")\n'+ ' string(APPEND CMAKE_${language}_FLAGS " -D__OHOS__")\n'+ ' endif()\n'+ 'endforeach()\n'+ )+ if not toolchain.exists() or toolchain.read_text(encoding="utf-8") != toolchain_content:+ toolchain.write_text(toolchain_content, encoding="utf-8")build = root / "build"- subprocess.run([str(cmake), "-S", str(source / "cmake"), "-B", str(build), "-G", "Ninja", f"-DCMAKE_MAKE_PROGRAM={ninja}", f"-DCMAKE_TOOLCHAIN_FILE={toolchain}", f"-DOHOS_ARCH={args.arch}", "-DCMAKE_BUILD_TYPE=Release", "-DSIYUAN_OHOS=ON", "-Donnxruntime_CROSS_COMPILING=ON", "-Donnxruntime_BUILD_SHARED_LIB=ON", "-Donnxruntime_BUILD_UNIT_TESTS=OFF", "-Donnxruntime_ENABLE_CPUINFO=OFF", "-Donnxruntime_ENABLE_CPU_FP16_OPS=OFF", "-Donnxruntime_USE_KLEIDIAI=OFF", "-Donnxruntime_USE_SVE=OFF", "-Donnxruntime_RUN_ONNX_TESTS=OFF", "-Donnxruntime_DISABLE_EXTERNAL_INITIALIZERS=ON", f"-DONNX_CUSTOM_PROTOC_EXECUTABLE={args.protoc.resolve()}", "--compile-no-warning-as-error"], check=True)+ configure = [str(cmake), "-S", str(source / "cmake"), "-B", str(build), "-G", "Ninja",+ f"-DCMAKE_MAKE_PROGRAM={ninja.as_posix()}", f"-DCMAKE_TOOLCHAIN_FILE={toolchain.as_posix()}",+ f"-DOHOS_ARCH={args.arch}", "-DCMAKE_BUILD_TYPE=Release", "-DSIYUAN_OHOS=ON",+ "-Donnxruntime_CROSS_COMPILING=ON", "-Donnxruntime_BUILD_SHARED_LIB=ON",+ "-Donnxruntime_BUILD_UNIT_TESTS=OFF", "-Donnxruntime_ENABLE_CPUINFO=OFF",+ "-Donnxruntime_ENABLE_CPU_FP16_OPS=OFF", "-Donnxruntime_USE_KLEIDIAI=OFF",+ "-Donnxruntime_USE_SVE=OFF", "-Donnxruntime_RUN_ONNX_TESTS=OFF",+ "-DFLATBUFFERS_BUILD_FLATC=OFF",+ "-Donnxruntime_DISABLE_EXTERNAL_INITIALIZERS=ON",+ f"-DONNX_CUSTOM_PROTOC_EXECUTABLE={args.protoc.resolve().as_posix()}",+ "--compile-no-warning-as-error"]+ if args.deps_mirror:+ configure.append(f"-Donnxruntime_CMAKE_DEPS_MIRROR_DIR={args.deps_mirror.resolve().as_posix()}")+ subprocess.run(configure, check=True)subprocess.run([str(cmake), "--build", str(build), "--target", "onnxruntime", "--parallel", str(args.jobs)], check=True)+ validate_runtime(build / "libonnxruntime.so", ndk, args.arch)destination = args.output.resolve() / args.archdestination.mkdir(parents=True, exist_ok=True)shutil.copyfile(build / "libonnxruntime.so", destination / "libonnxruntime.so")diff --git a/scripts/test_build_ocr_harmony.py b/scripts/test_build_ocr_harmony.pynew file mode 100644index 0000000000..bfa5bbf031--- /dev/null+++ b/scripts/test_build_ocr_harmony.py@@ -0,0 +1,141 @@+"""鸿蒙 OCR 构建缓存和源码隔离测试,不编译内核。"""++import argparse+import importlib.util+import io+import struct+from pathlib import Path+import tempfile+import unittest+from unittest.mock import patch++SPEC = importlib.util.spec_from_file_location("harmony_ocr", Path(__file__).with_name("build-ocr-harmony.py"))+harmony = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(harmony)+++def patch_fixture(source):+ (source / "patched").write_text("adapted", encoding="utf-8")+++class GitReader:+ def __init__(self, output):+ self.stdin = io.BytesIO()+ self.stdout = io.BytesIO(output)++ def __enter__(self):+ return self++ def __exit__(self, *_):+ self.stdout.close()++ def wait(self):+ return 0+++class SourceExportTests(unittest.TestCase):+ def test_export_reads_pinned_blobs_and_skips_submodules(self):+ tree = b"100644 blob abc\tcmake/source.txt\0" + b"160000 commit def\tcmake/external/onnx\0"+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ with patch.object(harmony.subprocess, "check_output", side_effect=[harmony.REVISION, tree]) as read, \+ patch.object(harmony.subprocess, "Popen", return_value=GitReader(b"abc blob 6\npinned\n")):+ harmony.export_source(root / "checkout", root / "export")+ self.assertEqual((root / "export/cmake/source.txt").read_text(), "pinned")+ self.assertFalse((root / "export/cmake/external/onnx").exists())+ self.assertEqual(read.call_args_list[1].args[0][5:], harmony.SOURCE_PATHS)++ def test_export_rejects_links_and_traversal(self):+ for tree in (b"120000 blob abc\tcmake/link\0", b"100644 blob abc\t../outside\0"):+ with self.subTest(tree=tree), tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ with patch.object(harmony.subprocess, "check_output", side_effect=[harmony.REVISION, tree]), \+ patch.object(harmony.subprocess, "Popen", return_value=GitReader(b"")):+ with self.assertRaisesRegex(ValueError, "Unsupported"):+ harmony.export_source(root / "checkout", root / "export")+ self.assertFalse((root / "outside").exists())+++class WorkDirectoryTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.root = Path(self.temp.name)+ self.args = argparse.Namespace(source=self.root / "checkout", ndk=self.root / "sdk",+ protoc=self.root / "protoc", arch="arm64-v8a")+ self.args.source.mkdir()+ (self.args.source / "original").write_text("upstream", encoding="utf-8")+ self.work = self.root / "work"++ def export_fixture(self, checkout, destination):+ destination.mkdir()+ (destination / "original").write_bytes((checkout / "original").read_bytes())++ def prepare(self):+ with patch.object(harmony, "export_source", side_effect=self.export_fixture), \+ patch.object(harmony, "patch_source", patch_fixture):+ return harmony.prepare_work_directory(self.work, self.args)++ def test_retry_preserves_sources_dependencies_and_build_outputs(self):+ source = self.prepare()+ generated = self.work / "build" / "_deps" / "dependency"+ generated.parent.mkdir(parents=True)+ generated.write_text("downloaded", encoding="utf-8")+ with patch.object(harmony, "export_source", side_effect=AssertionError("must reuse sources")), \+ patch.object(harmony, "patch_source", patch_fixture):+ self.assertEqual(harmony.prepare_work_directory(self.work, self.args), source)+ self.assertEqual(generated.read_text(), "downloaded")+ self.assertFalse((self.args.source / "patched").exists())++ def test_other_architecture_cannot_reuse_build_directory(self):+ self.prepare()+ self.args.arch = "x86_64"+ with self.assertRaisesRegex(ValueError, "configuration changed"):+ self.prepare()+ self.assertEqual((self.work / "source" / "original").read_text(), "upstream")++ def test_existing_unrecognized_directory_is_preserved(self):+ self.work.mkdir()+ original = self.work / "user-file"+ original.write_text("preserve", encoding="utf-8")+ with self.assertRaisesRegex(ValueError, "Unrecognized or incomplete"):+ self.prepare()+ self.assertEqual(original.read_text(), "preserve")++ def test_failed_patch_cannot_be_reused_as_ready_source(self):+ def failing_patch(source):+ raise RuntimeError("patch failed")++ with patch.object(harmony, "export_source", side_effect=self.export_fixture), \+ patch.object(harmony, "patch_source", failing_patch):+ with self.assertRaisesRegex(RuntimeError, "patch failed"):+ harmony.prepare_work_directory(self.work, self.args)+ self.assertFalse((self.work / "siyuan-ocr-build.json").exists())+ with self.assertRaisesRegex(ValueError, "Unrecognized or incomplete"):+ self.prepare()+++class RuntimeValidationTests(unittest.TestCase):+ def test_only_requested_architecture_and_loadable_api_are_accepted(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ library = root / "libonnxruntime.so"+ header = bytearray(20)+ header[:6] = b"\x7fELF\x02\x01"+ struct.pack_into("<HH", header, 16, 3, 183)+ library.write_bytes(header)+ symbols = "0x1 (SONAME) Library soname: [libonnxruntime.so]\n1: 100 20 FUNC GLOBAL DEFAULT 12 OrtGetApiBase@@VERS_1.24.3\n"+ with patch.object(harmony.subprocess, "check_output", return_value=symbols):+ harmony.validate_runtime(library, root, "arm64-v8a")+ with self.assertRaisesRegex(ValueError, "64-bit x86_64"):+ harmony.validate_runtime(library, root, "x86_64")+ with patch.object(harmony.subprocess, "check_output", return_value=symbols.replace("[libonnxruntime.so]", "[libonnxruntime.so.1]")):+ with self.assertRaisesRegex(ValueError, "SONAME"):+ harmony.validate_runtime(library, root, "arm64-v8a")+ with patch.object(harmony.subprocess, "check_output", return_value=symbols.replace("DEFAULT 12", "DEFAULT UND")):+ with self.assertRaisesRegex(ValueError, "export OrtGetApiBase"):+ harmony.validate_runtime(library, root, "arm64-v8a")+++if __name__ == "__main__":+ unittest.main()