Skip to content

fix: use context manager for PyMuPDF doc to prevent fd leak - #97

Closed
sylearn wants to merge 1 commit into
aiming-lab:mainfrom
sylearn:fix/pdf-extractor-resource-leak
Closed

sylearn wants to merge 1 commit into
aiming-lab:mainfrom
sylearn:fix/pdf-extractor-resource-leak

Conversation

@sylearn

@sylearn sylearn commented Mar 19, 2026 •

Copy link
Copy Markdown

Summary

  • extract_from_file() opens a PyMuPDF document with fitz.open() and calls doc.close() at the end
  • If any exception occurs between open and close (e.g. corrupt page, encoding error), the document is never closed, leaking a file descriptor
  • During batch PDF processing in the literature collection stage, this can exhaust the OS fd limit

Fix: Replace manual open()/close() with a with context manager.

Test plan

  • Verified fitz.Document supports the context manager protocol
  • Confirmed the return statement is outside the with block (metadata variables captured before exit)

If any exception occurs between fitz.open() and doc.close(), the
document object is never closed, leaking a file descriptor. During
batch PDF processing in the literature collection stage this can
exhaust the OS file descriptor limit.

Replace manual open/close with a `with` statement so the document
is always closed, even on error.

Made-with: Cursor
Copilot AI review requested due to automatic review settings March 19, 2026 04:08

Copilot AI 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.

Pull request overview

This PR prevents file descriptor leaks during PDF extraction by ensuring PyMuPDF documents are always closed, even when exceptions occur mid-extraction (important for batch PDF processing in the literature collection pipeline).

Changes:

  • Replaced manual fitz.open() / doc.close() handling with a with fitz.open(...) as doc: context manager in PDFExtractor.extract().

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@sylearn

sylearn commented Mar 19, 2026

Copy link
Copy Markdown
Author

Consolidated into #102 as requested.

@sylearn sylearn closed this Mar 19, 2026
@sylearn
sylearn deleted the fix/pdf-extractor-resource-leak branch March 19, 2026 06:40
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.

2 participants