Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 29 additions & 11 deletions build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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)"
Expand Down Expand Up @@ -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}"
Expand Down Expand Up @@ -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():
Expand Down
49 changes: 30 additions & 19 deletions internal/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
> 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)
Expand Down
91 changes: 68 additions & 23 deletions tools/scripts/download_dev_deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand All @@ -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.

Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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/<subdir>/<dir_version>/.

Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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",
),
Expand Down Expand Up @@ -941,11 +974,13 @@ def download_native_archives(goos, goarch):
version-keyed cache dir (~/ragflow-native-libs/<lib>/v<ver>/) 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}...")
Expand Down Expand Up @@ -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"),
Expand Down
Loading
Loading