Skip to content

Studio: stop RAG PDF parsing from starving the server on scanned pages - #13137

Merged
danielhanchen merged 3 commits into
mainfrom
studio-rag-pdf-scan-gil
Oct 9, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
studio-rag-pdf-scan-gil

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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/liveness within 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=True by default). For every page it renders the four 10pt page corners with page.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):

Thread "rag-folder-ingest_0" (active+gil)
    fz_opj_t1_decode_cblks (pymupdf/libmupdf.so.27.2)
    fz_load_jpx (pymupdf/libmupdf.so.27.2)
    fz_get_pixmap_from_image (pymupdf/libmupdf.so.27.2)
    fz_run_display_list (pymupdf/libmupdf.so.27.2)
    get_pixmap (pymupdf/__init__.py:11876)
    get_bg_color (pymupdf_rag.py:892)
    get_page_output (pymupdf_rag.py:981)
    to_markdown (pymupdf_rag.py:1250)
    _pdf_markdown (studio/backend/core/rag/parsers.py:174)

The event loop thread at the same moment is parked in pthread_cond_timedwait (the GIL wait) inside asyncio/selector_events.py accepting the probe's connection. OCR, Tesseract, the embedding model and llama-server are not involved: every stack showed the corner render.

Fix

_pdf_markdown now 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 with detect_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 two to_markdown calls that share the same whole-document header table to_markdown would 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/liveness was probed every 2 s with a 10 s timeout, the same budget the desktop watchdog uses.

arm probes max p99 probes > 3 s probes timed out at 10 s
main (1c946d1), 6 min 50 10.01 s 10.01 s 37 27
this PR, 6 min 181 0.076 s 0.062 s 0 0
this PR (final commit), 4 min 121 0.050 s 0.022 s 0 0

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_markdown on main vs this PR:

  • 5 real PDFs (3 arXiv papers, IRS W-4, IRS Publication 17; first 8 pages each): byte-identical.
  • JPEG2000 scans: byte-identical. The probe returned no colour on those pages anyway.

Tests:

  • tests/test_rag_parsing.py: 59 passed.
  • The new test_pdf_markdown_does_not_render_scanned_pages fails on main (the scan page is rendered 4 times) and passes here.
  • RAG-related backend tests (-k "rag and (pars or ingest or folder or pdf)"): 353 passed, 3 skipped.

Not covered

  • Windows was not run locally. The code path is the same PyMuPDF wheel and GIL behaviour on every OS, and a slower laptop CPU only makes each decode longer.
  • I do not have the reporter's PDFs; the repro uses JPEG2000 scans, which is how many archived scanned documents are stored.
  • When Tesseract is configured, OCR (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.

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
@danielhanchen danielhanchen self-assigned this Oct 9, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-09T14:14:52.410765Z 3724a10 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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 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)

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 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment thread studio/backend/core/rag/parsers.py Outdated
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()]

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 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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).

Comment thread studio/backend/core/rag/parsers.py Outdated
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()]

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 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 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)

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 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment thread studio/backend/core/rag/parsers.py Outdated
Comment on lines +204 to +206
identify = getattr(pymupdf4llm, "IdentifyHeaders", None)
if identify is not None:
kwargs["hdr_info"] = identify(doc)

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 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 3724a10797

ℹ️ 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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Server stopped unexpectedly while embedding documents

1 participant