Skip to content

fix: stream JSON answers again and repair main CI - #5147

Merged
kovtcharov-amd merged 2 commits into
mainfrom
fix/main-after-rc15-batch
Oct 15, 2026
Merged

kovtcharov-amd merged 2 commits into
mainfrom
fix/main-after-rc15-batch

Conversation

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Main is red on three jobs and rc15 is blocked on it. Answers the model wraps in {"thought": ..., "answer": ...} stopped streaming after #5121 held every envelope until it closed, so the chat sat blank through a long answer and Stop kept nothing; they now stream from the first token again while thoughts and tool calls stay hidden. The Chat Agent job failed because the frozen run_python adversarial tests still intercepted subprocess.run after #5104 moved Python jobs to Popen. Code Quality failed on two pylint findings in the Agent UI MCP control server; the unused host is now checked, so loopback-only transport settings refuse a network address instead of silently applying.

Test plan

  • python -m pytest tests/unit/test_json_answer_decoding.py tests/unit/chat/ui/test_sse_handler.py tests/unit/chat/ui/test_sse_tool_call_text.py tests/unit/test_model_phase_progress.py tests/unit/test_tool_call_progress.py (397 passed; the 5 streaming cases fail on main)
  • Every test file touching sse_handler, JSON answers, or agent_ui_control (2180 passed)
  • tests/unit/test_run_python_frozen_adversarial.py tests/unit/test_run_python_frozen.py (103 passed; 19 fail on main)
  • python util/lint.py --black --isort --pylint
  • CI: Unit Tests, Chat Agent Tests, Code Quality
  • Flagship eval: this changes what streams to the chat; covered by the combined run on main

Answers wrapped in {"thought": ..., "answer": ...} stopped streaming after
#5121: the envelope filter held the whole reply until its closing brace, so
the chat stayed blank and Stop kept nothing. The envelope scan now notes
where a top-level "answer" string begins (when no tool key came first) and
hands the rest to the answer decoder, so the answer streams from its first
token while thoughts and tool envelopes are still never shown.

The frozen run_python adversarial tests relayed subprocess.run, but #5104
moved Python jobs to Popen, so every case tried to start the fake binary.
They now relay Popen and keep running the real dispatch path.

Pylint on agent_ui_control.py: the step fold uses an empty dict instead of
None, and transport_security_settings now refuses a non-loopback host
instead of ignoring it, so a network bind cannot get loopback-only settings
without the bearer token.
@github-actions github-actions Bot added mcp MCP integration changes tests Test changes labels Oct 15, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Long replies the model wraps as {"thought": …, "answer": …} stream into the chat token by token again, instead of sitting blank until the reply closes. The PR also fixes the two CI breaks on main: tests that still patched the old way Python jobs were launched, and a lint finding in the Agent UI MCP server. That lint fix adds a real guard: the loopback-only transport settings now refuse a network address. The changes are correct and tightly scoped. Thoughts and tool calls stay hidden, and an answer that comes after a tool key, or sits inside a nested object, is still held back. The four touched test files pass locally (413 passed).

One small follow-up, not blocking: when the answer streams, any text the model writes after the closing brace is now dropped. Before this change it was shown. This is the same limit the existing {"answer": …}-first path already has, so it is rare in practice, but it is worth closing.

Real-world evidence

The evidence stage ran on a runner with no inference (ubuntu-latest, no Lemonade or GPU). It confirms the MCP and CLI side. The streaming change itself is pending strix-halo lane, so that part rests on static review and unit tests.

$ gaia mcp serve --host 0.0.0.0 --port 8799
❌ Refusing to listen on '0.0.0.0': it is reachable from the network, and this server can approve tool calls. ...
exit=2

transport_security_settings:
'0.0.0.0' / '::' / 'myhost.lan' -> RemoteBindError
'127.0.0.1' / 'localhost' / '::1' -> OK allowed_hosts=['127.0.0.1:*', 'localhost:*', '[::1]:*']

MCP over :8766 -> initialize OK, tools/list -> 27 tools; system_status / list_sessions / create_session OK
Origin: http://localhost:5174 -> HTTP 403 · Host: evil.example:8766 -> HTTP 421

turn_view (first status event, empty steps) -> is_error=False,
  "steps": [{"type": "status", "label": "Connecting to LLM...", "active": false}]
Surface Result
Answer-first streaming (sse_handler.py) ⏸ pending strix-halo lane

The thinking fold branches were not exercised, because no agent or model was loaded. A spot regression check of /api/health, /api/sessions, the messages route and /api/system/status all returned 200.

🔍 Technical details

Issues

🟢 Text after a streamed answer envelope is swallowed (src/gaia/ui/sse_handler.py:1144-1156)
Once _answer_stream takes over, everything after the closing quote goes into JsonStringStreamDecoder.tail until end of stream, and nothing reads it. A local probe with '{"thought":"t","answer":"Done."}\nTrailing prose after.' gave these results:

  • streamed in 5-char pieces: shows only Done.
  • delivered as one piece (the _ENV_COMPLETE path): shows Done. and also Trailing prose after.

So what the user sees depends on how the reply was chunked. Case 1b (around line 1515) has the same limit, so this is not new territory. A follow-up could hand decoder.tail back to _stream_buffer once closed is set and let the envelope or markup filter run on it.

🟢 Stale docstring (sse_handler.py, _take_leading_envelopes)
The docstring still says it "Holds an envelope until its closing brace however long it runs … its answer, if any, is emitted as the answer". It should mention that an answer-before-tool envelope now streams its answer value as chunk events once the opening quote arrives.

Checked and fine

  • transport_security_settings is called only on the token-less path in run_http (agent_ui_mcp.py:1095). --allow-remote goes through remote_app, so the new raise cannot break opted-in remote binds.
  • In _fold_step, last = {} instead of None: every last.get(...) guard returns falsy on an empty dict, and no branch writes to last without first checking its type.
  • Key tracking in _json_object_end: arrays aren't tracked, so a , inside a depth-1 array can mislabel an element as a key. The worst outcome is a spurious tool_seen, which only falls back to the old hold-until-close behavior. It cannot trigger a false answer stream.
  • A probe with an answer before a tool key ({"answer": "Checking now.", "tool": …}) shows the answer in every chunking, the same as main did through its one-shot answer event.

Strengths

  • The resumable scan state is extended rather than replaced, so a long envelope is still scanned once and never rescanned on every token.
  • The new tests run each case at chunk sizes 1, 4 and 64, so they cover keys split across tokens.
  • The relay fixture in the adversarial run_python tests now patches python_jobs.subprocess.Popen and passes non-relay spawns through to the real Popen. Unrelated subprocess calls no longer trip it.

@kovtcharov-amd
kovtcharov-amd merged commit debd870 into main Oct 15, 2026
@kovtcharov-amd
kovtcharov-amd deleted the fix/main-after-rc15-batch branch October 15, 2026 19:13
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 23, 2026
In the Agent UI on a desktop install, flagship answers didn't stream. A
400-word story sat on "Waiting on the model" for about 12 s and then
appeared all at once. Pressing Stop during that wait left an empty
"Stopped" bubble. The flagship runs in the daemon's sidecar there, and
the sidecar built its agent with streaming off, so the model call was
unstreamed and no answer text reached the relay until the turn ended.
Now every relayed turn streams its answer token by token, and Stop keeps
the text that has already arrived. This supersedes the draft amd#5006.

## Test plan

- [x] `pytest
hub/agents/gaia/python/tests/test_relayed_answer_streams.py`: drives the
real agent loop, a real sidecar socket and the UI's relay with a model
that parks mid-reply. It asserts answer text reaches the UI before the
model finishes, and that Stop keeps it. All 3 cases fail without the
fix.
- [x] `pytest hub/agents/gaia/python/tests/test_server_query.py`: 81
passed, including the new streaming, per-turn and stopped-run cases
- [x] `pytest tests/unit/chat -n 4`: 2164 passed
- [x] `pytest hub/agents/gaia/python/tests -n 4`: 769 passed. 3 fail in
`test_full_tool_bundles.py` /
`test_manifest_tools_count_matches_real_registry` because the optional
browser tools aren't installed locally. They don't touch this change.
- [x] `python util/lint.py --black --isort`
- [x] Live: a Fireworks model (deepseek-v4p1-flash) in the Agent UI on a
desktop install shows the answer growing (681 → 1,429 → 1,902
characters, 1 s apart); Stop kept the partial text (tested on local
Qwen3.6, whose answers run long enough to stop mid-way)
- [ ] Flagship eval on the next RC. Categories to watch: `gaia_core`,
`gaia_tool_selection`, `gaia_honesty`, `tool_selection`,
`error_recovery`

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

- Root cause: `build_query_agent` and `build_session_agent` construct
`GaiaAgent` with `GaiaAgentConfig`'s default `streaming=False`, and the
`/query` route never turned it on. The base loop therefore took the
`send_messages` branch and its "Waiting on the model" progress label,
and the only text the route ever saw was the final `answer`. The stdio
transport sets `streaming=True`, and so does the in-process Agent UI
path, so neither had this problem. The relay, the daemon proxy and
`SidecarProxy.iter_lines` already forward each event as it arrives.
- Fix: `agent.streaming = True` on every `/query` turn, set after
`agent.console = handler` so a retained session agent can't drift back.
- Stop can now land mid-generation, and the base loop then returns
`status: "cancelled"` with no text. `_terminal_from_run_result` maps
that to an empty `final`, the same as stdio, instead of the "finished
without producing an answer… This is a bug" error. `token` events are
dropped once the run is cancelled, so a half-written JSON reply flushed
at teardown can't leak.
- The Agent UI already saves the accumulated `chunk` text when a relayed
turn is stopped without an `answer`. `test_relayed_stop_keeps_text.py`
pins that behaviour, since the fix depends on it.
- Gateway and Fireworks models answer in the `{"thought", "answer"}`
envelope. `SSEOutputHandler` has streamed the `answer` field since
amd#5147, so those answers stream too, and the new end-to-end test uses
that envelope.
- The `/query` SSE contract is unchanged: `token` was already part of
it.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov pushed a commit to kovtcharov/gaia that referenced this pull request Oct 30, 2026
…er (amd#5404)

The proactive Claude reviews were failing about half the time, and each
failure was lost. The code and security audits failed 5 of the last 10
nights, and the doc walkthrough failed 4 of its last 5 runs. Running
three audits every night used up both Claude accounts' weekly limit by
mid-week, so most of those runs stopped before reviewing anything and
blamed a missing file. The next run never went back for the missed work.
Now one audit runs each night between 2 and 4am Pacific, so each audit
runs every third night. Each run checks Claude is available before
starting, and says plainly when it isn't. It picks up everything since
its last successful run, starts from what merged since then, and checks
against the bug types past audits missed. The dedup pass no longer
re-files duplicates that were already closed: 34 of them were closed
alongside this change.

## Test plan

- [ ] `python -m pytest tests/unit/test_audit_synthesis_prep.py
tests/unit/test_audit_history.py tests/unit/test_audit_rotation.py
tests/unit/test_require_claude.py tests/unit/test_recent_changes.py
tests/unit/test_miss_analysis.py
tests/unit/test_claude_audit_workflow_contract.py
tests/unit/test_closed_duplicates.py -q` passes (277 tests)
- [ ] After merge: `gh workflow run claude-audit-rotation.yml -R
amd/gaia -f dry_run=true`. The summary names tonight's audit and the
next five nights, and nothing is dispatched.
- [ ] After merge: `gh workflow run claude-nightly-audit.yml -R amd/gaia
-f dry_run=true`. Check the preflight summary: the mode, a window
reading "since this audit's last successful run", the Claude probe
passing, and "Recent changes read first". At the end, "Dry run
confirmed: no issue created".
- [ ] After merge: `gh workflow run claude-weekly-doc-walkthrough.yml -R
amd/gaia -f doc_filter=docs/quickstart.mdx -f dry_run=true`. The guide
is walked, "Using bash.exe from …" appears, and the dry-run watermark
step passes (it crashed before this change).
- [ ] After merge: `gh workflow run claude-security-audit.yml -R
amd/gaia`. Semgrep scans `tui`, `installer` and `.github/workflows`, and
the SARIF uploads.
- [ ] First scheduled night (10:13 UTC): the dispatched run is titled "…
rotation night N", files at most what's new, and an issue it files
carries `audit-cluster` / `audit-key` markers.

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

**Root causes (last ~2 weeks)**
- Code and security audits, Oct 7/10/12/13/14/17: every lens returned
`is_error` in under a second with "You've hit your weekly limit". The
primary account ran out on Oct 10, the secondary on Oct 12–14, both on
Oct 17. The account switch fired correctly; both accounts were spent.
- Walkthrough Oct 12: same weekly limit on every guide, queued over 57
hours on the Strix Point pool. Oct 5 and Oct 19: the `xsj-aimlab-stxp`
images have no Git for Windows (only WSL's `bash.exe`). Also on Oct 5,
the executor step's `GITHUB_OUTPUT` got UTF-16 appended by
`start-lemonade.ps1` under PowerShell 5.1 `>>`. Sep 21–28: Application
Control blocked `LemonadeServer.exe` and the job landed on Strix Halo
machines; both were fixed by the move to the `xsj-dispatch` pool on Oct
1.
- The walkthrough's two dry-run steps had a literal `\n` mid-command, so
`dry_run=true` always failed.

**Schedule.** One cron, `13 10 * * *` = 03:13 PDT / 02:13 PST. Only
10:00–11:00 UTC is inside 2–4am Pacific in both seasons. Slot = days
since epoch mod 3 → code audit, security audit, doc walkthrough. The
audits lost their own crons; `workflow_dispatch` still runs any of them
on demand. Deep code sweep: whenever the last successful one is over 8
days old (every third turn, retried on the next turn if it fails).

**Dedup bug.** The 2026-09-07 burst (78 issues) predates the dedup pass:
the run checked out main 7 hours before amd#3310 merged. Three duplicate
pairs still got through after amd#3310 (amd#3832/amd#3471, amd#3825/amd#3414,
amd#5199/amd#4875). Backlog matching compared findings against issue titles
only, so a same-section duplicate worded differently scored 0.05–0.15,
below the 0.18 threshold. Now matching includes each audit issue's own
markers (all 13 known pairs rank 1st–2nd). Closed duplicates hand their
keys to the open canonical, so consolidating into amd#1077/amd#4331 does not
trigger re-filing. Both syntheses share the `claude-audit-issue-filing`
concurrency group. The security audit files to private code scanning,
not issues, so it cannot duplicate the other two.

**Closed as duplicates (34):** into amd#4331: amd#3204 amd#3413 amd#3422 amd#3439 amd#3466
amd#3476. Into amd#1077: amd#3173 amd#3412 amd#3418 amd#3426 amd#3429 amd#3430 amd#3433 amd#3437 amd#3442
amd#3449 amd#3454 amd#3455 amd#3464 amd#3468 amd#3475 amd#3477 amd#3482. Into amd#3198: amd#3436
amd#3462. Others: amd#3425→amd#3169, amd#3457→amd#3195, amd#3440→amd#3180, amd#3486→amd#3064,
amd#3471→amd#3832, amd#3414→amd#3825, amd#3434 amd#3485→amd#3219, amd#5199→amd#4875.

**Miss-analysis (merged `fix` PRs, Jun 21–Oct 19).** 29 of 1005 (3%)
closed an issue an audit filed first. Missed, by title: no deadline 90
(amd#5346 amd#5384 amd#5380), release/CI ordering 71 (amd#5127 amd#5147), Windows
behaviour 38 (amd#5018 amd#5377), dishonest status 36 (amd#5112 amd#5317), shared
state across processes 34 (amd#5337 amd#5282 amd#5378), model output handling 27
(amd#4973 amd#5103), doc drift 27, cold start / non-default setup 26 (amd#4951
amd#5130). About 380 more were Agent UI/TUI or agent-behaviour fixes, which
a static read rarely catches. Noise: of the audit issues closed as
duplicate or not planned, 31 were duplicates of amd#1077, 12 of the
test-coverage umbrella amd#2988, and 6 each of amd#4331, amd#3149, amd#3308 and
amd#2922. What changed: `scripts/audit/missed_bug_classes.md` has a
checklist per class and a "Don't report" list, and all three prompts
read it at run time. The code audit gets a deterministic list of calls
with no deadline. The security audit's semgrep run and worklist now
cover TypeScript, Go, the installer and the workflows.
`scripts/audit/miss_analysis.py` refreshes the evidence monthly.

**Recent changes.** Each audit's first job writes `recent-changes.md`:
first-parent commits since the commit its last successful run checked
out, read from the run history, with PR title, a short body excerpt and
the paths each touched, capped at 30 KB. If that commit is unknown it
covers 3 days and says so.
</details>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

mcp MCP integration changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant