~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(pdf): follow-ups to #6459 — pypdf version refs, warn when stream release is disabled, tighter memory estimate (#6877)
LearningCircuitf9214169486e
diff --git a/changelog.d/6459.security.md b/changelog.d/6459.security.mdindex 36fb3c9927..eb63b28624 100644--- a/changelog.d/6459.security.md+++ b/changelog.d/6459.security.md@@ -1 +1 @@-Library download/ingestion PDF text extraction is now bounded by three ceilings, defined as module constants in ``utilities/pdf_extraction_limits``: pages walked (``MAX_PDF_EXTRACTION_PAGES``, 500 per attempt — the download service's PyPDF fallback runs only when pdfplumber produced no text, so one extraction there can walk up to 1,000 pages in total), characters kept (``MAX_PDF_EXTRACTED_CHARS``, 10,000,000 characters including the separators that join pages; the page that crosses the ceiling contributes the prefix that fits instead of being dropped), and CPU time between pages (``MAX_PDF_EXTRACTION_CPU_SECONDS``, 600 — one budget per whole extraction, shared by the pdfplumber attempt and its PyPDF fallback, which is not started once the budget is spent). The CPU budget counts only the extracting thread's own CPU time (``time.thread_time()``), not wall-clock time, so waiting for the GIL or for other users' extractions does not spend it; the switching overhead of GIL contention does count, and the budget is sized not to cut an honest document short under load: a dense 500-page document measured about 146 s of thread CPU alone and about 250-330 s with 4 to 16 extractions contending, leaving about 1.8x margin or more. The budget is checked between pages, so it is not a hard CPU cap: the page-tree parse, the page in progress when it runs out and, when pdfplumber found no text with budget left, the PyPDF fallback's parse all run to completion. A document longer than 500 pages therefore yields at most the text of its first 500 pages — fewer if the character ceiling, or on a much slower host the CPU budget, stops the walk first — and the stored text is not marked as partial. The download service's pdfplumber walk also closes every page it reaches, releasing that page's layout and text-map caches (about 25 MB for a dense page). Closing does not release what the PDF libraries decode and parse for a page: pdfminer and pypdf keep every decoded stream and parsed object for the life of the document, so a crafted page of 20 MB of spaces (about 20 KB compressed, no characters, about 0.17 s of CPU) added about 20 MB per page — about 10 GB at the page ceiling from a 10 MB file. All three walks (pdfplumber, its PyPDF fallback, the base helper) now release those caches once the decoded stream bytes plus an estimate of the parsed objects reach ``MAX_PDF_RETAINED_DECODED_BYTES`` (64 MiB): decoded streams go back to their encoded state and the parsed objects the walk added are dropped, to be read again from the file if a later page needs them. What a walk holds between pages therefore stays near that threshold — crafted PDFs that added 20-60 MB per page peaked about 100-250 MB above the starting memory — and honest documents, which stay far below it, are left alone. The release reaches into library internals, pinned to pdfplumber 0.11.10 / pdfminer.six 20260107 and pypdf 6.16.1; if an upgrade removes them the release is skipped, extraction carries on, and canary tests fail. The ceilings are enforced in the download service extractor and in the shared base-downloader ``extract_text_from_pdf`` that the library's downloader text branches and the search-time PDF fetcher route through. What is NOT bounded: page-tree materialisation — ``pdfplumber`` and ``pypdf`` build every page of the document before the first page is yielded, so a file with many pages costs O(all pages) time and memory before any ceiling is consulted, whatever page count it declares; and the cost of a single page — one page's ``extract_text()`` runs to completion inside the library with no check point available to the caller, and a few kilobytes of compressed content streams can take minutes or exhaust gigabytes of address space there, and what that page decodes and parses is held until the release after it. Bounding either would require a separate process. Nor is the memory held between releases bounded exactly: parsed objects are estimated per array item or dictionary entry, so it can exceed the threshold by a small multiple. The arXiv search engine's inline PDF text extraction, the web upload route's extraction service and the ``document_loaders``-based extraction used by RAG uploads and Zotero sync are not bounded by this change; a companion change (#6472) proposes the same page and character ceilings for the first two.+Library download/ingestion PDF text extraction is now bounded by three ceilings, defined as module constants in ``utilities/pdf_extraction_limits``: pages walked (``MAX_PDF_EXTRACTION_PAGES``, 500 per attempt — the download service's PyPDF fallback runs only when pdfplumber produced no text, so one extraction there can walk up to 1,000 pages in total), characters kept (``MAX_PDF_EXTRACTED_CHARS``, 10,000,000 characters including the separators that join pages; the page that crosses the ceiling contributes the prefix that fits instead of being dropped), and CPU time between pages (``MAX_PDF_EXTRACTION_CPU_SECONDS``, 600 — one budget per whole extraction, shared by the pdfplumber attempt and its PyPDF fallback, which is not started once the budget is spent). The CPU budget counts only the extracting thread's own CPU time (``time.thread_time()``), not wall-clock time, so waiting for the GIL or for other users' extractions does not spend it; the switching overhead of GIL contention does count, and the budget is sized not to cut an honest document short under load: a dense 500-page document measured about 146 s of thread CPU alone and about 250-330 s with 4 to 16 extractions contending, leaving about 1.8x margin or more. The budget is checked between pages, so it is not a hard CPU cap: the page-tree parse, the page in progress when it runs out and, when pdfplumber found no text with budget left, the PyPDF fallback's parse all run to completion. A document longer than 500 pages therefore yields at most the text of its first 500 pages — fewer if the character ceiling, or on a much slower host the CPU budget, stops the walk first — and the stored text is not marked as partial. The download service's pdfplumber walk also closes every page it reaches, releasing that page's layout and text-map caches (about 25 MB for a dense page). Closing does not release what the PDF libraries decode and parse for a page: pdfminer and pypdf keep every decoded stream and parsed object for the life of the document, so a crafted page of 20 MB of spaces (about 20 KB compressed, no characters, about 0.17 s of CPU) added about 20 MB per page — about 10 GB at the page ceiling from a 10 MB file. pdfminer also builds every font in a page's resources (and in a Form XObject's, each time the page invokes it), with tables it expands from short ranges: each font parses its ``/ToUnicode`` CMap into its own map, so one ``<0000> <FFFF>`` range in a ~100-byte compressed CMap that many fonts share becomes 65,536 entries per font. It caches the fonts that are objects of their own and builds those written inline in a resource dictionary again on every use, caching them nowhere; either way the map stays in a reference cycle that only a garbage collection frees. 20 pages of five such fonts held about 840 MB, from an 18 KB file or, with the fonts inline, a 13 KB one. All three walks (pdfplumber, its PyPDF fallback, the base helper) now release those caches once the decoded stream bytes plus an estimate of the parsed objects and, under pdfplumber, of the fonts pdfminer has built reach ``MAX_PDF_RETAINED_DECODED_BYTES`` (64 MiB): decoded streams go back to their encoded state, and the parsed objects and fonts the walk added are dropped, to be read or built again from the file if a later page needs them; under pdfplumber the release then runs a full garbage collection (spaced like the ones below, so a release can defer it), because pdfminer's parsers keep what they built (a font's ``/ToUnicode`` map and the decoded CMap bytes) in reference cycles that dropping the font does not free — its cost grows with everything the server process holds, about 0.06 s per million objects, and counts against the CPU budget. The estimate counts the decoded stream bytes, every object the walk parsed (including those pdfminer parses out of object streams, and a stream's dictionary, read without decoding the stream) with every array item and dictionary entry nested in it, and every font pdfminer built (counted as its ``get_font()`` returns them, cached or inline, each object once) with every element nested in the tables the build stores on it — its ``/ToUnicode`` map, its encoding table, its widths (each font builds its own copy of its ``/Widths`` array, even one that many fonts share, and a CID font expands its ``/W`` and ``/W2`` ranges) and a CID font's vertical displacements, a table that a parsed object or pdfminer still holds (a font's descriptor) counted once — with every string among all of these, dictionary keys included, counted by its size (a CID font joins its ``/CIDSystemInfo`` strings into a new one on every build), plus the decoded bytes each build feeds to a parser that pdfminer leaves in a reference cycle, where pdfminer parses them: the ``/ToUnicode`` CMap, and the first ``/Length1`` bytes of the ``/FontFile`` whose header a Type 1 font without ``/Encoding`` (and without built-in metrics) parses from a fresh copy; other memory the libraries hold for the document is not counted by the estimate. On Linux the walks also release once the process's resident memory (``/proc/self/statm``) has grown by the threshold since the last release, whatever the estimate says; it is the whole process's memory, so growth from other threads can make a release that frees nothing, and on other platforms only the estimate applies. Those parsers are garbage once the build returns, and the tokens a crafted input leaves on their stack hold up to about 170 bytes per decoded byte, so the pdfplumber walk also runs a full garbage collection, without a release and in the middle of a page if need be, once the bytes fed to them since the last one could hold the threshold's worth, when the font tables it holds reach the threshold's worth and are let go of, and on Linux once the resident memory has grown by the threshold since the last collection; such a collection, and a release's, waits until the walking thread has spent nine times the last one's duration since it ended (at most about a tenth of its CPU time), unless the resident memory has grown by four times the threshold; a release that defers its collection still drops the caches. A collection runs at once, however recent the last one, once the garbage that only a collection frees, released since the last one, reaches the threshold: what those parsers were fed (a fresh copy at once, a stream's own decoded bytes once the release rewinds the stream) and the tables of the fonts built with them once those fonts are dropped (an inline font's when its build returns, a cached font's at the release); and a collection still deferred when the walk ends runs then. What those counted structures hold between pages therefore stays near that threshold — crafted PDFs that added 20-60 MB per page peaked about 100-250 MB above the starting memory, and the 840 MB font files (fonts as objects of their own, inline, or inline in a Form XObject) about 35-75 MB, whether the process held no other objects or 8 million, with or without the resident-memory trigger — and honest documents, which stay far below it, are left alone. The release reaches into library internals, written against the pdfplumber, pdfminer.six and pypdf versions ``pdm.lock`` pins; if an upgrade removes them the release is skipped, extraction carries on, and canary tests fail. The ceilings are enforced in the download service extractor and in the shared base-downloader ``extract_text_from_pdf`` that the library's downloader text branches and the search-time PDF fetcher route through. What is NOT bounded: page-tree materialisation — ``pdfplumber`` and ``pypdf`` build every page of the document before the first page is yielded, so a file with many pages costs O(all pages) time and memory before any ceiling is consulted, whatever page count it declares; and the cost of a single page — one page's ``extract_text()`` runs to completion inside the library with no check point available to the caller, and a few kilobytes of compressed content streams can take minutes or exhaust gigabytes of address space there, and what that page decodes and parses is held until the release after it. Bounding either would require a separate process. Nor is the memory held between releases bounded exactly: parsed objects and font tables are estimated per array item or dictionary entry, so it can exceed the threshold by a small multiple, and a collection that the spacing defers lets the part of the parsers' residue that the worst-case factor counts beyond what each was fed pile up until it runs, for longer the more objects the server process holds (on Linux, at most until the resident memory has grown by four times the threshold). Nor are the names and keywords pdfminer interns: it keeps them in process-wide tables (``PSLiteralTable``, ``PSKeywordTable``) that it never clears and compares against by identity, so a 2 MB PDF of a million distinct names (or keywords) adds about 175 MB to the server process for good, and every upload of new ones adds more; the honest documents measured added 25 to 243 entries each. The arXiv search engine's inline PDF text extraction, the web upload route's extraction service and the ``document_loaders``-based extraction used by RAG uploads and Zotero sync are not bounded by this change; a companion change (#6472) proposes the same page and character ceilings for the first two.diff --git a/changelog.d/6877.security.md b/changelog.d/6877.security.mdnew file mode 100644index 0000000000..45be375056--- /dev/null+++ b/changelog.d/6877.security.md@@ -0,0 +1 @@+The PDF cache release added in #6459 now logs a WARNING the first time a library's releaser (pdfminer under pdfplumber, or pypdf) has to switch itself off in a process — at most one per library, for example after an upgrade changed the internals it relies on — since the memory held between pages is no longer bounded from then on; later occurrences stay at DEBUG. Its memory estimate also leaves less uncounted: every object a page caches counts for at least one element, so empty and scalar objects are no longer free; a stream's dictionary counts like any other parsed dictionary, read without decoding the stream (before, a stream counted one element, so a Form XObject whose dictionary holds hundreds of thousands of empty arrays cost up to about 85 times its file bytes uncounted: 300,000 of them, a 600 KB file, held 49 MB); the objects pdfminer parses out of object streams now count too, each once, including those no page has resolved yet; and so do the fonts pdfminer builds, which were not counted at all — counted as pdfminer's ``get_font()`` returns them rather than read off its font cache, so a font written inline in a resource dictionary, which pdfminer does not cache and builds again on every use (on every page, and on every invocation of a Form XObject), counts each time it is built: one element per font plus every element nested in the tables the build stores on it — its ``/ToUnicode`` map, its encoding table, its widths and a CID font's vertical displacements (a table several fonts share counts once, and one that a parsed object or pdfminer itself still holds, such as the font's descriptor or the items of a Type 3 font's ``/FontMatrix``, which a build stores as they are, is not counted or walked again while that holds it: walking it on every build, as the previous revision did once the tables it held reached the threshold's worth, made a page of 100 ``Do``s of a form whose inline font's descriptor holds 600,000 empty arrays take about 66 s of CPU, and about 130 s with them as a ``/FontMatrix`` item, against about 3 s without the releaser; it now takes about 6.3-6.7 s, the extra being one release and its collection) — and the decoded bytes it feeds to a parser pdfminer leaves in a reference cycle. Each font, simple ones included, builds its own widths table, copying its ``/Widths`` array even when many fonts share one: before that copy counted, 6 pages of six fonts sharing one 200,000-entry array grew about 97 MB per page with no release. A Type 1 font without ``/Encoding`` parses a fresh copy of its ``/FontFile``'s first ``/Length1`` bytes, which its parser keeps in a reference cycle: before that copy counted, three fonts a page sharing a 20 MB ``/FontFile`` of spaces (a ~30 KB file) grew about 57 MB per page with no release, 706 MB over 12 pages; both now stay flat, each page releasing. A CID font also joins its ``/CIDSystemInfo`` ``/Registry`` and ``/Ordering`` into a new string on every build, however long they are and however many fonts share them: ten pages of five such fonts sharing a 20 MB ``/Registry`` string (a 25 KB file) grew about 95 MB per page with the estimate at 0.1 MB and no release, about 1 GB over 10 pages; every string a font build stores, and every string in a parsed object (dictionary keys included: pdfminer turns a name that is not UTF-8 into the text of its repr, about four characters a byte), now counts by its size, and that file stays flat, about 19 MB above the starting memory between pages. Because each such allocation went unbounded until it was found, the release also has a measured trigger: on Linux, where the process's resident memory can be read from ``/proc/self/statm``, both walk releasers also release once it has grown by the threshold since the last release (or since the walk began), whatever the estimate says, and the pdfplumber walk also runs a collection in the middle of a page once it has grown by the threshold since the last collection; a read that fails keeps the previous baseline rather than switching the trigger off. With the string counting removed, the measured trigger alone holds the ``/Registry`` file at about 182 MB above the start between pages. The resident memory is the whole process's, so growth from other threads, or that a release cannot free, makes a release that frees nothing, and the next one waits for another threshold's worth of growth; on other platforms only the estimate applies. Because those parsers are garbage once the build returns, the walk also runs a full garbage collection, between releases and in the middle of a page, once the bytes fed to them could hold the threshold's worth (the tokens a crafted input leaves on their stack hold up to about 170 bytes per decoded byte) and when the font tables it holds reach the threshold's worth and are let go of: a page invoking a Form XObject of five inline 65,536-entry ``/ToUnicode`` fonts 20 times took the process to about 880 MB before and about 110 MB now. Those bytes count only where pdfminer parses them — the ``/FontFile`` header copy is its first ``/Length1`` bytes, and nothing for a font with ``/Encoding`` or with one of the standard ``/BaseFont`` names pdfminer has built-in metrics for — and a collection asked for in the middle of a page waits until the walking thread has spent nine times the last collection's duration since it ended, so that such collections take at most about a tenth of its CPU time, unless the resident memory has grown by four times the threshold; a release is spaced the same way (one the resident memory asks for waits, and one the estimate asks for drops the caches at once but defers its collection) — except that a collection runs at once, however recent the last one, once the garbage that only a collection frees, released since the last one, reaches the threshold: what those parsers were fed, which each keeps (a fresh copy, such as the ``/FontFile`` header, at once; a stream's own decoded bytes, once each, when the release rewinds the stream), and the tables of the fonts built with them, such as a ``/ToUnicode`` map, once those fonts are dropped (an inline font's when its build returns, a cached font's at the release). An earlier revision of this change spaced those too, holding them for as long as nine full collections of the server process's heap took: 40 pages of five fonts sharing a 65,536-entry ``/ToUnicode`` map peaked about 400 MB above the starting memory with 8 million objects held (about 430 MB without the resident-memory trigger, as on macOS or Windows), and it now peaks at 51-74 MB with 0 to 8 million objects held, with or without that trigger, as when every release collected (44-72 MB). What a deferred collection would still free, the part of the parsers' residue the worst-case factor counts beyond what each was fed, is held until it runs, for longer the more objects the process holds (on Linux at most until the resident memory has grown by four times the threshold); a collection still deferred when the walk ends runs then, as the releaser is let go of (or on its ``close()``), and none of the honest documents measured deferred one. After a font build that raised, the streams it may have parsed are looked up in the object cache only, so that the count parses nothing the build did not reach and follows no reference cycle. Before, counting the whole decoded ``/FontFile`` on every build made a 1.3 KB page of 2,000 ``Do``s of a form with one inline Type 1 font whose ``/Length1`` is 0 run 2,001 collections: about 141 s of CPU instead of about 0.45 s without the releaser, with a million objects held; it now runs none (0.58 s). With ``/Length1`` the whole 400 KB of spaces, which the worst-case factor over-counts, it ran 2,001 collections (191 s against 4.7 s) and now 11 (6.2 s). A release the estimate asks for can be as cheap: 100 pages whose font decodes a shared 64 MB ``/FontFile`` of zeros and parses none of it (a 92 KB file) release on every page, and with a million objects held ran 101 collections (about 25 s of CPU) and now 25 (about 20 s, the rest being the stream decoded again on every page), at the same peak memory. One of eight honest documents of 1 to 500 pages released once (a one-page form whose three embedded TrueType fonts grew the process by about 69 MB); none triggered a collection otherwise, at unchanged CPU time. Before, an 18 KB PDF of 20 pages, each with five fonts sharing one ~100-byte compressed ``/ToUnicode`` CMap that maps codes 0000-FFFF, held about 840 MB with the estimate at 64 KB and no release (about 21 GB at the 500-page ceiling, extrapolated), and 20 pages of five CID fonts whose ``/W [0 65535 500]`` expands to 65,536 widths each held about 450 MB, also with no release. Counting only the cached fonts, as an earlier revision of this change did, missed inline ones: the same five fonts written inline (a 13 KB file) still held about 840 MB over 20 pages with no release, and so did five inline fonts in a Form XObject; one inline font whose four-byte ``/ToUnicode`` range maps 262,144 codes (a 7 KB file) grew about 34 MB per page. A pdfminer release also frees what it drops now (the releaser holds the font tables it has counted while something else holds them, and up to the threshold's worth of those nothing else does, until then): the parser that builds a font's ``/ToUnicode`` map keeps the map and the decoded CMap bytes in a reference cycle, which the release used to leave for an automatic collection that such pages hardly trigger, so a walk whose shared ``/ToUnicode`` CMap decoded to 70 MB, enough to make every page release, still grew about 850 MB over 12 pages; the release now runs a full garbage collection (about 0.06 s per million objects the process holds, counted against the CPU budget), spaced as above. Measured between pages, with 0, 3 or 8 million other objects held and with the resident-memory trigger on or off, the ``/ToUnicode`` file now peaks 44-74 MB above the starting memory, at 20, 40 and 60 pages alike, the CID ``/W`` file 34-35 MB and the 70 MB-CMap file 33-45 MB, and over 20 pages the inline ``/ToUnicode`` file 47-69 MB, its Form XObject variant 19-64 MB and the four-byte one about 43 MB. pdfminer's process-wide tables of the names and keywords it has parsed (``PSLiteralTable``, ``PSKeywordTable``) are not bounded: it never clears them and compares against their entries by identity, so the release cannot drop them, and a 2 MB PDF of a million distinct names or keywords adds about 175 MB to the server process for good, each upload of new ones more (the honest documents measured added 25 to 243 entries each).diff --git a/src/local_deep_research/utilities/pdf_stream_release.py b/src/local_deep_research/utilities/pdf_stream_release.pyindex 545a6db822..f346b08581 100644--- a/src/local_deep_research/utilities/pdf_stream_release.py+++ b/src/local_deep_research/utilities/pdf_stream_release.py@@ -17,34 +17,200 @@ does not release it:pdfminer font object keeps its own copy of the widths. A page whosefont points at a 500,000-entry ``/Widths`` array held ~60 MB more perpage, at ~2 s of CPU per page.+- font tables. pdfminer builds every font in a page's resources (and+ in a Form XObject's, on every ``Do`` that invokes it), with tables it+ expands from short ranges: a ``/ToUnicode`` CMap's ``<0000> <FFFF>+ <0000> beginbfrange`` becomes a 65,536-entry dictionary, and every+ font builds its own copy even when they all point at one ~100-byte+ compressed CMap stream. A font that is an object of its own is kept+ in the resource manager's font cache; one written inline in a+ resource dictionary is built again on every use and cached nowhere.+ Either way the parser that builds each map keeps it, and the decoded+ CMap bytes, in a reference cycle, so dropping the font does not free+ them, and parsing them creates too few tracked objects for the+ automatic collector to run often. Twenty pages of five such fonts held+ ~840 MB, from an 18 KB file or, with the fonts inline, a 13 KB one.+ Each font also builds its own widths table, copying the /Widths array+ even when many fonts share one (six fonts a page sharing one+ 200,000-entry array grew ~97 MB a page); a Type 1 font without+ /Encoding hands a fresh copy of its /FontFile's first /Length1 bytes+ to a header parser that keeps it in a reference cycle (three fonts a+ page sharing a 20 MB /FontFile of spaces, a ~30 KB file, grew ~57 MB+ a page); the tokens a crafted /ToUnicode CMap or font header leaves+ on its parser's stack hold up to ~170 bytes per decoded byte, in the+ same cycle; and a CID font joins its /CIDSystemInfo /Registry and+ /Ordering into a new string of its own (five fonts a page sharing a+ 20 MB /Registry string, a 25 KB file, grew ~95 MB a page).A walker creates one releaser per document and calls ``before_page()``just before each page's ``extract_text()`` and ``after_page()`` once thepage is done. A lazy pdfplumber walk (``utilities/pdf_page_walk``) calls``before_page()`` before it builds each page instead, since building a-page resolves (and caches) its resources and contents. ``after_page()`` estimates what the object cache holds+page resolves (and caches) its resources and contents.+``after_page()`` estimates what the library's caches holdsince the last release -- decoded stream bytes, plus-``_BYTES_PER_PARSED_ELEMENT`` for every element of the objects the walk-has parsed -- and, once that reaches ``MAX_PDF_RETAINED_DECODED_BYTES``,-releases it: decoded streams go back to their encoded state (the next-access decodes them again from their raw bytes, so a stream a later-page shares still extracts correctly), and every object the walk added-to the cache is dropped, to be parsed again from the file if a later-page needs it. Objects cached before the first ``before_page()`` (the-page tree, when the walk materialised it up front) are kept. Honest documents stay far below the threshold and are left-alone.+``_BYTES_PER_PARSED_ELEMENT`` for every object the walk has parsed and+for every element nested in it (a stream's dictionary included, read+without decoding the stream: a Form XObject's can hold any number of+entries), including the objects pdfminer parses+out of object streams (each counted once, whether or not a page has+resolved it through the object cache), and for every font pdfminer's+resource manager builds or hands out and every element nested in the+tables a build stores on the font (``_font_tables()``; a font or a+table seen again is counted once, but see below), with every string+among all of these counted by its size, plus the decoded bytes each+build feeds to a parser it leaves in a reference cycle+(``_parser_input_bytes()``) -- and, once that reaches+``MAX_PDF_RETAINED_DECODED_BYTES``, releases it: decoded streams go back+to their encoded state (the next access decodes them again from their+raw bytes, so a stream a later page shares still extracts correctly),+and every object the walk added to the cache is dropped, to be parsed+again from the file if a later page needs it, and the fonts are+dropped (the font cache cleared, the releaser's own references let+go), to be built again, and the reference cycles pdfminer's parsers+leave are collected. Objects cached before the first ``before_page()``+(the page tree, when the walk materialised it up front) are kept.+Honest documents stay far below the threshold and are left alone.++That estimate counts what the cases found so far showed a page can+keep, and each case found later (fonts written inline, widths copied+per font, font header copies, the strings a CID font joins) went+unbounded until it was counted. So the release also has a measured+trigger: where the process's resident memory can be read+(``/proc/self/statm``, on Linux), ``after_page()`` also releases once it+has grown by the threshold since the last release (or since the walk+began), whatever the estimate says, and the pdfminer releaser runs a+collection in the middle of a page once it has grown by the threshold+since the last collection. It is the whole process's memory: growth+that other threads cause, or that a release cannot free (pdfminer keeps+every name it parses in a process-wide table), makes a release or a+collection that frees nothing, after which the baseline is where the+memory then is, so the next one waits for another threshold's worth of+growth. On other platforms only the estimate applies. Of the eight+honest documents measured (up to 500 pages) it released one, once: a+one-page form whose three embedded TrueType fonts grew the process by+~69 MB.++Fonts are counted where they are built, not read off the font cache,+which misses the inline ones: the releaser wraps this document's+``rsrcmgr.get_font`` (an instance attribute, holding the manager and+the releaser weakly) and counts every font it returns, once per font+object, remembering the fonts weakly so that it keeps none pdfminer+frees. To count a table several fonts share only once, it holds the+tables it has counted, and lets go of those nothing else holds once+the ones added since it last did reach the threshold's worth, after+every collection and on a release (a table seen again after that is a+new object, and counts in full); so it can keep up to about the+threshold's worth of tables that pdfminer would have freed sooner, such+as the widths of a CID font written inline in a Form XObject, built+again on every ``Do``, plus those that something else held when it last+let go (such a table weighs once more toward the next time, so it goes+soon after its holder, the font being built, lets go of it). The tables+something else still holds it keeps, and never counts or walks again: a build stores some parts of the parsed font as+they are (the descriptor, a CID font's /CIDSystemInfo, the items of a+Type 3 font's /FontMatrix), and walking those on every ``Do`` of a form+with an inline font cost more than the build (a page of 100 ``Do``s of+a form whose inline font's descriptor holds 600,000 empty arrays took+~66 s of CPU, and ~130 s as a Type 3 font's /FontMatrix item, against+~3 s without the releaser; now ~6.3-6.7 s, the extra being the one+release, which parses the form again to rewind it, and its+collection). A nested container that another holds too is counted as+a table of its own, for the same reason. When it lets go of tables it+also asks for a full garbage collection, as it does once the+bytes fed to parsers since the last one, times+``_PARSER_BYTES_PER_INPUT_BYTE``, reach the threshold: what those+parsers, and the fonts pdfminer has dropped, hold in reference cycles+is garbage as soon as a build returns, so it is freed in the middle of+a page too (a page invoking a form of five inline 65,536-entry+/ToUnicode fonts 20 times took the process to ~880 MB before, ~110 MB+with it). Those bytes count only where pdfminer+parses them, but the factor is the worst case (a whitespace input+leaves nothing), and a collection costs time in proportion to every+object the process holds, whatever it frees. So a collection asked for+in the middle of a page waits until the walking thread has spent+``_COLLECT_SPACING`` (9) times the last collection's duration since it+ended -- such collections then take at most about a tenth of its CPU+time -- unless the resident memory has grown by ``_FORCED_GROWTH`` (4)+times the threshold since the last one; a release that only the+resident memory asks for waits the same way, and a release the+estimate asks for drops the caches at once but defers its collection+the same way (until a later font build or page, or the walk's end) --+except that a collection runs at once, however recent the last one,+once the garbage that only a collection frees, released since the+last one, reaches the threshold: what those parsers were fed, which+each holds -- a fresh copy (a /FontFile header) at once, a stream's own+decoded bytes, once each, when the release rewinds the stream -- and+the tables of the fonts built with them (their /ToUnicode map, which+the parser's cycle holds) once those fonts are let go of -- an inline+font's when its build returns, a cached font's at the release. Spaced+too, as in the previous revision, those were held for as long as+nine full collections of the process's heap took: 40 pages of five+fonts sharing a 65,536-entry /ToUnicode map peaked ~400 MB above the+start with 8 million objects held (~430 MB without the measured+trigger), and now 51-74 MB, as without objects held. What a deferred+collection would free besides is the part of the parser residue the+factor counts beyond each parser's input, which stays held until it+runs, for longer the more objects the process holds (on Linux at most+until the resident memory has grown by four times the threshold); one+still pending when the walk ends runs then (``close()``, or once the+releaser is garbage), and honest documents defer none. Before the+spacing, a page of+2,000 ``Do``s of a form with one inline Type 1 font whose /FontFile+has a /Length1 of 0 (a 1.3 KB file) ran 2,001 collections: ~141 s of+CPU instead of ~0.45 s, with a million objects held; it now runs none,+and with a /Length1 of the whole 400 KB of whitespace (which the+factor over-counts) 11 instead of 2,001 (~6.2 s instead of ~191 s,+against ~4.7 s without the releaser). And 100 pages whose font decodes+a shared 64 MB /FontFile of zeros and parses none of it (a 92 KB file),+which releases on every page, ran 101 collections with a million+objects held (~25 s of CPU) and now 25 (~20 s; the rest is decoding+the stream again on every page). Not bounded here: the names and+keywords pdfminer interns, in process-wide tables+(``psparser.PSLiteralTable`` and ``PSKeywordTable``) that it never+clears and compares against by identity, so the releaser cannot drop+them -- a 2 MB PDF of a million distinct names or keywords adds+~175 MB to the process for good, and each upload of new ones adds+more; what+one font build allocates before it returns (a /W range, a bfrange or+a crafted parser input expands within that build), and what the fonts+pdfminer still holds (cached ones, a form's while it runs) keep until+the release after the page.Each ``after_page()`` scans the document's object cache, so it coststime in proportion to that cache: well under a second over a whole500-page honest document, ~0.16 s per page for a cache of a millionobjects, which takes a page tree of about a million pages (itself an-O(all pages) cost paid before the walk). That time is spent between-the CPU budget's checks and counts against it.+O(all pages) cost paid before the walk). A pdfminer release also runs a+full garbage collection (pdfminer's parsers leave what they built in+reference cycles), which costs time in proportion to the objects the+whole process holds: ~0.06 s per million, and so does each collection+the font counting runs between releases; the spacing above keeps all+of them to about a tenth of the walking thread's CPU time (apart from+those a growth of four times the threshold forces, and those the+threshold's worth of garbage only a collection frees forces, which+cost builds of that size first). On the honest+documents measured (eight, up to 500 pages) only the one release above+ran. That time is spent in the walking thread, between the CPU budget's checks, and counts+against it.-These are library internals, pinned to pdfplumber 0.11.10 /-pdfminer.six 20260107 and pypdf 6.19.0. Every access is guarded: if an-attribute is missing or anything raises, the releaser stops releasing-and extraction carries on unchanged. The canary tests in+These are library internals, written against the pdfplumber,+pdfminer.six and pypdf versions ``pdm.lock`` pins. Every access is+guarded: if an attribute is missing or anything raises, the releaser+stops releasing for that document and extraction carries on+unchanged (except the lookups of the streams a font build read, which+the document's data can make fail: one that fails counts nothing, as+the build could not have read that stream either; after a build that+raised they are looked up in the object cache only, which parses+nothing and follows no reference cycle), and the pdfminer+releaser removes its ``get_font`` wrapper and lets go of the font+tables it holds. The first time that happens to+each library's releaser in+a process (so at most two warnings) it is logged at WARNING, since the+memory bound is then off; later occurrences are logged at DEBUG.+pdfminer's object-stream cache entries are read as the ``(objects,+count)`` pairs it stores, taken in insertion order; an entry of another+shape is counted whole if it is a container (an over-count, which+brings the release sooner), and otherwise switches the releaser off. The canary tests in``tests/research_library/services/test_pdf_extraction_bounds.py``(``TestLibraryInternalsTheReleaseReliesOn``) fail if a library upgraderemoves what the releasers rely on, so an upgrade cannot undo them@@ -53,6 +219,12 @@ silently.from __future__ import annotations+import gc+import os+import sys+import threading+import time+import weakreffrom itertools import islicefrom typing import Any@@ -63,36 +235,404 @@ from . import pdf_extraction_limits# Estimated bytes a parsed object element (an array item, a dictionary# entry) keeps alive. Measured on a 500,000-entry /Widths array: ~124# bytes per entry in pypdf (a boxed number object plus its list slot),-# and in pdfminer the cached array plus the font's own widths table.+# and in pdfminer the cached array plus one font's own widths table+# together, which are now each counted (an over-count, which brings the+# release sooner)._BYTES_PER_PARSED_ELEMENT = 128+# Bytes a pdfminer parser that a font build leaves in a reference cycle+# can keep per byte it was fed: the tokens a ToUnicode CMap or a Type 1+# font header leaves on the parser's stack. Measured on pdfminer.six+# 20260107 (CMapParser and Type1FontHeaderParser alike): ~52 for "1 1 1",+# ~84 for "<<<<", ~168 for "[[[[" or "{{{{", 0 for whitespace. This is+# the worst case, so it over-counts most inputs (all of a whitespace+# one); what that over-count can cost is bounded by the spacing of the+# collections it asks for (_COLLECT_SPACING).+_PARSER_BYTES_PER_INPUT_BYTE = 192++# A collection that the threshold asks for in the middle of a page waits+# until the walking thread has spent this many times the last+# collection's duration since it ended, so that those collections take+# at most about a tenth of the thread's CPU time (a full collection+# costs ~0.06 s per million objects the process holds, whatever it+# frees) -- unless the process's resident memory has grown by+# _FORCED_GROWTH times the threshold since the last one.+_COLLECT_SPACING = 9+_FORCED_GROWTH = 4++# How often, in seconds of the walking thread's CPU time, a font build+# reads the process's resident memory (~10 us a read).+_RSS_CHECK_INTERVAL = 0.01++_STRINGS = (str, bytes, bytearray)++_rss_unavailable = False+++def _resident_bytes() -> int | None:+ """The process's resident memory in bytes, read from+ ``/proc/self/statm``; None where there is no such file (not Linux)+ or it cannot be read."""+ global _rss_unavailable+ if _rss_unavailable:+ return None+ try:+ with open("/proc/self/statm", "rb") as statm:+ pages = int(statm.read().split()[1])+ return pages * os.sysconf("SC_PAGE_SIZE")+ except (FileNotFoundError, AttributeError, ValueError, IndexError):+ # Not Linux (or not a statm we know): measure nothing from now on.+ _rss_unavailable = True+ except OSError:+ pass+ return None+++def _measured(previous: int | None) -> int | None:+ """A new resident-memory baseline: the memory now, or *previous* if+ it cannot be read this time (a transient failure must not leave the+ baseline unknown, which would switch the measured trigger off)."""+ now = _resident_bytes()+ return previous if now is None else now+++def _font_tables(font: object) -> list[object]:+ """The values a pdfminer font build stored that ``_font_built()``+ counts: every dictionary, list, tuple and string (``str`` or+ ``bytes``, by its size) held in an attribute of the font or of an+ object held in one (its ``unicode_map``, its ``cmap``), streams+ aside (their decoded bytes count where they are cached).++ That is the ``/ToUnicode`` map (``cid2unichr``) and the values its+ ``def``s set (``attrs``), the encoding's code-to-unicode table+ (``cid2unicode``, a copy per font when /Differences or the embedded+ font program gives one), the ``widths`` (simple and CID fonts alike:+ each build makes its own, with every array a width points at copied,+ even when many fonts share one /Widths array), a CID font's+ ``disps``, the descriptor, the bounding box, the font matrix, and+ strings such as a CID font's ``cidcoding``, which each build makes+ by joining its /CIDSystemInfo /Registry and /Ordering, however long+ those strings are and however many fonts share them. Every element+ nested in a container counts like a parsed element (a /ToUnicode+ map measured ~1.05x the estimate), and every string nested in one+ by its size as well. A value several fonts share (pdfminer's+ built-in encodings and metrics, a predefined CMap, a font+ descriptor) is counted once, and not again while something else+ holds it (``PdfplumberWalkReleaser._let_go_of_tables()``).+ """+ from pdfminer.pdftypes import PDFStream++ counted = _CONTAINERS + _STRINGS+ found = []+ held = []+ for value in getattr(font, "__dict__", {}).values():+ if isinstance(value, counted):+ found.append(value)+ elif hasattr(value, "__dict__") and not isinstance(+ value, (PDFStream, type)+ ):+ held.append(value)+ for owner in held:+ found.extend(v for v in vars(owner).values() if isinstance(v, counted))+ return found+++def _cached_value(value: object) -> object:+ """*value*, or, if it is a reference, what it resolves to in its+ document's object cache, without parsing anything: a reference that+ is not cached, or that leads back to one already followed (``8 0+ obj 8 0 R``), resolves to None."""+ from pdfminer.pdftypes import PDFObjRef++ followed = set()+ while isinstance(value, PDFObjRef):+ if value.objid in followed:+ return None+ followed.add(value.objid)+ cache = getattr(value.doc, "_cached_objs", None)+ entry = cache.get(value.objid) if isinstance(cache, dict) else None+ if not isinstance(entry, tuple) or not entry:+ return None+ value = entry[0]+ return value+++def _parser_input_bytes(+ spec: object, built: bool = True, inputs: list | None = None+) -> int:+ """Bytes the build of a font from *spec* fed to a pdfminer parser+ that it leaves in a reference cycle, under the conditions pdfminer+ parses them (``PDFResourceManager.get_font()`` picks the class from+ ``/Subtype``):++ - the decoded ``/ToUnicode`` CMap (``CMapParser``): resolved by a+ simple font (Type 1, TrueType, Type 3, or an unknown subtype); by a+ CID font only if it is a stream object itself rather than a+ reference (a Type 0 font hands its descendant the resolved one); a+ Type 0 font parses nothing itself, its descendant's build does;+ - for a Type 1 or TrueType font without ``/Encoding`` whose+ ``/BaseFont`` is not one of the standard fonts pdfminer has+ built-in metrics for (whose descriptor replaces the spec's), the+ copy of its decoded ``/FontFile``'s first ``/Length1`` bytes that+ ``Type1FontHeaderParser`` reads: exactly the length of that slice.++ A stream counts only if it is decoded (the lookup decodes nothing),+ which it is after a build that parsed it; a lookup that fails counts+ nothing, as the build could not have read that stream either. After+ a build that returned (*built*), the references followed are ones+ the build resolved itself; after one that raised, it may not have+ got that far, so they are looked up in the object cache only+ (``_cached_value()``): what the build resolved is there, and nothing+ is parsed, nor followed round a cycle.++ With *inputs*, each stream's decoded bytes the count includes are+ appended to it with the number of them fed, ``(data, fed)``: the+ parser holds *data* itself when it was fed all of it (pdfminer+ wraps it in a ``BytesIO``, which shares it), and a fresh copy of+ the first *fed* bytes otherwise."""+ from pdfminer.pdffont import FontMetricsDB+ from pdfminer.pdftypes import PDFStream, resolve1+ from pdfminer.psparser import PSLiteral, literal_name++ if not isinstance(spec, dict):+ return 0+ resolve = resolve1 if built else _cached_value++ def decoded(stream: object) -> bytes | None:+ if isinstance(stream, PDFStream) and stream.data is not None:+ return stream.data+ return None++ def resolved(holder: dict, key: str) -> object:+ try:+ return resolve(holder.get(key))+ except Exception as exc:+ logger.debug("font {} lookup failed ({})", key, type(exc).__name__)+ return None++ subtype = spec.get("Subtype")+ subtype = (+ literal_name(subtype)+ if isinstance(subtype, PSLiteral)+ else ("Type1" if subtype is None else None)+ )+ if subtype == "Type0":+ return 0+ if subtype in ("CIDFontType0", "CIDFontType2"):+ data = decoded(spec.get("ToUnicode"))+ if data is None:+ return 0+ if inputs is not None:+ inputs.append((data, len(data)))+ return len(data)+ data = decoded(resolved(spec, "ToUnicode"))+ total = len(data) if data is not None else 0+ if data is not None and inputs is not None:+ inputs.append((data, total))+ if subtype == "Type3" or "Encoding" in spec:+ return total+ basefont = spec.get("BaseFont")+ if isinstance(basefont, PSLiteral):+ try:+ FontMetricsDB.get_metrics(literal_name(basefont))+ return total # built-in metrics: the spec's descriptor unused+ except KeyError:+ pass+ except Exception:+ return total # the build raised before reading the font file+ descriptor = resolved(spec, "FontDescriptor")+ if not isinstance(descriptor, dict) or "FontFile" not in descriptor:+ return total+ font_file = resolved(descriptor, "FontFile")+ data = decoded(font_file)+ if data is None or "Length1" not in font_file.attrs:+ return total+ # pdfminer's int_value(): anything but an int is 0.+ length1 = resolved(font_file.attrs, "Length1")+ if not isinstance(length1, int):+ return total+ # The parser reads data[:length1], whatever the sign of /Length1.+ header = len(range(len(data))[:length1])+ if header and inputs is not None:+ inputs.append((data, header))+ return total + header+++# Libraries whose releaser has already warned that it disabled itself in+# this process; later disables are logged at DEBUG only.+_warned_disabled: set[str] = set()+_warned_lock = threading.Lock()+++def _log_disabled(library: str, exc: BaseException | None) -> None:+ """Log a releaser disabling itself: once per library at WARNING."""+ reason = type(exc).__name__ if exc is not None else "unknown"+ with _warned_lock:+ first = library not in _warned_disabled+ _warned_disabled.add(library)+ if first:+ logger.warning(+ "{} cache release disabled ({}): memory held between PDF pages "+ "is no longer bounded. The library internals it relies on may "+ "have changed; run tests/research_library/services/"+ "test_pdf_extraction_bounds.py. Further occurrences are logged "+ "at DEBUG.",+ library,+ reason,+ )+ else:+ logger.debug(+ "{} cache release disabled for this document ({})",+ library,+ reason,+ )++def _limit() -> int:return pdf_extraction_limits.MAX_PDF_RETAINED_DECODED_BYTES-def _count_elements(obj: object, skip: tuple[type, ...]) -> int:- """Number of items in the lists and dicts nested in *obj*.+_CONTAINERS = (dict, list, tuple)+++def _sole_holder_refcount() -> int:+ """What ``sys.getrefcount()`` reports, read the way ``_count_elements()``+ and ``_let_go_of_tables()`` read it (on a loop variable), for a value+ that one container holds and nothing else (3 on CPython 3.12, 2 on+ 3.14, whose loops borrow the reference); a value something else+ holds too reads more."""+ counts = [sys.getrefcount(value) for value in [[]]]+ return counts[0]+++_SOLE_HOLDER = _sole_holder_refcount()++# Passes _let_go_of_tables() makes at most (see there).+_LET_GO_PASSES = 4- Objects of the *skip* types (streams, accounted by their decoded- bytes instead) are not descended into. Parsed PDF objects are trees,- so the walk is linear in their size -- no more than parsing them cost.++def _count_elements(+ obj: object, skip: tuple[type, ...], shared: list | None = None+) -> int:+ """Number of items in the lists and dicts nested in *obj*, plus, for+ every string (``str`` or ``bytes``) among them, among the dicts'+ keys, or *obj* itself, its size in units of+ ``_BYTES_PER_PARSED_ELEMENT`` (none for a short one, which its item+ already accounts for). Keys count because pdfminer turns a name that+ is not UTF-8 into the text of its repr, about four characters a+ byte.++ Objects of the *skip* types nested in *obj* (streams, whose data is+ accounted by its decoded bytes, and whose dictionary is counted+ where the stream is cached) are not descended into; *obj* itself is+ counted whatever its type, so a pypdf stream, which is its own+ dictionary, counts its entries (a pdfminer stream's dictionary is+ its ``attrs``). A dictionary is read through ``dict``'s own methods,+ which a subclass cannot override to resolve references. Parsed PDF+ objects are trees, so the walk is linear in their size -- no more+ than parsing them cost.++ With *shared*, a nested container that something besides its parent+ also holds is appended to *shared* instead of descended into, so+ that the caller counts it once, however many tables hold it: a font+ build can store a new container that holds parts of a parsed object+ (a Type 3 font's ``matrix`` is a new tuple of its /FontMatrix+ items), and walking those parts again on every build would cost more+ than the build did."""count = 0stack = [obj]while stack:item = stack.pop()- if isinstance(item, skip):+ if item is not obj and isinstance(item, skip):+ continue+ if isinstance(item, _STRINGS):+ count += sys.getsizeof(item) // _BYTES_PER_PARSED_ELEMENTcontinueif isinstance(item, dict):- count += len(item)- stack.extend(item.values())+ items: Any = dict.values(item)+ keys = dict.keys(item)+ if any(issubclass(t, _STRINGS) for t in set(map(type, keys))):+ count += sum(+ sys.getsizeof(key) // _BYTES_PER_PARSED_ELEMENT+ for key in keys+ if isinstance(key, _STRINGS)+ )elif isinstance(item, (list, tuple)):- count += len(item)- stack.extend(item)+ items = item+ else:+ continue+ count += len(item)+ # A flat table (a font's widths, a /ToUnicode map) is told apart+ # from its item types alone, without a Python-level step per item.+ types = set(map(type, items))+ if any(issubclass(t, _CONTAINERS) for t in types):+ if shared is None:+ stack.extend(items)+ continue+ for value in items:+ if (+ isinstance(value, _CONTAINERS)+ and sys.getrefcount(value) > _SOLE_HOLDER+ ):+ shared.append(value)+ else:+ stack.append(value)+ elif any(issubclass(t, _STRINGS) for t in types):+ count += sum(+ sys.getsizeof(value) // _BYTES_PER_PARSED_ELEMENT+ for value in items+ if isinstance(value, _STRINGS)+ )return count+def _is_objstm_entry(value: object) -> bool:+ """Whether *value* has the shape pdfminer gives a ``_parsed_objs``+ entry: ``(objects, count)``, a list of the stream's header numbers+ and objects plus the number of objects."""+ return (+ isinstance(value, tuple)+ and len(value) == 2+ and isinstance(value[0], list)+ and isinstance(value[1], int)+ )+++def _require_container(value: object) -> None:+ """Raise unless ``_count_elements`` can count *value*: an entry with+ nothing to count it by stops the releaser (``_disable()`` warns)+ rather than going uncounted."""+ if not isinstance(value, (dict, list, tuple)):+ raise TypeError("unexpected pdfminer object stream cache entry")+++class _Pending:+ """What a pdfminer walk has left for the cycle collector: whether a+ collection is due (asked for, and deferred by the spacing), and an+ estimate, in bytes, of the garbage that only a collection frees,+ released since the last one (``PdfplumberWalkReleaser._font_parsed()``).+ Kept apart from the releaser so that the walk-end collection+ (``_collect_at_walk_end()``) can read it once the releaser is gone."""++ __slots__ = ("due", "garbage")++ def __init__(self) -> None:+ self.due = False+ self.garbage = 0+++def _collect_at_walk_end(pending: _Pending) -> None:+ """Run the collection a walk deferred, if what it would free is+ garbage only a collection frees, so that the walk does not end+ holding it. Honest documents never ask for one."""+ if pending.due and pending.garbage > 0:+ pending.due = False+ pending.garbage = 0+ gc.collect()++class PdfplumberWalkReleaser:"""Releases pdfminer's caches while pdfplumber walks a document."""@@ -101,7 +641,425 @@ class PdfplumberWalkReleaser:self._enabled = Trueself._pre_walk_keys: set | None = Noneself._page_mark: int | None = None+ # Set by before_page() alongside _page_mark (keep it there when+ # merging other before_page() changes): without it after_page()+ # counts every object stream parsed before the page, including+ # the pre-walk ones, against the threshold.+ self._objstm_mark: int | None = Noneself._parsed_elements = 0+ # Fonts counted since the last release, by id, held weakly: a+ # font handed out again (from pdfminer's cache, or as a Type0+ # font's descendant) is not counted twice, and holding the fonts+ # would keep ones pdfminer itself lets go of -- every unknown+ # font name in a Tf builds a new font that nothing caches.+ self._fonts_seen: weakref.WeakValueDictionary[int, Any] = (+ weakref.WeakValueDictionary()+ )+ # The font tables and long strings counted (by id, and held so+ # that no id is reused for a new one while it is here), so one+ # that several fonts share counts once; and the entries of those+ # added since the tables were last let go of (at least one per+ # table, so that empty tables cannot pile up). Holding them+ # keeps values pdfminer may already have let go of (an inline+ # CID font's widths die with the font), so once those entries+ # reach the threshold, and after every collection,+ # _let_go_of_tables() lets go of the tables nothing else holds;+ # the rest (a descriptor or a /FontMatrix item that a parsed+ # object holds, pdfminer's built-in tables) cost nothing to hold+ # and are kept, so that they are never walked again.+ self._table_ids: set[int] = set()+ self._tables: list[object] = []+ self._held_entries = 0+ # The entries of each table added since the tables were last+ # let go of, by id: one kept then (something else still held+ # it, such as the font being built) weighs again until the next+ # time, so that it is let go of soon after that holder is.+ self._new_tables: dict[int, int] = {}+ # Decoded bytes the font builds since the last release fed to+ # parsers left in reference cycles (_parser_input_bytes()),+ # counted against the threshold; and since the last collection+ # of those cycles.+ self._font_bytes = 0+ self._uncollected_bytes = 0+ # The measured side (_resident_bytes(); None where it cannot be+ # read): the process's resident memory after the last release+ # and after the last collection (or when the walk began), and+ # when (in the thread's CPU time) the last collection ended and+ # how long it took, which space the next one (_may_collect()).+ self._release_rss: int | None = None+ self._collect_rss: int | None = None+ self._collect_end = 0.0+ self._collect_cost = 0.0+ # Whether a collection is due, and the garbage only a collection+ # frees, released since the last one: the decoded bytes fed to+ # parsers (which those parsers keep in reference cycles once the+ # build returns) and the tables of the fonts built with them+ # (their /ToUnicode map, which the parser's cycle holds) once+ # those fonts are let go of -- an inline font's when its build+ # returns, a cached font's at the next release, when the font+ # cache is cleared. A collection runs at once, whatever the+ # spacing, when that garbage reaches the threshold+ # (_font_parsed(), after_page()). The tables of a build not+ # classified yet (a Type0 font's descendant, built inside it)+ # and of the cached fonts built since the last release:+ self._pending = _Pending()+ self._unclassified = 0+ self._cached_garbage = 0+ # The decoded streams fed whole to parsers since the last+ # release (their sizes, by the id of the bytes, which the stream+ # holds until the release rewinds it): garbage that only a+ # collection frees from then on.+ self._fed_streams: dict[int, int] = {}+ # A deferred collection still pending when the walk ends runs+ # then, when the releaser goes (or on close()).+ self._walk_end = weakref.finalize(+ self, _collect_at_walk_end, self._pending+ )+ self._walk_end.atexit = False+ # A release whose collection was deferred: the collection that+ # follows sets _release_rss.+ self._release_collect_due = False+ self._rss_checked = 0.0+ self._rsrcmgr: Any = None+ # ids of the objects counted from object-stream lists since the+ # last release. Every one stays reachable from _parsed_objs until+ # that release clears the set, so no id is reused for a different+ # object while it is here.+ self._counted: set[int] = set()++ def _count_fonts(self) -> None:+ """Wrap this document's ``rsrcmgr.get_font`` to count every font+ it returns, where it is built.++ pdfminer caches only fonts that are objects of their own+ (``_cached_fonts``, keyed by object number); a font dictionary+ written inline in a ``/Resources /Font`` dictionary -- a page's,+ or a Form XObject's, initialised on every ``Do`` -- is built again+ each time and cached nowhere, so the cache cannot show what a+ page built. Every font goes through ``get_font()``+ (``init_resources()``, an unknown font name in ``Tf``, and a+ Type0 font's descendant), which pdfminer calls on the instance.+ The wrapper is an instance attribute, so only this document's+ resource manager is affected, and it holds the manager and the+ releaser weakly: it adds no reference cycle, and once the+ releaser is gone or disabled it only passes calls through.+ """+ from pdfminer.pdfinterp import PDFResourceManager++ rsrcmgr = self._pdf.rsrcmgr+ if not isinstance(rsrcmgr, PDFResourceManager) or "get_font" in vars(+ rsrcmgr+ ):+ raise TypeError("unexpected pdfminer resource manager")+ cached = rsrcmgr._cached_fonts+ if not isinstance(cached, dict):+ raise TypeError("unexpected pdfminer font cache")+ build = type(rsrcmgr).get_font+ manager = weakref.ref(rsrcmgr)+ releaser = weakref.ref(self)+ # How many get_font() calls are running: a Type0 font builds its+ # descendant with a nested one, which is not cached, but lives+ # as long as the Type0 font does.+ depth = [0]++ def get_font(objid: object, spec: Any) -> Any:+ depth[0] += 1+ try:+ font = build(manager(), objid, spec)+ except BaseException:+ # A build that fails part-way may have parsed its+ # /ToUnicode already.+ owner = releaser()+ if owner is not None:+ owner._font_parsed(spec, built=False, outer=depth[0] == 1)+ raise+ finally:+ depth[0] -= 1+ owner = releaser()+ if owner is not None:+ fonts = getattr(manager(), "_cached_fonts", None)+ owner._font_built(+ font,+ spec,+ outer=depth[0] == 0,+ cached=bool(objid)+ and isinstance(fonts, dict)+ and fonts.get(objid) is font,+ )+ return font++ # Fonts cached before the walk are not its cost.+ for font in cached.values():+ self._fonts_seen[id(font)] = font+ rsrcmgr.get_font = get_font+ self._rsrcmgr = rsrcmgr++ def _font_built(+ self,+ font: object,+ spec: object,+ outer: bool = True,+ cached: bool = False,+ ) -> None:+ """Count a font ``get_font()`` returned: one element, the+ elements of its tables not counted yet, and the bytes its build+ fed to parsers (``_font_parsed()``). A font handed out again+ (from the cache, or a Type0 font's descendant) was not built+ again. A table, or a container nested in one, that something+ else holds too is counted once, as a table of its own, and kept+ while that holder keeps it (``_let_go_of_tables()``): a build+ stores some parts of the parsed font as they are (the+ descriptor, a CID font's /CIDSystemInfo, the items of a Type 3+ font's /FontMatrix), and an inline font in a form is built again+ on every ``Do``, so walking them again would cost more than the+ build (a 600,000-entry descriptor took ~0.9 s a ``Do``). *outer*+ is False for a build nested in another (a Type0 font's+ descendant), and *cached* tells whether pdfminer cached the font+ (``_font_parsed()``). Never raises (it runs inside pdfminer's+ page interpretation)."""+ if not self._enabled:+ return+ try:+ from pdfminer.pdftypes import PDFStream++ if self._fonts_seen.get(id(font)) is font:+ if outer and self._unclassified:+ self._font_parsed(None, outer=True, cached=cached)+ return+ self._fonts_seen[id(font)] = font+ self._parsed_elements += 1+ built = 0+ work = _font_tables(font)+ while work:+ table = work.pop()+ if id(table) in self._table_ids:+ continue+ shared: list = []+ entries = _count_elements(table, (PDFStream,), shared)+ if isinstance(table, _STRINGS) and not entries:+ continue # short: the font's own element covers it+ self._table_ids.add(id(table))+ self._tables.append(table)+ self._held_entries += max(1, entries)+ self._new_tables[id(table)] = max(1, entries)+ self._parsed_elements += entries+ built += entries+ work.extend(shared)+ let_go = self._held_entries * _BYTES_PER_PARSED_ELEMENT >= _limit()+ except Exception as exc:+ self._disable(exc)+ return+ # What the fonts pdfminer has let go of (an inline font built on+ # every Do of a form) holds in reference cycles is now free to+ # collect, in the middle of the page; the collection lets go of+ # the tables that leaves only the releaser holding. If the+ # spacing defers it, they are let go of here all the same.+ collected = self._collect_end+ self._font_parsed(+ spec, collect=let_go, entries=built, outer=outer, cached=cached+ )+ if let_go and self._enabled and self._collect_end == collected:+ try:+ self._let_go_of_tables()+ except Exception as exc:+ self._disable(exc)++ def _let_go_of_tables(self) -> None:+ """Let go of the font tables held that nothing else holds (the+ ones pdfminer has let go of), and keep the others: holding them+ costs nothing, their ids stay theirs, and so they are not+ counted, nor walked, again. Called once the entries of the+ tables added since the last call reach the threshold's worth,+ after every collection (which frees the reference cycles that+ hold the tables of fonts pdfminer dropped) and on a release."""+ tables, self._tables = self._tables, []+ # A container only the list holds, read the way the loop below+ # reads the tables: if it reads more (an interpreter whose+ # references differ from the calibration), the counts cannot be+ # trusted, and every table is let go of -- counted again if seen+ # again, an over-count -- rather than kept while nothing holds it.+ probe = [[]]+ trusted = True+ for index in range(len(probe)):+ table = probe[index]+ trusted = sys.getrefcount(table) <= _SOLE_HOLDER+ table = probe = None+ if not trusted:+ tables = []+ # Each one let go of at once, so that a table held only by+ # another one (a nested container counted as a table of its own)+ # goes with it; one counted before its holder goes in the next+ # pass (pdfminer's builds nest them a level or two deep).+ kept: list = []+ for _ in range(_LET_GO_PASSES):+ kept = []+ for index in range(len(tables)):+ table = tables[index]+ if sys.getrefcount(table) > _SOLE_HOLDER:+ kept.append(table)+ else:+ tables[index] = None+ table = None+ if len(kept) == len(tables):+ break+ tables = kept+ self._tables = kept+ self._table_ids = {id(table) for table in kept}+ # A table kept for the first time weighs once more: what still+ # held it may be about to let go of it (the font being built, a+ # cycle not collected yet). One kept again weighs nothing.+ new, self._new_tables = self._new_tables, {}+ self._held_entries = sum(new.get(id(table), 0) for table in kept)++ def _font_parsed(+ self,+ spec: object,+ collect: bool = False,+ built: bool = True,+ entries: int = 0,+ outer: bool = True,+ cached: bool = False,+ ) -> None:+ """Count the bytes a font build from *spec* fed to parsers that+ pdfminer leaves in reference cycles, and collect those cycles+ once what they can hold reaches the threshold (or when+ *collect*), or once the process's resident memory has grown by+ the threshold since the last collection -- spaced by+ ``_may_collect()`` either way.++ The parser and what it was fed are garbage as soon as the build+ returns, but only the cycle collector frees them, and they can+ create too few tracked objects for it to run: a Type 1 font+ without /Encoding parses a fresh copy of its /FontFile's first+ /Length1 bytes, and three such fonts a page sharing a 20 MB+ /FontFile of spaces grew ~57 MB a page; the tokens a crafted+ /ToUnicode leaves on its parser's stack hold up to+ ``_PARSER_BYTES_PER_INPUT_BYTE`` times its size. Collecting here,+ not after the page, also bounds a page that builds many such+ fonts. *built* is False after a build that raised+ (``_parser_input_bytes()`` then parses nothing).++ Those collections are spaced (``_may_collect()``), because the+ factor is the worst case, except once the garbage that only a+ collection frees, released since the last one, reaches the+ threshold: what the parsers were fed, which each holds in its+ cycle -- a fresh copy (a /FontFile header) at once, a stream's+ own decoded bytes (which the stream holds too, and which several+ builds can share) once each, when the release rewinds the+ stream -- and the tables (*entries*, counted by+ ``_font_built()``) of a font whose build fed one, whose+ /ToUnicode map its parser's cycle holds, once the font is let go+ of: an inline font's (not *cached*) as soon as its outermost+ build (*outer*) returns, a cached font's at the next release.+ That collection runs at once: the garbage it frees cost+ builds of its size, and deferring it held what it frees for as+ long as a collection of the whole process's heap took, nine+ times over (40 pages of five fonts sharing a 65,536-entry+ /ToUnicode map, with 8 million objects held, peaked ~400 MB+ above the start). Never raises."""+ if not self._enabled:+ return+ try:+ pending = self._pending+ inputs: list = []+ fed = (+ _parser_input_bytes(spec, built, inputs)+ if spec is not None+ else 0+ )+ self._font_bytes += fed+ self._uncollected_bytes += fed+ for data, count in inputs:+ if count < len(data):+ # A fresh copy (a /FontFile header): only the+ # parser's cycle holds it.+ pending.garbage += count+ else:+ # The stream's own decoded bytes: the parser's cycle+ # holds them once the release rewinds the stream.+ self._fed_streams[id(data)] = count+ del inputs+ if fed:+ self._unclassified += entries * _BYTES_PER_PARSED_ELEMENT+ if outer:+ if cached:+ self._cached_garbage += self._unclassified+ else:+ pending.garbage += self._unclassified+ self._unclassified = 0+ if pending.garbage >= _limit():+ self._collect()+ return+ if (+ collect+ or self._uncollected_bytes * _PARSER_BYTES_PER_INPUT_BYTE+ >= _limit()+ ):+ pending.due = True+ now = time.thread_time()+ if not pending.due:+ # Reading the resident memory costs ~10 us: not on every+ # build of a page that builds thousands of fonts.+ if now - self._rss_checked < _RSS_CHECK_INTERVAL:+ return+ self._rss_checked = now+ if self._collect_rss is None: # not read yet: from now on+ self._collect_rss = _resident_bytes()+ grown = self._grown(self._collect_rss)+ if (pending.due or grown >= _limit()) and self._may_collect(+ now, grown+ ):+ self._collect()+ except Exception as exc:+ self._disable(exc)++ def _grown(self, baseline: int | None) -> int:+ """How far the process's resident memory is above *baseline*+ (0 when either is unknown)."""+ if baseline is None:+ return 0+ now = _resident_bytes()+ return 0 if now is None else now - baseline++ def _may_collect(self, now: float, grown: int) -> bool:+ """Whether a collection the threshold asks for may run at *now*+ (the thread's CPU time): once the thread has spent+ ``_COLLECT_SPACING`` times the last collection's duration since+ it ended, or at once if the resident memory has grown by+ ``_FORCED_GROWTH`` times the threshold (*grown*). A collection+ costs time in proportion to every object the process holds,+ whatever it frees, and what asks for it can be cheap: unspaced,+ a page of 2,000 ``Do``s of a form with one inline font took+ ~191 s of CPU instead of ~4.7 s, with a million objects held."""+ if grown >= _FORCED_GROWTH * _limit():+ return True+ return now - self._collect_end >= _COLLECT_SPACING * self._collect_cost++ def _collect(self) -> None:+ """Run a full collection, timing it and measuring the resident+ memory it leaves (the measure taken before stands if that read+ fails), then let go of the font tables it left only the+ releaser holding."""+ start = time.thread_time()+ gc.collect()+ self._collect_end = time.thread_time()+ self._collect_cost = self._collect_end - start+ self._pending.due = False+ self._pending.garbage = 0+ self._uncollected_bytes = 0+ self._collect_rss = _measured(self._collect_rss)+ if self._release_collect_due:+ self._release_collect_due = False+ self._release_rss = self._collect_rss+ self._let_go_of_tables()++ def _collect_if_due(self, now: float) -> None:+ """Run a collection asked for earlier (by a release that+ deferred it) once ``_may_collect()`` allows it."""+ if self._pending.due and self._may_collect(+ now, self._grown(self._collect_rss)+ ):+ self._collect()def _parts(self) -> tuple[Any, dict, dict, dict]:doc = self._pdf.doc@@ -122,16 +1080,76 @@ class PdfplumberWalkReleaser:if not self._enabled:returntry:- _doc, cache, _parsed, _fonts = self._parts()+ _doc, cache, parsed_objstms, _fonts = self._parts()if self._pre_walk_keys is None:# What is cached here was not added by the walk and is# never dropped. In a lazy walk the page-tree nodes are# parsed as the walk reaches them, so they are counted# and released like any other object the walk added.self._pre_walk_keys = set(cache)+ self._count_fonts()+ self._release_rss = self._collect_rss = _resident_bytes()+ self._collect_end = self._rss_checked = time.thread_time()self._page_mark = len(cache)- except Exception:- self._disable()+ # Required for after_page() to skip object streams parsed+ # before this page; see __init__.+ self._objstm_mark = len(parsed_objstms)+ except Exception as exc:+ self._disable(exc)++ def _estimate(self, cache: dict, parsed_objstms: dict) -> int:+ """Count what this page added to the caches and return what+ they hold since the last release, in bytes."""+ from pdfminer.pdftypes import PDFStream++ skip = (PDFStream,)+ # Object streams this page parsed (new keys are appended, so+ # they follow _objstm_mark in insertion order): pdfminer keeps+ # every object of such a stream, and its header numbers, in+ # one list apart from the object cache -- including objects+ # no page has resolved yet.+ for value in islice(+ parsed_objstms.values(), self._objstm_mark or 0, None+ ):+ if not _is_objstm_entry(value):+ _require_container(value)+ # Not the (objects, count) pair this was written+ # against: count all of it (an over-count, which+ # brings the release sooner).+ self._parsed_elements += 1 + _count_elements(value, skip)+ continue+ objs = value[0]+ self._parsed_elements += len(objs)+ for obj in objs:+ if isinstance(obj, (dict, list)):+ self._counted.add(id(obj))+ self._parsed_elements += _count_elements(obj, skip)+ # Objects the getobj() calls of this page appended to the+ # cache; each counts at least one element, so empty and scalar+ # objects are not free. An object resolved out of an object+ # stream is the one in that stream's list, already counted+ # there (on this page or an earlier one).+ for obj, _genno in islice(cache.values(), self._page_mark, None):+ self._parsed_elements += 1+ if isinstance(obj, PDFStream):+ # Its dictionary is parsed like any other (a Form+ # XObject's can hold any number of entries); its data+ # counts below, by its decoded size, and is not decoded+ # here.+ self._parsed_elements += _count_elements(obj.attrs, skip)+ elif id(obj) not in self._counted:+ self._parsed_elements += _count_elements(obj, skip)+ # Fonts were counted as get_font() returned them+ # (_count_fonts()).+ self._page_mark = None+ self._objstm_mark = None+ held = (+ self._parsed_elements * _BYTES_PER_PARSED_ELEMENT + self._font_bytes+ )+ for obj, _genno in list(cache.values()):+ if isinstance(obj, PDFStream) and obj.data is not None:+ held += len(obj.data)+ return helddef after_page(self) -> bool:"""Call once the page is done (after ``close()``). Returns True@@ -142,16 +1160,23 @@ class PdfplumberWalkReleaser:from pdfminer.pdftypes import PDFStreamdoc, cache, parsed_objstms, fonts = self._parts()- # Objects the getobj() calls of this page appended to the cache.- for obj, _genno in islice(cache.values(), self._page_mark, None):- self._parsed_elements += _count_elements(obj, (PDFStream,))- self._page_mark = None- held = self._parsed_elements * _BYTES_PER_PARSED_ELEMENT- for obj, _genno in list(cache.values()):- if isinstance(obj, PDFStream) and obj.data is not None:- held += len(obj.data)+ # In a method of its own so that none of the objects it+ # looks at stays referenced from this frame: the release+ # below lets go of the font tables nothing else holds.+ held = self._estimate(cache, parsed_objstms)+ now = time.thread_time()+ if self._release_rss is None: # not read yet: from now on+ self._release_rss = _resident_bytes()+ measured = Falseif held < _limit():- return False+ # What the estimate misses, the resident memory shows:+ # release once it has grown by the threshold since the+ # last release, spaced like the other collections.+ grown = self._grown(self._release_rss)+ if grown < _limit() or not self._may_collect(now, grown):+ self._collect_if_due(now)+ return False+ measured = True# Rewound in place rather than dropped: pages hold the streams# cached before the walk directly (PDFPage.contents), and a# finished page's content parser, which pdfminer leaves in a@@ -165,13 +1190,57 @@ class PdfplumberWalkReleaser:del cache[objid]# Objects parsed out of object streams are cached separately.parsed_objstms.clear()- # Fonts keep their widths and embedded font program (a- # TrueType font holds its decoded FontFile2); rebuilt on demand.+ # Fonts keep their tables (counted as built) and embedded font+ # program (a TrueType font holds its decoded FontFile2);+ # rebuilt on demand. The fonts pdfminer did not cache+ # (inline ones) are held only by what the finished pages+ # left in reference cycles, and their tables by _tables+ # until the collection below lets go of them.fonts.clear()+ self._fonts_seen.clear()+ self._held_entries = 0self._parsed_elements = 0+ self._font_bytes = 0+ self._uncollected_bytes = 0+ self._counted.clear()+ # The cached fonts are let go of: the tables of those built+ # with parsers are now garbage that only a collection frees.+ self._pending.garbage += self._cached_garbage + sum(+ self._fed_streams.values()+ )+ self._cached_garbage = 0+ self._fed_streams.clear()+ # Dropping the fonts is not enough to free their /ToUnicode+ # maps: the CMapParser that built each one keeps it, and the+ # decoded CMap bytes, in a reference cycle (its bound-method+ # state), which only the cycle collector frees, and parsing+ # them creates too few tracked objects to trigger it. Without+ # this, a walk that released every second page still grew+ # ~840 MB over 20 pages. The collection is spaced like the+ # others: a release the estimate asks for can be cheap (a+ # 64 MB stream of zeros that a font build decodes and hardly+ # parses), and a collection costs time in proportion to every+ # object the process holds -- unless what it frees, the+ # garbage only a collection frees, has reached the threshold+ # (_font_parsed()): then it runs at once. A deferred one runs+ # once the spacing allows (at a later font build or page),+ # or once that garbage reaches the threshold, or when the+ # walk ends, and what it would free is held until then.+ if (+ measured+ or self._pending.garbage >= _limit()+ or self._may_collect(now, self._grown(self._collect_rss))+ ):+ self._collect()+ self._release_rss = self._collect_rss+ else:+ self._let_go_of_tables()+ self._pending.due = True+ self._release_collect_due = True+ self._release_rss = _measured(self._release_rss)return True- except Exception:- self._disable()+ except Exception as exc:+ self._disable(exc)return False@staticmethod@@ -206,9 +1275,33 @@ class PdfplumberWalkReleaser:obj.rawdata = fresh.rawdataobj.data = None- def _disable(self) -> None:+ def close(self) -> None:+ """Call once the walk is done (optional: it also runs when the+ releaser is garbage). Runs a collection a release or a font build+ deferred, if what it would free is garbage only a collection+ frees, so that the walk does not end holding it; honest+ documents never defer one. Never raises."""+ try:+ self._walk_end()+ except Exception as exc:+ logger.debug("walk-end collection failed ({})", type(exc).__name__)++ def _disable(self, exc: BaseException | None = None) -> None:self._enabled = False- logger.debug("pdfminer cache release disabled for this document")+ # Stop counting fonts and let go of the tables held: with the+ # release off they would otherwise be kept for the rest of the+ # walk.+ self._tables = []+ self._table_ids = set()+ self._new_tables = {}+ rsrcmgr, self._rsrcmgr = self._rsrcmgr, None+ if rsrcmgr is not None:+ try:+ del rsrcmgr.get_font+ except Exception:+ # The wrapper then only passes calls through.+ logger.debug("pdfminer get_font wrapper left in place")+ _log_disabled("pdfminer", exc)class PypdfWalkReleaser:@@ -220,6 +1313,9 @@ class PypdfWalkReleaser:self._pre_walk_keys: set | None = Noneself._page_mark: int | None = Noneself._parsed_elements = 0+ # The process's resident memory after the last release (or when+ # the walk began); None where it cannot be read.+ self._release_rss: int | None = Nonedef _cache(self) -> dict:cache = self._reader.resolved_objects@@ -236,9 +1332,10 @@ class PypdfWalkReleaser:if self._pre_walk_keys is None:# The page tree was flattened to yield this page.self._pre_walk_keys = set(cache)+ self._release_rss = _resident_bytes()self._page_mark = len(cache)- except Exception:- self._disable()+ except Exception as exc:+ self._disable(exc)def after_page(self) -> bool:"""Call once the page is done. Returns True when a release ran.@@ -249,8 +1346,12 @@ class PypdfWalkReleaser:from pypdf.generic import EncodedStreamObjectcache = self._cache()+ # Each new object counts at least one element, so empty and+ # scalar objects are not free; a stream counts the entries of+ # its dictionary (it is one) like any other, and its data by+ # its decoded size below.for obj in islice(cache.values(), self._page_mark, None):- self._parsed_elements += _count_elements(+ self._parsed_elements += 1 + _count_elements(obj, (EncodedStreamObject,))self._page_mark = None@@ -262,8 +1363,18 @@ class PypdfWalkReleaser:if copy is not None:held += len(copy.get_data())decoded.append(obj)+ if self._release_rss is None: # not read yet: from now on+ self._release_rss = _resident_bytes()if held < _limit():- return False+ # Release too once the resident memory has grown by the+ # threshold since the last release.+ now = _resident_bytes()+ if (+ self._release_rss is None+ or now is None+ or now - self._release_rss < _limit()+ ):+ return False# EncodedStreamObject keeps its raw bytes and decodes them# again when decoded_self is None.for obj in decoded:@@ -273,11 +1384,12 @@ class PypdfWalkReleaser:if key not in pre_walk:del cache[key]self._parsed_elements = 0+ self._release_rss = _measured(self._release_rss)return True- except Exception:- self._disable()+ except Exception as exc:+ self._disable(exc)return False- def _disable(self) -> None:+ def _disable(self, exc: BaseException | None = None) -> None:self._enabled = False- logger.debug("pypdf cache release disabled for this document")+ _log_disabled("pypdf", exc)diff --git a/tests/research_library/services/test_pdf_extraction_bounds.py b/tests/research_library/services/test_pdf_extraction_bounds.pyindex cef9a00545..2af569a69e 100644--- a/tests/research_library/services/test_pdf_extraction_bounds.py+++ b/tests/research_library/services/test_pdf_extraction_bounds.py@@ -10,6 +10,7 @@ and cap the total extracted characters.from __future__ import annotations+from types import SimpleNamespacefrom unittest.mock import MagicMock, Mock, patchimport pytest@@ -992,7 +993,22 @@ class TestPdfplumberPagesAreClosed:## The tests below use the real pdfplumber/pdfminer and pypdf on PDFs built# here with the standard library, and inspect the libraries' caches-# directly: RSS is too noisy to assert on.+# directly: RSS is too noisy to assert on. The releasers also measure the+# process's resident memory; that is off here (_no_resident_memory), and+# the tests of it feed it values of their own.++[email protected](autouse=True)+def _no_resident_memory(monkeypatch):+ """Keep the releasers' resident-memory bound out of tests that pin+ which page a release falls on: the process's memory moves with+ whatever else the test run allocates."""+ from local_deep_research.utilities import pdf_stream_release++ monkeypatch.setattr(+ pdf_stream_release, "_resident_bytes", lambda: None, raising=False+ )+_SERVICE_MODULE = ("local_deep_research.research_library.services.download_service"@@ -1001,49 +1017,211 @@ _RETAINED_LIMIT = ("local_deep_research.utilities.pdf_extraction_limits.""MAX_PDF_RETAINED_DECODED_BYTES")+_SPACING = "local_deep_research.utilities.pdf_stream_release._COLLECT_SPACING"_PAD = 2 * 1024 * 1024 # decoded bytes of whitespace per content stream---def _crafted_pdf(pages, pad=0, *, late_refs=0, widths=0):+_TOUNICODE_LAST = 0x0FFF # last code of _crafted_pdf's shared /ToUnicode+++def _crafted_pdf(+ pages,+ pad=0,+ *,+ late_refs=0,+ widths=0,+ objstm=False,+ unicode_fonts=0,+ inline=False,+ form_uses=0,+ ops=b"",+ simple_fonts=0,+ shared_widths=0,+ font_file=0,+ length1=None,+ cid_fonts=0,+ registry=0,+ registry_inline=False,+ unicode_dest=b"0000",+ descriptor_extra=b"",+ matrix=None,+ form_extra=b"",+):"""A PDF whose page ``i`` shows ``Page i``.Each page has its own FlateDecode content stream: the text operatorplus *pad* spaces, which compress to almost nothing and yield nocharacters. ``late_refs`` appends that many extra pages that reuse- the content streams of the first pages. ``widths`` gives every page+ the content streams of the first pages, in turn. ``widths`` gives every pageits own non-standard font whose ``/Widths`` is a separate arrayobject of that many entries.++ ``objstm`` writes a PDF 1.5 file with a cross-reference stream and+ object streams instead: one holding the catalog, the page tree and+ the pages (parsed before a walk's first page) and, with ``widths``,+ one per page holding that page's font and its ``/Widths`` array+ (parsed while the page is extracted). Streams stay top-level objects.++ ``unicode_fonts`` gives every page that many fonts of its own (the+ first shows the text), all pointing at one shared compressed+ ``/ToUnicode`` CMap whose single ``bfrange`` maps codes 0 to+ ``_TOUNICODE_LAST`` to themselves. With ``inline`` those font+ dictionaries are written inline in the resource dictionary instead+ of as objects of their own, and with ``form_uses`` they are the+ resources of a page's own Form XObject (which draws nothing) rather+ than the page's: the page shows its text in Helvetica and invokes+ the form that many times. ``ops`` is appended to every page's+ text operator.++ ``simple_fonts`` gives every page that many non-standard Type 1+ fonts of its own (objects; the page shows its text in Helvetica):+ with ``shared_widths`` they all point at one ``/Widths`` array+ object of that many entries, and with ``font_file`` at one+ FlateDecode ``/FontFile`` of that many spaces, whose ``/Length1`` is+ *length1* (by default one less), and have no ``/Encoding``. With+ ``inline`` they are written inline, and with ``form_uses`` they are+ the form's resources, as above.++ ``cid_fonts`` gives every page that many CIDFontType2 fonts of its+ own (objects; the page shows its text in Helvetica) whose+ ``/CIDSystemInfo /Registry`` is one string object of *registry*+ bytes that they all share, or with ``registry_inline`` a string of+ that size written in each font's /CIDSystemInfo dictionary.++ ``unicode_dest`` is the hex destination of the /ToUnicode+ ``bfrange`` (each code maps to it with its last four bytes counting+ up). ``descriptor_extra`` is appended to the simple fonts' font+ descriptor, and with ``matrix`` they are Type 3 fonts with that+ /FontMatrix instead. ``form_extra`` is written into the Form+ XObject's dictionary (with ``form_uses``), whose content is then+ compressed."""+ import structimport zlibbodies = []+ # Object number -> key of the object stream it is written into.+ packed = {}- def add(body):+ def add(body, group=None):bodies.append(body)+ if objstm and group is not None:+ packed[len(bodies)] = groupreturn len(bodies)- catalog = add(None)- root = add(None)- helvetica = add(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")+ catalog = add(None, "pre-walk")+ root = add(None, "pre-walk")+ helvetica = add(+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", "pre-walk"+ )++ def font_resources(fonts):+ return b" ".join(+ b"/F%d %s" % (k, f if isinstance(f, bytes) else b"%d 0 R" % f)+ for k, f in enumerate(fonts, 1)+ )- def page(font, stream):+ def page(font, stream, xobject=b""):+ fonts = font if isinstance(font, list) else [font]return add(b"<< /Type /Page /Parent %d 0 R /MediaBox [0 0 612 792] "- b"/Resources << /Font << /F1 %d 0 R >> >> /Contents %d 0 R >>"- % (root, font, stream)+ b"/Resources << /Font << %s >> %s>> /Contents %d 0 R >>"+ % (root, font_resources(fonts), xobject, stream),+ "pre-walk",+ )++ if unicode_fonts:+ cmap = zlib.compress(+ b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap "+ b"1 begincodespacerange <0000> <FFFF> endcodespacerange "+ b"1 beginbfrange <0000> <%04X> <%s> endbfrange "+ b"endcmap end end" % (_TOUNICODE_LAST, unicode_dest)+ )+ to_unicode = add(+ b"<< /Length %d /Filter /FlateDecode >>\nstream\n" % len(cmap)+ + cmap+ + b"\nendstream"+ )+ simple_spec = b"<< /Type /Font /Subtype /Type1 /BaseFont /Crafted"+ descriptor = (+ b"<< /Type /FontDescriptor /FontName /Crafted /FontBBox [0 0 1 1]"+ )+ if shared_widths:+ simple_spec += b" /FirstChar 0 /Widths %d 0 R" % add(+ b"[" + b"500 " * shared_widths + b"]"+ )+ if font_file:+ program = zlib.compress(b" " * font_file)+ descriptor += b" /FontFile %d 0 R" % add(+ b"<< /Length %d /Length1 %d /Length2 0 /Length3 0"+ b" /Filter /FlateDecode >>\nstream\n"+ % (len(program), font_file - 1 if length1 is None else length1)+ + program+ + b"\nendstream"+ )+ simple_spec += b" /FontDescriptor " + descriptor + descriptor_extra+ simple_spec += b" >> >>"+ if matrix is not None:+ simple_spec = (+ b"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1 1] "+ b"/FontMatrix %s /CharProcs << >> /Encoding << /Differences [] "+ b">> /FirstChar 0 /LastChar 0 /Widths [0] /Resources << >> >>"+ % matrix+ )+ if cid_fonts:+ string = b"(" + b"R" * registry + b")"+ cid_spec = (+ b"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /CraftedCID "+ b"/CIDSystemInfo << /Registry %s /Ordering (Identity) "+ b"/Supplement 0 >> /FontDescriptor << /Type /FontDescriptor "+ b"/FontName /CraftedCID /FontBBox [0 0 1 1] >> /W [0 [500]] >>"+ % (string if registry_inline else b"%d 0 R" % add(string)))-kids, streams = [], []for i in range(pages):- font = helvetica- if widths:- array = add(b"[" + b"500 " * widths + b"]")+ font, xobject = helvetica, b""+ if simple_fonts:+ font = [helvetica] + [+ simple_spec if inline else add(simple_spec, i)+ for _ in range(simple_fonts)+ ]+ if cid_fonts:+ font = [helvetica] + [add(cid_spec, i) for _ in range(cid_fonts)]+ if unicode_fonts:+ spec = (+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica "+ b"/ToUnicode %d 0 R >>" % to_unicode+ )+ font = [+ spec if inline else add(spec, i) for _ in range(unicode_fonts)+ ]+ if form_uses:+ # With form_extra the form's content is compressed, so that+ # pypdf keeps it as an encoded stream.+ content = zlib.compress(b"q Q") if form_extra else b"q Q"+ form = add(+ b"<< /Type /XObject /Subtype /Form /BBox [0 0 612 792] %s"+ b"/Resources << /Font << %s >> >> /Length %d %s>>\nstream\n"+ % (+ form_extra,+ font_resources(font if isinstance(font, list) else [font]),+ len(content),+ b"/Filter /FlateDecode " if form_extra else b"",+ )+ + content+ + b"\nendstream"+ )+ font, xobject = helvetica, b"/XObject << /X1 %d 0 R >> " % form+ elif widths:+ array = add(b"[" + b"500 " * widths + b"]", i)font = add(b"<< /Type /Font /Subtype /Type1 /BaseFont /Crafted%d "- b"/FirstChar 0 /LastChar 255 /Widths %d 0 R >>" % (i, array)+ b"/FirstChar 0 /LastChar 255 /Widths %d 0 R >>" % (i, array),+ i,)data = zlib.compress(- b"BT /F1 12 Tf 72 720 Td (Page %d) Tj ET\n" % i + b" " * pad+ b"BT /F1 12 Tf 72 720 Td (Page %d) Tj ET\n" % i+ + ops+ + b"/X1 Do\n" * form_uses+ + b" " * pad)streams.append(add(@@ -1052,14 +1230,16 @@ def _crafted_pdf(pages, pad=0, *, late_refs=0, widths=0):+ b"\nendstream"))- kids.append(page(font, streams[-1]))+ kids.append(page(font, streams[-1], xobject))for i in range(late_refs):- kids.append(page(helvetica, streams[i]))+ kids.append(page(helvetica, streams[i % pages]))bodies[catalog - 1] = b"<< /Type /Catalog /Pages %d 0 R >>" % rootbodies[root - 1] = b"<< /Type /Pages /Count %d /Kids [%s] >>" % (len(kids),b" ".join(b"%d 0 R" % kid for kid in kids),)+ if objstm:+ return _with_object_streams(bodies, packed, catalog, struct)out = bytearray(b"%PDF-1.4\n")offsets = []for number, body in enumerate(bodies, start=1):@@ -1076,6 +1256,53 @@ def _crafted_pdf(pages, pad=0, *, late_refs=0, widths=0):return bytes(out)+def _with_object_streams(bodies, packed, catalog, struct):+ """Serialise *bodies* as PDF 1.5: the objects in *packed* go into one+ object stream per group (in first-member order), the rest stay+ top-level, and a cross-reference stream indexes both."""+ groups = {}+ for number, group in packed.items():+ groups.setdefault(group, []).append(number)+ # Object number -> cross-reference stream row (type, field 2, field 3).+ rows = {0: (0, 0, 65535)}+ out = bytearray(b"%PDF-1.5\n")+ for number, body in enumerate(bodies, start=1):+ if number not in packed:+ rows[number] = (1, len(out), 0)+ out += b"%d 0 obj\n" % number + body + b"\nendobj\n"+ number = len(bodies)+ for members in groups.values():+ number += 1+ header, data = [], bytearray()+ for index, member in enumerate(members):+ header.append(b"%d %d" % (member, len(data)))+ data += bodies[member - 1] + b"\n"+ rows[member] = (2, number, index)+ head = b" ".join(header) + b"\n"+ rows[number] = (1, len(out), 0)+ out += (+ b"%d 0 obj\n<< /Type /ObjStm /N %d /First %d /Length %d >>\n"+ b"stream\n"+ % (number, len(members), len(head), len(head + data))+ + head+ + data+ + b"\nendstream\nendobj\n"+ )+ number += 1+ rows[number] = (1, len(out), 0)+ table = b"".join(struct.pack(">BIH", *rows[n]) for n in range(number + 1))+ xref = len(out)+ out += (+ b"%d 0 obj\n<< /Type /XRef /Size %d /W [1 4 2] /Root %d 0 R "+ b"/Length %d >>\nstream\n"+ % (number, number + 1, catalog, len(table))+ + table+ + b"\nendstream\nendobj\n"+ )+ out += b"startxref\n%d\n%%%%EOF\n" % xref+ return bytes(out)++def _page_texts(count, sep):return sep.join(f"Page {i}" for i in range(count))@@ -1092,6 +1319,43 @@ def _capture(mocker, target, real):return made+class _FakeFont(SimpleNamespace):+ """A stand-in for a pdfminer font: attributes as given, and weakly+ referenceable like the real ones."""+++def _fake_rsrcmgr(cached=None):+ """A real pdfminer resource manager whose ``get_font()`` hands back+ the *spec* it is given as the font built, so a test can stand any+ object in for a font; *cached* seeds its font cache."""+ from pdfminer.pdfinterp import PDFResourceManager++ class Manager(PDFResourceManager):+ def get_font(self, objid, spec):+ return spec++ manager = Manager()+ manager._cached_fonts.update(cached or {})+ return manager+++def _kept_elements(releaser):+ """Elements of the font tables *releaser* still holds. Right after a+ release these are the tables something else holds (pdfminer's+ built-in encodings and metrics), which the release cannot free: they+ were counted once, and are not counted again."""+ from pdfminer.pdftypes import PDFStream++ from local_deep_research.utilities.pdf_stream_release import (+ _count_elements,+ )++ return sum(+ max(1, _count_elements(table, (PDFStream,), []))+ for table in releaser._tables+ )++def _pdfminer_decoded(pdf):"""Decoded bytes pdfminer still holds: cached streams and thestreams pages hold directly."""@@ -1440,7 +1704,7 @@ class TestWalkReleasers:pdf = MagicMock()pdf.doc._cached_objs = {}pdf.doc._parsed_objs = {7: ([[0] * 10], 1)}- pdf.rsrcmgr._cached_fonts = {"F1": object()}+ pdf.rsrcmgr = _fake_rsrcmgr({"F1": _FakeFont()})releaser = PdfplumberWalkReleaser(pdf)releaser.before_page()pdf.doc._cached_objs[1] = (stream, 0)@@ -1463,14 +1727,1658 @@ class TestWalkReleasers:# stream is skipped.assert _count_elements(nested, (Stream,)) == 7+ def test_long_dictionary_keys_count_by_size(self):+ """Keys count by their size like values: pdfminer turns a name+ that is not UTF-8 into the text of its repr, about four+ characters a byte, so a dictionary of long names held about four+ times what its entries counted."""+ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ _count_elements,+ )++ key = "k" * (64 * _BYTES_PER_PARSED_ELEMENT)+ assert _count_elements({key: 1}, ()) >= 1 + 64+ assert _count_elements({1: key}, ()) >= 1 + 64+ assert _count_elements({"Type": 1, 2: 3}, ()) == 2++ def test_containers_something_else_holds_are_told_apart(self):+ """With a *shared* list, ``_count_elements()`` hands back, rather+ than descends into, a nested container that something besides+ its parent holds (``sys.getrefcount()``, calibrated once per+ interpreter), so that a font build's new container holding+ parts of a parsed object does not make the walk cost more than+ the build."""+ from local_deep_research.utilities.pdf_stream_release import (+ _count_elements,+ )++ held_elsewhere = [0] * 1000+ table = (held_elsewhere, [1, 2], {"a": [3]})+ shared = []+ assert _count_elements(table, (), shared) == 3 + 2 + 1 + 1+ assert len(shared) == 1+ assert shared[0] is held_elsewhere+ # Without a list to hand them back in, everything is descended.+ assert _count_elements(table, ()) == 3 + 1000 + 2 + 1 + 1++ def test_empty_and_scalar_objects_are_not_free(self, mocker):+ """Each object the walk caches counts at least one element, so a+ page that caches many empty arrays or plain numbers still adds+ to the estimate."""+ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ PypdfWalkReleaser,+ )++ objects = 100+ mocker.patch(_RETAINED_LIMIT, objects * _BYTES_PER_PARSED_ELEMENT)++ pdf = MagicMock()+ pdf.doc._cached_objs = {}+ pdf.doc._parsed_objs = {}+ pdf.rsrcmgr = _fake_rsrcmgr()+ releaser = PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ for objid in range(objects):+ pdf.doc._cached_objs[objid] = ([] if objid % 2 else 1000 + objid, 0)+ assert releaser.after_page() is True+ assert pdf.doc._cached_objs == {}++ reader = MagicMock()+ reader.resolved_objects = {}+ releaser = PypdfWalkReleaser(reader)+ releaser.before_page()+ for key in range(objects):+ reader.resolved_objects[(key, 0)] = [] if key % 2 else 1000 + key+ assert releaser.after_page() is True+ assert reader.resolved_objects == {}++ def test_stream_dictionaries_count(self, mocker):+ """A stream's dictionary is parsed like any other, and counts+ like one, without the stream being decoded: a Form XObject whose+ dictionary held hundreds of thousands of empty arrays cost ~30+ times its file bytes and counted one element, under pdfminer+ and pypdf alike."""+ import io++ import pdfplumber+ from pypdf import PdfReader++ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ PypdfWalkReleaser,+ )++ arrays = 20_000+ mocker.patch(_RETAINED_LIMIT, arrays * _BYTES_PER_PARSED_ELEMENT)+ data = _crafted_pdf(+ 1, form_uses=1, form_extra=b"/Junk [" + b"[] " * arrays + b"] "+ )+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ (page,) = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ assert page.extract_text() == "Page 0"+ page.close()+ assert releaser.after_page() is True+ assert releaser._enabled+ reader = PdfReader(io.BytesIO(data))+ (page,) = reader.pages+ releaser = PypdfWalkReleaser(reader)+ releaser.before_page()+ assert "Page 0" in page.extract_text()+ assert releaser.after_page() is True+ assert releaser._enabled++ def test_parsed_object_streams_count_against_the_threshold(self, mocker):+ """pdfminer parses every object of an object stream into one list+ kept in ``_parsed_objs``, apart from the object cache; those+ objects count against the threshold even when no page resolved+ them through the object cache."""+ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ )++ tokens = 1000+ mocker.patch(_RETAINED_LIMIT, tokens * _BYTES_PER_PARSED_ELEMENT)+ pdf = MagicMock()+ pdf.doc._cached_objs = {}+ # A pre-walk object stream big enough to cross the threshold on+ # its own: only before_page()'s _objstm_mark keeps it out of the+ # first page's estimate.+ pdf.doc._parsed_objs = {3: ([[] for _ in range(tokens)], 0)}+ pdf.rsrcmgr = _fake_rsrcmgr()+ releaser = PdfplumberWalkReleaser(pdf)++ # Parsed before the walk's page: not this page's cost.+ releaser.before_page()+ assert releaser.after_page() is False+ assert 3 in pdf.doc._parsed_objs++ releaser.before_page()+ pdf.doc._parsed_objs[9] = ([[] for _ in range(tokens)], 0)+ assert releaser.after_page() is True+ assert pdf.doc._parsed_objs == {}++ def test_object_stream_objects_are_counted_once(self, mocker):+ """An object resolved out of an object stream is the very object+ in that stream's list: it is counted there, not again when it+ reaches the object cache, on the same page or a later one."""+ from local_deep_research.utilities.pdf_stream_release import (+ PdfplumberWalkReleaser,+ )++ mocker.patch(_RETAINED_LIMIT, 1 << 40)+ widths, font = [0] * 1000, {"Widths": None}+ pdf = MagicMock()+ pdf.doc._cached_objs = {}+ pdf.doc._parsed_objs = {}+ pdf.rsrcmgr = _fake_rsrcmgr()+ releaser = PdfplumberWalkReleaser(pdf)++ releaser.before_page()+ pdf.doc._parsed_objs[7] = ([4, 0, 5, 9, widths, font], 2)+ pdf.doc._cached_objs[4] = (widths, 0)+ assert releaser.after_page() is False+ # 6 list slots + 1000 widths + 1 font entry + 1 cache entry.+ assert releaser._parsed_elements == 1008++ releaser.before_page()+ pdf.doc._cached_objs[5] = (font, 0)+ assert releaser.after_page() is False+ assert releaser._parsed_elements == 1009++ def test_unexpected_object_stream_entries_are_never_under_counted(+ self, mocker+ ):+ """after_page() reads pdfminer's ``(objects, count)`` pairs. An+ entry of another shape is counted whole when it is a container,+ and switches the releaser off (with the usual warning) when it+ is not, rather than letting it go uncounted."""+ from local_deep_research.utilities import pdf_stream_release++ mocker.patch(_RETAINED_LIMIT, 1 << 40)+ disabled = mocker.patch.object(pdf_stream_release, "_log_disabled")++ def walk(entry):+ pdf = MagicMock()+ pdf.doc._cached_objs = {}+ pdf.doc._parsed_objs = {}+ pdf.rsrcmgr = _fake_rsrcmgr()+ releaser = pdf_stream_release.PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ pdf.doc._parsed_objs[7] = entry+ releaser.after_page()+ return releaser++ reshaped = walk({"objects": [[0] * 1000], "count": 1})+ assert reshaped._enabled+ assert reshaped._parsed_elements >= 1000+ disabled.assert_not_called()++ opaque = walk(object())+ assert not opaque._enabled+ disabled.assert_called_once()++ def test_object_streams_of_a_real_file_count_once_and_release(self, mocker):+ """End to end on a real PDF 1.5 file with object streams: each+ page counts the object stream it parsed (its font and /Widths)+ once, the large pre-walk object stream holding the page tree is+ not charged to the first page, and the release fires once two+ pages' worth is held -- not after the first page, as it did when+ each resolved object counted twice."""+ import io++ import pdfplumber+ from pdfminer.encodingdb import EncodingDB++ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ _count_elements,+ )++ entries = 2000+ # Per page: the object stream list (2 objects -> 6 slots), the+ # /Widths entries, the font's 6 dictionary entries, 3 cache+ # entries (the object stream, the array, the font), the object+ # stream's 4 dictionary entries, the pdfminer font and its own+ # widths table, a copy of the /Widths entries.+ # The fonts share the standard encoding's table and the+ # (0, 0, 0, 0) bounding box pdfminer gives a font without a+ # descriptor, counted once: pdfminer holds them, so a release+ # cannot free them and they are not counted again.+ per_page = 6 + entries + 6 + 3 + 4 + 1 + entries+ shared = len(EncodingDB.get_encoding("StandardEncoding")) + 4+ assert shared < entries // 2+ mocker.patch(+ _RETAINED_LIMIT,+ (per_page + entries // 2) * _BYTES_PER_PARSED_ELEMENT,+ )+ # 500 extra pages make the pre-walk object stream large: charged+ # to the first page it alone would cross the threshold.+ data = _crafted_pdf(3, widths=entries, late_refs=500, objstm=True)+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ pages = pdf.pages+ (pre_walk,) = pdf.doc._parsed_objs+ assert (+ _count_elements(pdf.doc._parsed_objs[pre_walk], ())+ > per_page + entries // 2+ )+ releaser = PdfplumberWalkReleaser(pdf)+ released, texts = [], []+ for page in pages[:3]:+ releaser.before_page()+ texts.append(page.extract_text())+ page.close()+ released.append(releaser.after_page())+ if len(released) == 1:+ assert releaser._parsed_elements == per_page + shared+ assert len(pdf.doc._parsed_objs) == 2++ assert texts == ["Page 0", "Page 1", "Page 2"]+ assert released == [False, True, False]+ assert releaser._enabled+ assert releaser._parsed_elements == per_page++ def test_a_release_forgets_the_ids_it_counted(self, mocker):+ """A release clears the ids of the objects and font tables it+ has counted: once they are dropped, CPython can hand their ids+ to new objects, which must then be counted in full. Here the+ very same objects come back after the release, standing in for+ new objects that reuse the freed ids."""+ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ )++ entries = 1000+ mocker.patch(_RETAINED_LIMIT, entries * _BYTES_PER_PARSED_ELEMENT)+ array = [0] * entries+ font = _FakeFont(cid2unicode=dict.fromkeys(range(entries), "x"))+ pdf = MagicMock()+ pdf.doc._cached_objs = {}+ pdf.doc._parsed_objs = {}+ pdf.rsrcmgr = _fake_rsrcmgr()+ releaser = PdfplumberWalkReleaser(pdf)++ releaser.before_page()+ pdf.doc._parsed_objs[7] = ([4, 0, array], 1)+ pdf.rsrcmgr.get_font(9, font)+ assert releaser.after_page() is True++ # Top level in the object cache this time, not in an object+ # stream: counted in full, not as one already-counted entry.+ releaser.before_page()+ pdf.doc._cached_objs[4] = (array, 0)+ assert releaser.after_page() is True++ # A font table is let go of only once nothing else holds it, so+ # one that comes back is the same object, not a new one reusing+ # its id: the release could not free it, and it does not count+ # again (only the font, rebuilt, does).+ releaser.before_page()+ pdf.rsrcmgr.get_font(9, font)+ assert releaser.after_page() is False+ assert releaser._parsed_elements == 1+ table = id(font.cid2unicode)+ assert table in releaser._table_ids+ # Once nothing else holds it, the next release lets go of it,+ # and of its id.+ del font+ releaser.before_page()+ pdf.doc._cached_objs[5] = (array, 0)+ assert releaser.after_page() is True+ assert table not in releaser._table_ids+ assert releaser._tables == []+++class TestFontTablesAreReleased:+ """Fonts pdfminer builds count against the same threshold.++ pdfminer builds every font in a page's resources, with tables it+ expands from short ranges: each font parses its ``/ToUnicode`` CMap+ into its own map, so one ``<0000> <FFFF> bfrange`` in a ~100-byte+ compressed stream that many fonts share becomes 65,536 entries per+ font. It caches the fonts that are objects of their own; a font+ written inline in a resource dictionary is built again on every use+ and cached nowhere, its map left in a reference cycle. Before these+ were counted, 20 pages of five such fonts (an 18 KB file, or a+ 13 KB one with the fonts inline) held ~840 MB with the estimate at+ 64 KB and no release. Here each font's map has 4,096 entries.+ """++ _FONTS = 3++ def test_shared_tounicode_fonts_count_and_release(self, mocker):+ import io++ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ )++ per_page = self._FONTS * (_TOUNICODE_LAST + 1)+ mocker.patch(+ _RETAINED_LIMIT, per_page * 3 // 2 * _BYTES_PER_PARSED_ELEMENT+ )+ # Collect at every release: a deferred collection leaves the+ # dropped fonts' maps held (by their parsers' cycles) until it+ # runs (test_estimated_releases_space_their_collections).+ mocker.patch(_SPACING, 0)+ data = _crafted_pdf(4, unicode_fonts=self._FONTS)+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ pages = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ released, texts, counted, kept = [], [], [], []+ for page in pages:+ releaser.before_page()+ texts.append(page.extract_text())+ page.close()+ released.append(releaser.after_page())+ counted.append(releaser._parsed_elements)+ kept.append(_kept_elements(releaser))++ assert texts == [f"Page {i}" for i in range(4)]+ assert counted[0] >= per_page+ assert released == [False, True, False, True]+ assert pdf.rsrcmgr._cached_fonts == {}+ # Fonts built again after the release count again, all but+ # pdfminer's built-in tables.+ assert counted[2] == counted[0] - kept[1]+ assert releaser._enabled++ def test_released_tounicode_maps_are_freed(self, mocker):+ """Dropping the fonts does not free their /ToUnicode maps: the+ CMapParser that built each map keeps it (and the decoded CMap+ bytes) in a reference cycle. The release collects those cycles+ itself; automatic collection is off here so that only the+ release can. Without it, a walk that released every second page+ still grew ~840 MB over 20 pages."""+ import gc+ import io+ import weakref++ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ PdfplumberWalkReleaser,+ )++ mocker.patch(_RETAINED_LIMIT, 1)+ # A release's collection is spaced like the others+ # (test_estimated_releases_space_their_collections).+ mocker.patch(_SPACING, 0)+ data = _crafted_pdf(2, unicode_fonts=self._FONTS)+ was_enabled = gc.isenabled()+ gc.disable()+ try:+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ pages = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ for page in pages:+ releaser.before_page()+ page.extract_text()+ page.close()+ maps = [+ weakref.ref(font.unicode_map)+ for font in pdf.rsrcmgr._cached_fonts.values()+ ]+ assert len(maps) == self._FONTS+ assert releaser.after_page() is True+ assert [ref() for ref in maps] == [None] * self._FONTS+ finally:+ if was_enabled:+ gc.enable()++ def test_released_tounicode_maps_are_collected_at_once(self, mocker):+ """A release spaces its collection like the others, except when+ what it lets go of is the threshold's worth of garbage that only+ a collection frees: the /ToUnicode maps of the fonts it drops,+ which their parsers' cycles hold. Then it collects at once,+ however long the last collection took. Deferring it held the+ maps for as long as nine full collections of the process's heap+ took: 40 pages of five fonts sharing a 65,536-entry map, with 8+ million objects held, peaked ~400 MB above the start (~70 MB+ now). Here the last collection seems to have taken a second,+ and automatic collection is off."""+ import gc+ import io+ import weakref++ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ )++ per_page = self._FONTS * (_TOUNICODE_LAST + 1)+ mocker.patch(+ _RETAINED_LIMIT, per_page * 3 // 2 * _BYTES_PER_PARSED_ELEMENT+ )+ data = _crafted_pdf(4, unicode_fonts=self._FONTS)+ was_enabled = gc.isenabled()+ gc.disable()+ try:+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ pages = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ released, maps = [], []+ for page in pages:+ releaser.before_page()+ releaser._collect_cost = 1.0+ page.extract_text()+ page.close()+ maps += [+ weakref.ref(font.unicode_map)+ for font in pdf.rsrcmgr._cached_fonts.values()+ ]+ released.append(releaser.after_page())+ if released[-1]:+ assert [ref() for ref in maps] == [None] * len(maps)+ maps = []+ assert released == [False, True, False, True]+ assert releaser._enabled+ finally:+ if was_enabled:+ gc.enable()++ def test_a_deferred_collection_runs_when_the_walk_ends(self, mocker):+ """A release that the decoded streams ask for, with less than the+ threshold's worth of /ToUnicode maps to free, defers its+ collection; if the walk ends first, the collection runs then (on+ ``close()``, or once the releaser is garbage), so that the walk+ does not end holding them. A walk that deferred nothing (an+ honest document's) collects nothing when it ends."""+ import gc+ import io+ import weakref++ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ PdfplumberWalkReleaser,+ )++ mocker.patch(_RETAINED_LIMIT, _PAD // 2)+ collect = mocker.patch.object(gc, "collect", wraps=gc.collect)+ was_enabled = gc.isenabled()+ gc.disable()+ try:+ # (pad, whether the release defers a collection, walk end)+ for pad, deferred, close in (+ (_PAD, True, False),+ (_PAD, True, True),+ (0, False, True),+ ):+ collect.reset_mock()+ data = _crafted_pdf(1, pad=pad, unicode_fonts=1)+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ (page,) = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ releaser._collect_cost = 1.0+ page.extract_text()+ page.close()+ (font,) = pdf.rsrcmgr._cached_fonts.values()+ ref = weakref.ref(font.unicode_map)+ font = None+ assert releaser.after_page() is deferred+ assert collect.call_count == 0+ assert ref() is not None+ if close:+ releaser.close()+ else:+ del releaser+ assert collect.call_count == int(deferred)+ assert (ref() is None) is deferred+ if close:+ releaser.close()+ del releaser+ assert collect.call_count == int(deferred)+ finally:+ if was_enabled:+ gc.enable()++ def test_font_tables_count_once_and_only_for_new_fonts(self, mocker):+ """Each font counts one element plus every element nested in its+ tables (widths, simple or CID, displacements, maps); a table+ several fonts share counts once, and fonts cached before the+ page are not its cost."""+ from local_deep_research.utilities.pdf_stream_release import (+ PdfplumberWalkReleaser,+ )++ mocker.patch(_RETAINED_LIMIT, 1 << 40)+ shared = dict.fromkeys(range(100), "x")++ def font(entries):+ return _FakeFont(+ widths=dict.fromkeys(range(entries), 500),+ cid2unicode=shared,+ # A new tuple per entry, as pdfminer builds them.+ disps={cid: (0, -cid) for cid in range(entries)},+ unicode_map=SimpleNamespace(+ cid2unichr=dict.fromkeys(range(entries), "y")+ ),+ )++ pre = font(10_000)+ pdf = MagicMock()+ pdf.doc._cached_objs = {}+ pdf.doc._parsed_objs = {}+ pdf.rsrcmgr = _fake_rsrcmgr({"pre": pre})+ releaser = PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ get_font = pdf.rsrcmgr.get_font+ # Handed out again from the cache: built before the walk.+ get_font("pre", pre)+ a = get_font("a", font(10))+ get_font(None, font(20)) # inline: built, never cached+ get_font("a", a) # the same font again counts once+ # A font without tables (or a /ToUnicode map) counts one element.+ get_font(None, _FakeFont(unicode_map=None))+ # A simple font (no disps) builds its own widths too.+ get_font(+ "d",+ _FakeFont(+ widths=dict.fromkeys(range(1000), 500), cid2unicode=shared+ ),+ )+ # widths, disps (each entry a 2-tuple) and cid2unichr per font.+ expected = 4 + 100 + (10 + 30 + 10) + (20 + 60 + 20) + 1000+ assert releaser.after_page() is False+ assert releaser._parsed_elements == expected++ # Counted fonts are not counted again on a later page.+ releaser.before_page()+ get_font("a", a)+ assert releaser.after_page() is False+ assert releaser._parsed_elements == expected++ def test_fonts_sharing_one_widths_array_count_per_font(self, mocker):+ """Every simple font builds its own widths table from its+ /Widths array, so fonts sharing one array object each hold a+ copy of it; each copy counts. Before they did, 10 pages of six+ fonts sharing one 200,000-entry array grew ~97 MB a page with+ the estimate at 24 MB and no release."""+ import io++ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ )++ entries = 5000+ # A page's fonts hold 3 copies; the array counts once more when+ # first parsed. Two pages cross the threshold, one does not.+ mocker.patch(+ _RETAINED_LIMIT, entries * 11 // 2 * _BYTES_PER_PARSED_ELEMENT+ )+ data = _crafted_pdf(4, simple_fonts=3, shared_widths=entries)+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ pages = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ released, texts, counted, kept = [], [], [], []+ for page in pages:+ releaser.before_page()+ texts.append(page.extract_text())+ page.close()+ released.append(releaser.after_page())+ counted.append(releaser._parsed_elements)+ kept.append(_kept_elements(releaser))++ assert texts == [f"Page {i}" for i in range(4)]+ assert counted[0] >= 4 * entries+ assert released == [False, True, False, True]+ # All but pdfminer's built-in tables count again.+ assert counted[2] == counted[0] - kept[1]+ assert releaser._enabled++ def test_type1_header_copies_count_per_build(self, mocker):+ """A Type 1 font without /Encoding parses a fresh copy of its+ /FontFile's first /Length1 bytes, which the header parser keeps+ in a reference cycle: each build's copy counts, even when every+ font shares one /FontFile. Before it did, three fonts a page+ sharing a 20 MB /FontFile of spaces grew ~57 MB a page with no+ release."""+ import io++ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ PdfplumberWalkReleaser,+ )++ size = 256 * 1024+ # The decoded /FontFile counts once, a page's copies three times.+ mocker.patch(_RETAINED_LIMIT, size * 11 // 2)+ data = _crafted_pdf(4, simple_fonts=3, font_file=size)+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ pages = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ released, texts = [], []+ for page in pages:+ releaser.before_page()+ texts.append(page.extract_text())+ page.close()+ released.append(releaser.after_page())++ assert texts == [f"Page {i}" for i in range(4)]+ assert released == [False, True, False, True]+ assert releaser._enabled++ def test_font_parser_cycles_are_collected_between_releases(self, mocker):+ """The parsers a font build leaves in reference cycles (with the+ copy of the /FontFile header they read) are garbage once the+ build returns; the releaser collects them once what they were+ fed could hold the threshold's worth, before any release and in+ the middle of a page. Automatic collection is off here so that+ only the releaser can."""+ import gc+ import io+ import weakref++ import pdfminer.pdffont+ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ _PARSER_BYTES_PER_INPUT_BYTE,+ PdfplumberWalkReleaser,+ )++ size = 64 * 1024+ parsers = []+ real = pdfminer.pdffont.Type1FontHeaderParser++ def recording(*args, **kwargs):+ parser = real(*args, **kwargs)+ parsers.append(weakref.ref(parser))+ return parser++ mocker.patch.object(+ pdfminer.pdffont, "Type1FontHeaderParser", side_effect=recording+ )+ # A collection every second build (collections are not spaced+ # here; see test_mid_page_collections_are_spaced); no release.+ mocker.patch(_RETAINED_LIMIT, 2 * size * _PARSER_BYTES_PER_INPUT_BYTE)+ mocker.patch(_SPACING, 0)+ data = _crafted_pdf(2, simple_fonts=3, font_file=size)+ was_enabled = gc.isenabled()+ gc.disable()+ try:+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ pages = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ for page in pages:+ releaser.before_page()+ page.extract_text()+ page.close()+ assert releaser.after_page() is False+ assert len(parsers) == 6+ alive = [ref for ref in parsers if ref() is not None]+ assert len(alive) <= 1+ finally:+ if was_enabled:+ gc.enable()++ def test_font_tables_let_go_of_are_collected_mid_page(self, mocker):+ """When the tables held reach the threshold's worth and are let+ go of, the cycles holding the maps of fonts pdfminer has dropped+ (an inline font built on every ``Do`` of a form) are collected+ there, in the middle of the page. Before they were, a page+ invoking a form of five such fonts 20 times peaked at ~880 MB.+ Automatic collection is off here so that only the releaser can+ free them."""+ import gc+ import io+ import weakref++ import pdfminer.pdffont+ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ )++ built = []+ real = pdfminer.pdffont.FileUnicodeMap++ def recording(*args, **kwargs):+ unicode_map = real(*args, **kwargs)+ built.append(weakref.ref(unicode_map))+ return unicode_map++ mocker.patch.object(+ pdfminer.pdffont, "FileUnicodeMap", side_effect=recording+ )+ uses = 6+ mocker.patch(_SPACING, 0) # see test_mid_page_collections_are_spaced+ # The tables are let go of at every third build.+ mocker.patch(+ _RETAINED_LIMIT,+ (_TOUNICODE_LAST + 1) * 5 // 2 * _BYTES_PER_PARSED_ELEMENT,+ )+ data = _crafted_pdf(1, unicode_fonts=1, inline=True, form_uses=uses)+ was_enabled = gc.isenabled()+ gc.disable()+ try:+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ (page,) = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ assert page.extract_text() == "Page 0"+ page.close()+ assert len(built) == uses+ alive = [ref for ref in built if ref() is not None]+ assert len(alive) <= 2+ assert releaser.after_page() is True+ finally:+ if was_enabled:+ gc.enable()++ def test_inline_tounicode_maps_are_collected_at_once(self, mocker):+ """The /ToUnicode map of a font pdfminer does not cache (written+ inline, here in a form invoked on every ``Do``) is garbage that+ only a collection frees once its build returns and the font is+ let go of, and once the threshold's worth of those has been+ built the releaser collects them at once, in the middle of the+ page, however long the last collection took. Here it seems to+ have taken a second, and automatic collection is off."""+ import gc+ import io+ import weakref++ import pdfminer.pdffont+ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ )++ built = []+ real = pdfminer.pdffont.FileUnicodeMap++ def recording(*args, **kwargs):+ unicode_map = real(*args, **kwargs)+ built.append(weakref.ref(unicode_map))+ return unicode_map++ mocker.patch.object(+ pdfminer.pdffont, "FileUnicodeMap", side_effect=recording+ )+ uses = 6+ # Two and a half maps' worth: collected at every third build.+ mocker.patch(+ _RETAINED_LIMIT,+ (_TOUNICODE_LAST + 1) * 5 // 2 * _BYTES_PER_PARSED_ELEMENT,+ )+ data = _crafted_pdf(1, unicode_fonts=1, inline=True, form_uses=uses)+ was_enabled = gc.isenabled()+ gc.disable()+ try:+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ (page,) = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ releaser._collect_cost = 1.0+ assert page.extract_text() == "Page 0"+ page.close()+ assert len(built) == uses+ alive = [ref for ref in built if ref() is not None]+ assert len(alive) <= 2+ assert releaser._enabled+ finally:+ if was_enabled:+ gc.enable()++ def test_long_strings_a_font_build_makes_count(self, mocker):+ """A CID font joins its /CIDSystemInfo /Registry and /Ordering+ into a new string (``cidcoding``) on every build, however long+ they are and however many fonts share them; strings count by+ their size. Before they did, ten pages of five fonts sharing a+ 20 MB /Registry string (a 25 KB file) grew ~95 MB a page with the+ estimate at 0.1 MB and no release."""+ import io++ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ PdfplumberWalkReleaser,+ )++ size = 256 * 1024+ # The shared string counts once, a page's three fonts' strings+ # three times: two pages cross the threshold, one does not.+ mocker.patch(_RETAINED_LIMIT, size * 11 // 2)+ data = _crafted_pdf(4, cid_fonts=3, registry=size)+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ pages = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ released, texts = [], []+ for page in pages:+ before = set(pdf.rsrcmgr._cached_fonts)+ releaser.before_page()+ texts.append(page.extract_text())+ page.close()+ codings = [+ font.cidcoding+ for objid, font in pdf.rsrcmgr._cached_fonts.items()+ if objid not in before and hasattr(font, "cidcoding")+ ]+ assert len(codings) == 3+ assert all(len(c) > size for c in codings)+ assert len({id(c) for c in codings}) == 3, "one per build"+ released.append(releaser.after_page())++ assert texts == [f"Page {i}" for i in range(4)]+ assert released == [False, True, False, True]+ assert releaser._enabled++ def test_long_strings_in_a_tounicode_map_count(self, mocker):+ """A flat table of strings counts every long string in it by its+ size: a ``bfrange`` with a long destination maps every code to a+ long string of its own. Here they cross the threshold; counted+ as entries only, they do not."""+ import io++ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ )++ # 4,096 codes, each mapped to a 255-character string.+ mocker.patch(+ _RETAINED_LIMIT,+ 3 * (_TOUNICODE_LAST + 1) * _BYTES_PER_PARSED_ELEMENT,+ )+ data = _crafted_pdf(+ 1, unicode_fonts=1, unicode_dest=b"0041" * 253 + b"00000000"+ )+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ (page,) = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ page.extract_text()+ page.close()+ (font,) = pdf.rsrcmgr._cached_fonts.values()+ strings = font.unicode_map.cid2unichr.values()+ assert len(strings) == _TOUNICODE_LAST + 1+ assert min(map(len, strings)) == 255+ assert releaser.after_page() is True+ assert releaser._enabled++ def test_long_strings_in_parsed_dictionaries_count(self, mocker):+ """A /Registry string written in the /CIDSystemInfo dictionary+ of a font in an object stream counts by its size there, and in+ the font's ``cidsysteminfo`` (that same dictionary): both are+ flat tables of strings. Counted as entries only, the first page+ does not cross the threshold."""+ import io++ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ PdfplumberWalkReleaser,+ )++ size = 256 * 1024+ # A page's three fonts: each string counts in the parsed object+ # stream and in the font's cidsysteminfo, and the decoded object+ # stream and each font's cidcoding (a new string) hold another+ # copy: 12 copies a page, 6 of them without the first two.+ mocker.patch(_RETAINED_LIMIT, size * 9)+ data = _crafted_pdf(+ 2, cid_fonts=3, registry=size, registry_inline=True, objstm=True+ )+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ releaser = PdfplumberWalkReleaser(pdf)+ released = []+ for page in pdf.pages:+ releaser.before_page()+ page.extract_text()+ page.close()+ released.append(releaser.after_page())+ assert released == [True, True]+ assert releaser._enabled++ def test_parts_of_the_parsed_font_are_walked_once(self, mocker):+ """A font build stores some parts of the parsed font as they are+ (its descriptor; the /FontMatrix items of a Type 3 font, in a new+ tuple), and an inline font in a form is built again on every+ ``Do``. Those parts are walked once, not on every build: before,+ once they reached the threshold's worth the held tables were let+ go of and they were walked again on every ``Do`` (100 ``Do``s of+ a form whose font's descriptor holds 600,000 empty arrays took+ ~66 s of CPU against ~3 s without the releaser)."""+ import io++ import pdfplumber++ from local_deep_research.utilities import pdf_stream_release++ entries = 20_000+ uses = 20+ mocker.patch(+ _RETAINED_LIMIT,+ entries // 2 * pdf_stream_release._BYTES_PER_PARSED_ELEMENT,+ )+ mocker.patch(_SPACING, 0)+ walked = _capture(+ mocker,+ "local_deep_research.utilities.pdf_stream_release._count_elements",+ pdf_stream_release._count_elements,+ )+ arrays = b"[" + b"[]" * entries + b"]"+ for options in (+ {"descriptor_extra": b" /X " + arrays},+ {"matrix": b"[[%s] 0 [[]] 0.001 0 0]" % arrays},+ ):+ del walked[:]+ data = _crafted_pdf(+ 1, simple_fonts=1, inline=True, form_uses=uses, **options+ )+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ (page,) = pdf.pages+ releaser = pdf_stream_release.PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ page.extract_text()+ page.close()+ # Counted once: the parts' entries, plus per build the+ # font and what the build made.+ assert releaser._parsed_elements < entries + 300 * uses+ assert releaser.after_page() is True+ assert releaser._enabled+ # And once more, after the page, in the form's dictionary,+ # which holds the inline font.+ assert sum(walked) < 2 * entries + 300 * uses++ def test_a_failed_build_parses_nothing(self, mocker):+ """After a build that raised, the streams it may have parsed are+ looked up in the object cache only: the build may have failed+ before resolving them, so following their references could parse+ objects it never reached, or loop forever on a reference to+ itself (``8 0 obj 8 0 R``). What it did resolve is cached, and+ counts."""+ import pdfminer.pdfinterp+ from pdfminer.pdfinterp import PDFResourceManager+ from pdfminer.pdftypes import PDFObjRef, PDFStream+ from pdfminer.psparser import LIT++ from local_deep_research.utilities.pdf_stream_release import (+ PdfplumberWalkReleaser,+ )++ class Looped(BaseException):+ """Raised once the cyclic reference has been followed."""++ mocker.patch(_RETAINED_LIMIT, 1 << 40)+ pdf = MagicMock()+ pdf.doc._cached_objs = {}+ pdf.doc._parsed_objs = {}+ pdf.rsrcmgr = PDFResourceManager()+ followed = []++ def getobj(objid):+ followed.append(objid)+ if len(followed) > 100:+ raise Looped+ return PDFObjRef(pdf.doc, objid)++ pdf.doc.getobj.side_effect = getobj+ cmap = PDFStream({}, b"")+ cmap.data = b"x" * 100+ pdf.doc._cached_objs[9] = (cmap, 0)+ spec = {+ "Type": LIT("Font"),+ "Subtype": LIT("Type1"),+ "BaseFont": LIT("Crafted"),+ "ToUnicode": PDFObjRef(pdf.doc, 9),+ "FontDescriptor": {"FontFile": PDFObjRef(pdf.doc, 8)},+ }+ mocker.patch.object(+ pdfminer.pdfinterp, "PDFType1Font", side_effect=RuntimeError+ )+ releaser = PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ with pytest.raises(RuntimeError):+ pdf.rsrcmgr.get_font(None, spec)+ assert followed == []+ assert releaser._font_bytes == len(cmap.data)+ assert releaser._enabled++ def test_estimated_releases_space_their_collections(self, mocker):+ """A release the estimate asks for drops the caches at once but+ spaces its collection like the others: what triggers it can be+ cheap (a shared 64 MB stream of zeros that a font build decodes+ and hardly parses makes every page release), and a collection+ costs time in proportion to every object the process holds.+ Here every page releases, a page costs 10 ms of the thread's CPU+ and a collection 100 ms: the collections take about a tenth of+ the time, and the deferred ones still run. Before, every release+ collected: 100 such pages with a million objects held took ~25 s+ of CPU, now ~20 s."""+ import gc++ from pdfminer.pdftypes import PDFStream++ from local_deep_research.utilities import pdf_stream_release++ clock = {"now": 0.0}++ def collect(*args):+ clock["now"] += 0.1+ return 0++ mocker.patch("time.thread_time", side_effect=lambda: clock["now"])+ mocker.patch.object(gc, "collect", side_effect=collect)+ mocker.patch(_RETAINED_LIMIT, 1)+ stream = PDFStream({}, b"raw")+ stream.data = b"decoded"+ pdf = MagicMock()+ pdf.doc._cached_objs = {1: (stream, 0)}+ pdf.doc._parsed_objs = {}+ pdf.rsrcmgr = _fake_rsrcmgr()+ releaser = pdf_stream_release.PdfplumberWalkReleaser(pdf)+ released = []+ for _ in range(500):+ releaser.before_page()+ clock["now"] += 0.01+ released.append(releaser.after_page())+ collections = gc.collect.call_count+ assert all(released)+ assert collections >= 2, "deferred collections still run"+ assert collections * 0.1 <= 0.15 * clock["now"]+ assert releaser._enabled++ def test_font_files_pdfminer_does_not_parse_do_not_count(self, mocker):+ """Only what a build parses counts: a Type 1 font's /FontFile+ header is read from its first /Length1 bytes (none here), and not+ at all for a standard font, whose built-in metrics replace the+ descriptor. Counting the whole decoded /FontFile on every build+ made every ``Do`` of a form with such an inline font run a full+ collection: 2,000 of them took ~141 s of CPU instead of ~0.45 s,+ with a million objects held."""+ import gc+ import io+ import re++ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ _PARSER_BYTES_PER_INPUT_BYTE,+ PdfplumberWalkReleaser,+ )++ size = 64 * 1024+ uses = 20+ mocker.patch(_RETAINED_LIMIT, size * _PARSER_BYTES_PER_INPUT_BYTE)+ collect = mocker.patch.object(gc, "collect", wraps=gc.collect)++ def crafted(length1):+ return _crafted_pdf(+ 1,+ simple_fonts=1,+ font_file=size,+ length1=length1,+ inline=True,+ form_uses=uses,+ )++ # /Length1 0; and a standard font with the whole /FontFile as its+ # /Length1, decoded before the walk.+ standard = crafted(size).replace(+ b"/BaseFont /Crafted", b"/BaseFont /Courier"+ )+ for pdf_bytes in (crafted(0), standard):+ collect.reset_mock()+ with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:+ (page,) = pdf.pages+ if pdf_bytes is standard:+ (objid,) = re.findall(+ rb"(\d+) 0 obj\n<< /Length \d+ /Length1", pdf_bytes+ )+ assert len(pdf.doc.getobj(int(objid)).get_data()) == size+ releaser = PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ assert page.extract_text() == "Page 0"+ page.close()+ assert releaser.after_page() is False+ assert collect.call_count == 0+ assert releaser._font_bytes == 0+ assert releaser._enabled++ def test_mid_page_collections_are_spaced(self, mocker):+ """A collection costs time in proportion to every object the+ process holds, whatever it frees, and the builds that ask for one+ can be cheap. One the threshold asks for in the middle of a page+ waits until the thread has spent ``_COLLECT_SPACING`` times the+ last collection's duration since it ended. Here every build asks+ for one, a build costs 1 ms of the thread's CPU and a collection+ 100 ms: the collections take about a tenth of the time."""+ import gc++ from local_deep_research.utilities import pdf_stream_release++ clock = {"now": 0.0}++ def thread_time():+ return clock["now"]++ def collect(*args):+ clock["now"] += 0.1+ return 0++ def parsed(spec, built=True, inputs=None):+ clock["now"] += 0.001+ return 1 << 20 # the threshold's worth, at the factor below++ # The worst-case factor asks for a collection on every build;+ # what the builds fed is far below the threshold, so none of it+ # is garbage that must be collected at once.+ mocker.patch.object(+ pdf_stream_release, "_PARSER_BYTES_PER_INPUT_BYTE", 1 << 16+ )+ mocker.patch("time.thread_time", side_effect=thread_time)+ mocker.patch.object(gc, "collect", side_effect=collect)+ mocker.patch.object(+ pdf_stream_release, "_parser_input_bytes", side_effect=parsed+ )+ mocker.patch(_RETAINED_LIMIT, 1 << 36)+ pdf = MagicMock()+ pdf.doc._cached_objs = {}+ pdf.doc._parsed_objs = {}+ pdf.rsrcmgr = _fake_rsrcmgr()+ releaser = pdf_stream_release.PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ for _ in range(2000):+ pdf.rsrcmgr.get_font(None, _FakeFont())+ collections = gc.collect.call_count+ # Unspaced, every one of the 2,000 builds collected.+ assert collections >= 2, "still collects"+ assert collections * 0.1 <= 0.15 * clock["now"]+ assert releaser._enabled++ def test_inline_fonts_count_and_release(self, mocker):+ """pdfminer caches only fonts that are objects of their own; a+ font dictionary written inline in a page's resources is built+ on every page that uses it and cached nowhere, so the estimate+ cannot be read off the font cache. Before it counted the fonts+ get_font() builds, 20 pages of five such fonts (a 13 KB file)+ held ~840 MB with no release."""+ import io++ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ )++ per_page = self._FONTS * (_TOUNICODE_LAST + 1)+ mocker.patch(+ _RETAINED_LIMIT, per_page * 3 // 2 * _BYTES_PER_PARSED_ELEMENT+ )+ # Collect at every release: a deferred collection leaves the+ # dropped fonts' maps held (by their parsers' cycles) until it+ # runs (test_estimated_releases_space_their_collections).+ mocker.patch(_SPACING, 0)+ data = _crafted_pdf(4, unicode_fonts=self._FONTS, inline=True)+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ pages = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ released, texts, counted, kept = [], [], [], []+ for page in pages:+ releaser.before_page()+ texts.append(page.extract_text())+ page.close()+ assert pdf.rsrcmgr._cached_fonts == {}+ released.append(releaser.after_page())+ counted.append(releaser._parsed_elements)+ kept.append(_kept_elements(releaser))++ assert texts == [f"Page {i}" for i in range(4)]+ assert counted[0] >= per_page+ assert released == [False, True, False, True]+ # All but pdfminer's built-in tables count again.+ assert counted[2] == counted[0] - kept[1]+ assert releaser._enabled++ def test_form_xobject_fonts_count_per_use(self, mocker):+ """A Form XObject's resources are initialised on every ``Do``:+ its inline fonts are built again each time the page invokes it,+ and each build counts."""+ import io++ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ )++ uses = 3+ per_use = _TOUNICODE_LAST + 1+ # One page's builds cross the threshold; a single use does not.+ mocker.patch(+ _RETAINED_LIMIT, per_use * 5 // 2 * _BYTES_PER_PARSED_ELEMENT+ )+ data = _crafted_pdf(2, unicode_fonts=1, inline=True, form_uses=uses)+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ pages = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ released, texts = [], []+ for page in pages:+ releaser.before_page()+ texts.append(page.extract_text())+ page.close()+ # Only the page's own Helvetica, an object, is cached.+ assert len(pdf.rsrcmgr._cached_fonts) == 1+ released.append(releaser.after_page())++ assert texts == ["Page 0", "Page 1"]+ assert released == [True, True]+ assert releaser._enabled++ def test_released_inline_fonts_are_freed(self, mocker):+ """The releaser holds the font tables it has counted until the+ release, inline fonts' maps included (pdfminer holds those only+ in reference cycles); the release must let go of them. Automatic+ collection is off here so that only the release can free them.+ The threshold is above what the tables count, so the releaser+ holds them all, and the pages' padding crosses it."""+ import gc+ import io+ import weakref++ import pdfminer.pdffont+ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ )++ class Table(dict):+ """A /ToUnicode map's table that can be weakly referenced."""++ built = []+ real = pdfminer.pdffont.FileUnicodeMap++ def recording(*args, **kwargs):+ unicode_map = real(*args, **kwargs)+ unicode_map.cid2unichr = Table()+ built.append(weakref.ref(unicode_map))+ built.append(weakref.ref(unicode_map.cid2unichr))+ return unicode_map++ mocker.patch.object(+ pdfminer.pdffont, "FileUnicodeMap", side_effect=recording+ )+ tables = 2 * self._FONTS * (_TOUNICODE_LAST + 1) + 1000+ mocker.patch(_RETAINED_LIMIT, tables * _BYTES_PER_PARSED_ELEMENT)+ # A release's collection is spaced like the others+ # (test_estimated_releases_space_their_collections).+ mocker.patch(_SPACING, 0)+ data = _crafted_pdf(+ 2, _PAD * 2, unicode_fonts=self._FONTS, inline=True, form_uses=2+ )+ was_enabled = gc.isenabled()+ gc.disable()+ try:+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ pages = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ for page in pages:+ del built[:]+ releaser.before_page()+ page.extract_text()+ page.close()+ assert len(built) == 2 * 2 * self._FONTS+ assert all(ref() is not None for ref in built)+ assert len(releaser._tables) > 2 * self._FONTS+ assert releaser.after_page() is True+ assert [ref() for ref in built] == [None] * len(built)+ finally:+ if was_enabled:+ gc.enable()++ def test_disabled_releaser_stops_counting_fonts(self, mocker):+ """A releaser that switches itself off must not keep holding the+ font tables it counted, nor go on counting fonts for the rest of+ the walk."""+ from local_deep_research.utilities import pdf_stream_release++ mocker.patch.object(pdf_stream_release, "_log_disabled")+ mocker.patch(_RETAINED_LIMIT, 1 << 40)+ pdf = MagicMock()+ pdf.doc._cached_objs = {}+ pdf.doc._parsed_objs = {}+ manager = _fake_rsrcmgr()+ pdf.rsrcmgr = manager+ releaser = pdf_stream_release.PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ assert "get_font" in vars(manager)+ manager.get_font(None, _FakeFont(cid2unicode={1: "x"}))+ assert len(releaser._tables) == 1++ pdf.doc._parsed_objs = None # internals changed: disables+ assert releaser.after_page() is False+ assert not releaser._enabled+ assert releaser._tables == []+ assert "get_font" not in vars(manager)+ manager.get_font(None, _FakeFont(cid2unicode={2: "y"}))+ assert releaser._tables == []++ def test_fonts_pdfminer_lets_go_of_are_not_held(self, mocker):+ """Counting a font must not keep it: every unknown font name in+ a ``Tf`` builds a new font that pdfminer caches nowhere and+ frees at once, so holding them turned a 2 KB page of 100,000+ such operators into ~920 MB held. Automatic collection is off,+ so only a held reference keeps a font."""+ import gc+ import io+ import weakref++ import pdfminer.pdfinterp+ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ PdfplumberWalkReleaser,+ )++ built = []+ real = pdfminer.pdfinterp.PDFType1Font++ def recording(*args, **kwargs):+ font = real(*args, **kwargs)+ built.append(weakref.ref(font))+ return font++ mocker.patch.object(+ pdfminer.pdfinterp, "PDFType1Font", side_effect=recording+ )+ mocker.patch(_RETAINED_LIMIT, 1 << 40)+ uses = 200+ data = _crafted_pdf(1, ops=b"BT /Unknown 1 Tf ET\n" * uses)+ was_enabled = gc.isenabled()+ gc.disable()+ try:+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ (page,) = pdf.pages+ releaser = PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ assert page.extract_text() == "Page 0"+ page.close()+ assert releaser.after_page() is False+ assert len(built) >= uses+ alive = [ref for ref in built if ref() is not None]+ # The page's own Helvetica (cached) and at most the last+ # font a finished interpreter's cycle still holds.+ assert len(alive) <= 2+ assert releaser._parsed_elements >= uses+ finally:+ if was_enabled:+ gc.enable()++ def test_held_font_tables_are_bounded(self, mocker):+ """The tables counted are held so that their ids stay theirs,+ but no more of them than the threshold's worth that nothing else+ holds: past it those are let go of, while every font still+ counts. A table something else still holds then (here the last+ font's, which the build that crossed the threshold is still+ handing out) is kept until the next time."""+ from local_deep_research.utilities.pdf_stream_release import (+ _BYTES_PER_PARSED_ELEMENT,+ PdfplumberWalkReleaser,+ )++ entries = 1000+ mocker.patch(_RETAINED_LIMIT, 3 * entries * _BYTES_PER_PARSED_ELEMENT)+ pdf = MagicMock()+ pdf.doc._cached_objs = {}+ pdf.doc._parsed_objs = {}+ pdf.rsrcmgr = _fake_rsrcmgr()+ releaser = PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ for _ in range(10):+ pdf.rsrcmgr.get_font(+ None, _FakeFont(cid2unicode=dict.fromkeys(range(entries)))+ )+ assert releaser._held_entries < 3 * entries+ assert len(releaser._tables) <= 3+ assert releaser._parsed_elements == 10 * (1 + entries)++ def test_font_recording_holds_no_cycle(self):+ """The get_font() wrapper holds the manager and the releaser+ weakly: dropping the releaser leaves a working pass-through, and+ the document's objects stay free of new reference cycles."""+ from local_deep_research.utilities.pdf_stream_release import (+ PdfplumberWalkReleaser,+ )++ pdf = MagicMock()+ pdf.doc._cached_objs = {}+ pdf.doc._parsed_objs = {}+ manager = _fake_rsrcmgr()+ pdf.rsrcmgr = manager+ releaser = PdfplumberWalkReleaser(pdf)+ releaser.before_page()+ wrapper = vars(manager)["get_font"]+ held = [cell.cell_contents for cell in wrapper.__closure__]+ assert all(obj is not manager for obj in held)+ assert all(obj is not releaser for obj in held)+ del releaser+ font = _FakeFont()+ assert manager.get_font(None, font) is font+++class TestResidentMemoryBound:+ """What the estimate does not count, the process's resident memory+ shows: a release also runs once it has grown by the threshold since+ the last one, and a collection in the middle of a page once it has+ grown by the threshold since the last collection. Each case of the+ estimate missing an allocation (inline fonts, shared widths, font+ header copies, the strings a CID font joins) went unbounded until it+ was found; this bounds the next one. Fed values of its own here."""++ @pytest.fixture+ def rss(self, monkeypatch):+ from local_deep_research.utilities import pdf_stream_release++ memory = {"now": 1 << 30}+ monkeypatch.setattr(+ pdf_stream_release, "_resident_bytes", lambda: memory["now"]+ )+ return memory++ def _pdfminer(self):+ from local_deep_research.utilities.pdf_stream_release import (+ PdfplumberWalkReleaser,+ )++ pdf = MagicMock()+ pdf.doc._cached_objs = {}+ pdf.doc._parsed_objs = {}+ pdf.rsrcmgr = _fake_rsrcmgr()+ return pdf, PdfplumberWalkReleaser(pdf)++ def test_pdfminer_releases_once_resident_memory_grows(self, mocker, rss):+ import gc++ limit = 1 << 20+ mocker.patch(_RETAINED_LIMIT, limit)+ mocker.patch(_SPACING, 0) # see test_mid_page_collections_are_spaced+ collect = mocker.patch.object(gc, "collect")+ pdf, releaser = self._pdfminer()+ released = []+ for growth in (limit - 1, 1, limit, limit // 2):+ releaser.before_page()+ rss["now"] += growth+ released.append(releaser.after_page())+ # The second page reaches the threshold since the walk began; the+ # third and fourth are measured from the second's release.+ assert released == [False, True, True, False]+ assert collect.call_count == 2+ assert releaser._enabled++ def test_pdfminer_collects_mid_page_once_resident_memory_grows(+ self, mocker, rss+ ):+ import gc++ from local_deep_research.utilities import pdf_stream_release++ limit = 1 << 20+ mocker.patch(_RETAINED_LIMIT, limit)+ mocker.patch.object(pdf_stream_release, "_RSS_CHECK_INTERVAL", 0)+ collect = mocker.patch.object(gc, "collect")+ pdf, releaser = self._pdfminer()+ releaser.before_page()+ pdf.rsrcmgr.get_font(None, _FakeFont())+ assert collect.call_count == 0+ rss["now"] += limit+ pdf.rsrcmgr.get_font(None, _FakeFont())+ assert collect.call_count == 1+ # Measured from that collection, spaced like the others: without+ # the spacing met, only a growth of _FORCED_GROWTH times the+ # threshold collects.+ mocker.patch.object(pdf_stream_release, "_COLLECT_SPACING", 1e12)+ releaser._collect_cost = 1.0+ rss["now"] += limit+ pdf.rsrcmgr.get_font(None, _FakeFont())+ assert collect.call_count == 1+ rss["now"] += (pdf_stream_release._FORCED_GROWTH - 1) * limit+ pdf.rsrcmgr.get_font(None, _FakeFont())+ assert collect.call_count == 2+ # The page grew by more than the threshold: it releases too.+ assert releaser.after_page() is True+ assert releaser._enabled++ def test_a_failed_read_keeps_the_baseline(self, mocker, monkeypatch):+ """A read of the resident memory that fails once (an OSError+ reading /proc/self/statm) keeps the baseline it would have+ replaced: before, the baseline became unknown and the measured+ trigger was off for the rest of the walk. Here the read that+ follows the first release fails."""+ import gc++ from local_deep_research.utilities import pdf_stream_release++ limit = 1 << 20+ mocker.patch(_RETAINED_LIMIT, limit)+ mocker.patch(_SPACING, 0)+ mocker.patch.object(gc, "collect")+ for library in ("pdfminer", "pypdf"):+ memory = {"now": 1 << 30, "reads": 0}++ def read(memory=memory):+ memory["reads"] += 1+ return None if memory["reads"] == 3 else memory["now"]++ monkeypatch.setattr(pdf_stream_release, "_resident_bytes", read)+ if library == "pdfminer":+ _pdf, releaser = self._pdfminer()+ else:+ reader = MagicMock()+ reader.resolved_objects = {}+ releaser = pdf_stream_release.PypdfWalkReleaser(reader)+ released = []+ for growth in (limit, limit // 2, limit):+ releaser.before_page()+ memory["now"] += growth+ released.append(releaser.after_page())+ # The second page is measured from the baseline before the+ # first release (the read after it failed), the third from+ # the second's release.+ assert released == [True, True, True], library+ assert memory["reads"] > 3+ assert releaser._enabled++ def test_pypdf_releases_once_resident_memory_grows(self, mocker, rss):+ from local_deep_research.utilities.pdf_stream_release import (+ PypdfWalkReleaser,+ )++ limit = 1 << 20+ mocker.patch(_RETAINED_LIMIT, limit)+ reader = MagicMock()+ reader.resolved_objects = {}+ releaser = PypdfWalkReleaser(reader)+ released = []+ for growth in (limit - 1, 1, limit // 2):+ releaser.before_page()+ rss["now"] += growth+ released.append(releaser.after_page())+ assert released == [False, True, False]+ assert releaser._enabled+++class TestDisabledReleaserIsLoggedOnce:+ """A releaser that disables itself (library internals changed) turns+ the memory bound off, so the first one of each library in a process+ warns; the rest log at DEBUG so a broken upgrade does not flood the+ log."""++ def test_first_disable_warns_then_debug(self, monkeypatch):+ from loguru import logger++ from local_deep_research.utilities import pdf_stream_release++ monkeypatch.setattr(pdf_stream_release, "_warned_disabled", set())+ records = []+ sink = logger.add(+ lambda message: records.append(message.record),+ level="DEBUG",+ filter="local_deep_research.utilities.pdf_stream_release",+ )+ # The package disables its loguru logger on import; enable it for+ # this block only and put it back afterwards.+ logger.enable("local_deep_research")+ try:+ for _ in range(3):+ for cls in (+ pdf_stream_release.PdfplumberWalkReleaser,+ pdf_stream_release.PypdfWalkReleaser,+ ):+ releaser = cls(object())+ releaser.before_page()+ assert releaser.after_page() is False+ finally:+ logger.disable("local_deep_research")+ logger.remove(sink)++ warnings = [r for r in records if r["level"].name == "WARNING"]+ debugs = [r for r in records if r["level"].name == "DEBUG"]+ assert len(warnings) == 2, "one WARNING per library per process"+ assert {w["message"].split()[0] for w in warnings} == {+ "pdfminer",+ "pypdf",+ }+ assert "no longer bounded" in warnings[0]["message"]+ assert len(debugs) == 4+class TestLibraryInternalsTheReleaseReliesOn:"""Canaries: fail when a pdfplumber/pdfminer or pypdf upgrade removesthe internals ``utilities/pdf_stream_release`` relies on. Thereleasers swallow such failures by design, so without these anupgrade would silently bring the unbounded retention back.- Written against pdfplumber 0.11.10, pdfminer.six 20260107 and pypdf- 6.19.0."""+ Written against the pdfplumber, pdfminer.six and pypdf versions+ ``pdm.lock`` pins."""def test_pdfminer_internals(self):import io@@ -1515,6 +3423,313 @@ class TestLibraryInternalsTheReleaseReliesOn:stream.decoded_self = Noneassert stream.get_data() == data+ def test_reference_counts_tell_held_tables_apart(self, monkeypatch):+ """``_let_go_of_tables()`` keeps a table something besides the+ releaser holds and lets go of one only it holds, reading+ ``sys.getrefcount()`` against a count calibrated on this+ interpreter; if the reading of a container only its list holds+ ever exceeds the calibration, it keeps none (an over-count, never+ an under-count)."""+ from local_deep_research.utilities import pdf_stream_release++ releaser = pdf_stream_release.PdfplumberWalkReleaser(MagicMock())+ held = {"a": 1}+ releaser._tables = [held, {"b": 2}]+ releaser._table_ids = {id(t) for t in releaser._tables}+ releaser._let_go_of_tables()+ assert releaser._tables == [held]+ assert releaser._table_ids == {id(held)}++ monkeypatch.setattr(pdf_stream_release, "_SOLE_HOLDER", 0)+ releaser._let_go_of_tables()+ assert releaser._tables == []+ assert releaser._table_ids == set()++ def test_resident_memory_is_measured_on_linux(self, monkeypatch):+ """The releasers read the process's resident memory from+ ``/proc/self/statm`` (Linux); elsewhere they rely on the estimate+ alone."""+ import sys++ from local_deep_research.utilities import pdf_stream_release++ monkeypatch.undo() # the module's _no_resident_memory+ if not sys.platform.startswith("linux"):+ pytest.skip("resident memory is measured on Linux only")+ before = pdf_stream_release._resident_bytes()+ held = bytearray(64 * 1024 * 1024)+ after = pdf_stream_release._resident_bytes()+ assert before and after - before >= 32 * 1024 * 1024+ del held++ def test_pdfminer_font_internals(self):+ """pdfminer builds every font in a page's resources that is an+ object of its own into ``rsrcmgr._cached_fonts`` (keys added in+ build order; the release clears it), and each+ font expands a shared ``/ToUnicode`` bfrange into its own+ ``unicode_map.cid2unichr``; CID fonts expand /W and /W2 ranges+ into ``widths`` and ``disps``. ``_font_tables()`` finds every one+ of them among the font's attributes; on real pdfminer+ objects."""+ import io++ import pdfplumber+ from pdfminer.pdffont import PDFCIDFont+ from pdfminer.psparser import LIT++ from local_deep_research.utilities.pdf_stream_release import (+ _font_tables,+ )++ with pdfplumber.open(+ io.BytesIO(_crafted_pdf(2, unicode_fonts=2))+ ) as pdf:+ pages = pdf.pages+ fonts = pdf.rsrcmgr._cached_fonts+ assert isinstance(fonts, dict) and not fonts+ seen = []+ for page in pages:+ page.extract_text()+ assert list(fonts)[: len(seen)] == seen, "not in build order"+ seen = list(fonts)+ assert len(fonts) == 4, "every font in /Resources is built"+ maps = [font.unicode_map.cid2unichr for font in fonts.values()]+ for cid2unichr in maps:+ assert type(cid2unichr) is dict+ assert len(cid2unichr) == _TOUNICODE_LAST + 1+ assert len({id(m) for m in maps}) == 4, "maps are per font"+ for font in fonts.values():+ tables = _font_tables(font)+ assert any(t is font.unicode_map.cid2unichr for t in tables)+ assert type(font.cid2unicode) is dict+ assert any(t is font.cid2unicode for t in tables)++ vertical = PDFCIDFont(+ None,+ {+ "BaseFont": LIT("Crafted"),+ "Encoding": LIT("Identity-V"),+ "W2": [0, 9, 1000, 500, 880],+ },+ strict=False,+ )+ assert len(vertical.widths) == len(vertical.disps) == 10+ horizontal = PDFCIDFont(+ None,+ {+ "BaseFont": LIT("Crafted"),+ "Encoding": LIT("Identity-H"),+ "W": [0, 99, 500],+ },+ strict=False,+ )+ assert len(horizontal.widths) == 100+ for font in (vertical, horizontal):+ tables = _font_tables(font)+ for table in (font.widths, font.disps):+ assert type(table) is dict+ assert any(t is table for t in tables)++ def test_pdfminer_font_builds_copy_what_fonts_share(self):+ """What the releaser counts per font build rather than once per+ shared object, on real pdfminer objects: every simple font builds+ its own ``widths`` dict from a /Widths array that many fonts+ share (``_font_tables()`` counts each); and a Type 1 font without+ /Encoding hands ``Type1FontHeaderParser`` a fresh copy of its+ /FontFile's first /Length1 bytes, which the parser keeps in a+ reference cycle (its bound-method state), so only the cycle+ collector frees it (``_parser_input_bytes()`` counts that copy's+ length per build)."""+ import io+ from unittest import mock++ import pdfminer.pdffont+ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ _font_tables,+ _parser_input_bytes,+ )++ entries = 300+ data = _crafted_pdf(1, simple_fonts=2, shared_widths=entries)+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ pdf.pages[0].extract_text()+ fonts = [+ font+ for font in pdf.rsrcmgr._cached_fonts.values()+ if font.basefont == "Crafted"+ ]+ assert len(fonts) == 2+ first, second = (font.widths for font in fonts)+ assert type(first) is dict and len(first) == entries+ assert first == second and first is not second, "one per font"+ for font in fonts:+ assert any(t is font.widths for t in _font_tables(font))++ size = 4096+ parsers = []+ real = pdfminer.pdffont.Type1FontHeaderParser++ def recording(*args, **kwargs):+ parsers.append(real(*args, **kwargs))+ return parsers[-1]++ data = _crafted_pdf(1, simple_fonts=1, font_file=size)+ with (+ mock.patch.object(+ pdfminer.pdffont,+ "Type1FontHeaderParser",+ side_effect=recording,+ ),+ pdfplumber.open(io.BytesIO(data)) as pdf,+ ):+ spec = None+ build = pdf.rsrcmgr.get_font++ def get_font(objid, font_spec):+ nonlocal spec+ if getattr(font_spec.get("BaseFont"), "name", 0) == "Crafted":+ spec = font_spec+ return build(objid, font_spec)++ pdf.rsrcmgr.get_font = get_font+ pdf.pages[0].extract_text()+ (parser,) = parsers+ font_file = spec["FontDescriptor"]["FontFile"].resolve()+ assert len(font_file.data) == size+ header = parser.fp.getvalue()+ assert len(header) == size - 1+ assert header is not font_file.data, "a copy per build"+ assert vars(parser)["_parse1"].__self__ is parser, "a cycle"+ assert _parser_input_bytes(spec) == len(header)++ def test_pdfminer_builds_every_font_through_get_font(self):+ """pdfminer caches only fonts that are objects of their own: a+ font dictionary written inline in a resource dictionary is built+ on every use (each page, each ``Do`` of a Form XObject) and+ cached nowhere. Every build goes through ``get_font()`` looked+ up on the resource manager instance (a Type0 font's descendant+ too), which ``_count_fonts()`` wraps; it relies on all of it."""+ import io+ import weakref++ import pdfplumber+ from pdfminer.pdfinterp import PDFResourceManager+ from pdfminer.psparser import LIT++ def recording(manager):+ assert "get_font" not in vars(manager)+ built = []+ real = manager.get_font++ def get_font(objid, spec):+ built.append((objid, real(objid, spec)))+ return built[-1][1]++ manager.get_font = get_font+ return built++ for form_uses, per_page in ((0, 2), (3, 2 * 3)):+ data = _crafted_pdf(+ 2, unicode_fonts=2, inline=True, form_uses=form_uses+ )+ with pdfplumber.open(io.BytesIO(data)) as pdf:+ pages = pdf.pages+ assert isinstance(pdf.rsrcmgr, PDFResourceManager)+ built = recording(pdf.rsrcmgr)+ for page in pages:+ del built[:]+ assert page.extract_text().startswith("Page")+ inline = [font for objid, font in built if objid is None]+ assert len(inline) == per_page+ assert len({id(font) for font in inline}) == per_page+ for font in inline:+ assert len(font.unicode_map.cid2unichr) == (+ _TOUNICODE_LAST + 1+ )+ # The releaser remembers the fonts it counted+ # weakly.+ assert weakref.ref(font)() is font+ assert all(+ font not in pdf.rsrcmgr._cached_fonts.values()+ for font in inline+ )+ if form_uses:+ # The page's own Helvetica is an object: cached.+ assert len(pdf.rsrcmgr._cached_fonts) == 1+ else:+ assert pdf.rsrcmgr._cached_fonts == {}++ manager = PDFResourceManager()+ built = recording(manager)+ font = manager.get_font(+ None,+ {+ "Type": LIT("Font"),+ "Subtype": LIT("Type0"),+ "BaseFont": LIT("Crafted"),+ "Encoding": LIT("Identity-H"),+ "DescendantFonts": [+ {+ "Type": LIT("Font"),+ "Subtype": LIT("CIDFontType2"),+ "BaseFont": LIT("Crafted"),+ }+ ],+ },+ )+ assert [built_font for _, built_font in built] == [font, font]++ def test_pdfminer_object_stream_internals(self):+ """``_parsed_objs`` maps an object stream's id to ``(objects,+ count)``: the list of its header numbers then its objects, and+ the number of objects. Keys are added in parse order, and the+ object getobj() caches is the one in that list. after_page()+ relies on all of it; on a real PDF 1.5 file."""+ import io++ import pdfplumber++ from local_deep_research.utilities.pdf_stream_release import (+ _is_objstm_entry,+ )++ with pdfplumber.open(+ io.BytesIO(_crafted_pdf(2, widths=10, objstm=True))+ ) as pdf:+ pages = pdf.pages+ parsed = pdf.doc._parsed_objs+ assert isinstance(parsed, dict)+ (pre_walk,) = parsed # catalog, page tree and pages+ for page in pages:+ page.extract_text()+ keys = list(parsed)+ assert keys[0] == pre_walk and len(keys) == 3+ assert keys == sorted(keys), "not in parse order"+ for key, value in parsed.items():+ assert _is_objstm_entry(value)+ objs, count = value+ assert type(value) is tuple and type(objs) is list+ assert type(count) is int and count > 0+ stream = pdf.doc.getobj(key)+ assert stream.get("Type").name == "ObjStm"+ assert stream.get("N") == count+ assert len(objs) == 3 * count+ for index in range(count):+ objid = objs[2 * index]+ cached = pdf.doc._cached_objs.get(objid)+ if cached is not None:+ assert cached[0] is objs[2 * count + index]+ # Each page's font and its /Widths array came out of the+ # page's own object stream and are the objects in its list.+ for key in keys[1:]:+ objs, count = parsed[key]+ assert count == 2+ assert [type(obj) for obj in objs[2 * count :]] == [list, dict]+ assert pdf.doc._cached_objs[objs[0]][0] is objs[4]+ assert pdf.doc._cached_objs[objs[2]][0] is objs[5]+class TestReleaserWiring:"""Every loop hands each page to its releaser in the right order."""