Skip to content

fix(pdf): don't reopen NamedTemporaryFile while it's still held open - #1393

Open
MsfPablo wants to merge 1 commit into
khoj-ai:masterfrom
MsfPablo:fix/pdf-windows-tempfile
Open

fix(pdf): don't reopen NamedTemporaryFile while it's still held open#1393
MsfPablo wants to merge 1 commit into
khoj-ai:masterfrom
MsfPablo:fix/pdf-windows-tempfile

Conversation

@MsfPablo

@MsfPablo MsfPablo commented Aug 3, 2026

Copy link
Copy Markdown

Summary

Fixes #1368. On Windows, PdfToEntries.extract_text fails to index any PDF because PyMuPDFLoader is passed the path of a still-open NamedTemporaryFile(delete=True), and Windows doesn't allow reopening a file that's still held open by another handle.

  • Create the temp file with delete=False and close the with block before handing the path to PyMuPDFLoader
  • Clean up the temp file ourselves via os.unlink() in a finally block, so behavior is unchanged on close/error paths

Test plan

  • Ran PdfToEntries.extract_pdf_entries directly against tests/data/pdf/singlepage.pdf and tests/data/pdf/multipage.pdf — entry counts match what tests/test_pdf_to_entries.py expects (1 and 6 entries respectively)
  • Confirmed no temp files are leaked after extraction (checked tempfile.gettempdir() before/after)
  • Could not run the full pytest suite locally (requires a Postgres instance for Django test DB setup, unrelated to this change) — happy to have CI confirm

On Windows, PyMuPDFLoader cannot open a NamedTemporaryFile's path while
the file handle from tempfile.NamedTemporaryFile(delete=True) is still
open, causing PermissionError: [WinError 32] and silently skipping all
PDF indexing.

Use delete=False, close the handle before handing the path to
PyMuPDFLoader, and clean up the temp file ourselves in a finally block.

Fixes khoj-ai#1368
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.

PDF indexing fails on Windows: NamedTemporaryFile(delete=True) blocks PyMuPDFLoader from opening the temp file

1 participant