Skip to content

fix(inference): recover one JSON object wrapped in LLM prose - #297

Merged
rng1995 merged 17 commits into
mainfrom
naren/port-llm-json-preamble
Nov 5, 2026
Merged

rng1995 merged 17 commits into
mainfrom
naren/port-llm-json-preamble

Conversation

@rng1995

@rng1995 rng1995 commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Keep the whole-reply json.loads parse in LLMClient.extract_json_from_response, including Markdown fence stripping, as the first path. The fence strip no longer raises IndexError on a fenced reply written on one line (```{...}```); such a reply now reaches the fallback below.
  • If that parse fails, scan the reply for string-aware balanced {...} and [...] spans and accept exactly one span that decodes to a JSON object. A reply with several objects raises LLMClientError ("found N JSON objects; expected exactly one") instead of picking one.
  • Each span is decoded as a whole and then skipped, so nothing nested inside it is promoted: not the members of a valid object or array, and not an object inside a malformed container (missing comma, unquoted key, object where a key is expected, malformed array). Decoded arrays are skipped without being counted, so chunk citations such as [1] in the prose are harmless. A span that never closes, closes with a mismatched bracket or nests deeper than 128 levels ends the scan.
  • Spans never overlap, so the fallback stays linear in the reply length.
  • Both the whole reply and each embedded span are decoded with the same strict hooks as the Tier 3 judge: an object with a duplicate key, a NaN/Infinity constant or a number that overflows a float is rejected instead of letting the last key win or passing a non-finite value through.
  • Nesting deeper than 128 levels is checked before decoding, for the whole reply as well as embedded spans, so the outcome does not depend on the Python version or stack size (Python 3.14 can decode very deep JSON that 3.13 rejects with RecursionError). Replies the decoder cannot handle (over-deep nesting, integers beyond Python's digit limit) fail closed with LLMClientError instead of raising RecursionError/ValueError, both when the payload is the whole reply and when it is embedded in prose.
  • The span scan, nesting bound and decode hooks move from the Tier 3 judge (tier3/eval_core/llm_judge.py) into a new shared module, skillevaluator/inference/json_span.py (balanced_json_container_end, json_nesting_within_limit, STRICT_JSON_DECODE_HOOKS). The judge imports them with unchanged behavior, and the inference client imports the shared module, so it does not import Tier 3. The standalone Harbor eval.py template keeps its own copy, as before.
  • Documents the accepted reply shape in docs/tier2-deduplication.mdx and adds a CHANGELOG entry under Unreleased > Fixed.

Why

Tier 2 deduplication asks the chat LLM for a JSON-only verdict. Replies that use prompt-only JSON can add a short explanation before or after the object, or put a fenced block after a preamble. Bedrock always uses prompt-only JSON. Other providers fall back to it after an endpoint rejects the structured-output schema (the downgrade added for #207), and so do endpoints that accept response_format but ignore it. extract_json_from_response passed the whole reply to json.loads, so a valid verdict inside prose failed with LLM returned invalid JSON. Tier 2 then marked deduplication incomplete with a nonzero exit, which also blocks BENCHMARK.md publication.

Kept from public

  • The current extract_json_from_response signature (response_schema, schema_name) and the structured-output request and schema-downgrade logic are unchanged. Recovery only runs after the strict parse fails.
  • Tier 2's handling of failed clusters is unchanged: incomplete scan, provider/model diagnostic, no invented findings. The verdict checks in analyze_cluster are also unchanged.
  • The optional plugin bundle verdict (deduplication/plugin/llm_analyzer.py) calls the same method and keeps its own object, verdict and confidence checks; a recovered object goes through them unchanged.
  • The fallback follows the hardening conventions of the Tier 3 judge's JSON extraction (_extract_json), and both now use the shared balanced_json_container_end, nesting bound and decode hooks in skillevaluator.inference.json_span (only the standalone Harbor eval.py template keeps its private _balanced_json_container_end copy):
    • skip each string-aware balanced container as a whole, so an object is never promoted out of a malformed one
    • stop at a container that never closes, closes with a mismatched bracket or nests too deeply
    • reject duplicate keys, non-standard constants and non-finite floats
    • catch RecursionError and ValueError alongside JSONDecodeError
    • reject ambiguous multi-document replies
  • One deliberate difference: Tier 3 counts top-level arrays as documents, while this fallback skips them, because Tier 2 accepts only an object and its prose often cites chunks as [1].
  • The tests use the existing monkeypatch provider setup (SKILL_EVAL_LLM_PROVIDER=nv_build, NVIDIA_API_KEY) and the Bedrock litellm.completion mock pattern.

Tests

  • New tests in tests/inference/test_llm_client.py::TestExtractJsonFromResponse. Each test that expects recovery fails on main.
    • a Tier 2 verdict surrounded by prose
    • a fenced object after a preamble
    • a fenced object written on one line
    • a nested object counted once
    • non-JSON prose braces and bracketed citations skipped
    • two objects rejected
    • an object not promoted out of another container: missing comma after a nested object, missing comma before a nested key, an object where a key is expected, an unquoted key, an outer object that never closes, a malformed array and a valid array
    • nesting just beyond the 128-level limit, very deep nesting and an oversized integer failing closed with LLMClientError, as the whole reply and inside prose; an object exactly at the limit is accepted
    • a duplicate key (top-level and nested), NaN, -Infinity and a float overflow rejected, as the whole reply and inside prose, and a rejected draft object not hiding the one valid object
    • over-deep nesting blocking a later object
    • 5,000 malformed {x} spans skipped before the object is recovered
    • a Bedrock prompt-only reply with a preamble recovered (and no response_format sent)
  • New tests/inference/test_json_span.py: the Tier 3 judge and the inference client use the shared helpers, plus unit tests for the span scan, the nesting bound and the strict decode hooks.
  • With the PR's own tests, on the branch merged with current main: tests/inference, tests/deduplication, tests/validators, tests/embedding/test_client.py, tests/test_llm_client_retry.py, tests/test_llm_judge.py, tests/test_tier2_command_failures.py, tests/tier3/test_judge_parse_robustness.py, OSS packaging tests, and the docs and CHANGELOG readers (test_accuracy_arithmetic.py, test_benchmark_rollout_docs.py, test_ci_change_classifier.py, test_tier3_public_runtime.py): 4293 passed, 3 skipped.
  • ruff check and ruff format --check are clean on the changed files (this also wraps two long monkeypatch.setattr lines in test_llm_client.py that fail ruff format --check on main).
  • scripts/check_oss_boundary.py passed.

🤖 Generated with Claude Code

rng1995 and others added 2 commits October 30, 2026 11:59
Tier 2 deduplication asks the chat LLM for a JSON-only verdict, but replies
that use prompt-only JSON (Bedrock always; other providers after an endpoint
rejects the structured-output schema) sometimes add a short explanation
before or after the object, or put a fenced block after a preamble.
extract_json_from_response passed the whole reply to json.loads, so these
clusters failed with "LLM returned invalid JSON" and Tier 2 was reported
incomplete even though the verdict itself was valid.

Keep the strict whole-reply parse (with fence stripping) as the first path.
When it fails, scan the reply with JSONDecoder.raw_decode and accept exactly
one complete top-level object. Several objects are rejected with
"found N JSON objects; expected exactly one" instead of guessing. The scan
resumes after each decoded object, so nested objects are not counted twice,
and after the failure point of a malformed container, so an object nested
inside it is never promoted. Replies the decoder cannot handle (nesting past
the recursion limit, integers past the digit limit) and replies with more
than 64 malformed brace candidates fail closed with LLMClientError, which
keeps the fallback linear in the reply length.

Tier 2 verdict validation is unchanged.

Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The prose fallback resumed scanning at the decoder's failure point, so an
outer object that failed before or at a nested '{' let the nested object
be returned as the verdict. A reply such as
{"verdict": "RELATED_BUT_DISTINCT" "detail": {"verdict": "DUPLICATE"}}
became a DUPLICATE finding, and objects inside malformed arrays were
promoted the same way.

Scan string-aware balanced {...} and [...] spans instead, the way the
Tier 3 judge extraction does, decode each span as a whole and skip it.
Nothing nested inside a span is promoted. Decoded arrays are skipped
without being counted, so chunk citations such as [1] stay harmless. A
span that never closes, closes with a mismatched bracket or nests deeper
than 128 levels ends the scan. Spans never overlap, so the scan is
linear and the malformed-candidate cap is no longer needed.

Also catch RecursionError and ValueError on the strict whole-reply
parse, so an over-deep or oversized-integer reply fails with
LLMClientError when it is not wrapped in prose, and strip a Markdown
fence with partition so a fenced reply on one line reaches the fallback
instead of raising IndexError.

Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

@rng1995 rng1995 left a comment

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.

Review summary: no findings.

Checked the strict-parse-first order, the one-line fence fix (partition instead of split/IndexError), the string-aware balanced-span scan (linear, depth-capped, fail-closed on RecursionError/ValueError), the one-object rule, and the CHANGELOG (Unreleased > Fixed) and docs entries. tests/inference passes locally (190 passed) and ruff check is clean.

Reviewed with Claude Code.

Conflicted files: CHANGELOG.md.

Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

@chrisknvidia chrisknvidia left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I went through the strict-parse-first path, the string-aware span scan and the exactly-one-object rule, and ran scratch replies through the helper: braces and quotes in prose, braces and escaped quotes inside strings, an array wrapping the verdict, {} in prose, an unclosed span, a quoted example object, two fenced blocks. Each either recovers the right object or fails closed, and an object quoted from the skill text only gets through if it carries a valid verdict, same as a pure-JSON reply would. Nothing blocking; one small cleanup note.

Comment thread src/skillevaluator/inference/client.py Resolved
rng1995 and others added 9 commits November 3, 2026 04:14
Conflicted: CHANGELOG.md.

Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… judge

Move the string-aware container scan, the nesting bound and the strict
decode hooks (duplicate members, NaN/Infinity, float overflow) from the
Tier 3 judge into skillevaluator.utils.json_spans. The judge keeps its
private names as aliases, and the inference client imports the shared
module instead of carrying its own copy, so it does not depend on Tier 3.

The client now decodes both the whole reply and embedded spans with the
shared hooks, so a verdict such as {"verdict": "DUPLICATE", ...,
"verdict": "RELATED_BUT_DISTINCT"} is rejected instead of letting the
last key win.

Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The whole-reply parse handed any depth to json.loads, so a 100,000-level
reply raised RecursionError on Python 3.13 but decoded on Python 3.14
when the C stack allowed it, and the fail-closed test failed on the
3.14 CI job. Check the 128-level bound that the embedded scan and the
Tier 3 judge already use before decoding, so an over-deep reply fails
with LLMClientError on every Python version and stack size.

Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Move the balanced-span scanner and strict decode hooks into
inference/json_span.py so the inference client and the Tier 3 judge accept and
refuse the same replies. The client now rejects duplicate keys, NaN/Infinity
and overflowing floats in embedded objects, as the judge does.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Narendran Raghavan <[email protected]>
Conflicted: CHANGELOG.md (Unreleased > Fixed) kept main's new Tier 3
progress-interval and SkillSpector watchdog entries unchanged and placed this
PR's Tier 2 JSON-preamble entry after them. client.py, the Tier 2 docs and
test_llm_client.py merged cleanly alongside main's LLM timeout and refusal
changes.

Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in 4cba632 (shared JSON span scanning with the Tier 3 judge), pushed
while main was being merged. No conflicts: client.py and test_llm_client.py
merged cleanly; json_span.py and llm_judge.py are untouched by main.

Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eamble

Conflicted: CHANGELOG.md, src/skillevaluator/inference/client.py, src/skillevaluator/tier3/eval_core/llm_judge.py; the shared helpers now live only in inference/json_span.py (utils/json_spans.py dropped, its nesting bound moved there).

Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicted: CHANGELOG.md.

Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
test_ambiguous_object_is_rejected already covers the duplicate key, NaN
and float overflow cases inside prose, as well as the whole-reply cases.

Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

@chrisknvidia chrisknvidia left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Follow-up on the current head. The span scan, nesting bound and strict decode hooks now live in inference/json_span.py, and both the inference client and the Tier 3 judge import them, so duplicate keys, NaN/Infinity and overflowing floats are handled the same way in both places, including when the whole reply is the object. Checking the nesting bound before the whole-reply decode also makes the deep-nesting case independent of the Python version. Nothing further from me.

rng1995 and others added 4 commits November 5, 2026 22:29
Resolve the CHANGELOG.md conflict under Unreleased by keeping this
branch's Tier 2 JSON preamble entry and main's new entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Narendran Raghavan <[email protected]>
@rng1995
rng1995 enabled auto-merge (squash) November 5, 2026 18:06
@rng1995
rng1995 merged commit 61ca935 into main Nov 5, 2026
22 checks passed
@rng1995
rng1995 deleted the naren/port-llm-json-preamble branch November 5, 2026 18:39
rng1995 added a commit that referenced this pull request Nov 5, 2026
Resolve the CHANGELOG.md conflict: keep main's Tier 2 JSON-in-prose entry
(#297) and add this PR's failing-score explanation entries after it.

Signed-off-by: Narendran Raghavan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@rng1995 rng1995 mentioned this pull request Nov 6, 2026
7 of 8 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants