Skip to content

fix(agent): stop truncating JSON answers at their first quote - #4973

Merged
kovtcharov-amd merged 6 commits into
mainfrom
fix/answer-json-quote-truncation
Oct 15, 2026
Merged

kovtcharov-amd merged 6 commits into
mainfrom
fix/answer-json-quote-truncation

Conversation

@kovtcharov-amd

@kovtcharov-amd kovtcharov-amd commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Needs a flagship eval before merge — dispatched on this branch: https://github.com/amd/gaia/actions/runs/38129665575 (all lanes; the dispatch has no category filter, so read conversation, tools, and gaia-docs first).

Before: when a model answered in {"thought": …, "answer": "…"} form and the JSON wasn't strictly valid (raw newlines in a long answer, or output cut off), the answer was silently cut at its first quote — a 1200-word essay ended at "The press became the". While it streamed, a long answer started mid-text, showed literal \n\n## … and a trailing "}, and stopping it kept only that garbled fragment. After: the answer is decoded with its escapes honoured, so quotes, newlines and unicode come through intact; a reply genuinely cut off keeps everything received and ends with a note saying it was cut off; streaming shows clean text from the first word, and a stopped answer keeps that clean text.

Test plan

  • python -m pytest tests/unit/test_json_answer_decoding.py — embedded and escaped quotes, \uXXXX and surrogate pairs, raw newlines, a truncated JSON reply, a stop mid-escape, every chunk split point of a >4 KB streamed answer
  • python -m pytest tests/unit/agents/ tests/unit/chat/ui/ tests/unit/mcp tests/unit/test_tool_call_priority.py
  • python util/lint.py --black --isort
  • Flagship eval run above shows no PASS→FAIL against tests/fixtures/eval_baselines/gaia-flagship/ in conversation, tools, or gaia-docs (re-run any lone flip)
  • In the TUI or Agent UI, ask for a 1000+ word essay containing quoted phrases: it streams clean from the first word and the final answer is complete

Adversarial tests

tests/unit/test_json_answer_decoding_adversarial.py (74 cases) attacks answer parsing and streaming with:

  • unescaped quotes and trailing backslashes
  • Windows and UNC paths
  • tool JSON quoted inside an answer, and an "answer" key quoted inside the thought
  • back-to-back objects and trailing garbage
  • answers that only look truncated, next to ones that really are
  • tool calls that carry answer text
  • a 1 MB answer and 50k unescaped quotes, to catch quadratic slowdowns
  • the same shapes streamed at several split sizes

They found one real bug, fixed in this push: an unescaped Windows path came back with control characters in it. C:\Users\me\file.txt got a form feed and C:\temp got a tab, where the old regex had kept the path as written. When an answer contains a drive path written with single backslashes, the \f, \t and similar escapes inside that path now stay literal. Newlines in the surrounding prose still decode.

Unchanged, and the same as on main: a code-fenced {"answer": ...} followed by prose is shown raw.

Long answers given in {"thought": ..., "answer": "..."} form were cut off
at their first embedded quote whenever the JSON failed strict parsing, and
streamed as raw escaped text that started mid-answer.

- The malformed-JSON fallback pulled the answer with a `[^"]*` regex, which
  stops at the first escaped quote and never unescapes. It now decodes the
  JSON string with escapes honoured (quotes, \n, \uXXXX, surrogate pairs);
  raw newlines inside the string parse leniently first, and a value cut off
  before its closing quote keeps everything received plus a note saying so.
- The SSE stream dropped the buffered opening once a JSON answer passed
  4 KB, then emitted the rest raw (literal \n, trailing "}). It now streams
  the decoded answer value from its first character, holds escapes split
  across chunks, and drops the closing JSON structure, so a stopped answer
  keeps clean text.
@github-actions github-actions Bot added mcp MCP integration changes tests Test changes agents labels Oct 11, 2026
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

Holding: the eval run linked above is incomplete. The gaia-docs lane (one of the three to read first) and memory never scored a scenario because the Claude eval quota ran out, so this still needs a re-run of at least gaia-docs after the quota resets.

🔍 Technical details
  • Run 38129665575 on 9e32e08: both gaia-docs and memory stopped at the preflight check with QUOTA EXHAUSTED (402/429-class), so their "Regressed categories: none" lines compare nothing.
  • This PR has to be eval-gated: _parse_llm_response now runs a lenient json.loads(strict=False) pass before extraction, which changes which model outputs parse as tool calls or answers. It also appends TRUNCATED_ANSWER_NOTE to cut-off answers, and that text goes back into conversation history.

… answers

A malformed answer whose model forgot to escape an inner quote was still
cut at that quote, and an answer ending in a bare backslash (C:\Users\me\)
was reported as cut off and got the truncation note. A closing quote now
only counts when JSON structure follows it.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

Pushed one fix: a malformed answer was still cut short when the model forgot to escape an inner quote, and an answer ending in a bare backslash (C:\Users\me\) was wrongly marked as cut off. Both now come through whole. Still waiting on the gaia-docs eval re-run.

🔍 Technical details
  • extract_json_string_field only accepts a closing quote when JSON structure follows it (}, ], , "key":, or end of text). Otherwise the quote stays in the value. A value ending in \"} is read as a trailing backslash plus the closing quote, so TRUNCATED_ANSWER_NOTE is only added when the closing quote really is missing.
  • New tests in tests/unit/test_json_answer_decoding.py: unescaped inner quotes (including "red", "green"), a truncation right after an unescaped quote, and a trailing-backslash path that must not get the note.
  • Known gap, low severity, not fixed: if a reply puts "answer" before "tool", the answer text streams as chunks before the tool runs. The old code held the whole object and filtered it. The final answer event replaces the streamed text in the Agent UI, so the leak only shows while the turn is running.
  • Checked: the strict=False pass only relaxes control characters inside strings, so it can't turn a non-tool reply into a tool call. Tool calls with raw newlines in tool_args now run with their real arguments instead of {}.

… paths

The lenient answer decoder turned an unescaped Windows path into control
characters: C:\Users\me\file.txt came back with a form feed and C:\temp with a
tab, where the old regex kept the path verbatim. When the answer holds a drive
path written with single backslashes, \b \f \n \r \t that continue a drive
path now stay literal; newlines in the surrounding prose still decode.

Adds tests for unescaped quotes, trailing backslashes, Windows paths, JSON
inside the answer, an answer key quoted in another value, back-to-back
objects, trailing garbage, real versus apparent truncation, tool calls that
look like answers, a 1 MB answer, and the streamed SSE path.
@kovtcharov-amd
kovtcharov-amd marked this pull request as ready for review October 15, 2026 08:28
@github-actions

Copy link
Copy Markdown
Contributor

Skill audit

Skill Verdict Claimed tier Cleared tiers Findings Rules
.claude/skills/driving-the-tui ✅ ALLOW experimental experimental, community none —
.claude/skills/gaia-release ✅ ALLOW experimental experimental, community none —
hub/agents/gaia/npm ✅ ALLOW experimental experimental 2 high body.injection.credential_request, body.injection.persona_override

✅ All audited skills cleared the tier they claim.

Per-finding detail is withheld here on purpose. Read it in the Security > Code scanning tab, or download the skill-audit-reports artifact from this run. Offending source text is withheld from CI everywhere — reproduce it locally with gaia skill audit <dir> --show-snippets.

# Conflicts:
#	src/gaia/agents/base/agent.py
#	src/gaia/ui/sse_handler.py
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions (merge once the eval actually runs)

Long {"answer": "…"} replies used to stop at their first quote. Now they decode with escapes intact, stream as clean text, and a reply that really was cut off keeps all of its text plus a visible "cut off" note. The fix is careful and well tested, and the live evidence below confirms it on the real backend.

  • The required flagship eval hasn't actually run. This changes how model replies are parsed, so CLAUDE.md requires an eval. Every lane on the re-dispatched run failed after about 8 seconds, which is a setup failure, not a score. Re-dispatch it and check conversation, tools and gaia-docs against the baseline before merging.
  • One small robustness gap in the streaming handler is listed below. It doesn't block.

Real-world evidence

The evidence stage ran the real Agent UI backend and the real gaia agent at this PR's head, using a stand-in model that splits JSON escapes across chunks. The Agent UI screenshot is pending strix-halo lane, and the CLI is N/A (no command changed).

Escaped quotes, a backslash, \n and \u00e9, split across chunks (POST /api/chat/send):

data: {"type": "chunk", "content": "He said "}
data: {"type": "chunk", "content": "\"use C:"}
data: {"type": "chunk", "content": "\\temp\" then"}
data: {"type": "chunk", "content": "\nline two with "}
data: {"type": "chunk", "content": "\u00e9 ok."}
data: {"type": "answer", "content": "He said \"use C:\\temp\" then\nline two with \u00e9 ok.", "elapsed": 0.37, "steps": 1, "tools_used": 0}
HTTP 200

A truncated reply, after this PR and then on the base commit:

data: {"type": "answer", "content": "Step one: open \"Settings\".\nStep two: pick the mo\n\n*(This answer was cut off before the model finished.)*", ...}
=== base: truncated      (answer cut at the first escaped quote)
data: {"type": "answer", "content": "Step one: open \\", ...}

MCP send_message through a real stdio client returned "content": "He said \"use C:\\temp\" then\nline two with é ok.". The spot checks all passed: a plain-text reply with quotes, GET /api/chat/active, GET /api/sessions and MCP list_sessions. The fix works on the HTTP and MCP surfaces. How a real model behaves, and the rendered UI, are still unproven until the strix-halo lane runs.

🔍 Technical details

🟡 The flagship eval gate isn't met. This PR changes tool-call and answer parsing (_parse_llm_response gains a strict=False pass, and the regex fallback was replaced). That is on CLAUDE.md's list of changes that require an eval. Run 38129665575 concluded failure, and on the latest push every Scenario eval - <lane> job failed in 8s. That is infra, not a result. Before merging, get a run that produces scorecards, then diff it against tests/fixtures/eval_baselines/gaia-flagship/. The strict=False path now accepts tool-call JSON with raw newlines in tool_args (for example, file contents) that used to go through _extract_json_from_response. The tools lane is where any change in behaviour would show up.

🟢 Answer-stream state only resets on end_of_stream or signal_done (src/gaia/ui/sse_handler.py:775). The cancelled_by_console: break path and a mid-stream exception followed by the context-trim retry (agent.py ~8025 and ~8060) both skip print_streaming_text("", end_of_stream=True). If a stream dies mid-answer and the loop retries, the retry's raw {"thought": … would be fed into the still-open decoder and shown as answer text. It's unlikely in practice, since overflow errors usually come before the first chunk, but resetting at the start of each model call would close the gap. One option is to reset _answer_stream in _announce_model_call, or wherever the handler marks the start of a new LLM request.

🟢 Case 1b matches an "answer" key at any depth. json_string_field_start finds the first unescaped "answer": " anywhere in the buffer. Case 1 ("tool") runs first, so a tool call whose tool_args holds an answer field is usually caught there. It isn't caught if the model writes tool_args before "tool". That ordering is rare, but anchoring on a top-level key (or requiring that "tool" hasn't appeared once the value closes) would be stricter.

Strengths

  • decode_json_string_prefix correctly holds back escapes that are still incomplete (\, \u00, a lone high surrogate), so splitting the stream at any point can't corrupt text. The test that tries every split point of a >4 KB answer pins this.
  • Truncation is reported loudly: a logged warning and a visible note in the answer, never a silently shortened reply. That fits the fail-loudly rule.
  • The adversarial suite (Windows/UNC paths, unescaped quotes, a 1 MB answer, 50k quotes to catch quadratic slowdowns) found and fixed a real bug, the drive-path control characters, before merge.

… answer

The JSON-string decoder keeps a quote that is not followed by JSON
structure; the fallback test still expected the regex's cut at it.
# Conflicts:
#	src/gaia/ui/sse_handler.py
@kovtcharov-amd
kovtcharov-amd merged commit 85bb527 into main Oct 15, 2026
@kovtcharov-amd
kovtcharov-amd deleted the fix/answer-json-quote-truncation branch October 15, 2026 11:36
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

agents mcp MCP integration changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant