Skip to content

fix: strip leading UTF-8 BOM before JSON content-shape detection - #4397

Merged
cragwolfe merged 1 commit into
Unstructured-IO:mainfrom
chuenchen309:chuenchen309/fix-json-bom-misdetection
Nov 17, 2026
Merged

cragwolfe merged 1 commit into
Unstructured-IO:mainfrom
chuenchen309:chuenchen309/fix-json-bom-misdetection

Conversation

@chuenchen309

@chuenchen309 chuenchen309 commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Problem

detect_filetype() decodes a file's text head as plain "utf-8". If the source has a leading UTF-8 byte-order-mark, that BOM survives the decode as a literal U+FEFF character at the start of the text.

_TextFileDifferentiator._is_json requires the first non-whitespace character to be [ or {:

if text_head.lstrip()[0] not in "[{":
    return False

str.lstrip() doesn't strip U+FEFF (it's not whitespace), so this check fails immediately for BOM-prefixed content — _is_json returns False without even attempting to parse it. When this happens for a payload with no .json/.ndjson extension and libmagic guesses a generic text/plain MIME type (which it does for BOM-prefixed content — confirmed BOM changes libmagic's own guess from application/json/application/x-ndjson to text/plain), the file falls all the way through to FileType.TXT instead of FileType.JSON.

Repro

import io, json
from unstructured.file_utils.filetype import detect_filetype

json_bytes = b"\xef\xbb\xbf" + json.dumps([{"example": "data"}]).encode("utf-8")
detect_filetype(file=io.BytesIO(json_bytes), metadata_file_path="filename.pdf")
# -> FileType.TXT  (before this fix)
# -> FileType.JSON (after this fix, matching the non-BOM case)

Fix

Strip a leading BOM once in _FileTypeDetectionContext.text_head (the property consumed by _is_json/_is_csv/_is_eml), rather than changing the .encoding property itself — an existing test (it_knows_the_encoding_asserted_by_the_caller_and_normalizes_it) asserts .encoding returns the literal string "utf-8", so I kept that contract untouched and fixed the actual text consumption point instead.

Only one BOM can come from decoding, so at most one U+FEFF is removed (removeprefix, not lstrip); a second one is content and stays.

Rebased onto current main; no CHANGELOG.md / __version__.py edits, per the updated contributing guide.

Testing

  • test_it_identifies_json_with_a_leading_utf8_bom_and_no_extension and it_strips_only_the_leading_utf8_bom_and_not_a_later_literal_ufeff_char fail on main and pass with the fix.
  • test_unstructured/file_utils/ (566 passed, test_file_conversion.py skipped: needs pypandoc) and test_json.py / test_ndjson.py / test_text.py (263 passed).
  • ruff check / ruff format --check clean.

AI disclosure

This PR was written and tested by an AI coding agent working autonomously; I review each change after it is opened and take responsibility for it. (An earlier version of this section said I had traced the bug and run the tests myself before opening; that was not accurate.)

Review in 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.

All reported issues were addressed across 4 files

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

Re-trigger cubic

Comment thread unstructured/file_utils/filetype.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 auto-approve. Corrects UTF-8 BOM handling in file type detection with a targeted, low-risk change (strip one character) and adds a test. No core logic, infrastructure, or security impact.

Re-trigger cubic

@chuenchen309
chuenchen309 force-pushed the chuenchen309/fix-json-bom-misdetection branch from 143723e to 5cbac58 Compare July 15, 2026 21:58
chuenchen309 added a commit to chuenchen309/unstructured that referenced this pull request Jul 15, 2026
…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]>
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. -->
detect_filetype() decodes a file's text head as plain "utf-8", which
leaves a leading byte-order mark as a literal U+FEFF character. That
defeats _TextFileDifferentiator._is_json's content-shape check (first
non-whitespace character must be "[" or "{"), so a BOM-prefixed JSON
payload with no .json extension and a text/plain libmagic guess is
detected as FileType.TXT instead of FileType.JSON.

Strip at most one leading U+FEFF in _FileTypeDetectionContext.text_head,
which _is_json, _is_csv and _is_eml read. Only one BOM can come from
decoding, so a second U+FEFF is content and is kept.
@chuenchen309
chuenchen309 force-pushed the chuenchen309/fix-json-bom-misdetection branch from 5cbac58 to d1ada0d Compare November 14, 2026 10:53

@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 at d1ada0d against main.

This change is correct and narrowly scoped. Removing one leading U+FEFF in _FileTypeDetectionContext.text_head fixes all three content-shape checks that read it (_is_json, _is_csv, _is_eml), and because the removal sits in the property itself it applies equally to file paths, binary file-like objects and text file-like objects. I checked the downstream routing too. _is_json still parses the raw bytes with json.load(), which recognizes a UTF-8 BOM. For a single BOM-prefixed value, JSON/NDJSON disambiguation still falls back to FileType.JSON. When no encoding is passed, partition_json() decodes through detect_file_encoding() (utf-8-sig), so an extensionless BOM-prefixed JSON payload now partitions as JSON and no longer as plain text. Using removeprefix and not lstrip is the right choice, and the new tests cover both the detection result and the one-BOM-only boundary.

Two non-blocking observations; neither needs a change in this PR:

  • If a caller passes an explicit encoding="utf-8", partition_json() decodes with plain utf-8, so the BOM is kept and parsing fails with "Not a valid json". That already happens on main for a BOM-prefixed .json file. With this change it can also reach an extensionless BOM-prefixed JSON payload, which used to partition as text. Treating a leading UTF-8 BOM as utf-8-sig in _decode_bytes() would close the gap, but that belongs in a separate change.
  • In it_strips_only_the_leading_utf8_bom_and_not_a_later_literal_ufeff_char, the expected value contains a literal invisible U+FEFF character. Writing it as "{}" would make the assertion readable.

CI on this commit is green: every check passed except the third-party AI reviewer check, which finished neutral.

(authored by codex)

@cragwolfe
cragwolfe added this pull request to the merge queue Nov 17, 2026
Merged via the queue into Unstructured-IO:main with commit 0c166fc Nov 17, 2026
53 checks passed
chuenchen309 added a commit to chuenchen309/unstructured that referenced this pull request Nov 20, 2026
…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]>
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