Repository navigation
Studio: stop RAG PDF parsing from starving the server on scanned pages - #13137
Conversation
pymupdf4llm guesses each page's background colour by rendering its four corners. When a scan image covers a corner, that render decodes the whole image inside one PyMuPDF call that holds the GIL (about 2 s per JPEG2000 page), so the event loop could not answer /api/liveness and the desktop watchdog killed the backend during linked-folder ingestion. Skip the background probe only on pages where an image overlaps a probed corner; every other page keeps the upstream behaviour and output. Fixes #13094
Codex Review SummaryThis 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. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: df2a99f18b
ℹ️ 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".
| ): | ||
| if not group: | ||
| continue | ||
| part = pymupdf4llm.to_markdown(doc, pages = group, detect_bg_color = detect, **kwargs) |
There was a problem hiding this comment.
Serialize calls that change the global background flag
When a linked folder parses a scanned PDF concurrently with an ordinary PDF, which is the default because folder_sync.py runs two ingestion workers, these calls race: the legacy PyMuPDF4LLM extractor stores detect_bg_color in the module-level DETECT_BG_COLOR variable rather than per invocation. Another worker's normal call can therefore overwrite False while the scanned pages are still being processed, causing their corner renders—and the original server starvation—to return; the reverse race can also alter ordinary-PDF output. Protect all to_markdown invocations, including the unsplit path, with one shared lock or otherwise isolate this mutable library state.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not a race: DETECT_BG_COLOR is a local of to_markdown captured by its nested get_page_output (it is in to_markdown.code.co_cellvars, and pymupdf_rag has no module attribute of that name), so each call reads its own flag.
| for x in (r.x0, r.x1 - 10) | ||
| for y in (r.y0, r.y1 - 10) | ||
| ] | ||
| boxes = [fitz.Rect(info["bbox"]) for info in page.get_image_info()] |
There was a problem hiding this comment.
Transform image boxes before comparing rotated pages
When a page has a 90° or 270° rotation, this compares coordinates from different spaces: PyMuPDF documents that page.rect reflects rotation while coordinates returned by methods such as get_image_info() remain unrotated. A large image covering a displayed corner can therefore be missed, leaving detect_bg_color=True and reproducing the expensive corner render on that page. Transform each image bbox with page.rotation_matrix before testing it against corners derived from page.rect.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b349c98: image boxes from get_image_info are unrotated, so they are now mapped through page.rotation_matrix before the corner check; added a 0/90/180/270 test (90 and 270 failed before).
| for x in (r.x0, r.x1 - 10) | ||
| for y in (r.y0, r.y1 - 10) | ||
| ] | ||
| boxes = [fitz.Rect(info["bbox"]) for info in page.get_image_info()] |
There was a problem hiding this comment.
Account for images in annotation appearances
When a PDF uses an image-backed stamp, button, or other annotation over a corner, get_image_info() does not report that annotation image because it inspects the page-content display instructions, while get_pixmap() normally renders annotations too. Moreover, the PyMuPDF4LLM extractor bakes annotated PDFs before running its background probe, making the image permanent page content after this check has already classified the page as safe. A large compressed annotation image can therefore still be decoded by the corner probe and recreate the stall; bake before collecting image boxes or separately account for annotation appearances.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Below the bar: the stall needs a large scan image decoded on every page, and that lives in page content. Annotation appearance images are small stamps that decode quickly, so they cannot hold the GIL for seconds.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b349c98405
ℹ️ 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".
| boxes = [fitz.Rect(info["bbox"]) * page.rotation_matrix for info in page.get_image_info()] | ||
| except Exception: | ||
| return False | ||
| return any(box.intersects(corner) for box in boxes for corner in corners) |
There was a problem hiding this comment.
Restrict the bypass to costly scan-sized images
When an ordinary PDF has a small logo, badge, or decoration touching a corner, this predicate classifies the page as a scan regardless of the image's dimensions or displayed area, so line 214 disables background detection even though rendering that image is cheap. This is not output-neutral: PyMuPDF4LLM uses the detected color to exclude background-colored vector fills before computing layout regions (upstream implementation); retaining those fills can therefore change reading order or omit chart text on otherwise normal pages. Gate the bypass on a proxy for expensive decoding, such as source pixel count and scan-sized page coverage, rather than any corner intersection.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3724a10: only images of at least 1 megapixel count (JPEG2000 decodes at roughly 45 ms per megapixel), so a corner logo keeps the background probe; added a test.
| identify = getattr(pymupdf4llm, "IdentifyHeaders", None) | ||
| if identify is not None: | ||
| kwargs["hdr_info"] = identify(doc) |
There was a problem hiding this comment.
Build shared headers after baking form appearances
When a form or annotated PDF also enters the split path, this constructs IdentifyHeaders before either to_markdown call, while PyMuPDF4LLM normally calls doc.bake() before constructing its default header detector (upstream ordering). Text in widget or annotation appearance streams is therefore absent from the font-frequency table even though the subsequent extraction bakes and emits that text; common appearance fonts can consequently be misclassified as headings, or appearance headings can lose their markers. Bake before creating the shared detector, preserving the upstream ordering.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3724a10: the shared hdr_info is gone, so each to_markdown call builds IdentifyHeaders(doc) itself after baking, as on main. A form PDF and a paper with scan pages inserted now produce the same Markdown as main on every page.
… call build its own header table
|
@codex review |
1 similar comment
|
@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". |
Fixes #13094
Problem
Linking a folder with scanned PDFs could make Unsloth Desktop report "Server stopped unexpectedly" (
terminal_reason=unresponsive_health_check). The backend was not dead: its event loop could not answer/api/livenesswithin the watchdog's 10 s probe budget three times in a row, so the desktop app killed it.The cause is pymupdf4llm's background-colour probe (
detect_bg_color=Trueby default). For every page it renders the four 10pt page corners withpage.get_pixmap(clip=...). When a scan image covers a corner, MuPDF decodes the whole image for that clip, and it does so inside a single PyMuPDF call that holds the GIL. On JPEG2000 scans (common for archive.org / DTIC style documents) that is about 1.5 to 2 s per page. While an ingest worker thread holds the GIL for one decode after another, the asyncio thread waits behind each one every time it needs the GIL to accept, read and answer a request.Stack of the GIL holder during a stall (py-spy, backend on
main):The event loop thread at the same moment is parked in
pthread_cond_timedwait(the GIL wait) insideasyncio/selector_events.pyaccepting the probe's connection. OCR, Tesseract, the embedding model and llama-server are not involved: every stack showed the corner render.Fix
_pdf_markdownnow checks each page's image boxes (page.get_image_info(), which does not decode anything) against the corners the probe renders. Only pages where an image overlaps a probed corner run withdetect_bg_color=False; all other pages go through pymupdf4llm exactly as before. When no page needs the change, the call is byte-for-byte the old one. When it does, the pages are split into twoto_markdowncalls that share the same whole-document header tableto_markdownwould build itself, and are put back in page order.The narrower split matters: turning the probe off for every page changes output on ordinary PDFs. On the QLoRA paper (arXiv 2305.14314), for example, it drops chart axis labels and legends on pages 6, 22 and 26. With the per-page check that output is unchanged.
Measured from rendering the corners of one 600 dpi JPEG2000 page: an image covering a corner takes 1.57 s, while the same image inset from the corners takes 0.001 s. MuPDF only decodes images that intersect the clip, so the check targets exactly the pages that pay.
Evidence
Backend launched from source on this host. A JPEG2000 scanned corpus was linked through
POST /api/rag/projects/{id}/linked-folders, with no Tesseract and the EmbeddingGemma embedding model configured.GET /api/livenesswas probed every 2 s with a 10 s timeout, the same budget the desktop watchdog uses.On main the timeouts came 3 to 4 in a row, which is the watchdog's 3-strike kill. Markdown extraction of the first 8 pages of each JPEG2000 file went from 12 to 15 s per file to 0.07 s.
Output parity,
_pdf_markdownon main vs this PR:Tests:
tests/test_rag_parsing.py: 59 passed.test_pdf_markdown_does_not_render_scanned_pagesfails on main (the scan page is rendered 4 times) and passes here.-k "rag and (pars or ingest or folder or pdf)"): 353 passed, 3 skipped.Not covered
get_textpage_ocr) still renders scanned pages at 150 dpi on a worker thread. It is capped at 20 pages per document, and it is not part of this report, where Tesseract was missing.