Skip to content

fix: walk pdfplumber pages lazily during extraction - #7346

Merged
LearningCircuit merged 3 commits into
LearningCircuit:mainfrom
AbarnaaSree:fix/6363-lazy-pdf-walk
Oct 14, 2026
Merged

LearningCircuit merged 3 commits into
LearningCircuit:mainfrom
AbarnaaSree:fix/6363-lazy-pdf-walk

Conversation

@AbarnaaSree

Copy link
Copy Markdown
Contributor

Summary

  • Replace eager pdf.pages iteration with the existing lazy iter_pdfplumber_pages helper in the download service.
  • Preserve page, character, and CPU extraction limits during the pdfplumber walk.
  • Close each processed page and the PDF input stream to help limit retained resources.
  • Update tests to cover the lazy page-walker integration and decoded-stream release behavior.

Testing

  • test_pdf_extraction_bounds.py: 102 passed, 1 skipped.
  • Targeted download-service tests: 2 passed.
  • Additional related PDF tests: 176 passed, 1 skipped.
  • git diff --check: passed.

Two tests in the broader combined run failed because they expected Unix-style paths (/tmp/...) on Windows, where the service returned D:\tmp\.... These were path-format assertion failures; the unmodified baseline was not tested.

Scope and limitations

This change avoids eager page materialization in the pdfplumber extraction path. The original reported peak-memory issue has not yet been reproduced and measured end-to-end. The PyPDF fallback still iterates over reader.pages and may warrant separate investigation.

@AbarnaaSree

Copy link
Copy Markdown
Contributor Author

Hi maintainers, the CI annotation says the full pytest suite is required before merging and asks for the test:pytest or a readiness label. Could someone apply the appropriate label so the full test suite can run? Thank you!

@LearningCircuit LearningCircuit added the test:pytest Maintainer request for full pytest before merge; reruns on later pushes while the label remains. label Oct 12, 2026
@LearningCircuit

Copy link
Copy Markdown
Owner

@AbarnaaSree please check the precommit

@LearningCircuit

Copy link
Copy Markdown
Owner

Thanks for this — the core change is right and I verified it end-to-end: routing a crafted 20,000-page PDF through the real DownloadService._extract_text_from_pdf, main performs 40,000 Page constructions in 4.8s (+108 MB peak RSS) while this branch performs 501 in 2.8s (+58 MB) — the 500-page ceiling plus the page that shows it was reached — and both trees return the same result. The wiring also honors the walker's documented contract (before_page() belongs inside the walker; no PDF.close(), which would materialize every page). This completes the lazy-walk migration that #6472 started — after it, every remaining eager page-tree walker in src/ is pypdf, not pdfplumber. Four items need changes before merge, though:

1. The change breaks two existing tests (the red full-suite run).
tests/research_library/services/test_download_service_coverage.py:625 (test_pdfplumber_success) and :683 (test_pdfplumber_pages_with_none_text) fail at this head with assert None == 'Page 1 text' / assert None == 'Text from page 2' (2 failed, 60608 passed in the labeled run; reproduced locally, and both pass on main). These tests mock pdfplumber.open but not the walker — the service now drives the real iter_pdfplumber_pages over a MagicMock document, which yields zero pages, so extraction falls through and returns None. The PR updated the two test files it knew about but missed this third consumer. Note these are not the Windows path-format failures mentioned in the description — they fail on Linux too, deterministically. Please update them like the others (or see item 4 for the better shape).

2. Pre-commit is red on the changed files.
The failing hook is ruff format: both changed test files would be reformatted (download_service.py itself is clean). The specific hunks: the split strings "…pdf_page_walk." / "iter_pdfplumber_pages" in test_download_service.py:487-489,686-688 and test_pdf_extraction_bounds.py:66-68,3788-3790 fit within the 80-column limit and should be joined; plus a few blank-line placements (test_pdf_extraction_bounds.py around lines 46, 1366, 1448, 3872). pre-commit run ruff-format --all-files locally will show them all. (The earlier 11:25Z "All Pytest" red is just the label gate — the labeled run is the real one; its post-step HttpError: Resource not accessible by integration is the known first-time-contributor fork comment class, not a test problem.)

3. The central bounds documentation this change falsifies needs its update.
src/local_deep_research/utilities/pdf_extraction_limits.py:53-63 still states the eager page-tree cost "is paid by every pypdf walk and by the download service's pdfplumber walk" — no longer true after this PR for this walk, where page-tree construction is now interleaved with the ceiling checks. Same for the What is NOT bounded paragraph in the _extract_text_from_pdf docstring (download_service.py:1779-1784), which still claims the parser's page-tree construction is unchecked for this path. This file is the cross-path authority the other docstrings cite; #6472 updated it when it converted the other paths, and this PR is the first in the series that doesn't.

4. Nothing in the test changes actually pins the new behavior.
I copied this PR's two test files onto a main checkout: 168/168 pass against main's eager service. Every changed test mocks the walker, so a regression that reintroduces .pages (e.g. restoring the old len(pdf.pages) in the ceiling warning) is invisible to the entire suite — and the description notes the memory issue was never reproduced end-to-end. Please add one service-level laziness test in the sibling style (tests/web/services/test_pdf_extraction_bounds_siblings.py:495-515 is the template): real pdfplumber.open + a crafted many-page PDF (the _crafted_pdf helper is already there), extract, then assert not hasattr(pdf, "_pages") — that test fails on main and passes here. Two smaller notes in the same vein: test_download_service_deadline_covers_pdfplumber_open (test_pdf_extraction_bounds.py:487-525) now feeds the real walker a MagicMock document, which yields zero pages — its two mock pages are unreachable dead fixture and its first assertion can never fire; and the sibling suites solve the mock/real dispatch with one autouse fixture (tests/web/services/test_pdf_extraction_service.py:15-32 routes real pdfplumber.PDF objects through the real walker and Magics through iter(pdf.pages)) — adopting that here instead of four hand-rolled mocks would have prevented item 1.

Optional: a changelog.d/7346.bugfix.md fragment (the convention #6472 followed with 6472.security.md); and the eager reader.pages flattening that remains in the PyPDF fallback (download_service.py:1901) and the other pypdf walkers (downloaders/base.py:703, document_loaders/bounded_pdf.py:37,55) is a known, documented gap worth a follow-up issue of its own — pypdf has no create_pages equivalent, so it's its own project, not something to bolt onto this PR.

Verified along the way: touched suites 168/168 on the branch and on main (no test in the repo discriminates this change today — in the wrong direction); merge is conflict-free against current main; walker contract and per-page/stream close ordering read correct on all break paths.

Sibling PRs: 4448, 5769, 6986 share the two large test files (file-overlap only; no competing lazy-walk change — none affects merge order here).

Decision: CHANGES REQUESTED

AI-assisted review.

@LearningCircuit LearningCircuit removed the test:pytest Maintainer request for full pytest before merge; reruns on later pushes while the label remains. label Oct 12, 2026
@AbarnaaSree

Copy link
Copy Markdown
Contributor Author

I've addressed the review feedback and pushed the updates in commit eea5ecf43.

  • Fixed the mocked-PDF tests to work with the lazy page walker.
  • Added a regression assertion to verify that service extraction does not eagerly materialize pdfplumber's page list.
  • Updated the documentation to clarify the remaining eager page-tree construction in the PyPDF fallback.
  • Verified formatting and lint checks.

Tests: 233 passed, 1 skipped.

Please take another look when you have a chance. Thank you for the review and feedback!

@AbarnaaSree

Copy link
Copy Markdown
Contributor Author

Hi maintainers, the latest All Pytest Tests + Coverage check is still stopping at the readiness-label gate, with the message that test:pytest or a readiness label is required to run the full suite. Could you please reapply the test:pytest label so the required full pytest workflow can run? Thank you!

@LearningCircuit LearningCircuit added the test:pytest Maintainer request for full pytest before merge; reruns on later pushes while the label remains. label Oct 13, 2026
@LearningCircuit

Copy link
Copy Markdown
Owner

@AbarnaaSree pre-commit

@LearningCircuit

Copy link
Copy Markdown
Owner

Follow-up verified at a691fae0 — every required item from the review is addressed, and the fix holds under re-probing. One optional recommendation remains.

What was verified

  • The two broken tests (test_pdfplumber_success, test_pdfplumber_pages_with_none_text) fail exactly as reported at the previous head and both pass now (299/299 across the three touched suites). The mock/real dispatch fixture routes mocked documents through their page list while sending real pdfplumber.PDF objects through the real lazy walker — the isinstance gate keeps the real-walker tests honest.
  • Formatting is clean: ruff format --check and ruff check pass on all five changed files, and CI pre-commit is green at this head (this also covers the later pre-commit nudge — the style commit resolved it; the check completed successfully at 07:05Z).
  • Both docstrings now state the truth. Verified against the code and the installed library: _extract_text_from_pdf calls iter_pdfplumber_pages (download_service.py:1810–1824), which iterates PDFPage.create_pages directly and never touches PDF.pages; in installed pdfplumber, the first .pages access builds every page object and caches them as _pages (pdf.py:145–170), which is exactly what the new regression assertion detects.
  • The new regression assertion is a genuine discriminator, not a vacuous guard: not hasattr(opened[0], "_pages") fails on unpatched main (1/299 fails there via test_pdfplumber_walk_releases_decoded_streams, all 299 pass on the branch) — reintroducing eager .pages access in the service is now caught through the real walker with a real crafted PDF.
  • The headline behavior is preserved at this head: a crafted 20,000-page PDF through the real _extract_text_from_pdf constructs 501 pages (ceiling + 1) in 0.27 s with +7.6 MB RSS, versus 40,000 constructions / ~4.8 s / +108 MB on unpatched main.
  • The runtime delta since the reviewed head is docstring-only — the walker wiring is untouched — and the branch still merges cleanly into current main.

Optional

  • A changelog fragment is still missing (6472.security.md from the earlier PR in this series is the model — e.g. changelog.d/7346.fixes.md describing the bounded page walking). Not a blocker.

The test:pytest label has been reapplied as part of recording this verdict, so the full-suite gate the author asked about will now run at this head.

Sibling PRs: none shares this fix target — #4448 (resumable research waves), #5769 (file-write containment) and #6986 (release decision binding) also touch download_service.py/test files but on unrelated surfaces (merge-order overlap only).

Decision: APPROVED — OPTIONAL CHANGES

AI-assisted review.

@LearningCircuit LearningCircuit added the ai_code_review Maintainer-only: apply or re-add to run AI code review. Release notes: Automation (18/20). label Oct 13, 2026
@github-actions github-actions Bot removed the ai_code_review Maintainer-only: apply or re-add to run AI code review. Release notes: Automation (18/20). label Oct 13, 2026
@LearningCircuit LearningCircuit added the ai_code_review Maintainer-only: apply or re-add to run AI code review. Release notes: Automation (18/20). label Oct 13, 2026
@github-actions github-actions Bot removed the ai_code_review Maintainer-only: apply or re-add to run AI code review. Release notes: Automation (18/20). label Oct 13, 2026
@LearningCircuit LearningCircuit added test:pytest Maintainer request for full pytest before merge; reruns on later pushes while the label remains. and removed test:pytest Maintainer request for full pytest before merge; reruns on later pushes while the label remains. labels Oct 13, 2026
Repository owner deleted a comment from github-actions Bot Oct 13, 2026
@LearningCircuit
LearningCircuit merged commit ada9db3 into LearningCircuit:main Oct 14, 2026
@LearningCircuit

Copy link
Copy Markdown
Owner

Final review

Verdict: ready to merge.

  • Walking pages through iter_pdfplumber_pages builds at most ceiling + 1 pages instead of the whole page tree. That bounds the cost of hostile PDFs with huge page counts.
  • Not calling PDF.close() is correct. It would iterate self.pages and undo the change, and with a BytesIO input it never closed the stream anyway. This matches pdf_extraction_service.py and file_upload_validator.py.
  • Every page is still closed on every exit path: success, page/char/CPU ceiling breaks, and exceptions. The input stream is now explicitly closed in finally.
  • Behaviour for page-tree errors, the ceilings, the CPU deadline and the PyPDF fallback is unchanged. releaser.before_page() runs inside the walker as its contract requires.
  • The real-PDF laziness test fails on main and passes here. The PR merges cleanly with current main.

Optional:

  • Add a changelog.d fragment.
  • Worth a separate issue: the PyPDF fallback and downloaders/base.py (~703) still build all pages eagerly.

@LearningCircuit

Copy link
Copy Markdown
Owner

Extracted follow-up from the review (now that the code is on main):

This branch was previously deployed

1 inactive deployment
ci — a691fae0 Deployed Oct 13, 2026 by LearningCircuit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

code-review/approved-optional PR-review campaign verdict: APPROVED with optional changes follow-up-issues-extracted All eligible follow-up issues have been extracted from the PR review test:pytest Maintainer request for full pytest before merge; reruns on later pushes while the label remains.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants