Skip to content

fix(utils): find JSON after placeholder braces in model output - #4332

Merged
kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/untested-module-tests
Sep 25, 2026
Merged

kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/untested-module-tests

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Document and image extraction failed whenever the model wrote a placeholder such as {field} before its JSON answer: the parser only tried the first {, gave up, and the extraction raised "did not parse". It now moves past an invalid span and finds the real JSON. It still never looks inside a broken object, so truncated or malformed output returns nothing instead of a misleading fragment. Also adds table tests for the JSON parser behind every VLM extraction path, and tests that pin the Stable Diffusion prompt text to the real per-model defaults so the size, steps, and CFG the model is told to use can't drift from them.

Covers the parser and SD-prompt parts of #4257. Chunking and cache-clearing are in #4262 and #4260. deltas_cli, code_bench_fixtures, and the TUI flag wiring already had tests. talk/app.py is left out because it needs a design decision (see the issue).

Test plan

  • python -m pytest tests/unit/test_parsing.py: 2 placeholder cases fail on main, 13/13 pass with the fix
  • python -m pytest tests/unit/test_parsing.py tests/unit/test_sd_prompts.py tests/unit/test_file_watcher.py tests/unit/test_structured_vlm_extraction.py tests/unit/test_vlm_extraction_failures.py tests/unit/test_sd_mixin.py tests/unit/test_sd_error_messages.py hub/agents/gaia/python/tests/test_sd_tools_do_not_rewrite_the_prompt.py: 176 passed, 3 skipped
  • black, isort, and pylint (errors-only, CI config) are clean on the changed files
  • python util/check_test_lane_coverage.py does not flag either new file (the pytest tests/unit/ lane runs them)

Part of #4257

Structured extraction returned nothing when the model wrote a placeholder
like "{field}" before its JSON, because only the first "{" was ever tried.
The parser now resumes after an invalid span, but never inside one, so a
malformed or truncated object still yields None rather than a fragment.

Adds table tests for extract_json_from_text (fenced code, arrays of
objects, brackets inside strings, trailing text, truncation) and pins the
SD prompt text to LemonadeClient.SD_MODEL_DEFAULTS so the size/steps/cfg
the model is told to use can't drift from the real defaults.

Part of amd#4257
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

The fix works — the parser now skips past a {field} placeholder and finds the real JSON, and the new tests are the good kind: they pin behaviour a user would notice, not implementation shape. One thing to tighten before or just after merge.

The PR promises that broken model output returns nothing rather than a misleading fragment, but that promise only holds when the broken part and the fragment are the same kind of bracket. If a truncated object contains a list, the parser still hands back that inner list as if it were the whole answer — exactly the "looks like a complete answer" failure the PR set out to prevent. The new tests don't catch it because every "must return nothing" case uses only curly braces. This is pre-existing behaviour on main, not something this PR introduced, so it isn't a merge blocker — but the new comment and tests assert an invariant the code doesn't actually enforce, and the one-line change to close it is small enough to be worth doing here.

Nothing else blocking. No security concerns.

Real-world evidence

N/A — no user-facing surface here (a parsing helper plus two new unit-test files), and no evidence-bundle.md was produced for this run. The verdict rests on static review plus one check I ran myself: I exercised the changed parsing function directly and confirmed both the intended fix and the gap described above. I could not run pytest in this environment (not installed), so the PR's own test-plan results are taken at face value.

🔍 Technical details

Issues

🟡 Fragment leak survives across bracket types (src/gaia/utils/parsing.py:111-113)

When a balanced span parses invalidly, only that bracket type's cursor is advanced past end. The other type's cursor may still point inside the failed span, so the next iteration returns an inner value from it. Verified against the changed code:

'{"a": [1, 2], oops}'            -> [1, 2]
'{"a": [1,2], "b": '             -> [1, 2]
'Rows: {"r": [{"x":1}], truncated' -> [{'x': 1}]

The last two are the array-flavoured twins of NOT_FOUND's truncated-outer-object / malformed-outer-object, which pass only because they contain no [. Same result on main, so this is an incomplete fix rather than a regression — but the comment at :111 and the test_returns_none_rather_than_a_fragment docstring both state the stronger invariant.

Advancing every cursor that sits inside the failed span closes it. Keep the end is None branch as-is — unclosed-array-then-object depends on an unclosed opener yielding to the other type:

        # Resume after an invalid span (e.g. a "{field}" placeholder) but never
        # inside it, so a malformed value can't yield one of its fragments.
        if end is None:
            next_start[open_ch] = -1
        else:
            for ch, ch_start in next_start.items():
                if ch_start != -1 and ch_start <= end:
                    next_start[ch] = text.find(ch, end + 1)

Termination still holds: the selected open_ch always has start <= end, so its cursor strictly increases or goes to -1.

Worth adding to NOT_FOUND alongside it:

    pytest.param('{"a": [1, 2], oops}', id="malformed-outer-object-around-array"),
    pytest.param('{"a": [1, 2], "b": ', id="truncated-outer-object-around-array"),

🟢 Private registry access in the SD test (tests/unit/test_sd_prompts.py:250)

tools.py:259 exposes get_tool_metadata(); the save/restore fixture genuinely needs the dict, but the lookup doesn't.

    listed = tool_registry.get_tool_metadata("list_sd_models")["function"]()["models"]

Strengths

  • Returning the close-bracket index from _extract_balanced_json is the right shape for this — it gives the caller a guaranteed-forward resume point, so the new while loop can't spin.
  • test_sd_prompts.py guards a real silent-drift class: prompt text telling the model to pass steps=/cfg_scale= values that no longer match SD_MODEL_DEFAULTS would degrade output with nothing failing. Deriving the expectations from SD_MODELS / SD_MODEL_DEFAULTS rather than hardcoding them means the test follows the defaults automatically.
  • test_system_prompt_before_init_sd_has_no_model_section correctly matches the hasattr guard in get_sd_system_prompt (src/gaia/sd/mixin.py:541), and the negative assertion that other models' sections are absent is the part that actually catches a bad refactor.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 25, 2026
Merged via the queue into amd:main with commit 641e40b Sep 25, 2026
27 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants