Repository navigation
fix: catch UnicodeDecodeError in _is_json to avoid crashing detect_filetype() - #4398
Open
chuenchen309 wants to merge 2 commits into
Open
chuenchen309 wants to merge 2 commits into
chuenchen309 wants to merge 2 commits into
Conversation
Contributor
There was a problem hiding this comment.
All reported issues were addressed across 4 files
Shadow auto-approve: would not auto-approve because issues were found.
Re-trigger cubic
Contributor
There was a problem hiding this comment.
0 issues found across 1 file (changes from recent commits).
Shadow auto-approve: would auto-approve. Minimal bug fix: catches UnicodeDecodeError in _is_json to prevent crash on non-UTF-8 bracket-prefixed text. Includes a regression test and changelog.
Re-trigger cubic
This was referenced Jul 14, 2026
chuenchen309
force-pushed
the
fix/is-json-unicode-decode-crash
branch
from
July 15, 2026 21:59
1840cad to
0a1fd19
Compare
cragwolfe
pushed a commit
that referenced
this pull request
Oct 22, 2026
## Problem
`partition_json()` and `partition_ndjson()` read the source with a
hard-coded
UTF-8, and neither accepts an `encoding` parameter:
```python
if filename is not None:
with open(filename, encoding="utf8") as f: # hard-coded
file_text = f.read()
elif file is not None:
file_content = file.read()
file_text = file_content if isinstance(file_content, str) else file_content.decode() # UTF-8
```
Because both signatures end in `**kwargs: Any`, an `encoding=` passed by
the
caller — directly, or forwarded by `partition()` — is swallowed
silently. On
`main` (`ee2b3a35`):
```python
>>> partition_json(filename="utf16.json", encoding="utf-16")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
```
The same call succeeds for the sibling text formats, which is where the
inconsistency shows:
| partitioner | takes `encoding` | reads via |
|---|---|---|
| `partition_text` | yes | `read_txt_file()` |
| `partition_csv` | yes | passed to the reader |
| `partition_json` | **no** | `open(..., encoding="utf8")` |
| `partition_ndjson` | **no** | `open(..., encoding="utf8")` |
UTF-16 JSON is not exotic — it is what several Windows tools emit by
default,
and `json.dump` to a file opened in a non-UTF-8 encoding produces it
too.
## Fix
Add `encoding` to both signatures and read through the existing
`read_txt_file()` helper, exactly as `partition_text()` does:
```python
if filename is not None:
_, file_text = read_txt_file(filename=filename, encoding=encoding)
elif file is not None:
_, file_text = read_txt_file(file=file, encoding=encoding)
file.seek(0)
```
`read_txt_file()` uses the given encoding when one is supplied and falls
back to
`detect_file_encoding()` when it is not, so this also makes a non-UTF-8
document
readable *without* naming its encoding. The `text=` path is untouched,
and
`file.seek(0)` is preserved so the detect-then-partition sequence over
one handle
still works.
Source change is +11/-8 across the two files; no new helper, no
behaviour change
for UTF-8 input.
## Verification
```
$ pytest test_unstructured/partition/test_json.py test_unstructured/partition/test_ndjson.py
35 failed, 75 passed
```
The 35 failures are pre-existing on `main` in this environment — they
come from
`unstructured/nlp/tokenize.py` failing to import an optional dependency
(`ModuleNotFoundError: No module named 'installer'`), unrelated to these
files.
I compared the failure sets with `git stash`: **identical before and
after**, and
the pass count goes 70 → 75, which is exactly the five tests added here.
Five regression tests, following the existing naming style in both
files:
- explicit `encoding="utf-16"` for `filename=` (both partitioners)
- explicit `encoding="utf-16"` for `file=` (both partitioners)
- no `encoding` given, UTF-16 detected (json)
**Rollback proof.** Restoring just the two read blocks to the hard-coded
form —
leaving the new parameter in place — fails exactly those five and
nothing else:
```
FAILED test_json.py::it_honors_an_explicit_encoding_for_a_non_utf8_file
FAILED test_json.py::it_honors_an_explicit_encoding_for_a_non_utf8_file_like_object
FAILED test_json.py::it_detects_the_encoding_of_a_non_utf8_file_when_none_is_specified
FAILED test_ndjson.py::it_honors_an_explicit_encoding_for_a_non_utf8_file
FAILED test_ndjson.py::it_honors_an_explicit_encoding_for_a_non_utf8_file_like_object
5 failed, 105 deselected
```
each with `UnicodeDecodeError`. `ruff check` on the four changed files
is clean,
and a CHANGELOG entry is added under the current `0.27.8-dev0` section.
## Notes
This is the *parsing* side. There are open PRs (#4397, #4398, #4447)
addressing
non-UTF-8 crashes during *file-type detection* in
`file_utils/filetype.py`; I
checked all currently open PRs and none touches `partition/json.py` or
`partition/ndjson.py`, so this does not overlap with them.
I kept the scope to honoring the parameter. I did not change what
happens when a
document really is undecodable, nor touch the `text=` path.
<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4483?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="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
…letype()
_TextFileDifferentiator._is_json calls json.load() directly on the raw
file bytes when libmagic guesses a generic text/plain MIME type and the
content starts with `[`/`{`. If the bytes aren't valid UTF-8, json.load()
raises UnicodeDecodeError (via its internal detect_encoding step), which
wasn't caught by the existing `except json.JSONDecodeError`, so it
propagated straight out of the public detect_filetype() API instead of
falling back to FileType.TXT like any other undetectable content.
Broaden the except clause to also catch UnicodeDecodeError.
Added a regression test with non-UTF-8 bytes wrapped in braces and no
file extension, confirming detect_filetype() returns FileType.TXT
instead of raising. Confirmed it fails against the pre-fix code and
passes after. Ran the full test_unstructured/file_utils/ suite (380
passed, 1 xfailed -- no regressions), ruff check/format, and bumped
__version__.py + CHANGELOG.md per the contribution checklist (note:
this may create a merge conflict with my other open PR Unstructured-IO#4397, which
also bumps to 0.25.1 from the same base -- happy to rebase whichever
merges second).
Disclosure: I used an AI coding assistant (Claude) to help identify
this bug and draft the fix. I independently reproduced the
UnicodeDecodeError crash before writing the test and ran the full
local test suite before opening this PR.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…test Addresses cubic-dev-ai review feedback: the test was named "...with_no_extension" but passed metadata_file_path="filename.pdf", so it didn't actually exercise the no-extension code path (extension would resolve to ".pdf", not ""). Drop metadata_file_path entirely — an io.BytesIO with no .name attribute makes `_FileTypeDetectionContext.extension` resolve to "" (genuinely no extension), matching what the test name claims. Behavior is unchanged either way since ".pdf" isn't in _TextFileDifferentiator's special-cased extension list, but the test now actually asserts what it says it does. Co-Authored-By: Claude Opus 4.8 <[email protected]>
chuenchen309
force-pushed
the
fix/is-json-unicode-decode-crash
branch
from
November 20, 2026 10:43
0a1fd19 to
acb4330
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
_TextFileDifferentiator._is_jsoncallsjson.load()directly on the raw file bytes when libmagic guesses a generictext/plainMIME type and the content starts with[/{:If the bytes aren't valid UTF-8,
json.load()raisesUnicodeDecodeError(via its internaldetect_encodingstep) — a different exception type thanjson.JSONDecodeError, so it's not caught. It propagates straight out of the publicdetect_filetype()API instead of falling back toFileType.TXT, the behavior for any other content libmagic can't identify more specifically.Repro
Fix
Broaden the
exceptclause to also catchUnicodeDecodeError.Testing
test_it_does_not_crash_on_non_utf8_bracket_prefixed_text_with_no_extension, confirmingdetect_filetype()returnsFileType.TXTinstead of raising. Confirmed it fails against the pre-fix code and passes after.test_unstructured/file_utils/suite (380 passed, 1 xfailed — no regressions).ruff check/ruff format --checkclean. Rebased on currentmain; noCHANGELOG.mdor version change, per the current contributing guide.Disclosure: I used an AI coding assistant (Claude) to help identify this bug and draft the fix. I independently reproduced the crash before writing the regression test and ran the full local test suite before opening this PR.