fix(partition): read spooled uploads in place instead of copying them
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 #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-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_byteson 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 thewithblock. - Files named by a
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). - 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.