Skip to content

fix(filetype): decode JSON/NDJSON disambiguation with fallback character-set detection - #4494

Open
ayam04 wants to merge 8 commits into
Unstructured-IO:mainfrom
ayam04:fix/json-ndjson-disambiguation-encoding-fallback
Open

ayam04 wants to merge 8 commits into
Unstructured-IO:mainfrom
ayam04:fix/json-ndjson-disambiguation-encoding-fallback

Conversation

@ayam04

@ayam04 ayam04 commented Sep 22, 2026 •

Copy link
Copy Markdown

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) using errors="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 as FileType.JSON instead of FileType.NDJSON:

>>> import io, json
>>> from unstructured.file_utils.filetype import detect_filetype
>>> records = [{"sku": "GRD-8842"}, {"sku": "GRD-1290"}]          # UTF-16, e.g. Windows tooling
>>> payload = "\n".join(json.dumps(r) for r in records).encode("utf-16")
>>> detect_filetype(file=io.BytesIO(payload), content_type="application/json")
<FileType.JSON: 'json'>        # before -- the read decoded to '{\x00"\x00s\x00k\x00u\x00...'
<FileType.NDJSON: 'ndjson'>    # after

The same read path is used for file paths, so a .json file holding UTF-16 NDJSON was misclassified the same way.

Fix

text_head already decoded through fallback character-set detection; that logic is now extracted into _decode_head_bytes() and shared by both call sites:

  1. strict decode with the declared encoding;
  2. on failure, _decode_prefix() withholds only the trailing bytes the codec itself reports as an unfinished sequence, and only within one encoding unit of the end;
  3. on failure, 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_head contract this read now shares rather than new inventions:

  • Undecodable content fails loudly. When neither the declared encoding nor any common encoding decodes the content, detection raises UnprocessableEntityError instead of silently stripping bytes. Previously such a payload classified as JSON/TXT with characters missing, and only the partitioner raised later (or not at all). This is the delivered text_head behaviour, and the file-path branch has always had it.
  • Inferred encodings still warn. A legacy or BOM-less UTF-16/32 payload decoded through detection emits 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_head half 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).

$ python -m pytest test_unstructured/file_utils/test_filetype.py -q
27 failed, 292 passed in 5.76s

$ python -m pytest test_unstructured/file_utils/test_filetype.py -q -k "read_boundary or cut_character"
9 passed, 305 deselected in 0.86s

$ ruff check unstructured/file_utils/filetype.py test_unstructured/file_utils/test_filetype.py
All checks passed!
$ ruff format --check unstructured/file_utils/filetype.py test_unstructured/file_utils/test_filetype.py
2 files already formatted

The 27 failures are pre-existing environment artifacts, not caused by this branch. On this Windows dev box python-magic cannot load libmagic (the loader picks up Git's MSYS msys-magic-1.dll and hangs the interpreter), so every libmagic-dependent test fails. Running the same file with the source change reverted gives 30 failed: the same 27 plus exactly the 3 new assertions, and the diff of the two FAILED lists contains only those 3.

Both directions for the new assertions — with the previous retry (withhold one to four trailing bytes) restored:

FAILED ...::and_it_keeps_a_complete_character_at_the_read_boundary_in_the_text_it_classifies
    assert <FileType.TXT: 'txt'> is <FileType.CSV: 'csv'>
FAILED ...::it_decodes_a_cut_character_without_dropping_a_rejected_one[a,b\naaaa...\xc3\xa9,-ascii-None]
FAILED ...::it_decodes_a_cut_character_without_dropping_a_rejected_one[ab\xff-ascii-None]

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 None so detection decides.

Not run locally: the libmagic-dependent tests above and the wider test_unstructured suite; 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 UnprocessableEntityError instead 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 raises EncodingDetectionWarning. Migration: pass encoding= for a source whose encoding is known, or decode before upload; callers that prefer an exception to a guessed encoding can promote EncodingDetectionWarning to an error.

Checklist

  • The PR title is a user-facing release-note entry with a conventional commit prefix.
  • Apply a category label (enhancement, bug, or an appropriate existing label), or ask a maintainer to apply it.
  • For breaking changes, use ! in the title and explain impact and migration above.

CHANGELOG.md and unstructured/__version__.py are untouched: per d1535fe (#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 current main.

…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).
@ayam04
ayam04 force-pushed the fix/json-ndjson-disambiguation-encoding-fallback branch from 0991159 to 4a477d9 Compare October 21, 2026 03:45
@ayam04

ayam04 commented Oct 21, 2026

Copy link
Copy Markdown
Author

Rebased onto main (07d978b) — the PR had gone CONFLICTING and now sits MERGEABLE. What the rebase changed, beyond replaying the fix:

  • unstructured/file_utils/filetype.py: main had picked up an inline version of the same boundary/fallback decode inside text_head (the #4434 fix). This PR keeps one shared helper, _decode_head_bytes(), and text_head calls it, so the two paths cannot drift; main's inline block is removed in favour of it. The helper now passes final=eof_reached into detect_file_encoding(), matching what main's inline block did, so a multi-byte sequence cut at the 4096-byte boundary is still buffered rather than treated as a wrong encoding.
  • CHANGELOG.md + unstructured/__version__.py: the entry moves to 0.27.33 (the released 0.27.32 section stands as main has it). pyproject.toml needs nothing, the version is dynamic.

The change itself is unchanged: _disambiguate_json_file_type reads the head through _decode_head_bytes() instead of head.decode(encoding, errors="ignore"), so a non-UTF-8 payload (UTF-16 NDJSON from Windows tooling, JSON fetched from an object store) is no longer stripped into text whose lines do not parse, which classified a multi-record payload as FileType.JSON instead of FileType.NDJSON.

Local validation, honestly: python -m py_compile and ast.parse on both changed files pass, and ruff check + ruff format --check are clean on them. I could not run the test suite here — the checkout's .venv on this Windows host segfaults on import of unstructured.file_utils.filetype (Segmentation fault, exit 139), so test_unstructured/file_utils/test_filetype.py cannot even be collected. The added tests are the same three as before the rebase (and_it_classifies_a_non_UTF8_ndjson_file_like_object_as_NDJSON, and_it_classifies_a_non_UTF8_json_file_as_NDJSON, and_it_decodes_a_non_UTF8_head_without_stripping_its_characters); CI is the only place they can run for this branch. @CyMule or @badGarnet — could one of you take a look when you have a moment?

@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 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)

Comment thread unstructured/file_utils/filetype.py Outdated
except (UnicodeDecodeError, UnicodeError):
decoder = codecs.getincrementaldecoder(encoding)()
try:
return decoder.decode(content, final=eof_reached)

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] 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)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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] -- the MAX + 1 prefix of a BOM-less payload decodes to exactly the withheld prefix's text, with detect_file_encoding patched 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, with encoding= asserted, EncodingDetectionWarning promoted to an error, and detection asserted not called. Old code classified both as FileType.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)

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] 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)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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 raised UnprocessableEntityError with 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 at MAX + 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
@ayam04

ayam04 commented Oct 24, 2026

Copy link
Copy Markdown
Author

Both P2s are addressed in c1687e0, in one commit on top of the reviewed head.

Short reads. The prefix is now read by _read_prefix(file, MAX + 1), which continues until the budget is spent or an empty read proves EOF, so a short read no longer ends the document early. The one-byte size probe past the bound is unchanged. An empty source hands back its own empty read, so the caller's text/bytes type is preserved.

Codec byte order at the bound. codecs.getincrementaldecoder() is gone: it re-runs BOM detection over the prefix and rejects BOM-less native-endian UTF-16/32 that the plain codec accepts (measured: "Stream does not start with BOM", then 1,048,577 characters out of inference instead of 524,288). _decode_prefix() withholds one to four trailing bytes and retries the declared codec instead, and only when eof_reached=False and the failure lands within the last four bytes.

New tests, all RED against the previous head and green now:

  • and_it_reads_past_a_short_read_until_the_budget_or_EOF -- 4095-byte short reads over an above-bound payload: NDJSON, prefix accumulates to exactly MAX + 1 with 4095-byte chunks, then the one-byte probe, no read above the budget, handle at position 0, still open and readable, plus the below-bound case stopping at exactly len(payload).
  • and_it_still_fails_a_prefix_whose_tail_is_missing_at_EOF -- the real malformed case still raises UnprocessableEntityError; at eof_reached=False the text differs from the whole document by exactly the withheld character.
  • and_it_decodes_a_BOM_less_prefix_cut_inside_a_code_unit[utf-16|utf-32] -- detect_file_encoding patched out and asserted not called.
  • and_it_classifies_above_bound_BOM_less_UTF16_and_UTF32_payloads_as_NDJSON[utf-16|utf-32] -- byte stream and file path, encoding= asserted, EncodingDetectionWarning promoted to an error, detection asserted not called.

Validation actually run here:

pytest test_unstructured/file_utils/test_filetype.py -q   ->  278 passed, 27 failed
ruff check / ruff format --check (both files)              ->  clean

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 magic module, and the failure set is byte-for-byte identical on the same test file without this commit (32 failed there -- the five new boundary tests are the difference). file_head/MIME-detection tests are among them, which is why they show up in this run rather than in CI.

@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 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
@ayam04

ayam04 commented Oct 29, 2026

Copy link
Copy Markdown
Author

Rebased onto main (e5dafa4) and both P2 items are addressed in 4ea15740 / d53e7fc5 (commit pair rebased again as the merge branch keeps the same diff).

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 (unexpected end of data, truncated data, incomplete multibyte sequence), starting exactly at error.start — the longest decodable prefix, nothing decodable dropped. Bytes a codec rejects outright, such as \xc3\xa9 under ASCII, are no longer trimmed: they fall through to the same fallback that kept the comma before.

Your example is the regression test, and_it_keeps_a_complete_character_at_the_read_boundary_in_the_text_it_classifies: b"a,b\n" + b"a" * 4089 + b"\xc3\xa9,rest\n", encoding="ascii", guessed MIME fixed to text/plain. It asserts the resulting type is CSV and that the text the classification consumed (text_head) still ends with "é,". Red on the old retry with assert <FileType.TXT: 'txt'> is <FileType.CSV: 'csv'>; green now. The unit table next to it covers both directions per codec: unfinished characters withheld (UTF-8 2/3/4-byte, UTF-16, UTF-32, Shift-JIS/GBK lead byte), rejected bytes and wrong encodings further from the end returning None, and a read that is entirely one unfinished character returning None so detection decides. The BOM-less native-endian UTF-16/32 cases you flagged as repaired stay covered by the existing tests.

Whole file: 292 passed, 27 failed; the 27 are the libmagic-dependent tests that fail identically with this change reverted on the same host (libmagic will not load here), and the diff of the two failure lists contains only the 3 new assertions. ruff check and ruff format --check are clean.

Behaviour change, explicitly accepted and documented. Detection now raises UnprocessableEntityError for content no common encoding can decode, and emits EncodingDetectionWarning when a legacy or BOM-less encoding is inferred. That is the delivered text_head contract, and the file-path branch has always had it, so accepting it makes the two reads consistent: detection stops returning a confident type for content it cannot read. I added a "Behaviour change and release treatment" section to the PR body and a Release note section with the migration text, since per d1535fe (#4578) ordinary PRs no longer edit the frozen changelog. Calling it out here so you can accept or push back on the release treatment before this is queued.

Release policy and conflicts. CHANGELOG.md and unstructured/__version__.py are no longer touched by this branch — that is what put them in conflict with current main, and dropping them is the reconciliation #4578 asks for. GitHub now reports the PR MERGEABLE. The release note text lives in the PR body for the releaser to paste.

@ayam04

ayam04 commented Oct 29, 2026

Copy link
Copy Markdown
Author

Correction on the SHAs above: the two commits on the pushed head are 6610157d (the decode fix) and d53e7fc5 (the tests). 4ea15740 was an intermediate local rebase and is not on this branch.

@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 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.
@ayam04

ayam04 commented Oct 30, 2026

Copy link
Copy Markdown
Author

P2, BOM offset. You were right that the offset is in the wrong space. utf-8-sig strips three bytes before it reports error.start, so _decode_prefix() was applying a post-BOM index to the original buffer: on your payload it cut at 4092 rather than 4095 and took the row delimiter plus the two as before it.

443cf463 no longer uses error.start as a slice point. When the full decode fails with an incomplete-sequence reason, the retry withholds one trailing byte at a time, up to one encoding unit, and stops at the first prefix the codec accepts. The whole buffer including the BOM always reaches the plain decoder, so only trailing unfinished bytes are dropped and the codec keeps deciding BOM handling and byte order. That also covers the second half of your finding: a complete multibyte character ahead of the cut is never inside the withheld suffix, so the retry cannot raise on it. A byte the codec rejects outright still returns None and falls through to detection, unchanged.

Regressions, stream and path:

  • and_it_withholds_only_the_cut_character_when_UTF8_sig_carries_a_BOM: your payload read at 4,096 bytes; every complete character and the delimiter survive.
  • and_it_keeps_a_multibyte_character_that_sits_ahead_of_the_cut_character: complete é immediately before an unfinished \xc3; the retry returns the whole prefix instead of raising.
  • and_it_classifies_a_BOM_prefixed_UTF8_sig_CSV_cut_inside_a_character: end to end on a byte stream with MIME fixed to text/plain. Classifies FileType.CSV, detect_file_encoding is never called, EncodingDetectionWarning promoted to an error does not fire, and text_head ends on the delimiter.
  • and_it_classifies_the_same_BOM_prefixed_UTF8_sig_CSV_from_a_path: the same payload from disk.

unstructured/__version__.py is reconciled: the branch is merged with main at 6c304a96 and reads 0.27.37-dev, same as main. Since you flagged it separately, say if you would rather the bump be dropped from the diff entirely.

On the compatibility decision, agreed that it is the maintainers'. I have not changed that behaviour here beyond the boundary trim: text_head on main already raises or warns on a non-UTF-8 payload, and this PR makes the JSON/NDJSON disambiguation read match it instead of silently stripping characters. If you want it written down, CHANGELOG.md is frozen, so tell me which file carries release notes and I will put the note there.

CI: Socket is green on 443cf463; the lint and unit workflows for this head have not reported yet, so I am not claiming a full run. test_unstructured/file_utils/test_filetype.py is 296 passed locally, with the 27 libmagic-dependent cases failing on this host because libmagic will not load here.

@ayam04

ayam04 commented Nov 4, 2026

Copy link
Copy Markdown
Author

@cragwolfe — the BOM-offset P2 went in on 30 Oct in 443cf463 (with main merged at 6c304a96), together with the preceding multibyte character case: the withheld bytes are measured from the end of the prefix now, so utf-8-sig gets the whole buffer and only a genuinely unfinished tail is dropped. The CSV delimiter case you reported classifies as CSV again.

Locally: 296 passed with the same 27 libmagic-dependent failures as the unmodified head (magic will not load on this Windows box), so no regressions on that set. Anything else you would like changed before this lands?

This branch has not been deployed

No deployments
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