Skip to content

fix(llm,ui): keep UTF-8 in model error messages and Agent UI JSON - #5563

Merged
kovtcharov-amd merged 3 commits into
amd:mainfrom
kovtcharov:kalin/model-error-encoding
Oct 23, 2026
Merged

kovtcharov-amd merged 3 commits into
amd:mainfrom
kovtcharov:kalin/model-error-encoding

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

When a scheduled run's model call failed, its error came back from the Agent UI API with "—" garbled into "—" on Windows. The stored text was fine. The API sent JSON without naming a charset, so Windows PowerShell 5.1 read the UTF-8 as Latin-1. Lemonade error bodies sent as text/plain with no charset were garbled the same way when GAIA read them. Both now arrive intact.

Test plan

  • pytest tests/unit/test_utf8_error_bodies.py: a UTF-8 error body with an em-dash, served over a real socket, round-trips through _send_request and chat_completions. The Agent UI's 503 detail decodes intact. Four of these tests fail with the fix reverted.
  • pytest tests/unit -k "lemonade or schedule or error" -n 4: 3943 passed, 86 skipped, 1 failed. The failure is test_lemonade_embedded.py::TestArchiveSafety::test_a_tar_symlink_inside_the_tree_is_still_recreated, which is unrelated (tar symlink extraction) and skips when run alone.
  • pytest on test_lemonade_client_http.py, chat/ui/test_server.py, test_scheduler.py, test_llm_retry_adversarial.py: 352 passed.
  • python util/lint.py --black --isort
  • End to end in a temp GAIA_HOME with LEMONADE_BASE_URL=http://127.0.0.1:9/api/v1: created a schedule via POST /api/schedules and let it fire. Before the fix, Invoke-RestMethod /api/schedules showed the garbled dash. After it, the header is application/json; charset=utf-8 and the dash is intact.
🔍 Technical details
  • Where it broke: the scheduler stores and serves correct UTF-8. The raw response bytes were \xe2\x80\x94. Starlette's JSONResponse sends content-type: application/json with no charset, and PowerShell 5.1 falls back to Latin-1 for that. Browsers and the Go TUI always decode JSON as UTF-8, so fetch().json() was not affected.
  • UI fix: Utf8JsonMiddleware in server.py rewrites application/json to application/json; charset=utf-8 on every response, including the ones built by exception handlers.
  • Same bug in the LLM layer: requests decodes a text/* body with no charset as ISO-8859-1. The new retry.http_body_text() decodes UTF-8 unless the server names a charset. It replaces response.text on the Lemonade error paths in lemonade_client.py (chat/completions, completions, pull, responses, _send_request), and also in gateway.py, lemonade_service.py and the Fireworks provider.
  • _parse_sse_stream (the /responses stream) used iter_lines(decode_unicode=True), which decodes text/event-stream as ISO-8859-1. It now decodes each line as UTF-8.
  • Checked and left alone: httpx call sites (turn_insights.py, routers/system.py) already default to UTF-8. Subprocess text=True sites in src/gaia/llm either write to a log file or parse a version number, so they never reach this error path.

A failed scheduled run's error read back from GET /api/schedules showed
"—" as "—" on Windows. The stored text was correct; the Agent UI served
JSON without a charset, so clients applying HTTP's Latin-1 default
(PowerShell 5.1's Invoke-RestMethod) misread it. Lemonade error bodies sent
as text/plain without a charset were also decoded as ISO-8859-1 by
requests' Response.text, mangling the same characters at the source.

- Agent UI responses now declare application/json; charset=utf-8.
- Lemonade, gateway, daemon-start and Fireworks error bodies are read with
  http_body_text(), which decodes UTF-8 unless the server names a charset.
- The /responses SSE parser decodes lines as UTF-8 instead of relying on
  requests' text/event-stream default.
@github-actions github-actions Bot added llm LLM backend changes tests Test changes performance Performance-critical changes labels Oct 22, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

On Windows, an em-dash in an error message reached users as "—". This PR fixes that in two places: where GAIA reads Lemonade and provider error bodies, and where the Agent UI API sends JSON. Both fixes are small and correct, and the tests use a real socket and fail when the fix is reverted. Nothing blocks the merge.

Two optional follow-ups:

  • The new charset header misses a few responses: the generic 500 handler and the 401s from the tunnel-auth check. Those messages are plain ASCII today, so nobody sees a problem yet. Registering the middleware last would cover them too.
  • The fix for streamed /responses replies has no test.

Real-world evidence

N/A: no evidence bundle was produced for this run. The PR description reports a manual end-to-end check: a schedule fired against a dead Lemonade, and the API then returned application/json; charset=utf-8 with the dash intact. That run isn't reproduced here, so the verdict on the HTTP surface rests on static review plus the new TestClient test.

🔍 Technical details

Issues

🟢 Some responses skip the middleware (src/gaia/ui/server.py:766). In Starlette, the middleware added last runs outermost. Because Utf8JsonMiddleware is added first, it sits inside TunnelAuthMiddleware and UIRequestGuardMiddleware. Responses those two build themselves (the tunnel-auth 401s at lines 235/247) never go through it. Separately, the @app.exception_handler(Exception) 500 at line 829 is served by ServerErrorMiddleware, which sits outside every user middleware. All of these bodies are ASCII today, so this is only a latent gap. The PR body's claim that the header is set "on every response, including the ones built by exception handlers" holds for HTTPException handlers only. Moving the add_middleware(Utf8JsonMiddleware) call below the last add_middleware covers the middleware-built responses. The generic 500 would still go uncovered.

🟢 No test for the SSE decode change (src/gaia/llm/lemonade_client.py:6618). The _parse_sse_stream switch from iter_lines(decode_unicode=True) to per-line UTF-8 decoding is correct, but nothing tests it. A responses stub with content_type="text/event-stream" and a data: {"delta":"—"} line would pin it.

Strengths

  • http_body_text respects a charset the server declares and decodes UTF-8 only when none is named, so a correct server is never overridden. It lives in retry.py next to tag_http_failure, so every call site shares one helper.
  • In chat_completions, the body is now decoded once and the same string goes to the error message and to tag_http_failure. The retry verdict and the user-facing message can no longer drift apart.
  • test_requests_alone_mangles_an_undeclared_text_body proves the bug exists, so the other tests are checking something real rather than a mocked assumption.

The charset middleware sat inside the request guard and tunnel auth, so
the 401s they build and the generic 500 handler went out without a
charset. It now wraps every other middleware, and the 500 handler names
its charset itself. Adds tests for both and for streamed /responses.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Both suggestions are in: every Agent UI JSON response now says charset=utf-8, including the guard and tunnel-auth 401s and the generic 500. The streamed /responses decode has a test.

🔍 Technical details
  • Utf8JsonMiddleware is now registered last, so it is outermost and wraps UIRequestGuardMiddleware and TunnelAuthMiddleware. It only rewrites the Content-Type header, so the guard still runs first and its CORS-free rejections are unchanged. The guard's comment no longer calls itself outermost.
  • The Exception handler is served by ServerErrorMiddleware, outside every user middleware, so it now passes media_type="application/json; charset=utf-8" itself.
  • New tests in tests/unit/test_utf8_error_bodies.py: a tunnel-auth 401, an unhandled-error 500, and a text/event-stream stub carrying a raw UTF-8 "—" through responses(stream=True). The first two fail with the server.py change reverted.
  • Ran: that file (9 passed), tests/unit/chat plus the HTTP guard, Lemonade client HTTP and tests/test_api.py under -n 4 (2353 passed; one xdist-only setup error in TestEmailSendOutlook502Fix, which passes serially and doesn't touch this code), and util/lint.py --black --isort.
  • CI was already green before this push.
  • Commit: 2dd6e73

kovtcharov-amd pushed a commit that referenced this pull request Oct 23, 2026
…5610)

Four timing-sensitive unit tests failed 8 unrelated PRs this week
(#5537, #5539, #5562, #5563, #5564, #5565, #5566, #5568) and one of
main's last 11 completed runs. Each still guards the same bug, but no
longer races the clock on a busy runner. Every rewritten test was
checked by breaking the code: it fails on the real bug and passes 50/50
runs, including under full CPU load. The PR also keeps three tests out
of the developer's real `~/.gaia`.

## Test plan
- [x] `pytest tests/unit/mcp/client/test_stdio_hung_server.py
tests/unit/test_file_lock.py tests/unit/test_mcp_bridge_concurrency.py
tests/unit/chat/ui/test_agent_model_override.py
tests/integration/test_folder_indexing.py -n 4`: 316 passed, 3 skipped
- [x] The four de-flaked tests, run 50x each: 250/250 serial, and
250/250 under xdist (32 workers) with all 32 cores also running busy
loops. Main's versions in that same loaded run: redaction failed 10/50.
- [x] Each test fails when its bug is put back in the code (see details)
- [x] `tests/integration/test_folder_indexing.py -n 4`, 5 runs: all
pass. Main's version fails 7 to 9 tests per run.
- [x] Test 841 passes with `GAIA_HOME` set to a temp dir. Main's version
fails.
- [x] Electron `npx jest`: 1098 passed. The one failure,
`test_electron_chat_installer.js` (component size 103,725 > 102,400),
also fails on main and is unrelated.
- [ ] CI green on Linux, macOS and Windows unit lanes

<details>
<summary>🔍 Technical details</summary>

**`test_redaction_stays_fast_on_dense_escapes`** (Linux, 2.01 to 2.03 s
against a 2 s limit)
- Cause: an absolute 2 s bound. Locally the worst text takes 0.19 s. On
a 4-worker, coverage-traced runner it took about 10x that.
- Fix: time one 1M-char text against eight 125K texts with the same
total length, on the same machine. Linear code scores about 1.0 and a
quadratic scan scores 8, so the test asserts < 3. It takes the best of
up to three paired runs, and uses the lower of the wall-clock and CPU
(`thread_time`) ratios. Contention inflates wall time, and Windows
samples CPU time on ticks. The test also fails if the 1M text takes more
than 15 s of CPU, which catches a per-position rescan: that is linear
but takes minutes.
- Break checks: a quadratic prefix copy in `_candidate_windows`
(`len(text[:start].rstrip("\\"))`) gives a ratio of 5.9x and the test
fails. Main's 2 s test passed that same regression locally (1.57 s). A
per-anchor rescan without merging takes 56 s and hits the 15 s ceiling.

**`test_children_of_an_exited_server_are_still_stopped`** (Linux)
- Cause: the test slept a fixed 2 s for the child watcher. The watcher
backs off (0.5, 1, 2, 4 s…), so on a slow start its next scan came after
the launcher had exited and the child was never recorded.
- Fix: poll until `child_pid in transport._children`, with a deadline of
3 × `_CHILD_SCAN_MAX_S`.
- Break checks: never recording children fails with "never recorded".
Clearing `_children` before stopping fails with "kept running". Delaying
the watcher's first scan by 2.5 s reproduces the CI failure on main's
test, and the new test passes.
- Note for the product side: a launcher that spawns a child and exits
inside a backoff window still orphans that child. Real `npx`/`uvx`
launchers outlive the window.

**`test_the_next_waiter_takes_the_lock_within_milliseconds`** (macOS,
median 6.5 to 8.1 ms against 5 ms)
- Cause: macOS stretches `sleep(0.001)` under load, and the 5 ms median
left no headroom.
- Fix: the test wraps `_poll_interval`, which records each interval and
signals the moment the waiter starts a poll's sleep. The lock is
released right then, so the whole interval stands between the waiter and
the lock.
- Assertions: every interval the front waiter asks for is ≤ 2 ms, and
the median hand-off is < 15 ms. A 20 ms poll always waits at least 20
ms, so it fails the median even with the bound widened.
- Break checks: `_NEXT_POLL_SECONDS = 0.02` or `0.1` fails the interval
assertion. Sleeping `_POLL_SECONDS` directly, so `_poll_interval` is
bypassed, fails the median (20.8 ms).

**`test_a_dropped_idle_connection_is_logged[True]`** (Linux)
- Cause: the test asserted that `"Traceback"` was absent from the stderr
captured by `capsys`. The traceback in that run came from a fake
Lemonade server that `test_lemonade_shared_server.py` left running on
the same xdist worker (`BrokenPipeError`).
- Fix: the `serve` fixture records the bridge server's own
`handle_error` calls, and the test asserts that list is empty.
socketserver calls `handle_error` before it closes the connection, so
the check doesn't race. A plugin that writes a traceback to stderr
during the test fails main's version and passes the new one.
- Break check: making `log_error` also call the base `log_error`, and
reverting `str(args[0])`, raises `TypeError` in the handler, and the
test fails.

**Isolation fixes**
- `test_folder_indexing.py`: `temp_folder` now lives in
`isolated_gaia_home`, a per-test fake home, so `ensure_within_home`
still admits it. Parallel workers no longer share or delete
`~/.gaia/test_temp`.
- `test_issue_841…`: the test now sets `GAIA_HOME` itself, so an
inherited value can't override the patched `Path.home`.
- `tests/electron/setup.js`: `os.homedir()` points at a per-file temp
dir. It is assigned rather than spied, so `jest.restoreAllMocks()` can't
undo it. Setting `HOME` would not work, because Jest's sandboxed
`process.env` never reaches `os.homedir()`.
- The "Ignoring invalid agents section in …\.gaia\tray-config.json" log
came from `crash-loop-notification.test.cjs`, which mocks `fs` with a
config the validator rejects. The real file was never read, but the path
now names the temp home.
</details>
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 23, 2026
Merged via the queue into amd:main with commit af14f85 Oct 23, 2026
42 of 44 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the kalin/model-error-encoding branch October 23, 2026 07:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

llm LLM backend changes performance Performance-critical changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants