Repository navigation
perf: Free decode buffers sooner when restoring original elements - #4524
Conversation
|
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.
No issues found across 5 files
Shadow auto-approve: would not auto-approve. This PR does not meet the repository auto-approval settings.
Re-trigger cubic
0a5d6e5 to
c1dc2ab
Compare
There was a problem hiding this comment.
No issues found across 5 files
Shadow auto-approve: would not auto-approve. This PR does not meet the repository auto-approval settings.
View guided diff | Re-trigger cubic
c1dc2ab to
02215b9
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.
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.
Keep the original branch development version and authored release notes alongside the complete current main changelog. All runtime files equal the automatic merge of main.
Set version 0.27.33 under the established one-ahead-of-main convention. Preserve authored notes above the complete main changelog. All runtime files equal the automatic merge of main; sibling version reuse is expected.
…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. -->
# Conflicts: # CHANGELOG.md # unstructured/__version__.py
cragwolfe
left a comment
There was a problem hiding this comment.
Reviewed e6fe294 against main at cb82b55 with GPT Pro. No actionable source defects or material missing regression coverage found.
The buffer releases follow each input's last use and preserve decoding, size checks, errors, nested original elements, and metadata restoration. The change is compatible with the merged serialization and chunking changes in #4517 and #4565. The new lifetime and compatibility tests cover the intended behavior. Benchmark percentages remain author-reported; no local tests or benchmarks were run for this review.
Source approval is separate from CI readiness: required test_unit (3.12), test_ingest_src (3.12), and test_dockerfile checks are still in progress. Required lint, changelog, and Socket alert checks have passed.
(authored by codex)
# Conflicts: # CHANGELOG.md # unstructured/__version__.py
…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.
Drops the `-dev6` suffix so 0.27.34 can be tagged and published. There are no code changes. Since 0.27.33, this release contains: - Free decode buffers sooner when restoring original elements (Unstructured-IO#4524) - Free image buffers sooner during figure extraction (Unstructured-IO#4523) - Honor `encoding=` in `partition_json` and `partition_ndjson` (Unstructured-IO#4483) - Read a PowerPoint line break as a newline (Unstructured-IO#4571) - Drop the empty entry of an email address group (Unstructured-IO#4576) - Read CSV and TSV cells as the file holds them (Unstructured-IO#4574) - Classify text as an email address only when all of it is one (Unstructured-IO#4577) After merge, create the `0.27.34` GitHub release from the merge commit. That publishes to PyPI. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4582?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. -->
Summary
Restoring
orig_elementsnow 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:
mainruns out of memory and this branch completes.Behavior
Validation
tracemalloctest checks thatjson.loadsand element construction each start with only their own input alive. Removing any one of the three releases fails it.mainruns out of memory. This branch completes with identical metadata, text and payload hash.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-dev3 here); whichever merges after another rebases and renumbers the CHANGELOG heading, as usual for this repo.#4517 changes the serializing side of
orig_elementsin 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.