Repository navigation
perf(xlsx): reduce dense-worksheet partitioning memory - #4563
Conversation
There was a problem hiding this comment.
All reported issues were addressed across 7 files
Shadow auto-approve: would not auto-approve because issues were found.
View guided diff | Re-trigger cubic
d3234e1 to
ad25c14
Compare
cragwolfe
left a comment
There was a problem hiding this comment.
Reviewed commit ad25c14 against its actual stacked base, feat/xlsx-protected-workbook-reader at 4d8418c, with GPT Pro. No actionable introduced defects found.
The flood fill preserves populated-cell admission, four-neighbor connectivity, component order, and the existing overlap-merging behavior. The renderer retains whole-column pandas formatting and the existing cell normalization while avoiding the full-table HTML tree. NetworkX is removed from runtime usage and retained for comparison tests.
This is source approval, with execution limits: no local tests or benchmarks were run. At this exact head, GitHub reports no Actions runs or required checks for the stacked base. CI and CodeQL target main, so the successful external review/security checks do not establish test execution. Run the normal CI suite when this change targets main before merging.
Memory use is reduced, not capped: pandas formatted columns, component traversal storage, and final text/HTML still scale with the input. The author’s performance measurements were not independently verified.
(authored by codex)
4d8418c to
ca90089
Compare
ad25c14 to
7c31fee
Compare
Resolve changelog and version conflicts by retaining both release-note sections and the existing branch development version. Runtime files match the automatic base merge.
Keep the original branch development version and authored release notes above the complete current main changelog. All runtime files equal the automatic merge of main.
# Conflicts: # CHANGELOG.md # unstructured/__version__.py
Keep the original branch development version and authored release notes above the complete current main changelog. All runtime files equal the automatic merge of main.
…Unstructured-IO#4419) ## What Partitioning and file-type detection read a `SpooledTemporaryFile` upload in place. They no longer copy the whole document into a `BytesIO` first. ``` Before: upload spool (disk) → BytesIO copy in detect_filetype → BytesIO copy in DOCX/PPTX/PDF/TSV/XML partitioner After: upload spool (disk) → read in place by both ``` Two related robustness fixes come with it, since removing the detector copy exposes both: | Input | Before | After | |---|---|---| | `detect_filetype(file=<rolled-over spool>, metadata_file_path="a.md")` | `.name` is an int fd, so extension lookup raises `TypeError` (previously hidden by the copy) | `.md` taken from `metadata_file_path` | | `convert_to_bytes(tempfile.TemporaryFile())` or any file-like wrapper | `ValueError: Invalid file-like object type` (text-encoding detection, PDF page rendering) | bytes, stream rewound | A spool passed to `detect_filetype()` still comes back at position 0, as before. ## Why Python 3.11+ (this package's minimum) gives `SpooledTemporaryFile` the full buffered-I/O interface that `zipfile`, `pandas` and the detectors need. The `BytesIO` copies 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 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-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 - New regression tests for in-place detection (in-memory and rolled-over spools), the non-string-name fallback, and `convert_to_bytes` on generic streams. All fail without this change. - Before/after comparison over `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 the `with` block. - Files named by a `bytes` path 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). - Non-seekable streams (a pipe or subprocess stdout, binary or text) are read once instead of failing on a rewind (regression tests for both modes). - Ruff check/format pass.
…#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.
# Conflicts: # CHANGELOG.md # unstructured/__version__.py # unstructured/partition/xlsx.py
Version 0.27.34 with this branch's changelog section on top. main reads worksheets through ExcelWorkbookReader.parse now (Unstructured-IO#4562, Unstructured-IO#4563), so the dtype=object read moves there; it reaches partition_xlsx and open_excel_workbook() callers alike.
…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
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:
to_htmlstring, 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.networkxis no longer needed at runtime by the XLSX partitioner, so it moves from thexlsxextra to the test dependencies (it's still used by other extras that depend on it).Behavior
text_as_htmland metadata; exact-output tests cover mixed types, NaN/empty cells, wide floats that switch to scientific notation in another row, dates and HTML escaping.OpenpyxlReader. Verified on pandas 2.1.4 (renderer-parity comparisons), 2.2.3 and 2.3.3.Validation
Release
Sets the release to 0.27.32 (0.27.31 was taken by #4538, which merged first). It merges after #4419, #4516, #4517 and #4562, and its CHANGELOG collects their entries and this one into a single 0.27.32 section. #4524 and #4523 are not included and will go into a later release.
Supersedes #4357.