diff --git a/build.sh b/build.sh index c9cc6e5f978..9d1b804deee 100755 --- a/build.sh +++ b/build.sh @@ -193,23 +193,39 @@ ort_static_lib_prefix() { # dir means the cache is incomplete, so build.sh triggers the downloader itself # (controlled auto-download) rather than silently linking a stale or wrong lib. +_pdfium_deps_present() { + local stamp="${PDFIUM_STATIC_PREFIX}/.ragflow_platform" cached_platform + [ -s "${PDFIUM_STATIC_PREFIX}/lib/libpdfium.a" ] || return 1 + if [ "$TARGET_OS" = "linux" ]; then + [ -s "${PDFIUM_STATIC_PREFIX}/lib/libc++.a" ] || return 1 + [ -s "${PDFIUM_STATIC_PREFIX}/lib/libc++abi.a" ] || return 1 + fi + # Preserve pre-provisioned caches without a stamp. A downloader-stamped + # cache must match the build target before it can be used. + if [ -f "$stamp" ]; then + IFS= read -r cached_platform < "$stamp" || return 1 + [ "$cached_platform" = "${TARGET_OS}/${TARGET_ARCH}" ] || return 1 + fi + return 0 +} + # True when every native lib the Go build links is already in the versioned user # cache for the target platform. Used to skip the network entirely on an # already-provisioned host. _native_libs_present() { + if [ -z "$_TARGET_PLATFORM_DETECTED" ]; then + detect_target_platform + _TARGET_PLATFORM_DETECTED=1 + fi [ -f "${OFFICE_OXIDE_PREFIX}/lib/liboffice_oxide.a" ] || return 1 [ -f "${OFFICE_OXIDE_PREFIX}/include/office_oxide_c/office_oxide.h" ] || return 1 - [ -f "${PDFIUM_STATIC_PREFIX}/lib/libpdfium.a" ] || return 1 + _pdfium_deps_present || return 1 [ -f "${PDF_OXIDE_PREFIX}/lib/${TARGET_OS}_${TARGET_ARCH}/libpdf_oxide.a" ] || return 1 # ORT must match the SAME version+platform-keyed dir that check_onnxruntime_deps # links (*/${ort_dir_prefix}${ort_version}*/lib/*.a). A shared cache holding # only an OLD version or a DIFFERENT platform's ORT must be reported missing so # the controlled auto-downloader runs, instead of being silently treated as # present and failing only at link time. - if [ -z "$_TARGET_PLATFORM_DETECTED" ]; then - detect_target_platform - _TARGET_PLATFORM_DETECTED=1 - fi local ort_version ort_dir_prefix ort_version="$(deepdoc_ort_version "$PROJECT_ROOT")" || return 1 ort_dir_prefix="$(ort_static_lib_prefix)" @@ -604,12 +620,12 @@ check_pdfium_deps() { # auto-download in setup_cgo_env; there is no /opt pre-bake to recover from. local lib_path="${PDFIUM_STATIC_PREFIX}/lib/libpdfium.a" - if [ -f "$lib_path" ]; then + if _pdfium_deps_present; then echo " pdfium (static) → ${PDFIUM_STATIC_PREFIX}" return 0 fi - echo " pdfium (static) not found" + echo " pdfium (static) missing or incompatible with ${TARGET_OS}/${TARGET_ARCH}" echo " Expected: ${lib_path}" echo " Run: uv run tools/scripts/download_dev_deps.py" echo " Or: curl -fsSL https://github.com/kognitos/pdfium-static/releases/download/chromium%2F${PDFIUM_STATIC_VERSION}/$(pdfium_asset) | tar xz -C ${PDFIUM_STATIC_PREFIX}" @@ -913,22 +929,24 @@ setup_cgo_env() { # ── pdfium ──────────────────────────────────────────────────────── check_pdfium_deps || return 1 - export CGO_LDFLAGS="$CGO_LDFLAGS ${PDFIUM_STATIC_PREFIX}/lib/libpdfium.a" + local pdfium_link_dir + pdfium_link_dir="$(pdfium_static_link_dir "${PDFIUM_STATIC_PREFIX}/lib" "$TARGET_OS" "${PROJECT_ROOT}/.cache/pdfium")" || return 1 + export CGO_LDFLAGS="$CGO_LDFLAGS \"${pdfium_link_dir}/libpdfium.a\"" # Linux: Chromium-built objects use Clang's .eh_frame format which GNU ld # cannot merge. Use lld (LLVM linker) which handles them correctly. # --allow-multiple-definition: pdf_oxide and office_oxide are both Rust # staticlibs that embed the Rust runtime; linking them together produces # duplicate rust_eh_personality / compiler-rt builtins. Those duplicates are # ABI-IDENTICAL, so merging them is benign. - if [ "$(uname -s)" = "Linux" ]; then + if [ "$TARGET_OS" = "linux" ]; then if ! command -v ld.lld >/dev/null 2>&1; then echo -e "${RED}Error: ld.lld not found. Install with: sudo apt install lld-20 && sudo ln -s /usr/bin/ld.lld-20 /usr/bin/ld.lld${NC}" echo " lld is required to static-link Chromium-built pdfium (.eh_frame format)" return 1 fi export CGO_LDFLAGS="$CGO_LDFLAGS \ - ${PDFIUM_STATIC_PREFIX}/lib/libc++.a \ - ${PDFIUM_STATIC_PREFIX}/lib/libc++abi.a \ + \"${pdfium_link_dir}/libc++.a\" \ + \"${pdfium_link_dir}/libc++abi.a\" \ -fuse-ld=lld -Wl,--allow-multiple-definition" # The re2 regex-library collision between onnxruntime.a and # librag_tokenizer_c_api.a is fixed at the .a level in build_cpp(): diff --git a/internal/development.md b/internal/development.md index 6775d49d579..b8e06feed98 100644 --- a/internal/development.md +++ b/internal/development.md @@ -199,28 +199,39 @@ The image contains Go DeepDoc weights, tokenizer assets, and the BPE table. Deep > OFFICE_OXIDE_PREFIX="${RAGFLOW_DEPS}/office_oxide/v${OFFICE_OXIDE_VERSION}" > PDFIUM_PREFIX="${RAGFLOW_DEPS}/pdfium-static/v${PDFIUM_STATIC_VERSION}" > PDF_OXIDE_PREFIX="${RAGFLOW_DEPS}/pdf_oxide/v${PDF_OXIDE_VERSION}" +> # Keep the Go link cache keyed to PDFium contents, even for a reissued archive +> # with the same version. Resolve the same linker paths as build.sh. +> if PDFIUM_LINK_DIR="$(pdfium_static_link_dir "${PDFIUM_PREFIX}/lib" "$TARGET_OS" "${REPO_ROOT}/.cache/pdfium")"; then +> OFFICE_OXIDE_A="${OFFICE_OXIDE_PREFIX}/lib/liboffice_oxide.a" +> PDFIUM_A="${PDFIUM_LINK_DIR}/libpdfium.a" +> PDF_OXIDE_A="${PDF_OXIDE_PREFIX}/lib/${PLATFORM}/libpdf_oxide.a" +> # macOS PDFium uses the system libc++ provided by the flags above. +> PDFIUM_CXX_ARCHIVES="" +> if [ "$TARGET_OS" = "linux" ]; then +> PDFIUM_CXX_ARCHIVES="\"${PDFIUM_LINK_DIR}/libc++.a\" \"${PDFIUM_LINK_DIR}/libc++abi.a\"" +> fi > -> OFFICE_OXIDE_A="${OFFICE_OXIDE_PREFIX}/lib/liboffice_oxide.a" -> PDFIUM_A="${PDFIUM_PREFIX}/lib/libpdfium.a" -> PDFIUM_CXX_A="${PDFIUM_PREFIX}/lib/libc++.a" -> PDFIUM_CXXABI_A="${PDFIUM_PREFIX}/lib/libc++abi.a" -> PDF_OXIDE_A="${PDF_OXIDE_PREFIX}/lib/${PLATFORM}/libpdf_oxide.a" -> -> # Derive the include dir from the resolved office_oxide archive: the shell does -> # not expand globs inside double quotes, so a literal -> # ".../office_oxide/v*/include/..." passed to CGO_CFLAGS would never resolve and -> # cgo would fail to find office_oxide.h on the first native compile. -> export CGO_CFLAGS="-I$(dirname "$(dirname "$OFFICE_OXIDE_A")")/include/office_oxide_c" -> export CGO_LDFLAGS="\ -> ${OFFICE_OXIDE_A} \ -> ${PDFIUM_A} \ -> ${PDFIUM_CXX_A} \ -> ${PDFIUM_CXXABI_A} \ -> ${PDF_OXIDE_A} \ -> ${ORT_LINK} \ -> ${SYS_LIBS}" +> # Derive the include dir from the resolved office_oxide archive: the shell does +> # not expand globs inside double quotes, so a literal +> # ".../office_oxide/v*/include/..." passed to CGO_CFLAGS would never resolve and +> # cgo would fail to find office_oxide.h on the first native compile. +> export CGO_CFLAGS="-I$(dirname "$(dirname "$OFFICE_OXIDE_A")")/include/office_oxide_c" +> export CGO_LDFLAGS="\ +> ${OFFICE_OXIDE_A} \ +> \"${PDFIUM_A}\" \ +> ${PDFIUM_CXX_ARCHIVES} \ +> ${PDF_OXIDE_A} \ +> ${ORT_LINK} \ +> ${SYS_LIBS}" +> else +> unset CGO_CFLAGS CGO_LDFLAGS +> printf '%s\n' 'Could not prepare PDFium linker inputs. Run uv run tools/scripts/download_dev_deps.py.' >&2 +> false +> fi > ``` > +> When sourcing this block from a build script, check its exit status before invoking Go. +> > All four native libraries are statically linked — no `LD_LIBRARY_PATH` or `-Wl,-rpath` needed. > > **ONNX Runtime is mandatory for the production binary.** The in-process (Go) diff --git a/tools/scripts/download_dev_deps.py b/tools/scripts/download_dev_deps.py index 3363235db16..7a44a1c0aad 100755 --- a/tools/scripts/download_dev_deps.py +++ b/tools/scripts/download_dev_deps.py @@ -254,6 +254,19 @@ def pdfium_url(goos: str, goarch: str) -> str: return f"{gh_proxy()}https://github.com/kognitos/pdfium-static/releases/download/chromium%2F{PDFIUM_VERSION}/{PDFIUM_STATIC_ASSETS[(goos, goarch)]}" +def pdfium_required_files(goos: str) -> list[str]: + """Required files inside the pdfium-static archive for `goos`. + + kognitos/pdfium-static bundles lib/libc++.a and lib/libc++abi.a only in the + Linux tarballs (which build.sh links with -fuse-ld=lld on Linux); the macOS + tarballs ship lib/libpdfium.a and include/fpdfview.h and rely on the system + libc++ from the macOS SDK. + """ + if goos == "linux": + return ["lib/libpdfium.a", "lib/libc++.a", "lib/libc++abi.a", "include/fpdfview.h"] + return ["lib/libpdfium.a", "include/fpdfview.h"] + + def pdfium_local_asset_name(goos: str, goarch: str) -> str: """Local deps/ filename for the pdfium tarball, suffixed with the resolved chromium build number so two pdfium versions never share a path. @@ -480,15 +493,26 @@ def _stamp_present(data, version, stamp_format): return needle in data -def native_lib_provisioned(directory, required_files, version=None, stamp_format="null"): - """True when DIRECTORY already holds every file in REQUIRED_FILES (non-empty) - and, for .a files when VERSION is set, the expected version stamp. +def native_lib_provisioned(directory, required_files, version=None, stamp_format="null", *, platform=None, archive_hash=None): + """Check required files and version stamps in a provisioned native library. - This is the same check _extract_native_archive.complete() performs, lifted to - module scope so the download pass can skip fetching a lib whose version-keyed - cache dir is already populated (e.g. a CI builder's mounted pre-baked native - libs cache) instead of re-downloading it every run. pdfium passes VERSION - None (its .a carries no stamp), so only file presence is checked there.""" + PDFium callers also supply the target platform and, when available, the + archive hash so download and extraction use the same cache validation. + """ + if platform is not None or archive_hash is not None: + stamp_path = os.path.join(directory, ".ragflow_platform") + if not os.path.isfile(stamp_path): + return False + with open(stamp_path, encoding="utf-8") as stamp_file: + lines = stamp_file.read().splitlines() + stamp_platform = lines[0].strip() if lines else "" + stamp_hash = lines[1].strip() if len(lines) > 1 else "" + if platform is not None: + platform_token = f"{platform[0]}/{platform[1]}" if isinstance(platform, tuple) else str(platform) + if stamp_platform != platform_token: + return False + if archive_hash is not None and stamp_hash != archive_hash: + return False for name in required_files: path = os.path.join(directory, name) if not os.path.isfile(path) or os.path.getsize(path) == 0: @@ -500,7 +524,7 @@ def native_lib_provisioned(directory, required_files, version=None, stamp_format return True -def _extract_native_archive(archive_path, target, required_files, version=None, stamp_format="null"): +def _extract_native_archive(archive_path, target, required_files, version=None, stamp_format="null", *, platform=None, archive_hash=None): """Extract ARCHIVE_PATH into TARGET, verifying REQUIRED_FILES (and, for .a files, an optional VERSION stamp) before promoting the staged tree. @@ -512,11 +536,11 @@ def _extract_native_archive(archive_path, target, required_files, version=None, Path-traversal / absolute / non-regular members are rejected before extraction, and an incomplete archive raises instead of replacing a previously good directory.""" + platform_token = None + if platform is not None: + platform_token = f"{platform[0]}/{platform[1]}" if isinstance(platform, tuple) else str(platform) - def complete(directory): - return native_lib_provisioned(directory, required_files, version, stamp_format) - - if complete(target): + if native_lib_provisioned(target, required_files, version, stamp_format, platform=platform, archive_hash=archive_hash): print(f" ✓ {os.path.basename(target)} already extracted to {target}") return os.makedirs(os.path.dirname(target), exist_ok=True) @@ -528,8 +552,16 @@ def complete(directory): if os.path.isabs(member.name) or ".." in member.name.split("/") or not (member.isfile() or member.isdir()): raise tarfile.TarError(f"Unsafe native archive member: {member.name}") archive.extractall(staging, members=members) - if not complete(staging): + if not native_lib_provisioned(staging, required_files, version, stamp_format): raise RuntimeError(f"{archive_path} is missing required native files or version {version}") + if platform_token is not None or archive_hash is not None: + with open(os.path.join(staging, ".ragflow_platform"), "w", encoding="utf-8") as stamp_file: + if platform_token is not None: + stamp_file.write(f"{platform_token}\n") + else: + stamp_file.write("\n") + if archive_hash is not None: + stamp_file.write(f"{archive_hash}\n") if os.path.isdir(target): shutil.rmtree(target) os.replace(staging, target) @@ -542,7 +574,7 @@ def complete(directory): print(f" ✓ extracted {os.path.basename(archive_path)} to {target}") -def extract_native_lib(archive_path, subdir, dir_version, required_files, stamp_version=None, stamp_format="null"): +def extract_native_lib(archive_path, subdir, dir_version, required_files, stamp_version=None, stamp_format="null", *, platform=None): """Extract a native static archive into the version-keyed cache dir ~/ragflow-native-libs///. @@ -554,8 +586,8 @@ def extract_native_lib(archive_path, subdir, dir_version, required_files, stamp_ no-op for an already-provisioned cache. STAMP_FORMAT is forwarded to _extract_native_archive (see its docstring): - "null" for office_oxide, "text" for pdf_oxide. pdfium passes stamp_version - None and is not stamp-checked. + "null" for office_oxide, "text" for pdf_oxide. PDFium has no embedded version + stamp. It passes PLATFORM to key cache reuse on the target and archive hash. Returns True when extraction ran or was skipped-successfully (the dir is in place afterwards), False when the archive is absent (caller must then @@ -565,8 +597,9 @@ def extract_native_lib(archive_path, subdir, dir_version, required_files, stamp_ print(f" Skipping extraction: {os.path.basename(archive_path)} not found") return False target = os.path.join(native_libs_dir(), subdir, dir_version) + archive_hash = _sha256_of(archive_path) if platform is not None else None try: - _extract_native_archive(archive_path, target, required_files, stamp_version, stamp_format) + _extract_native_archive(archive_path, target, required_files, stamp_version, stamp_format, platform=platform, archive_hash=archive_hash) except (tarfile.TarError, EOFError, RuntimeError): os.unlink(archive_path) raise @@ -911,7 +944,7 @@ def native_lib_specs(goos, goarch): pdfium_url(goos, goarch), pdfium_local_asset_name(goos, goarch), "v" + PDFIUM_VERSION, - ["lib/libpdfium.a", "lib/libc++.a", "lib/libc++abi.a", "include/fpdfview.h"], + pdfium_required_files(goos), None, "null", ), @@ -941,11 +974,13 @@ def download_native_archives(goos, goarch): version-keyed cache dir (~/ragflow-native-libs//v/) is already provisioned (e.g. a CI builder's mounted pre-baked native-libs cache) — the download pass consults that cache, not just the transient deps/ archive, so a - pre-baked lib is never re-fetched. Falls back to the deps/ archive check, + valid pre-baked lib is not re-fetched. Falls back to the deps/ archive check, then network.""" for subdir, url, archive, dir_version, required_files, stamp_version, stamp_format in native_lib_specs(goos, goarch): target = os.path.join(native_libs_dir(), subdir, dir_version) - if native_lib_provisioned(target, required_files, stamp_version, stamp_format): + platform = (goos, goarch) if subdir == "pdfium-static" else None + archive_hash = _sha256_of(archive) if platform is not None and os.path.isfile(archive) else None + if native_lib_provisioned(target, required_files, stamp_version, stamp_format, platform=platform, archive_hash=archive_hash): print(f" ✓ {subdir} {dir_version} already provisioned at {target}; skipping download") continue print(f"Downloading {archive} from {url}...") @@ -1002,11 +1037,21 @@ def main(): # avoided re-fetching it), so a pre-baked native-libs cache is a no-op here. for subdir, _url, archive, dir_version, required_files, stamp_version, stamp_format in native_lib_specs(goos, goarch): target = os.path.join(native_libs_dir(), subdir, dir_version) - if native_lib_provisioned(target, required_files, stamp_version, stamp_format): + platform = (goos, goarch) if subdir == "pdfium-static" else None + archive_hash = _sha256_of(archive) if platform is not None and os.path.isfile(archive) else None + if native_lib_provisioned(target, required_files, stamp_version, stamp_format, platform=platform, archive_hash=archive_hash): print(f" ✓ {subdir} {dir_version} already provisioned at {target}; skipping extraction") continue archive_path = os.path.join(RAGFLOW_DEPS_DIR, archive) - extract_native_lib(archive_path, subdir, dir_version, required_files, stamp_version, stamp_format) + extract_native_lib( + archive_path, + subdir, + dir_version, + required_files, + stamp_version, + stamp_format, + platform=platform, + ) if not extract_onnxruntime( os.path.join(native_libs_dir(), "onnxruntime", "static_lib"), diff --git a/tools/scripts/native_lib_version.sh b/tools/scripts/native_lib_version.sh index 33b76beac6c..0d8bc3b05dd 100644 --- a/tools/scripts/native_lib_version.sh +++ b/tools/scripts/native_lib_version.sh @@ -59,6 +59,49 @@ pdfium_static_version() { printf '%s\n' "7809" } +# Give cgo immutable archive paths that change when any linked PDFium archive +# changes, even under the same version. Keep these copies in the project's +# writable cache so a pre-provisioned native dependency cache can be read-only. +pdfium_static_link_dir() ( + local source_dir="$1" target_os="$2" cache_dir="$3/archives" + local -a archives=(libpdfium.a) hash_command=(sha256sum) + if [ "$target_os" = "linux" ]; then + archives+=(libc++.a libc++abi.a) + fi + command -v sha256sum >/dev/null || hash_command=(shasum -a 256) + + local hashes digest link_dir + hashes="$(cd "$source_dir" && "${hash_command[@]}" "${archives[@]}")" || return 1 + digest="$(printf '%s\n' "$hashes" | "${hash_command[@]}")" || return 1 + digest="${digest%% *}" + link_dir="$cache_dir/$digest" + if [ ! -d "$link_dir" ]; then + mkdir -p "$cache_dir" || return 1 + local staging staged_dir archive staged_hashes + staging="$(mktemp -d "$cache_dir/.pdfium.XXXXXX")" || return 1 + trap 'rm -rf -- "$staging"' EXIT + trap 'rm -rf -- "$staging"; exit 130' INT + trap 'rm -rf -- "$staging"; exit 143' TERM + staged_dir="$staging/$digest" + mkdir "$staged_dir" || return 1 + for archive in "${archives[@]}"; do + cp "$source_dir/$archive" "$staged_dir/$archive" || return 1 + done + staged_hashes="$(cd "$staged_dir" && "${hash_command[@]}" "${archives[@]}")" || return 1 + if [ "$staged_hashes" != "$hashes" ]; then + echo "PDFium archives changed while preparing linker inputs. Retry the build." >&2 + return 1 + fi + # Rename into the cache parent in one operation. The published directory + # is outside the attempt's cleanup, and another build may publish first. + if ! mv -f "$staged_dir" "$cache_dir/" 2>/dev/null && [ ! -d "$link_dir" ]; then + echo "Could not publish the PDFium linker cache at $link_dir" >&2 + return 1 + fi + fi + printf '%s\n' "$link_dir" +) + # deepdoc_ort_version # Reads the ONNX Runtime version the in-process (Go) DeepDoc backend links from # /internal/common/environments.go's DeepDocORTVersion const. diff --git a/tools/scripts/test_download_dev_deps.py b/tools/scripts/test_download_dev_deps.py index 1deb9faccf6..cfda5f1c869 100644 --- a/tools/scripts/test_download_dev_deps.py +++ b/tools/scripts/test_download_dev_deps.py @@ -327,6 +327,116 @@ def test_incomplete_native_archive_preserves_existing_directory(tmp_path): assert (target / "existing").read_bytes() == b"keep" +def test_pdfium_required_files_by_platform(): + """Verify PDFium required archive entries for Linux vs. macOS.""" + assert native.pdfium_required_files("linux") == [ + "lib/libpdfium.a", + "lib/libc++.a", + "lib/libc++abi.a", + "include/fpdfview.h", + ] + assert native.pdfium_required_files("darwin") == [ + "lib/libpdfium.a", + "include/fpdfview.h", + ] + + +def test_extracts_darwin_pdfium_archive_without_bundled_libcxx(tmp_path): + """Darwin PDFium archives without bundled libc++ extract on macOS and fail Linux checks.""" + archive = tmp_path / "pdfium-mac-arm64-static.tgz" + with tarfile.open(archive, "w:gz") as tf: + for rel, payload in [ + ("lib/libpdfium.a", b"!\npdfium"), + ("include/fpdfview.h", b"// header"), + ]: + info = tarfile.TarInfo(rel) + info.size = len(payload) + tf.addfile(info, io.BytesIO(payload)) + + darwin_target = tmp_path / "pdfium-darwin" + native._extract_native_archive( + str(archive), + str(darwin_target), + native.pdfium_required_files("darwin"), + platform=("darwin", "arm64"), + ) + assert (darwin_target / "lib" / "libpdfium.a").is_file() + assert (darwin_target / "include" / "fpdfview.h").is_file() + + linux_target = tmp_path / "pdfium-linux" + with pytest.raises(RuntimeError, match="missing required native file"): + native._extract_native_archive(str(archive), str(linux_target), native.pdfium_required_files("linux")) + + +def test_extract_native_archive_replaces_cached_tree_when_platform_changes(tmp_path): + """Switching target platform/arch replaces a cached PDFium tree instead of reusing it.""" + + def write_pdfium_tar(path, payload): + """Create a minimal Darwin PDFium tar.gz with the given libpdfium.a payload.""" + with tarfile.open(path, "w:gz") as tf: + for rel, data in [ + ("lib/libpdfium.a", payload), + ("include/fpdfview.h", b"// header"), + ]: + info = tarfile.TarInfo(rel) + info.size = len(data) + tf.addfile(info, io.BytesIO(data)) + + arm64_archive = tmp_path / "pdfium-mac-arm64-static.tgz" + amd64_archive = tmp_path / "pdfium-mac-x64-static.tgz" + write_pdfium_tar(arm64_archive, b"!\narm64-pdfium") + write_pdfium_tar(amd64_archive, b"!\namd64-pdfium") + + target = tmp_path / "pdfium-static" + required = native.pdfium_required_files("darwin") + native._extract_native_archive(str(arm64_archive), str(target), required, platform=("darwin", "arm64")) + assert (target / "lib" / "libpdfium.a").read_bytes() == b"!\narm64-pdfium" + + native._extract_native_archive(str(amd64_archive), str(target), required, platform=("darwin", "amd64")) + assert (target / "lib" / "libpdfium.a").read_bytes() == b"!\namd64-pdfium" + + +def test_extract_native_lib_replaces_cached_pdfium_when_hash_changes(tmp_path, monkeypatch): + """A changed archive replaces PDFium cached under the same version and platform.""" + + def write_pdfium_tar(path, payload): + with tarfile.open(path, "w:gz") as tf: + for rel, data in [ + ("lib/libpdfium.a", payload), + ("include/fpdfview.h", b"// header"), + ]: + info = tarfile.TarInfo(rel) + info.size = len(data) + tf.addfile(info, io.BytesIO(data)) + + archive_v1 = tmp_path / "pdfium-v1.tgz" + archive_v2 = tmp_path / "pdfium-v2.tgz" + write_pdfium_tar(archive_v1, b"!\npdfium-v1") + write_pdfium_tar(archive_v2, b"!\npdfium-v2") + + monkeypatch.setenv("RAGFLOW_NATIVE_LIBS_DIR", str(tmp_path / "native-libs")) + dir_version = f"v{native.PDFIUM_VERSION}" + target = tmp_path / "native-libs" / "pdfium-static" / dir_version + required = native.pdfium_required_files("darwin") + native.extract_native_lib( + str(archive_v1), + "pdfium-static", + dir_version, + required, + platform=("darwin", "arm64"), + ) + assert (target / "lib" / "libpdfium.a").read_bytes() == b"!\npdfium-v1" + + native.extract_native_lib( + str(archive_v2), + "pdfium-static", + dir_version, + required, + platform=("darwin", "arm64"), + ) + assert (target / "lib" / "libpdfium.a").read_bytes() == b"!\npdfium-v2" + + @pytest.mark.parametrize("kind", ["traversal", "absolute", "symlink", "hardlink", "fifo", "device"]) def test_native_archive_rejects_unsafe_members(tmp_path, kind): target = tmp_path / "native"