Skip to content

fix: use context manager for file read in pdf_renderer.py - #106

Open
loganbail wants to merge 1 commit into
OpenNSWM-Lab:mainfrom
loganbail:fix/pdf-renderer-unclosed-file
Open

fix: use context manager for file read in pdf_renderer.py#106
loganbail wants to merge 1 commit into
OpenNSWM-Lab:mainfrom
loganbail:fix/pdf-renderer-unclosed-file

Conversation

@loganbail

Copy link
Copy Markdown

What I found

The _requires_xelatex helper in backend/app/services/pdf_renderer.py (line 55) opens a .tex file and reads the first 4096 bytes without a context manager:

content = open(main_tex_path, "r", encoding="utf-8", errors="ignore").read(4096)

The file handle is never explicitly closed. In CPython with refcounting GC it gets collected quickly, but under PyPy or if read() itself raises, the handle leaks. This is especially relevant because _requires_xelatex is called inside compile_latex_project — during a LaTeX compilation run, multiple files could be probed.

The fix

Wrapped the read in a with statement so the file handle is deterministically closed:

with open(main_tex_path, "r", encoding="utf-8", errors="ignore") as f:
    content = f.read(4096)

The existing encoding="utf-8" and errors="ignore" parameters are preserved — the only change is ensuring deterministic file handle cleanup.

Testing

Added tests/test_pr_07_pdf_renderer_file.py with five tests:

Test What it checks
test_requires_xelatex_with_ctexart Returns True for ctexart document class
test_requires_xelatex_with_standard_latex Returns False for standard article class
test_requires_xelatex_with_fontspec Returns True when fontspec package is used
test_requires_xelatex_missing_file Returns False for nonexistent files (no crash)
test_no_unclosed_file_reads Golden check: no open(...).read(...) patterns remain

All five pass.

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.

1 participant