Skip to content

Studio: install PDF dependencies on demand - #17206

Closed
AlbertoLMa wants to merge 10 commits into
unslothai:mainfrom
AlbertoLMa:codex/pdf-optional
Closed

AlbertoLMa wants to merge 10 commits into
unslothai:mainfrom
AlbertoLMa:codex/pdf-optional

Conversation

@AlbertoLMa

@AlbertoLMa AlbertoLMa commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Problem and resulting behavior

Studio installs PyMuPDF and pymupdf4llm for every user, even when they never process PDFs or MuPDF-backed ebooks. This moves those dependencies out of the initial Studio installation and loads them automatically when the feature is first used, following the on-demand support pattern in #14157.

The document-loading interface and API response shapes stay the same. An existing installation is reused immediately. Otherwise, the first PDF/ebook request uses a complete cache or downloads missing wheels, then imports them into the running backend without a restart. Users who never use these formats avoid the corresponding initial download and storage. Users who do use them obtain the packages later and reuse the cache on subsequent requests.

Dependency declarations

  • Remove PyMuPDF and pymupdf4llm from the studio extra, requirements/studio.txt, requirements/no-torch-runtime.txt, requirements/single-env/data-designer-deps.txt, and the local unstructured-seed plugin's dependencies.
  • Add an optional pdf extra and synchronized studio/backend/requirements/pdf.txt containing PyMuPDF, pymupdf4llm, and tabulate.
  • Preserve the existing native pins: PyMuPDF 1.27.2.3 normally and 1.28.2 on Windows ARM64. Preserve pymupdf4llm 0.3.4 and use the existing Python-specific tabulate pins (0.10.0 on Python >=3.10, 0.9.0 on older Python).
  • Keep the shared tabulate dependency in requirements/extras.txt; its removal is not counted as a saving.
  • Remove the obsolete fitz -> pymupdf entry from the CLI's required-Studio dependency map and its old test parameter. PDF imports now belong to the optional loader and its installation guidance.
  • Explicitly install requirements/pdf.txt in the backend and repo-CPU test environments. Existing PDF tests import native PyMuPDF directly, so optional-at-runtime packages remain required test dependencies. This keeps the PDF tests exercised while production defaults remain PDF-free.

Isolated first-use loader

studio/backend/utils/optional_pdf.py exposes load_pdf_module(name) for only fitz, pymupdf, and pymupdf4llm. Each import target is written out literally so the risky-loader audit can verify it without adding a security baseline exception.

  1. Try the existing import first. Installed packages retain precedence and do not need a cache or network access.
  2. Reuse a complete cached installation before checking download opt-out/offline settings.
  3. If needed, install missing packages with uv, falling back to this interpreter's python -m pip when uv cannot run or exits unsuccessfully. Each attempt gets its own staging directory.
  4. Request wheels only, with --no-deps, an explicit PyPI index, and a separate cache target. Do not run a resolver against or replace packages in the live environment. Installer children receive transport/TLS/proxy settings without application credentials or package-source/target overrides.
  5. Serialize installation with a thread lock and a process file lock. The lock/install sequence has a 120-second total budget, including contention.
  6. Validate distribution metadata and recorded files, write a completion marker, and publish the staging directory atomically. Cache identity includes requirements, interpreter/environment paths, Python version/implementation, platform, ABI, and free-threaded configuration.
  7. Append the published target to sys.path and invalidate import caches. Do not process .pth files. Preserve the upstream wheel contents, metadata, and license files.

An existing compatible tabulate installation is accepted rather than forced to the download pin. Incompatible or broken installed native packages and incomplete/damaged caches produce repair guidance instead of being overwritten. Failed installation attempts do not publish a partial cache.

UNSLOTH_PDF_AUTO_INSTALL=0 disables new downloads. A complete cache or preinstalled packages still work offline. Missing dependencies, offline/disabled downloads, and installation failures produce PDFDependencyUnavailable guidance containing:

python -m pip install "unsloth[pdf]"

The error also names the uv installation spelling for environments created without pip.

Backend integration

  • Replace local PDF imports in RAG parsing/extraction, figure handling/rendering, citation-region lookup, and OCR with calls to the loader.
  • Preserve the existing processing algorithms and fallback behavior. An AST comparison against the baseline is identical for parsers.py, locators.py, and pdf_ocr.py after normalizing only these import replacements.
  • Preserve actionable PDF dependency guidance in the existing unstructured-upload error field. Failed uploads remove their raw and extracted files. Unrelated extraction errors retain their existing handling.
  • Keep ordinary unit tests from downloading PDF wheels; installer tests explicitly opt in.

There are no README, frontend, upload-dialog, file-selector, button, API response-schema, or S3 implementation changes.

Measured installation-size reduction

Measured on macOS arm64 / Python 3.12.2 using equivalent isolated environments and core + Studio dependency sets, retaining the shared tabulate pin. The baseline was bdebdc8331; candidate resolution was constrained to the baseline's resolved versions so unrelated dependency changes could not inflate the result.

Logical installed dependency files Bytes
Baseline 461,622,572
Candidate 407,780,059
Deferred until PDF use 53,842,513 (51.35 MiB)

Only pymupdf and pymupdf4llm disappeared. No distributions were added; retained versions, measured file sizes, and license metadata stayed identical. The corresponding two wheel downloads total 23,356,907 bytes (22.28 MiB).

This measures dependency files, excluding bytecode, project-wheel contents, development/test tooling, GPU/ML extras, model caches, and filesystem block allocation. It is not the size of the entire GPU application. PDF users eventually consume the deferred storage in their cache.

Validation

  • 1,499 passed, 1 skipped across the focused PDF/RAG, OCR, office-format, ingestion, upload/path, optional-dependency, metadata, native-pin, and Windows ARM64 marker suites. These totals include existing parameterized tests.
  • 202 passed, 383 platform skips in the complete CLI dependency and PowerShell boolish suites after the CLI map adjustment. Both focused runs were repeated successfully on the final commit after rebasing onto current upstream main.
  • Add 38 installer test cases covering installed-package precedence, the module allowlist, first use, uv/pip fallback, concurrent threads, cache reuse, opt-out/offline modes, failures/timeouts, damaged caches, tabulate compatibility, incompatible/broken native packages, environment isolation, .pth non-execution, and bounded lock waits.
  • Add upload-error regression cases for PDF, MOBI, and FB2, including unchanged response keys, installation guidance, and cleanup. Add a packaging contract for the PDF extra/default declarations and adapt the existing native-platform pin tests.
  • In real PDF-free isolated environments, ordinary text parsing and multipart text upload work without importing/installing PDF modules. First PDF multipart upload succeeds through actual uv installation and, separately, actual pip fallback after an intentionally failing uv executable.
  • Compare actual PDF text, PNG and figure-tile hashes, citation boxes, native Tesseract OCR, and upload response fields against the baseline: outputs match exactly through uv, pip, and fresh-process offline/disabled cache reuse.
  • With downloads disabled and an empty cache, the real upload route preserves installation guidance and leaves no failed PDF files behind.
  • Two real processes sharing a fresh cache invoke exactly one installer and load the same native engine. A separate partial-stack check retains the existing native PyMuPDF and tabulate 0.9.0 module objects/paths while downloading only the missing wrapper.
  • Build the final wheel and verify the runtime helper, CLI source, pdf.txt, and optional-extra metadata. Compare 113 native and 19 wrapper wheel files byte for byte against the cache, including COPYING/LICENSE, excluding installer-generated RECORD.
  • Run the complete workflow-guard/security command from .github/workflows/workflow-trigger-lint.yml in an isolated Linux x86_64 container with Python 3.12.16 and -n 4: 3,004 passed, 180 skipped, zero failures. This covers the full 3,184-case job that originally reported the dynamic-import failure; the skipped cases remain subject to their normal environment/history/tool-availability conditions. The workflow-trigger and backend Python-floor steps also pass in that container.
  • Run 17 local source gates, including whole-repository syntax/Ruff, execution/loader/scanner audits and their self-tests, duplicate definitions, import/clamp checks, workflow rules, and Python compatibility: all pass.
  • The complete risky-loader security test file and focused PDF suites pass together: 1,545 passed, 1 skipped, including all three literal import targets. This reproduces and fixes the CI loader-audit failure without changing the audit rules or baseline.
  • Verify the CI dependency correction in a fresh environment: the default Studio requirements contain no PDF modules; after explicitly adding pdf.txt, the complete affected PDF/OCR/fallback/captioning and optional-loader files pass 102 tests with no skips, with automatic PDF downloads disabled. Workflow/packaging checks also pass (313 passed, 45 platform skips), and the workflow-trigger linter passes. This addresses the three missing-PyMuPDF collection errors and seven missing-PyMuPDF test failures seen in the backend shard without removing or skipping tests.
  • The checked-in-file encoding guard passes all 16 batches after explicitly reading and writing the requirements-copy fixture as UTF-8; the 38 optional-PDF loader cases also pass. No guard or test assertions were removed.
  • Repository-pinned formatting, Ruff checks for all changed Python files, and git diff --check pass.

For a configured Studio development environment with PDF dependencies installed for native coverage, the focused runs can be reproduced with:

PYTHONPATH=studio/backend/plugins/data-designer-unstructured-seed/src python -m pytest \
  studio/backend/tests/test_optional_pdf.py \
  studio/backend/tests/test_rag_parsing.py \
  studio/backend/tests/test_rag_pdf_table_guard.py \
  studio/backend/tests/test_rag_extract_text.py \
  studio/backend/tests/test_rag_preview.py \
  studio/backend/tests/test_rag_locator_page_memo.py \
  studio/backend/tests/test_rag_ocr_fallback.py \
  studio/backend/tests/test_pdf_local_ocr.py \
  studio/backend/tests/test_pdf_ocr_regressions.py \
  studio/backend/tests/test_rag_office_formats.py \
  studio/backend/tests/test_rag_captioning.py \
  studio/backend/tests/test_rag_ingestion.py \
  studio/backend/tests/test_data_recipe_seed.py \
  studio/backend/tests/test_data_recipe_seed_path_quote.py \
  tests/studio/install/test_studio_extra_matches_requirements.py \
  tests/studio/install/test_pymupdf_platform_pins.py \
  tests/python/test_windows_arm64_requirement_markers.py -q

python -m pytest \
  tests/studio/install/test_studio_deps_cli.py \
  tests/studio/install/test_uv_boolish_parity.py -q

Broader-suite accounting and platform limits

The exploratory full installer run was 8,725 passed, 1,701 skipped, 35 failed. Of those failures, 31 independently reproduce on the pristine baseline in AMD/ROCm, Docker/native-runtime, filesystem/repair, and import-cost tests. One PDF-related CLI drift-guard failure was fixed by removing the obsolete mapping above. Three failures came from test collection seeing transient files while a wheel build ran concurrently; the complete affected CLI/PowerShell suites passed when rerun sequentially after moving build artifacts out of the checkout. The slow full installer suite was not repeated after that focused repair; the complete affected suites were rerun.

Native integration checks ran on macOS arm64/Python 3.12; development pytest ran on Python 3.13. Windows/Linux/Windows ARM64 have marker and pin coverage here, but were not exercised natively. First use adds installation latency and needs network/wheel availability unless packages are preinstalled or a complete cache exists. A fresh empty cache does not provide offline PDF support.

@danielhanchen

Copy link
Copy Markdown
Member

The Repo tests (CPU, rest-2) failure on this PR comes from the PR itself, not main:

tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding[9]
Left contains one more item: 'studio/backend/tests/test_optional_pdf.py:277: read_text()'

test_optional_pdf.py:277 calls pdf._REQUIREMENTS.read_text() with no encoding, and that guard requires reads of checked-in files to say encoding = "utf-8" so they do not depend on the Windows code page. Changing it to pdf._REQUIREMENTS.read_text(encoding = "utf-8") should clear it. The other red jobs on this PR are the GitHub release-asset 504 outage from earlier today and will clear on a rerun.

danielhanchen added a commit that referenced this pull request Nov 9, 2026
…rpreter teardown (#17244)

## Summary

`Repo tests (CPU, gloo-tp)` keeps going red on
`tests/test_tp_native_gloo.py::test_trainer_length_samplers_resume_like_an_uninterrupted_run[2-group_by_length]`,
always the same way:

```
E   AssertionError: rank exit codes [-6, 0, 0, 0]
terminate called without an active exception
```

It hit `main` itself (Nov 9 00:25 UTC), #17206 and a staging run of
#17237 within about 15 hours, on PRs that do not touch tensor
parallelism. In each run, one rank of four died with SIGABRT from
`std::terminate` on a joinable C++ thread while the interpreter was
tearing down, after the case had run and the process group had been
destroyed. The other three ranks exited 0. It never reproduced locally,
in 25 runs of that test.

`_worker` now records that the case finished and its result was saved,
destroys the process group as before, then flushes stdio and calls
`os._exit(0)`. Interpreter teardown can no longer change the exit code
of a rank whose work is done. A case that raises, a failed `torch.save`
or a failing `destroy_process_group` still exits non-zero, so the parent
still fails, and the results are still read back and checked exactly as
before.

## Changes

- `tests/test_tp_native_gloo.py`:
- `_worker` skips interpreter teardown once the case has finished and
its result is on disk.
- New `teardown_abort` case, which registers `os.abort` with `atexit` to
stand in for an abort during teardown.
- New test
`test_a_rank_that_finished_is_not_failed_by_an_abort_in_teardown`, which
runs that case on two ranks and expects both results back.

The other `*_gloo.py` suites only import helpers from this file and have
their own workers, so they are unchanged.

## Testing

- The new test passes. With the `os._exit` path disabled it fails with
`rank exit codes` on the `atexit` abort, so it guards the fix.
- The full `tests/test_tp_native_gloo.py` passes locally (57 passed).
- ruff and the scanner-shape and exec-literal lints are clean.
@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T01:27:58.798059Z 3b494ac Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b261aa3bfc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/utils/optional_pdf.py Outdated
Comment on lines +252 to +255
module = _import(name)
if module is not None:
return module
_install_unless(lambda: _import(name) is not None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Wait for installation completion before importing PDF modules

With concurrent first-use PDF requests, the second request can execute this import while _install() is still writing wheel files into live site-packages. Neither installation lock protects this initial import, so it can cache an empty namespace or partially written package in sys.modules, or report a spurious broken-install error. A cached incomplete module is then also returned to the installing request and subsequent requests after installation completes, leaving PDF parsing broken until that worker restarts. Synchronize imports and readiness checks with installation completion, not just concurrent installer subprocesses.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4a73eea: the first import of a PDF module in a process, and every ensure_pdf_support() check, now run under the same thread lock and environment file lock the installer holds, so a reader waits for an install in progress instead of importing a half-written package. Reproduced before the fix with a real pip-fallback install: all 800 concurrent loads, and the installing request, got a cached pymupdf module without open(). After the fix all 800 get the complete module, and 40 separate processes started mid-install all wait and load it (11 of 40 failed before).

Comment on lines +264 to +266
return all(
importlib.util.find_spec(name) is not None for name in sorted(_MODULES | {"tabulate"})
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check only the PDF modules required by each consumer

If PyMuPDF is already installed but pymupdf4llm or tabulate is absent and downloads are disabled/offline, this all-modules predicate makes ensure_pdf_support() fail even for native-only consumers. The new calls from _python_exec and _fetch_url_raw therefore reject import fitz and readable PDF URLs, although parsers._pdf_markdown() explicitly falls back to plain PyMuPDF text when the wrapper is unavailable. Check only the modules required by the requested operation, or let the web parser use its existing lazy-loading/fallback path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this. The state needs pymupdf installed without pymupdf4llm or tabulate and downloads disabled. Studio installs all three together, both on first use and through the documented unsloth[pdf] preinstall, and existing environments already have all three from the old defaults. A manual partial install like that gets installation guidance, not a crash.

@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4a73eea5e6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +178 to +182
subprocess.run(
command,
check = True,
capture_output = True,
timeout = _remaining(deadline),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the install lock across extraction-worker cancellation

On a first-use PDF/MOBI/FB2 upload, routes/data_recipe/seed.py::_extract_text_from_file_async() runs this loader inside to_process.run_sync(..., cancellable=True). Cancelling that task kills the worker, but the uv/pip subprocess created here survives while the worker's FileLock is released. A subsequent request can therefore acquire the lock and import a partially written package; caching an incomplete namespace can leave that reader unable to parse PDFs even after installation finishes. This remains possible despite the import-lock fix because the installer outlives the lock owner. Move installation outside the cancellable worker or otherwise retain the lock until the installer exits.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d1c174c: _extract_text_from_file_async() now runs ensure_pdf_support() on a server thread before dispatching PDF and MuPDF e-book extraction to the cancellable worker. anyio does not abandon that thread on cancellation, so the install finishes under the lock and the worker only imports. Reproduced the mechanism with anyio and a real pip install: cancelling at 0.8 s returned the request while the worker's pip child kept running with the lock released. After the change no installer outlives the request. I did not catch a broken import end to end (60 timed retries all loaded the complete module), but a retry in that window could also start a second installer on the same files. RAG ingestion and the chat export child are not affected: the first parses on server threads, and the second has a 300 s timeout against the 120 s install budget.

@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 3b494ac0da

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@oobabooga

Copy link
Copy Markdown
Member

Thanks for this, @AlbertoLMa. The loader is careful work, and your size measurements made the tradeoff easy to evaluate. I'm closing it, though, because the saving is small next to a full install. Your baseline counts about 440 MiB of core and Studio dependencies; measured against complete environments, the PDF libraries are a small share:

Install Size PDF libraries Share
Full GPU Studio environment 8.1 GB 62 MB under 1%
Chat-only (no PyTorch) 1.2 GB 57 MB about 5%

In exchange, these features would depend on downloading PyMuPDF the first time they are used:

  • Knowledge bases, project documents, and linked folders (indexing, OCR, figures, citation highlights)
  • Recipe dataset uploads for PDF, MOBI, and FB2
  • Reading a PDF from a web link
  • Exporting a chat as PDF
  • The Python tool opening an attached PDF

A new install without internet access would have no PDF features, and every other new install waits for a download on first use. Making it work also took several fixes, because the original cache was not visible to the separate processes Studio starts for chat export and the Python tool. The S3 SDK (#14157) uses the same pattern, but it serves a niche feature, while PDF support reaches most users who work with documents.

Thanks again for the contribution and the thorough write-up.

@oobabooga oobabooga closed this Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants