Repository navigation
Studio: install PDF dependencies on demand - #17206
AlbertoLMa wants to merge 10 commits into
Conversation
|
The
|
…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.
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| module = _import(name) | ||
| if module is not None: | ||
| return module | ||
| _install_unless(lambda: _import(name) is not None) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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).
| return all( | ||
| importlib.util.find_spec(name) is not None for name in sorted(_MODULES | {"tabulate"}) | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
There was a problem hiding this comment.
💡 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".
| subprocess.run( | ||
| command, | ||
| check = True, | ||
| capture_output = True, | ||
| timeout = _remaining(deadline), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
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:
In exchange, these features would depend on downloading PyMuPDF the first time they are used:
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. |
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
studioextra,requirements/studio.txt,requirements/no-torch-runtime.txt,requirements/single-env/data-designer-deps.txt, and the local unstructured-seed plugin's dependencies.pdfextra and synchronizedstudio/backend/requirements/pdf.txtcontaining PyMuPDF, pymupdf4llm, and tabulate.requirements/extras.txt; its removal is not counted as a saving.fitz -> pymupdfentry 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.requirements/pdf.txtin 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.pyexposesload_pdf_module(name)for onlyfitz,pymupdf, andpymupdf4llm. Each import target is written out literally so the risky-loader audit can verify it without adding a security baseline exception.python -m pipwhen uv cannot run or exits unsuccessfully. Each attempt gets its own staging directory.--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.sys.pathand invalidate import caches. Do not process.pthfiles. 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=0disables new downloads. A complete cache or preinstalled packages still work offline. Missing dependencies, offline/disabled downloads, and installation failures producePDFDependencyUnavailableguidance containing:python -m pip install "unsloth[pdf]"The error also names the uv installation spelling for environments created without pip.
Backend integration
parsers.py,locators.py, andpdf_ocr.pyafter normalizing only these import replacements.errorfield. Failed uploads remove their raw and extracted files. Unrelated extraction errors retain their existing handling.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.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
.pthnon-execution, and bounded lock waits.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..github/workflows/workflow-trigger-lint.ymlin 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.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.git diff --checkpass.For a configured Studio development environment with PDF dependencies installed for native coverage, the focused runs can be reproduced with:
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.