Skip to content

Fall back to utf-8 when charset autodetection needs unread content - #3879

Open
qianeric-backup wants to merge 1 commit into
encode:masterfrom
qianeric-backup:response-encoding-fallback
Open

qianeric-backup wants to merge 1 commit into
encode:masterfrom
qianeric-backup:response-encoding-fallback

Conversation

@qianeric-backup

Copy link
Copy Markdown

Discussed first, as the contributing guide asks: #3878.

Response.encoding caches a charset Python has no codec for when default_encoding is a callable and the content has not been read yet:

>>> response.encoding
'x-user-defined'
>>> b"".join(response.iter_bytes()).decode(response.encoding)
LookupError: unknown encoding: x-user-defined

_is_known_encoding() correctly rejects the header's x-user-defined, and the property then picks a replacement:

        if isinstance(self.default_encoding, str):
            encoding = self.default_encoding
        elif hasattr(self, "_content"):
            encoding = self.default_encoding(self._content)
        ...
        self._encoding = encoding or "utf-8"

A string default_encoding replaces the rejected charset. A callable one with unread content takes neither branch, so encoding is still the rejected value, and or "utf-8" does not catch it because a non-empty string is truthy. The same response via client.get() decodes fine, so whether a response is readable depends on how it was fetched.

The callable form exists for autodetection, which by definition needs the body; before that point there is nothing to detect from, and the line above already falls back to utf-8 when there is no charset at all.

Change

         elif hasattr(self, "_content"):
             encoding = self.default_encoding(self._content)
+        else:
+            # The callable `default_encoding` requires the response content,
+            # which has not been read yet. Fall back to utf-8 rather than
+            # passing an unusable charset through.
+            encoding = None

Tests

Three cases in tests/models/test_responses.py: the streaming call above, the same response read eagerly (unchanged behaviour), and a known charset with unread content (still honoured).

tree suite
master 1417 passed, 1 skipped
master + the tests, _models.py untouched 2 failed, 1418 passed, 1 skipped — both LookupError: unknown encoding: x-user-defined
with this patch 1420 passed, 1 skipped

comm -3 over the failure lists is empty against master and shows exactly the two new tests against the red tree.

18 legal responses compared byte for byte (known and unknown charsets, string and callable default_encoding, eager and streaming reads, absent charset) produce identical output before and after.

ruff format --diff, ruff check, mypy, scripts/sync-version, and coverage --fail-under=100 (100% after the change) are clean.

Noting the guide's point that effort has moved to hip: this is small and contained, but I understand if it is not worth triaging now.

Response.encoding rejects a header charset that is not a Python codec, then
tries to replace it with default_encoding. With a callable default_encoding
and unread content neither the string branch nor the callable branch runs,
so the rejected charset survives `or "utf-8"` (it is truthy) and is cached,
making every later text access raise LookupError.

The callable form is for autodetection, which needs the body; before that
there is nothing to detect from. Fall back to utf-8, as the same line
already does when no charset was given at all.

Discussed in encode#3878.
@qianeric-backup
qianeric-backup marked this pull request as ready for review November 28, 2026 02:58

@ege-arhan ege-arhan left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

encoding memoizes the fallback, so the autodetection callable never runs once the content is available.

httpx/_models.py:672-676: when default_encoding is a callable and _content is missing, the new branch sets encoding = None and line 676 then stores "utf-8" in self._encoding. text and iter_text both go through this property, so by the time the body is read the value is already cached and default_encoding(self._content) is never called.

Repro on 598711f:

import httpx

body = "Euro Currency: \u20ac abcdef".encode("cp1252")
r = httpx.Response(
    200,
    headers={"Content-Type": "text/plain; charset=invalid-codec"},
    stream=httpx.ByteStream(body),
    default_encoding=lambda content: "cp1252",
)
print(r.encoding)  # utf-8, cached by the new branch
r.read()
print(r.encoding)  # still utf-8
print(r.text == body.decode("cp1252"))  # False, the euro sign decodes to U+FFFD

On main the same code raises LookupError: unknown encoding: invalid-codec from TextDecoder, so the crash itself is fixed. But the detected encoding is thrown away, and every response that is streamed before .text is accessed decodes with utf-8 and replacement characters instead. The new tests only use a utf-8 autodetect function, so this path is not covered.

Returning the placeholder without caching keeps the fix and lets the property re-evaluate:

else:
    # The content has not been read yet, so the callable cannot run.
    # Do not memoize the placeholder; the next access can autodetect.
    return "utf-8"

With that change the repro prints utf-8, then cp1252, and r.text matches body.decode("cp1252").

python -m pytest tests/models/test_responses.py on this branch: 4 failed, 105 passed. The same 4 fail on main here (chardet picks iso8859-15 for the latin-1 fixtures), so they are unrelated to the PR.

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

Development

Successfully merging this pull request may close these issues.

2 participants