Skip to content

perf(chunking): bound image payload and original-element serialization memory - #4517

Merged
CyMule merged 14 commits into
mainfrom
perf/bound-orig-element-serialization-memory
Oct 20, 2026
Merged

CyMule merged 14 commits into
mainfrom
perf/bound-orig-element-serialization-memory

Conversation

@CyMule

@CyMule CyMule commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

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 #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-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.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 8 files

Shadow auto-approve: would not auto-approve because issues were found.

Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 1 file (changes from recent commits).

Shadow auto-approve: would not auto-approve. This PR does not meet the repository auto-approval settings.

Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 5 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="unstructured/staging/base.py">

<violation number="1" location="unstructured/staging/base.py:284">
P2: `_has_large_string` ignores dictionary keys, so a large key in valid metadata such as `data_source.record_locator` bypasses bounded fragmentation and allocates the entire JSON value in one fragment. Include keys in this traversal.</violation>
</file>

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

Comment thread unstructured/staging/base.py Resolved
@CyMule CyMule changed the title perf(chunking): bound image payload and original-element serialization memory (0.27.12) perf(chunking): bound image payload and original-element serialization memory (0.27.14) Oct 2, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Re-trigger cubic

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 8 files

Shadow auto-approve: would not auto-approve because issues were found.

Re-trigger cubic

@CyMule
CyMule force-pushed the perf/bound-orig-element-serialization-memory branch from b8b3e7b to 1b6fc93 Compare October 20, 2026 16:54
@CyMule CyMule changed the title perf(chunking): bound image payload and original-element serialization memory (0.27.14) perf(chunking): bound image payload and original-element serialization memory Oct 20, 2026
@CyMule

CyMule commented Oct 20, 2026

Copy link
Copy Markdown
Contributor Author

@cubic review

@cubic-dev-ai

cubic-dev-ai Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

@cubic review

@CyMule I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread unstructured/chunking/base.py Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Values without a string longer than the fragment size are emitted with one
json.dumps call, so typical original elements no longer pay the per-node
generator cost. Large strings are still escaped in bounded fragments.
@CyMule
CyMule force-pushed the perf/bound-orig-element-serialization-memory branch from 933c6a0 to 741409f Compare October 20, 2026 17:40

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 741409f against main 3f716e2. One P2 performance regression remains in original-element serialization; see the inline finding. The four prior findings are addressed in the current source.

Exact-head unit, ingest, lint, changelog, and security checks passed; Docker remains running. No local tests were run.

(authored by codex)

Comment thread unstructured/staging/base.py Outdated
raise ValueError("Circular reference detected")
active_containers.add(container_id)
try:
if not _has_large_string(value):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Avoid rescanning every descendant at each nesting level

Each _Nested value calls _json_parts() again, which starts another full _has_large_string() traversal. For valid metadata.data_source.record_locator containing a 70,000-character leaf inside 300 lists, each with 1,000 zeros before its nested child, the scans visit those zeros 1,000 × (300 + 299 + … + 1) = 45,150,000 times for roughly 1 MB of JSON, before emission and compression. The previous implementation encoded the graph once. This introduces CPU amplification and longer worker occupancy for nested metadata; the visit count follows from the loops, rather than a measured timing.

Classify containers once per element with cycle-aware reusable results, or emit without restarting descendant scans. Keep state local to the element to preserve streaming memory behavior. Add a deterministic traversal-work regression with broad prefixes and a large leaf, alongside byte-parity, cycle, and shared-container checks.

(authored by codex)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 11ee43b. Containers are now classified once per element in a single cycle-aware post-order pass (_containers_with_large_strings, shared containers reuse their result), and emission looks the classification up instead of restarting descendant scans. Added test_nested_large_strings_are_classified_once_per_container (60 levels × 200 prefix items + a large leaf): item visits drop from 367,830 to at most one per item, with byte parity against the sorted standard encoder; the existing cycle, shared-container and deep-nesting tests still pass. Your 300 × 1,000 example now serializes in ~0.4 s locally with identical bytes.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Shadow auto-approve: would not auto-approve. Auto-approval skipped because cubic reviewed only this push, not the earlier force-push. Comment @cubic review to review the whole pull request.

View guided diff | Re-trigger cubic

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 11ee43b against main 3f716e2. No actionable findings remain after a full GPT Pro source review and verification against the current code and tests.

The previous P2 repeated descendant scans are fixed: containers are classified once per element, shared containers reuse their result, and emission uses the classification without rescanning descendants. The new regression checks traversal work and JSON byte parity. The four earlier findings remain resolved.

Exact-head lint, ingest, changelog, and security checks passed. Unit, PDF-image, and Docker checks are still running, so this approval does not establish that CI is complete. No local tests were run.

(authored by codex)

Resolve changelog and version conflicts by retaining both release-note
sections and the existing branch development version. Runtime files match
the automatic base merge.
# Conflicts:
#	CHANGELOG.md
#	unstructured/__version__.py
@CyMule
CyMule enabled auto-merge October 20, 2026 20:28
@CyMule
CyMule added this pull request to the merge queue Oct 20, 2026
Merged via the queue into main with commit 73b4295 Oct 20, 2026
54 checks passed
@CyMule
CyMule deleted the perf/bound-orig-element-serialization-memory branch October 20, 2026 21:23
joaquinhuigomez pushed a commit to joaquinhuigomez/unstructured that referenced this pull request Oct 20, 2026
…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.
joaquinhuigomez pushed a commit to joaquinhuigomez/unstructured that referenced this pull request Oct 20, 2026
…#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.
linhongyu510 pushed a commit to linhongyu510/unstructured that referenced this pull request Oct 21, 2026
…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. -->
linhongyu510 pushed a commit to linhongyu510/unstructured that referenced this pull request Oct 21, 2026
…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. -->
feiiiiii5 pushed a commit to feiiiiii5/unstructured that referenced this pull request Oct 21, 2026
…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.
linhongyu510 pushed a commit to linhongyu510/unstructured that referenced this pull request Oct 21, 2026
…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.
anupamgit pushed a commit to anupamgit/unstructured that referenced this pull request Nov 18, 2026
…ructured-IO#4744)

## Problem

With table isolation enabled (the default), `PreChunkBuilder.will_fit()`
scans every accumulated element to decide whether a table is already
present. Repeating this for every new element makes admission quadratic
in the number of elements in a pre-chunk. Text-size limits do not bound
a run of images without extracted text, and the default
`include_orig_elements=True` retains those images individually.

For 300 empty images followed by one text element, the existing public
chunking path performs 45,452 table-family checks.

## Change

Record whether a table-family element has been added, update that flag
during admission, and reset it with the rest of the builder state before
`flush()` yields. The existing `isinstance(Table)` predicate also covers
`TableChunk` subclasses. No original elements, metadata, chunk
boundaries, overlap rules or table-isolation behavior are changed.

This is separate from Unstructured-IO#4517, which compacts excluded image payloads when
`include_orig_elements=False`; the repeated scan still affects the
default mode that preserves originals.

## Validation

- A deterministic linear-work budget exercises both the list and lazy
public chunking APIs. On unchanged source: **2 failing work-bound
regressions and 4 passing controls**. The two failures perform 45,452
checks instead of meeting a 1,204-check bound.
- Controls cover the existing compacted-image path, preserved source
object identity, metadata and the reset timing for `Table`/`TableChunk`
before a flush iterator is exhausted.
- **510 tests pass** across the new regressions and existing base,
basic, title and table-isolation suites.
- Ruff lint/format and `git diff --check` pass. An independent read-only
review found no state-lifecycle regression. No complete repository suite
was run.

## Measurements

Local Python 3.12, seven alternating before/after pairs with collection
before each call. The benchmark invokes public `chunk_elements()` using
the exact baseline/current builder methods; input construction and
result serialization are outside the timer. Images contain empty text
and page-number metadata, followed by one visible text element.

| Input | Preserve originals | Before median | After median |
| --- | --- | ---: | ---: |
| 100 images | Yes (default) | 1.162 ms | 0.379 ms |
| 1,000 images | Yes (default) | 78.745 ms | 2.369 ms |
| 5,000 images | Yes (default) | 2,029.488 ms | 11.035 ms |
| 5,000 images | No | 22.358 ms | 21.071 ms |
| 5,000 short text elements, 20,000-character window | Yes | 1,959.048
ms | 11.632 ms |

All serialized content and metadata fingerprints match after excluding
only newly generated chunk UUIDs, which differ between identical
unmodified calls too. Original-element metadata remains in the
comparison. These synthetic measurements cover chunking
already-partitioned elements, not file parsing or whole ingestion
throughput.

Suggested label: `enhancement`.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4744?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. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants