Skip to content

Studio: fall back when a page declares a charset we do not know - #10221

Merged
oobabooga merged 7 commits into
unslothai:mainfrom
NilayYadav:fix-web-fetch-unknown-charset
Sep 4, 2026
Merged

oobabooga merged 7 commits into
unslothai:mainfrom
NilayYadav:fix-web-fetch-unknown-charset

Conversation

@NilayYadav

@NilayYadav NilayYadav commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

web_search hands the charset from the response header straight to the decoder. If Python cannot decode with that name the whole fetch fails and the model gets an error instead of the page, even though the bytes are already downloaded. Pages labelled unicode or utf8mb4 load fine in a browser.

Several classes of label hit this, all with the same user-visible result:

Label Where it raises Message the model got
unicode, utf8mb4, x-user-defined codecs.lookup → LookupError Failed to fetch URL: unknown encoding: unicode
base64, hex, zlib, quopri, rot13, uu, bz2 passes lookup, then bytes.decode → LookupError Failed to fetch URL: 'base64' is not a text encoding
undefined passes lookup, raises UnicodeError on every decode by design Failed to fetch URL: undefined encoding
idna passes lookup and a strict decode, but rejects errors = "replace" Failed to fetch URL: Unsupported error handling: replace
a NUL inside the label codecs.lookup → ValueError Failed to fetch URL: embedded null character

Rather than enumerate those, the decode we already perform is now the guard: if decoding with the declared label fails for any reason, the label is treated as if it had never been sent and the existing BOM/UTF-8 fallback runs. The fallback only ever uses _UNICODE_BOM_CODECS entries or UTF-8 with errors = "replace", so it cannot itself raise.

A label that is real and decodes the page normally is untouched, including wide codecs such as utf-16 and utf-32.

@NilayYadav
NilayYadav force-pushed the fix-web-fetch-unknown-charset branch 2 times, most recently from 90d070b to 080dd85 Compare September 2, 2026 20:15
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Review + GitHub Actions reproduction

Reproduced on GitHub Actions against fresh upstream main (c9f98dbd). Three branches, byte-identical workflow and probe — only studio/backend/core/inference/tools.py differs. The probe drives the real _fetch_page_text with the network stubbed exactly as test_web_fetch_binary_guard.py does, and each job prints the decode block it actually ran.

Case Content-Type base main first fix (30aa540f) this head (cf1e744f)
A charset=unicode FAIL PASS PASS
B charset=utf8mb4 FAIL PASS PASS
C charset=x-user-defined FAIL PASS PASS
D charset=utf16le + UTF-16 BOM FAIL PASS PASS
E control charset=utf-8 PASS PASS PASS
F control charset=iso-8859-1 PASS PASS PASS
G charset=base64 FAIL FAIL PASS
  • Base main — expected-failing run: 5/7 cases lost the page. Real values: Failed to fetch URL: unknown encoding: unicode, ... utf8mb4, ... x-user-defined, ... utf16le, and Failed to fetch URL: 'base64' is not a text encoding; use codecs.decode() to handle arbitrary codecs. Controls E/F returned the page, so the harness is sound.
  • First fix — run: A–D fixed, but G still returned the same class of failure, because codecs.lookup("base64") succeeds and only bytes.decode rejects it — outside the except LookupError. That gap is what the follow-up commit closes.
  • This head — passing run: REPRO: all 7 cases returned the page text.

Tests: 11 new cases in test_web_fetch_binary_guard.py. Against 30aa540f 8 of them fail and 3 pass; against this head all 11 pass. The 3 that pass either way are test_declared_wide_codec_still_honoured[utf-16|utf-16-le|utf-32], which exist to prove the new one-byte probe does not discard a correctly declared wide codec. Full file: 85 passed / 10 skipped. The wider tests/test_web_*.py set goes 1312 → 1323 passing with no new failures (7 pre-existing failures in test_web_access_policy.py and test_web_rank.py reproduce identically without this change and are missing-optional-dependency failures in the local env).

No screenshot: the change has no visible UI element — the user-visible effect is the tool result text quoted above, which is what the table reports.

Conclusion: the defect and the fix are both verified on Actions; the one finding I raised against the first commit is fixed and covered by a regression test.

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

Please review head cf1e744f, and I do intend to iterate on this one until it converges — the diff is small, so flag anything genuine rather than saving it.

The whole change is one guard in _fetch_url_raw (studio/backend/core/inference/tools.py) that decides whether to trust the charset a page declares. Worth the most attention:

  1. Except-clause ordering. except UnicodeError deliberately precedes except (LookupError, ValueError). UnicodeDecodeError is a ValueError, so the order is load-bearing: reversing it would discard utf-16/utf-32 pages, which is a live regression the third new test covers. Please confirm the ordering is right and that no exception the try can raise ends up in the wrong arm.
  2. The b"a".decode(declared) probe. It exists only to reject the stdlib's non-text codecs, which pass codecs.lookup and fail at decode. Is there a real text codec for which a single ASCII byte raises something other than UnicodeError, and so would be wrongly discarded?
  3. declared_codec = None is now initialised before the try. Please confirm there is no path that leaves it stale or unbound, and that the downstream cp1252 rescue (declared_codec in (None, "iso8859-1")) still behaves correctly now that an unusable label yields None there.
  4. Whether treating an undecodable label as absent is the right call versus surfacing it, given the bytes are already downloaded.

Actions evidence for the before/after is in the comment above.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cf1e744fbb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/core/inference/tools.py Outdated
Comment on lines +12114 to +12117
except UnicodeError:
# A real text codec that simply cannot decode this probe (utf-16 and
# other wide codecs reject a lone byte). Keep it.
pass

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject the always-failing undefined codec

When a page declares charset=undefined, Python's registered encodings.undefined codec makes the probe raise UnicodeError, so this arm preserves both declared and declared_codec; that codec deliberately raises UnicodeError for every decode, causing the real decode below to escape to the outer handler as Failed to fetch URL: undefined encoding instead of falling back. Distinguish the truncated-input errors from wide text codecs from codecs such as undefined that cannot decode any input.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed and fixed in ba5f63a7.

codecs.lookup("undefined") succeeds and encodings.undefined raises UnicodeError on every decode, so the probe landed in the except UnicodeError arm that was meant for wide codecs and the label was kept — then the real decode raised and the fetch was lost. Reproduced exactly as described.

Rather than enumerate which UnicodeErrors mean "truncated input" and which mean "unusable codec", I dropped the separate probe: the real raw_bytes.decode(...) is now the guard, so anything that cannot decode this page falls back. charset=undefined is a case in test_unusable_codec_charset_falls_back.

Comment thread studio/backend/core/inference/tools.py Outdated
declared_codec = codecs.lookup(declared).name
# base64/hex/zlib and friends pass lookup but are not text codecs,
# so they raise only here, where the decode below would fail the fetch.
b"a".decode(declared)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Probe codecs with the downstream error mode

When a page declares charset=idna, this strict-mode probe succeeds, but the actual decode below supplies errors="replace", which Python's idna codec rejects with UnicodeError: Unsupported error handling: replace; the fetch therefore still returns a failure instead of treating this unusable page charset as absent. Probe with the same error mode used by the real decode, or otherwise reject codecs that cannot accept it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed and fixed in ba5f63a7 — this one was the more useful half of the pair, because it says the probe was the wrong shape rather than the wrong arm.

Verified: b"a".decode("idna") succeeds in strict mode, while body.decode("idna", errors = "replace") raises UnicodeError: Unsupported error handling: replace, so a strict probe could never have predicted the real call.

Taking your suggestion literally: the decode below is now itself wrapped, so the probe and the downstream call are the same call and cannot disagree about error mode. charset=idna is a case in test_unusable_codec_charset_falls_back.

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Actions reproduction, round 2 — after the Codex findings

Both Codex P2s reproduced exactly as described, so the approach changed rather than the arm: the separate probe is gone and the real raw_bytes.decode(...) is now itself the guard, which makes it impossible for the probe and the downstream call to disagree about codec or error mode. Head is now ba5f63a7.

Same fresh base (c9f98dbd), same byte-identical workflow and probe on both branches, now 9 cases:

Case Content-Type base main head ba5f63a7
A charset=unicode FAIL PASS
B charset=utf8mb4 FAIL PASS
C charset=x-user-defined FAIL PASS
D charset=utf16le + UTF-16 BOM FAIL PASS
E control charset=utf-8 PASS PASS
F control charset=iso-8859-1 PASS PASS
G charset=base64 FAIL PASS
H charset=undefined (Codex) FAIL PASS
I charset=idna (Codex) FAIL PASS
  • Base main — expected-failing run: REPRO: 7/9 case(s) could not read the page. Controls E/F returned the page, so the harness is sound.
  • Head ba5f63a7 — passing run: REPRO: all 9 cases returned the page text.

Tests: test_unusable_codec_charset_falls_back now covers all nine unusable labels including undefined and idna. Against base main 10 of the 13 new cases fail; against the previous head cf1e744f exactly 2 fail — [undefined] and [idna], i.e. precisely the two Codex found — and against this head all 13 pass. test_declared_wide_codec_still_honoured[utf-16|utf-16-le|utf-32] passes in all three, which is what stops the guard from swallowing a correctly declared wide codec. Full file: 87 passed / 10 skipped; the wider tests/test_web_*.py set goes 1312 → 1325 passing with no new failures.

Upstream CI: the two red checks — "Repo tests (CPU)" and "workflow-trigger lint" — are tests/security/test_scan_packages.py::test_context_dependent_unsloth_zoo_findings_are_digest_pinned, which fails on main itself at this PR's merge base c9f98dbd. Not related to this change.

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

Both of your P2s were right and are fixed in ba5f63a7. The separate probe is gone: raw_bytes.decode(...) is now wrapped directly, so the check and the real call are the same call.

Please confirm the new shape, in particular that except (LookupError, ValueError) around the decode is the right width — UnicodeError is a ValueError, so it is meant to cover truncated-input errors too, and the fallback decode below it uses only _UNICODE_BOM_CODECS entries or UTF-8 with errors = "replace", which I believe cannot raise. If you agree there is nothing further, say so and I will treat this as converged.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Studio UI evidence — before/after

Two isolated install.sh --local builds, SHA-stamped c9f98dbd5 (merge base) and ba5f63a73, each with its own home, port and logs. Nothing is seeded: a stored conversation would replay bytes the frontend already has and photograph identically, so the whole path runs for real — the model emits web_search, Studio fetches the page over the network, and the SPA draws the card.

The pages are httpbin.org/response-headers, which echoes whatever Content-Type the query string asks for. They have to be public: _validate_and_resolve_host refuses every non-global address, so a local fixture server cannot be the thing fetched. Four URLs in one turn, the last one an ordinary label as the control.

PR 10221 Studio before/after

Declared charset BEFORE c9f98dbd5 AFTER ba5f63a73
unicode Failed to fetch URL: unknown encoding: unicode page body, 122 chars
base64 Failed to fetch URL: 'base64' is not a text encoding; use codecs.decode() to handle arbitrary codecs page body, 121 chars
idna Failed to fetch URL: Unsupported error handling: replace page body, 119 chars
utf-8 (control) page body, 120 chars page body, 120 chars
pages_read 1, page_shows_fetch_failure true pages_read 4, page_shows_fetch_failure false

The assistant bubble is written mechanically from the tool results alone, so it is the backend's own output quoted back rather than a stand-in's opinion: "1 returned the page (utf-8) and 3 failed to fetch (unicode, base64, idna)" becomes "4 returned the page (unicode, base64, idna, utf-8)".

Both sides are comparable, not just different: each issued the same four URLs, rendered 4 tool calls, took 4 Allow clicks, and returned a byte-identical 120-character result for the utf-8 control. If that control had failed on either side the run would have been a network problem and would prove nothing.

One detail the table does not show: BEFORE, each failing result also carried The tool call encountered an issue. Please try a different approach or rephrase your request. — so the model was actively steered away from the page, not merely handed less text.

Photographed at ba5f63a73. The current head 4eeff7e17 differs from it only by a corrected comment in a test file, so the shipped behaviour in the image is the behaviour on head.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

1 similar comment
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 4eeff7e170

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this still hits studio/backend/core/inference/tools.py where codecs.lookup(declared) and the decode below it are unguarded, so a page labelled unicode or base64 is lost even though the bytes are in hand. Will get this reviewed.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-03T19:32:07.865610Z 202d012 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

oobabooga pushed a commit to oobabooga/unsloth-test that referenced this pull request Sep 3, 2026
oobabooga pushed a commit to oobabooga/unsloth-test that referenced this pull request Sep 3, 2026
@oobabooga

Copy link
Copy Markdown
Member

This makes web_search fall back to UTF-8 when a site declares an encoding Python cannot use, instead of dropping the page and handing the model an error. I am merging it for correctness, but it is hardening rather than a fix for anything reported: there is no linked issue, and the 183 real sites I checked all declared encodings Python handles fine. The gap is still real, since unicode and x-user-defined are valid WHATWG labels that browsers decode and Python has no codec for.

Guarding the decode itself rather than testing the label first is the right shape, and it catches undefined and idna, which pass a separate test and then fail the decode anyway. Correctly labelled pages are unchanged. In Studio, a page declaring charset=utf8mb4 returned Failed to fetch URL: unknown encoding: utf8mb4 on main and the page text on this branch. One caveat: unicode actually means UTF-16LE and we fall back to UTF-8, so a UTF-16LE page with no BOM still comes back unreadable. That is no worse than the hard failure it replaces, but mapping WHATWG labels to Python codecs would be the complete fix.

@oobabooga
oobabooga merged commit a12162a into unslothai:main Sep 4, 2026
34 checks passed
imaderaya pushed a commit to pub-forks/unsloth that referenced this pull request Sep 4, 2026
…lothai#10284)

`(Python 3.13)` is red on `main` at `a12162ab5`, on one test out of 37,035, failing on `[entry] = monitor.snapshot()` while its status code and message assertions pass.

Two sites in `produce_openai_chat_completions` reject a `confirm_tool_calls` plus `stream=false` request, and `_should_validate_before_switch()` decides which one runs. The early site runs ahead of the model switch, so an invalid request cannot evict the resident model, and it returns before the API monitor row is opened. The later site goes through `_reject`, which fails a row that is already open. That predicate is `_automatic_model_load_may_run() or _preview_slot_is_owned()`, both process-wide state, and the test never pinned it, so it asserted whichever site the rest of the xdist worker happened to leave reachable.

unslothai#10221 is not at fault. Its change is confined to charset handling in `_fetch_url_raw` and cannot affect whether a monitor row exists. It added 17 parametrized cases, which changed how xdist packs its four workers and shook loose a latent ordering flake. The twelve `main` commits before it are green on this check, it is red exactly at it, and the test passes alone, passes with its file serially, and passes with its file under `-n 4`.

The predicate is now pinned and parametrized over both values, so each rejection site is asserted deliberately rather than by accident. That also adds coverage, since the early site was previously reached only by luck. Pinning it is what the rest of the suite already does, five times in `test_active_generations.py` and again in `test_openai_auto_switch.py`.

A second test had the same fragility, `test_confirm_tool_calls_requires_streaming_for_safetensors_tools`. A regex scan missed it; running the file with the predicate forced found it. Both are fixed.

Verified by forcing the predicate, which reproduces the CI failure exactly at the same line. The file is 360 passed both with the predicate as the environment leaves it and with it forced, up from 358. Before the change the forced column was 1 failed. Sweeping the whole backend suite the same way found no other test resting on this predicate.

Left alone deliberately: the two sites disagree about whether a rejected request is recorded at all, so the same 400 is logged or not depending on whether an automatic load could have run. That predates unslothai#10221, and recording a row at the early site changes what the monitor shows, so it wants its own PR rather than being folded into an unblock.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants