Repository navigation
fix(partition): read spooled uploads in place instead of copying them - #4419
Conversation
There was a problem hiding this comment.
All reported issues were addressed across 11 files
Shadow auto-approve: would not auto-approve because issues were found.
Re-trigger cubic
There was a problem hiding this comment.
0 issues found across 2 files (changes from recent commits).
Shadow auto-approve: would not auto-approve. Auto-approval blocked by 1 unresolved issue from previous reviews.
Re-trigger cubic
There was a problem hiding this comment.
0 issues found across 3 files (changes from recent commits).
Shadow auto-approve: would not auto-approve. This PR does not meet the repository auto-approval settings.
Re-trigger cubic
There was a problem hiding this comment.
All reported issues were addressed across 7 files (changes from recent commits).
Shadow auto-approve: would not auto-approve because issues were found.
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
All reported issues were addressed across 14 files
Shadow auto-approve: would not auto-approve because issues were found.
Re-trigger cubic
8f7d3c1 to
d8ba5bc
Compare
|
@cubic review |
There was a problem hiding this comment.
All reported issues were addressed across 14 files
Shadow auto-approve: would not auto-approve because issues were found.
View guided diff | Re-trigger cubic
There was a problem hiding this comment.
0 issues found across 2 files (changes from recent commits).
Shadow auto-approve: would not auto-approve. This PR does not meet the repository auto-approval settings.
View guided diff | Re-trigger cubic
Remove the remaining SpooledTemporaryFile-to-BytesIO copy from detect_filetype(), keeping the spool rewound afterward. Ignore non-string file names when deriving the extension so a rolled-over spool falls back to metadata_file_path, and let convert_to_bytes() read any seekable binary stream. Release as 0.27.11 since 0.27.10 is already tagged.
4c3d3b0 to
b699d3d
Compare
cragwolfe
left a comment
There was a problem hiding this comment.
Reviewed the full change at b699d3de6eeb481ff570c61a9f84d9903018101e against current main. No actionable material defects found.
The earlier stream-name, descriptor-ownership, Windows temporary-file, and buffered text-pipe findings are resolved in the current code. The in-place paths retain the required rewinds and caller ownership, and the added regressions cover both spool storage modes. I found no demonstrated compatibility break from the internal helper rename.
This is a source approval. Exact-head CI still has test_unit (3.12) and test_dockerfile running; the other four required checks have passed. No local tests were run.
(authored by codex)
…#4516) ## Summary OCR-only PDF partitioning kept ten decoded page images in memory at once, and the OCR step copied the whole upload into one byte string for the entire OCR run. This PR renders one page at a time, copies uploads to temporary disk in 1 MiB blocks, and closes each rendered page image after OCR, including when OCR fails. Pixels, format, rotation metadata, page order, upload cursor behavior and caller-owned stream lifetime are preserved. Uploads may be any readable, seekable stream (duck-typed `read`/`seek`), not only `BytesIO`, `SpooledTemporaryFile` or buffered files. ## Validation - New ownership, bounded-read, generator cancellation, OCR cleanup, native render parity and generic-stream tests pass locally; the original 13 also passed in an isolated Linux container. - Full PDF/OCR/utilities and new regression suite pass locally (with Korean OCR data installed). - OCR-only partitioning of rotated and content-bearing multi-page fixtures in a Linux container: every element matches the baseline JSON hashes exactly. - Large synthetic OCR-only PDF in a memory-limited Linux container: `main` runs out of memory where this branch completes at the same limit. With enough memory for both, peak RSS drops to under a third, runtime is unchanged and output hashes match. - Uploads opened through a `bytes` path are re-read from that path, leaving the caller's cursor untouched (regression test for text and binary modes). - Repository Ruff checks/format and the Linux version-sync checker pass. ## Operational impact OCR rendering reads uploads from temporary disk instead of holding a full upload-sized copy in memory. Spooled uploads (`SpooledTemporaryFile`) are still copied in full, briefly, by `spooled_to_bytes_io_if_needed` for the text-extraction check before the OCR branch; the saving is that this copy is not held while OCR runs. There is no new upload size cap. Working render memory is bounded by one page; extracted output and memory retained by callers still scale with content. Public render-generator images remain usable after iteration and are owned by the caller. ## Follow-up `_pdf_source_path` and `convert_to_bytes` (Unstructured-IO#4419) both decide how to read a given upload type. Once Unstructured-IO#4419 lands, both should use one shared helper in `unstructured/partition/common/common.py` that copies a stream to disk in blocks. ## Release Targets **0.27.32** (0.27.31 was taken by Unstructured-IO#4538, which merged first.) Released together with Unstructured-IO#4419, Unstructured-IO#4516, Unstructured-IO#4517, Unstructured-IO#4524, Unstructured-IO#4523, Unstructured-IO#4562 (XLSX workbook reader) and Unstructured-IO#4563 (dense worksheets). Each PR takes the next `0.27.32-devN` in that merge order (0.27.32-dev1 here); whichever merges after another rebases and renumbers the CHANGELOG heading, as usual for this repo.
…n memory (Unstructured-IO#4517) ## Summary A stream of empty images can hold every base64 payload until a later text element even when `include_orig_elements=False` and those image fields are dropped from output. Fold metadata incrementally for contiguous empty-image runs and release excluded image payloads immediately, preserving metadata order and chunk boundaries. Original-element serialization now adjusts and encodes one element at a time, escapes large JSON strings in bounded fragments (values without large strings still use one standard `json.dumps` call), and spills compressed buffers above 1 MiB to temporary disk. Avoid the redundant deep copy of the whole original-element graph in `ElementMetadata.to_dict()`. ## Validation - Chunking, original-element staging and element suites pass locally; the new regression cases also pass in an isolated Linux container. - 120 mixed-image/text/title/table/page-break cases with overlap preserve chunk boundaries and metadata against the identity-preserving path. Original Image identity remains intact with the default `include_orig_elements=True`. - Exact legacy JSON field order is preserved, including continuation metadata and empty originals. - Exact legacy compressed bytes match for empty inputs, multiple elements, long Unicode/control-character strings, metadata precision and sorted JSON keys on the same zlib implementation. - Many streamed large image payloads in a Linux container: chunking peak RSS drops to under a quarter and runs faster; serialization peak RSS drops by roughly an order of magnitude with slightly lower runtime. Output hashes match exactly. - Under a constrained container memory limit, both `main` cases run out of memory; both cases on this branch complete with no OOM events. - Metadata nested as deeply as the standard JSON encoder accepts still serializes: the large-string scan is iterative, not recursive (regression test with 600 nested lists). - Repository Ruff checks/format and the Linux version-sync checker pass. ## Operational impact Compressed original-element buffers above 1 MiB use temporary disk. Final serialized output and metadata actually included in chunks still require memory proportional to output. `include_orig_elements=True` continues retaining original objects; changing that identity contract would require a separate API decision. ## Release Targets **0.27.32** (0.27.31 was taken by Unstructured-IO#4538, which merged first.) Released together with Unstructured-IO#4419, Unstructured-IO#4516, Unstructured-IO#4517, Unstructured-IO#4524, Unstructured-IO#4523, Unstructured-IO#4562 (XLSX workbook reader) and Unstructured-IO#4563 (dense worksheets). Each PR takes the next `0.27.32-devN` in that merge order (0.27.32-dev2 here); whichever merges after another rebases and renumbers the CHANGELOG heading, as usual for this repo.
…tructured-IO#4562) ## What Adds a public way to read a workbook one worksheet at a time with the same protections `partition_xlsx()` uses: ```python from unstructured.partition.xlsx import open_excel_workbook with open_excel_workbook(file_bytes, compact_empty_rows=True) as workbook: for name in workbook.sheet_names: frame = workbook.parse(name, header=None) ... # release `frame` before parsing the next sheet ``` `open_excel_workbook()`: - rejects non-Office and password-protected files with `UnprocessableEntityError`, as `partition_xlsx()` does; - picks the engine from the file signature (`openpyxl` for XLSX, `xlrd` for XLS) and rejects anything else with `UnprocessableEntityError`; - runs the existing `XLSX_MAX_CELLS` worksheet cell-count check before any worksheet is read; - optionally reads with runs of empty rows compacted (XLSX only), as subtable detection already does; - closes the reader when the block exits, including on errors. `partition_xlsx()` now reads through the same function, so its behavior is unchanged. ## Why Integrations that need their own per-worksheet processing currently have two options: call `pandas.read_excel` directly, which skips the cell-count limit and reads every sheet into memory at once, or import private helpers (`_check_worksheet_cell_count`, `_RowCompactingOpenpyxlReader`) that can change without notice. A tiny file with one far-away cell can still expand into a huge dense data-frame through the first route. This gives such callers a supported, guarded entry point. ## Validation - New `test_xlsx_reader.py`: engine selection, password-protected rejection, cell-limit enforcement before reading (independent of the ambient `XLSX_MAX_CELLS`), empty-row compaction, repeated worksheet reads, and reader cleanup on success and on a consumer error. - XLSX partitioner suite passes unchanged; baseline-vs-branch workbook comparisons produce identical elements. - Ruff check/format pass. ## Release Targets **0.27.32** as `0.27.32-dev5` (0.27.31 was taken by Unstructured-IO#4538, which merged first.) Released together with Unstructured-IO#4419, Unstructured-IO#4516, Unstructured-IO#4517, Unstructured-IO#4524 and Unstructured-IO#4523, and followed by the stacked dense-worksheet PR. Whichever merges after another rebases and renumbers the CHANGELOG heading, as usual for this repo. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4562?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
…IO#4563) ## What `partition_xlsx()` with subtable detection (the default) needs substantially less memory on dense worksheets, and the saving grows with sheet size. Output is unchanged. On synthetic dense sheets (a ten-column sheet split into three dense subtables, half integers, half short Unicode strings), peak RSS in a fresh process drops by roughly 40–60% depending on size, with comparable runtime. Working memory per populated cell drops to roughly a third. Serialized element JSON is byte-identical before and after. ## Why Two whole-sheet intermediates dominated memory on dense sheets: 1. **Subtable detection built a NetworkX graph** with a node per populated cell and an edge per neighbor pair. It now uses an iterative four-neighbor flood fill over populated cells (the approach from Unstructured-IO#4357), with the same component admission order, cell membership, row-overlap merging, table order and bounding boxes. 2. **Table HTML was rendered for the whole table at once** (pandas `to_html` string, its parsed DOM and a full-table token list). Rows are now formatted by pandas' formatter for the whole column, so float/date/string formatting is unchanged, and each row is rendered and parsed on its own before the next. `networkx` is no longer needed at runtime by the XLSX partitioner, so it moves from the `xlsx` extra to the test dependencies (it's still used by other extras that depend on it). ## Behavior - Same elements, text, `text_as_html` and metadata; exact-output tests cover mixed types, NaN/empty cells, wide floats that switch to scientific notation in another row, dates and HTML escaping. - The renderer uses pandas' private formatter classes, as the existing reader already does for `OpenpyxlReader`. Verified on pandas 2.1.4 (renderer-parity comparisons), 2.2.3 and 2.3.3. - The worksheet cell limit, empty-row compaction, empty-sheet handling and XLS padding handling are unchanged. ## Validation - XLSX and dense-memory suites pass. New tests compare component detection and rendered HTML against the previous implementation on generated sheets. - Ruff check/format pass. ## Release Sets the release to **0.27.32** (0.27.31 was taken by Unstructured-IO#4538, which merged first). It merges after Unstructured-IO#4419, Unstructured-IO#4516, Unstructured-IO#4517 and Unstructured-IO#4562, and its CHANGELOG collects their entries and this one into a single 0.27.32 section. Unstructured-IO#4524 and Unstructured-IO#4523 are not included and will go into a later release. Supersedes Unstructured-IO#4357. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4563?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
…structured-IO#4524) ## Summary Restoring `orig_elements` now releases each intermediate buffer before the next stage builds its own copy. Previously the compressed bytes, decompressed bytes and JSON text all stayed alive until the end. Restoring one element that carries a very large image payload: - Peak memory drops by roughly a quarter. - Under a constrained memory limit, `main` runs out of memory and this branch completes. - Restored elements are identical. ## Behavior - Unchanged: - the Base64, zlib, UTF-8, JSON and element constructors; - restored values, metadata order and error behavior; - the existing 200 MiB decompressed-byte cap. - No new cap is added. The existing cap bounds UTF-8 bytes, not Python string size, so wide-Unicode JSON can still grow in memory. The full element graph is still returned. - This removes avoidable overlap between buffers. It does not guarantee that every input fits a fixed memory budget. ## Validation - Staging tests pass. New regression tests cover Unicode, nested originals, metadata and order, malformed input, trailing data and the exact size boundary. - A `tracemalloc` test checks that `json.loads` and element construction each start with only their own input alive. Removing any one of the three releases fails it. - The new tests also pass in an isolated Linux container against the module from this commit (import path and SHA256 verified). - Included benchmark: one element with a very large BMP stored as a Base64 payload. - Under a constrained memory limit, `main` runs out of memory. This branch completes with identical metadata, text and payload hash. - With enough memory for both, peak RSS falls as above; decode time is essentially unchanged. - Escaped wide-Unicode text and raw UTF-8 mixed with the image payload also restore identically, with a similar peak-memory reduction. - Ruff, diff checks and the version checker pass. ## Release Targets **0.27.32** (0.27.31 was taken by Unstructured-IO#4538, which merged first.) Released together with Unstructured-IO#4419, Unstructured-IO#4516, Unstructured-IO#4517, Unstructured-IO#4524, Unstructured-IO#4523, Unstructured-IO#4562 (XLSX workbook reader) and Unstructured-IO#4563 (dense worksheets). Each PR takes the next `0.27.32-devN` in that merge order (0.27.32-dev3 here); whichever merges after another rebases and renumbers the CHANGELOG heading, as usual for this repo. Unstructured-IO#4517 changes the serializing side of `orig_elements` in the same module. A test merge with this branch conflicts only on version and changelog lines, passes the staging, element and chunking suites, and round-trips identical elements.
…d-IO#4523) ## Summary Image and PDF figure extraction now frees each decoded page, crop and JPEG buffer as soon as it is no longer needed. Image uploads are copied to the temporary file in 1 MiB blocks instead of being held in memory whole. Extracting full-page figures from a very large synthetic image: - Peak memory drops by roughly 40%. - Under a constrained memory limit, `main` runs out of memory and this branch completes. - Output is byte-identical. ## What changed - Uploads are copied to the existing temporary file in 1 MiB blocks. - Decoded pages, RGBA intermediates, output crops and JPEG buffers are closed as soon as their pixels or bytes are used. ## Behavior - Unchanged: JPEG bytes, Base64 payloads, saved filenames, element order, metadata and padding. Caller-owned streams keep the same rewind/EOF behavior. - No size cap or disk policy is added; image uploads already used the same temporary file. - Output payloads, and the current page plus its crop, can still be large. ## Validation - Extraction/utility tests pass. They include: - exact JPEG bytes for RGB, RGBA and grayscale, in both payload and saved-file output; - bounded upload reads; - caller stream ownership and EOF; - multi-crop cleanup after an encoder failure. - The new regression tests also pass in an isolated Linux container against the module from this commit (import path and SHA256 verified). - Included benchmark (`scripts/performance/benchmark_image_extraction_memory.py`): full-page figures from a deterministic very-high-resolution image. - Under a constrained memory limit, `main` runs out of memory and this branch completes. - A healthy `main` run produces the same metadata and payload hash. - With enough memory for both, peak RSS falls as above and extraction is slightly faster. - This measures the extraction stage, not end-to-end partition latency. - Full native PDF/image suite passes. Ruff, diff checks and the version checker pass. ## Release Targets **0.27.32** (0.27.31 was taken by Unstructured-IO#4538, which merged first.) Released together with Unstructured-IO#4419, Unstructured-IO#4516, Unstructured-IO#4517, Unstructured-IO#4524, Unstructured-IO#4523, Unstructured-IO#4562 (XLSX workbook reader) and Unstructured-IO#4563 (dense worksheets). Each PR takes the next `0.27.32-devN` in that merge order (0.27.32-dev4 here); whichever merges after another rebases and renumbers the CHANGELOG heading, as usual for this repo. Unstructured-IO#4516 also edits `pdf_image_utils.py`, but a different function. Downstream dependency bumps need the published release.
What
Partitioning and file-type detection read a
SpooledTemporaryFileupload in place. They no longer copy the whole document into aBytesIOfirst.Two related robustness fixes come with it, since removing the detector copy exposes both:
detect_filetype(file=<rolled-over spool>, metadata_file_path="a.md").nameis an int fd, so extension lookup raisesTypeError(previously hidden by the copy).mdtaken frommetadata_file_pathconvert_to_bytes(tempfile.TemporaryFile())or any file-like wrapperValueError: Invalid file-like object type(text-encoding detection, PDF page rendering)A spool passed to
detect_filetype()still comes back at position 0, as before.Why
Python 3.11+ (this package's minimum) gives
SpooledTemporaryFilethe full buffered-I/O interface thatzipfile,pandasand the detectors need. TheBytesIOcopies were a <3.11 workaround, and each one is an extra heap allocation the size of the document. Fixing it here also removes the need for API callers to wrap uploads in proxy objects to avoid the copy.Release
Targets 0.27.32 (0.27.31 was taken by #4538, which merged first.) Released together with #4419, #4516, #4517, #4524, #4523, #4562 (XLSX workbook reader) and #4563 (dense worksheets). Each PR takes the next
0.27.32-devNin that merge order (0.27.32-dev0 here); whichever merges after another rebases and renumbers the CHANGELOG heading, as usual for this repo.Impact
Partitioning a large DOCX upload: peak memory drops by roughly the size of the document (the removed copy), with no change in latency.
Validation
convert_to_byteson generic streams. All fail without this change.file_utils,partition/common, DOCX, PPTX, text, XML, TSV, MD, HTML and auto suites: no new failures. The one existing test that read the detection context after closing the spool now asserts inside thewithblock.bytespath or a path object, text or binary, are still re-read from their path, so their cursor is untouched; a text file opened on a bare descriptor is read as bytes through its binary buffer (regression tests for each).