Repository navigation
Conversation
…ter-set detection `_disambiguate_json_file_type` reads the first 1 MiB of the source as bytes and decoded it with the declared encoding (UTF-8 unless the caller asserted otherwise) using `errors="ignore"`. Every byte that encoding could not decode was silently dropped, so a non-UTF-8 payload -- UTF-16 NDJSON written by Windows tooling, or JSON downloaded from an object store -- was mangled into text whose lines no longer parsed, and a multi-record payload classified as JSON instead of NDJSON. Decode that read through the same fallback character-set detection `text_head` already uses, extracted into `_decode_head_bytes()` and shared by both call sites: a strict decode, an incremental-decoder retry for a multi-byte character split at the read bound, then `detect_file_encoding()`. File-like objects and file paths both go through this decode. - `pytest test_unstructured/file_utils/test_filetype.py -q` -- 249 passed, 27 failed; the 27 are pre-existing in this Windows dev environment (libmagic unavailable, CRLF example-docs) and the failure set is identical on unmodified origin/main. - `pytest test_unstructured/file_utils/test_filetype.py -q -k "non_UTF8"` -- 4 passed. - With the decode reverted to `errors="ignore"`, the two new classification tests fail (JSON instead of NDJSON). - `ruff check .` and `ruff format --check .` -- clean. Refs Unstructured-IO#4434 (its `text_head` path was fixed by Unstructured-IO#4438; this closes the same class of gap in the remaining read path).
0991159 to
4a477d9
Compare
|
Rebased onto
The change itself is unchanged: Local validation, honestly: |
cragwolfe
left a comment
There was a problem hiding this comment.
Reviewed this head with GPT Pro. Two P2 boundary regressions remain in the new JSON/NDJSON decode path; details are inline. No High or Critical issue found.
No local tests or reproductions were run. At this head, required changelog, lint (3.12), and ingest checks have passed; required unit (3.12) and Docker checks are still running. This review does not establish completed CI.
(authored by codex)
| except (UnicodeDecodeError, UnicodeError): | ||
| decoder = codecs.getincrementaldecoder(encoding)() | ||
| try: | ||
| return decoder.decode(content, final=eof_reached) |
There was a problem hiding this comment.
[P2] Preserve explicit BOM-less UTF-16/32 semantics at the read boundary
For native-endian, BOM-less NDJSON with encoding="utf-16", a payload larger than 1 MiB makes the MAX+1 prefix end inside a code unit. The ordinary decoder accepts BOM-less native-endian input, but this incremental decoder requires a BOM. Its retry therefore falls into charset inference even though the caller supplied the correct encoding. With EncodingDetectionWarning promoted to an error, valid input that previously classified as NDJSON now fails. Generic utf-32 has the same distinction. For example, 70,000 repetitions of {"x":1}\n encoded as native-endian UTF-16 without a BOM cross this boundary.
Use a prefix decoder that preserves the selected codec’s BOM/native-order semantics while withholding an incomplete suffix. Add above-bound UTF-16/32 tests for paths and byte streams, with inference warnings treated as errors and an assertion that detection is not called.
(authored by codex)
There was a problem hiding this comment.
Fixed in c1687e0.
You were right that the incremental decoder is the wrong tool here: codecs.getincrementaldecoder("utf-16")().decode(prefix, final=False) fails with "Stream does not start with BOM" once the prefix carries no BOM, so a BOM-less native-endian payload above the bound fell through to charset inference. Measured on the reported shape (70,000 x {"x":1}\n as BOM-less UTF-16), the old path returned 1,048,577 characters -- the byte count standing in for the text -- instead of 524,288.
The retry is now _decode_prefix(): withhold one to four trailing bytes and retry the plain bytes.decode() with the declared encoding, which keeps that codec's BOM detection and native byte order exactly as they are for a whole file. It only withholds when eof_reached=False, and only when the decode failure is within the last four bytes -- a failure further from the end is a wrong encoding, not a split character, and still goes to inference.
Coverage added:
and_it_decodes_a_BOM_less_prefix_cut_inside_a_code_unit[utf-16|utf-32]-- theMAX + 1prefix of a BOM-less payload decodes to exactly the withheld prefix's text, withdetect_file_encodingpatched out and asserted not called. Old code: 1,048,577 characters instead of 524,288 / 262,144.and_it_classifies_above_bound_BOM_less_UTF16_and_UTF32_payloads_as_NDJSON[utf-16|utf-32]-- the same payload as a byte stream and as a file path, withencoding=asserted,EncodingDetectionWarningpromoted to an error, and detection asserted not called. Old code classified both asFileType.JSON.
| head | ||
| if isinstance(head, str) | ||
| else head.decode(encoding=self._ctx.encoding, errors="ignore") | ||
| else _decode_head_bytes(head, self._ctx.encoding, eof_reached=not truncated) |
There was a problem hiding this comment.
[P2] Establish actual EOF before finalizing a short stream read
A seekable raw stream or adapter may return fewer bytes than requested while more data remains. If a BOM-prefixed UTF-16 JSON stream returns 4,095 bytes here, the prefix ends inside a code unit. Because len(head) is below MAX, the current truncation expression skips the probe, and this call receives eof_reached=True. Both strict decode attempts fail; BOM-aware fallback then finalizes the same incomplete prefix and raises UnprocessableEntityError for a valid document. The previous permissive decode returned JSON in this case.
Accumulate reads within the existing bound until the limit or an empty read establishes EOF, then retain the extra size probe. Add a seekable short-read regression that checks classification, the read budget, position zero, and continued caller ownership, plus a genuine malformed-EOF case.
(authored by codex)
There was a problem hiding this comment.
Both fixed in c1687e0.
The read is now accumulated by _read_prefix(file, MAX + 1): it keeps reading until the budget is spent or an empty read proves EOF, so a short read no longer ends the prefix. The size probe past the bound is unchanged, and an empty source still hands back its own empty read so the text/bytes type is preserved.
Test and_it_reads_past_a_short_read_until_the_budget_or_EOF uses a 4095-byte-at-a-time seekable stream over an 8-byte-record NDJSON payload:
- classification is
FileType.NDJSON(it raisedUnprocessableEntityErrorwith the single read restored, which is the reported failure); - the prefix reads start at position 0, the largest returned chunk is exactly 4095, and they sum to exactly
MAX + 1, followed by the one-byte probe atMAX + 1; - no read in the log requests more than
MAX + 1, the handle is at position 0 when detection returns, it is still open, and a follow-up read from 0 returns the payload's first bytes.
The genuine malformed-EOF case is and_it_still_fails_a_prefix_whose_tail_is_missing_at_EOF: the same bytes with the last byte dropped still raise UnprocessableEntityError at eof_reached=True, and at eof_reached=False the decoded text differs from the whole document by exactly the withheld character. A sub-bound short read is also covered: an empty read stops the accumulation at exactly len(payload).
…at the bound Two boundary defects in the JSON/NDJSON disambiguation read, both raised in review of the previous commit. A single `read(n)` does not establish EOF: a raw stream or adapter may return fewer bytes while more data remains. Reading the prefix with one call meant a short read was treated as the end of the document, so a UTF-16 payload delivered 4095 bytes at a time had its prefix cut inside a code unit, both decode attempts failed, and a valid NDJSON document raised `UnprocessableEntityError`. `_read_prefix()` now accumulates until the budget is spent or an empty read proves EOF, and the size probe past the bound is unchanged. The retry for a character split at the boundary no longer uses `codecs.getincrementaldecoder()`. That decoder re-runs BOM detection over the prefix, which no longer carries a BOM, so it refuses BOM-less native-endian UTF-16/32 that the plain codec accepts -- a 70,000-record BOM-less UTF-16 NDJSON payload above the bound decoded through character-set inference into the byte count in characters. `_decode_prefix()` instead withholds one to four trailing bytes and retries the declared codec, which keeps BOM handling and byte order exactly as they are for a whole file. A failure further from the end is a wrong encoding, not a split character, and `eof_reached=True` never withholds: a tail missing at the end of the document stays a decode failure. - `pytest test_unstructured/file_utils/test_filetype.py -q` -- 278 passed, 27 failed; the 27 are pre-existing in this Windows dev environment (libmagic unavailable or replaced by a stand-in module because python-magic's DLL search hangs here) and the failure set is identical on the same file without this commit. - With the previous decode and the single read restored, the five new boundary tests fail: the BOM-less prefix decodes to 1048577 characters instead of 524288, both above-bound classification cases fall to JSON, and the short-read stream raises `UnprocessableEntityError`. - `ruff check` and `ruff format --check` -- clean on both files. Refs Unstructured-IO#4434, Unstructured-IO#4494
|
Both P2s are addressed in c1687e0, in one commit on top of the reviewed head. Short reads. The prefix is now read by Codec byte order at the bound. New tests, all RED against the previous head and green now:
Validation actually run here: The 27 failures are libmagic-dependent and pre-existing in this environment: python-magic's DLL search hangs on this Windows host, so I ran with a stand-in |
cragwolfe
left a comment
There was a problem hiding this comment.
Reviewed c1687e013ae3e8e42c586fad38564627d9c912b7 against base 07d978b8c182404b800fba27c01f4a2c633cfffc with GPT Pro. Both previous P2 findings are resolved. One new P2 remains; no High or Critical issue was found.
P2 — Only trim a genuinely incomplete character, not an invalid suffix (unstructured/file_utils/filetype.py:221–230). _decode_prefix() removes trailing bytes until the declared codec accepts the remainder, but proximity to the boundary does not prove the bytes are incomplete. It can delete a complete character and valid punctuation, then skip encoding fallback.
For example, consider this valid UTF-8 byte stream with encoding="ascii", no filename extension, and a guessed MIME type of text/plain:
payload = b"a,b\n" + b"a" * 4089 + b"\xc3\xa9,rest\n"The first 4,096 bytes end with the complete UTF-8 é and the following comma. Because more data follows, text_head enables prefix trimming. Removing three bytes drops both the character and comma, makes ASCII decoding succeed, and bypasses fallback. _is_csv then rejects the second row because its delimiter disappeared, changing CSV classification to TXT. Previously, the invalid ASCII decode reached the deterministic UTF-8 fallback and preserved the comma. This example is derived from source; I did not execute it.
Keep fallback for bytes that are already invalid under the declared codec. Withhold only an incomplete suffix, while preserving the repaired BOM-less native-endian UTF-16/32 behavior. Add a regression for the example above with MIME detection fixed to text/plain, alongside the genuine incomplete-character cases.
The reported short-read and BOM-less UTF-16/32 cases are repaired in the current source and covered by the new tests; I am not repeating those findings.
Maintainer compatibility decision: replacing permissive byte deletion in JSON disambiguation with fallback means detection can now raise UnprocessableEntityError, emit EncodingDetectionWarning, or fail when warnings are promoted to errors. Please explicitly accept and document that behavior and its release treatment. Improved detection alone does not establish end-to-end non-UTF-8 partitioning support.
No local tests or reproductions were run. At this head, only one successful Socket Security check and one neutral check were returned; full test CI is missing. GitHub reports conflicts with current main. Separately, CHANGELOG.md and unstructured/__version__.py differ from current main and need release-policy reconciliation. CHANGELOG.md and uv.lock were excluded from the Pro review. This review does not establish integration readiness.
(authored by codex)
# Conflicts: # CHANGELOG.md # unstructured/__version__.py
Retrying with a shorter prefix treated proximity to the read boundary as proof that the trailing
bytes were an unfinished character. A complete character the declared codec rejects produces the
same shorter-prefix result, so an ASCII-asserted CSV whose 4096-byte read ended on a UTF-8 `é`
and the comma after it had both deleted, ASCII accepted the remainder, the character-set fallback
that decodes them never ran, and the second row lost its delimiter -- the file classified TXT
instead of CSV.
Only the reasons a codec reports for finding the end of data inside a character ("unexpected end
of data", "truncated data", "incomplete multibyte sequence") describe a boundary split now, and
the withheld tail starts at the first rejected byte, so the longest decodable prefix is kept and
no decodable byte is dropped. Bytes a codec rejects outright fall through to character-set
detection, as they did before the prefix retry existed.
Refs Unstructured-IO#4434, Unstructured-IO#4494
The prefix retry passed a test that only asked whether the text decoded: a complete character deleted from the tail also decodes. These pin which bytes the retry is allowed to withhold. The end-to-end case is the reported one -- an ASCII-asserted CSV whose 4096-byte read ends on UTF-8 `é` and the comma after it -- asserted through `detect_filetype()` with the guessed MIME type fixed to text/plain, and through the text the classification consumed (`text_head` keeps the `é,`). The unit table states both sides of the distinction per codec: an unfinished character is withheld and the decodable prefix kept (UTF-8, UTF-16, Shift-JIS lead byte), while bytes the codec rejects outright, a wrong encoding further from the end, and a read that is entirely one unfinished character all return `None` so character-set detection decides. Red on the parent commit, with the retry restored and these tests in place: 30 failed, 3 of them these (the ASCII `é,` case returned the trimmed text instead of `None`, `ab\xff` returned "ab", and the end-to-end case classified TXT). Green at this head: `pytest test_unstructured/file_utils/test_filetype.py` -- 292 passed, 27 failed, and the 27 are the libmagic-dependent tests that fail identically on the parent commit (libmagic is unavailable in this Windows dev environment; the same file's failure list is unchanged). Refs Unstructured-IO#4494
|
Rebased onto P2 — trim only a character the codec reports as unfinished. You were right that proximity to the boundary proved nothing. The retry now asks the codec what the failure was and withholds the tail only for its incomplete-sequence reasons ( Your example is the regression test, Whole file: Behaviour change, explicitly accepted and documented. Detection now raises Release policy and conflicts. |
|
Correction on the SHAs above: the two commits on the pushed head are |
cragwolfe
left a comment
There was a problem hiding this comment.
Reviewed d53e7fc5efb9b0b6ad291c6acbd6a23658b3d6ec against base e5dafa419b2b66d98da892b28f6fb38eb573c1d0 with GPT Pro. The earlier ASCII/CSV delimiter finding is fixed. One different P2 regression remains; no High or Critical issue was found.
P2 — Preserve the byte offset when decoding UTF-8 with a BOM (unstructured/file_utils/filetype.py:237–243). Python's utf-8-sig decoder removes the three-byte BOM before reporting a UnicodeDecodeError offset. _decode_prefix() applies that offset to the original buffer, so it can drop three valid bytes before a genuinely incomplete trailing character. If that slice cuts an earlier multibyte character, its second decode raises an uncaught UnicodeDecodeError on valid input. It can also silently remove a CSV delimiter and change the detected type to TXT.
For example, with a BOM-prefixed CSV stream, encoding="utf-8-sig", no extension, and MIME detection fixed to text/plain, this valid payload crosses the 4,096-byte text-head boundary inside é:
payload = b"\xef\xbb\xbf" + b"a,b\n" + b"a" * 4087 + b",\xc3\xa9rest\n"The decoder reports an offset relative to the bytes after the BOM. The current slice removes the second row's comma as well as the incomplete suffix, so _is_csv() rejects the file. A similar boundary in JSON disambiguation can raise when the incorrect slice splits an earlier complete multibyte character.
Use a prefix decoding approach that accounts for the codec's transformed buffer, while retaining the existing BOM-less native-endian UTF-16/32 behavior. Add path and stream regressions for BOM-prefixed utf-8-sig, including a preceding multibyte character and the CSV delimiter case; assert that all complete characters survive and no inference warning occurs. Catching the second exception alone would not fix silent byte loss.
The prior short-read, BOM-less UTF-16/32, and ASCII delimiter findings are addressed in the current source and tests. The compatibility decision remains separate: detection can now raise an encoding error or emit EncodingDetectionWarning, including when warnings are treated as errors. Maintainers should explicitly decide the behavior and release treatment. Improved detection alone does not establish end-to-end non-UTF-8 support.
No local tests or reproductions were run. GitHub reports two successful Socket checks on this head; full test CI is not established. Separately, unstructured/__version__.py differs from current main (e43c6da); reconcile it with release policy. CHANGELOG.md and uv.lock were excluded from the Pro review. This review does not establish integration readiness.
(authored by codex)
…offset `utf-8-sig` strips its three BOM bytes before reporting a `UnicodeDecodeError` offset, so `_decode_prefix()` applying that offset to the original buffer deleted three decodable bytes ahead of the cut. A BOM-prefixed CSV read at the boundary lost the row delimiter that sat there and classified as TXT, and a complete multibyte character before the cut could be split by the retry. The withheld length is now measured from the end of the prefix, so the whole buffer, BOM included, reaches the plain codec and only trailing unfinished bytes are dropped. The incomplete-sequence guard on the failure reason is unchanged.
|
P2, BOM offset. You were right that the offset is in the wrong space.
Regressions, stream and path:
On the compatibility decision, agreed that it is the maintainers'. I have not changed that behaviour here beyond the boundary trim: CI: Socket is green on |
|
@cragwolfe — the BOM-offset P2 went in on 30 Oct in Locally: 296 passed with the same 27 libmagic-dependent failures as the unmodified head ( |
Summary
_FileTypeDetector._disambiguate_json_file_type()read the first 1 MiB of the source as bytes and decoded it with the declared encoding (UTF-8 unless the caller asserted otherwise) usingerrors="ignore". Every byte that encoding could not decode was silently dropped, so a non-UTF-8 payload was mangled into text whose lines no longer parsed. A multi-record payload therefore classified asFileType.JSONinstead ofFileType.NDJSON:The same read path is used for file paths, so a
.jsonfile holding UTF-16 NDJSON was misclassified the same way.Fix
text_headalready decoded through fallback character-set detection; that logic is now extracted into_decode_head_bytes()and shared by both call sites:_decode_prefix()withholds only the trailing bytes the codec itself reports as an unfinished sequence, and only within one encoding unit of the end;detect_file_encoding(file=content)— the same charset-normalizer + common-encoding fallback the file-path branch uses.Step 2 distinguishes a read cut inside a character from bytes the codec rejects outright, which is the difference between "the rest of this character was not in this read" and "this byte sequence does not belong to this encoding". Only the codec's own incomplete-end reasons (
unexpected end of data,truncated data,incomplete multibyte sequence) count, and the withheld tail starts exactly at the first rejected byte, so the longest decodable prefix is kept and nothing decodable is dropped. Bytes the codec rejects fall through to step 3.No behaviour change for payloads the declared encoding can decode;
errors="ignore"is gone from the disambiguation read.Behaviour change and release treatment
Review asked for this to be stated explicitly. Two user-visible effects, both inherited from the
text_headcontract this read now shares rather than new inventions:UnprocessableEntityErrorinstead of silently stripping bytes. Previously such a payload classified asJSON/TXTwith characters missing, and only the partitioner raised later (or not at all). This is the deliveredtext_headbehaviour, and the file-path branch has always had it.EncodingDetectionWarning, which callers can promote to an error; the declared-encoding path stays warning-free.Scope: only sources whose payload is neither the declared encoding nor any common encoding change outcome. Accepting this means detection no longer reports a confident file type for content it cannot read, which is the point of the fix. If accepted, the PR title carries the fix into generated release notes; the user-facing detail below can go into the release's note body.
Relation to #4434
#4434 asks for fallback encoding detection for file-like objects. Its
text_headhalf was already fixed and merged by #4438 (released in 0.26.3), so this PR does not re-fix that path — it closes the same class of gap in the remaining read path in the same module, where the file-like/SpooledTemporaryFile-from-S3/GCS scenario the issue describes still lost characters. The issue can be closed once this lands.Validation
Environment: Windows 11, Python 3.12.10, branch rebased onto
main(e5dafa4).The 27 failures are pre-existing environment artifacts, not caused by this branch. On this Windows dev box
python-magiccannot load libmagic (the loader picks up Git's MSYSmsys-magic-1.dlland hangs the interpreter), so every libmagic-dependent test fails. Running the same file with the source change reverted gives30 failed: the same 27 plus exactly the 3 new assertions, and the diff of the twoFAILEDlists contains only those 3.Both directions for the new assertions — with the previous retry (withhold one to four trailing bytes) restored:
The unit table also states the side that must keep working: an unfinished character is withheld and the decodable prefix kept (UTF-8 2/3/4-byte, UTF-16, UTF-32, Shift-JIS/GBK lead byte), while rejected bytes, a failure further from the end, and a read that is entirely one unfinished character return
Noneso detection decides.Not run locally: the libmagic-dependent tests above and the wider
test_unstructuredsuite; CI is the oracle for those.Release note
Detection of JSON/NDJSON for a source whose bytes are neither the asserted encoding nor any common character encoding now fails with
UnprocessableEntityErrorinstead of returning a file type based on text with every undecodable byte stripped. Payloads that are valid in a common encoding decode as before, through character-set detection when the asserted encoding does not apply, and a detected legacy or BOM-less UTF-16/32 encoding raisesEncodingDetectionWarning. Migration: passencoding=for a source whose encoding is known, or decode before upload; callers that prefer an exception to a guessed encoding can promoteEncodingDetectionWarningto an error.Checklist
enhancement,bug, or an appropriate existing label), or ask a maintainer to apply it.!in the title and explain impact and migration above.CHANGELOG.mdandunstructured/__version__.pyare untouched: perd1535fe(#4578) ordinary PRs no longer edit the frozen changelog or advance the development version, so the release note lives above and in the PR title. That also clears the conflicts this branch had with currentmain.