From 0abc2b74597e87f6e9c9907f27f5e6ced7614773 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Thu, 29 Oct 2026 10:42:06 -0700 Subject: [PATCH 1/6] fix(inference): recover one JSON object wrapped in LLM prose 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 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +++ docs/tier2-deduplication.mdx | 5 ++ src/skillevaluator/inference/client.py | 49 ++++++++++++++- tests/inference/test_llm_client.py | 83 ++++++++++++++++++++++++++ 4 files changed, 142 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3f173a3a..b7c4c77c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -309,6 +309,13 @@ All notable changes to SkillEvaluator are documented in this file. `quality-check` before any report was written. The schema check reports the malformed `metadata`, and the quality score counts `metadata.author` and `metadata.tags` as missing, as it already did for other non-mapping values. +- Tier 2 deduplication no longer fails a content cluster when the model wraps + its JSON verdict in prose or puts a fenced block after a short preamble. + Such replies come from prompt-only JSON, which Bedrock always uses and other + providers fall back to after rejecting the structured-output schema; they + previously failed with `LLM returned invalid JSON` and left Tier 2 + incomplete. Exactly one embedded JSON object is accepted. Replies with + several objects are still rejected instead of guessed. ## 0.6.0 - 2026-10-20 diff --git a/docs/tier2-deduplication.mdx b/docs/tier2-deduplication.mdx index 8e72f9eab..7b393008a 100644 --- a/docs/tier2-deduplication.mdx +++ b/docs/tier2-deduplication.mdx @@ -149,6 +149,11 @@ Duplicate findings map to severities by confidence: | `DUPLICATE` with confidence < 0.70 | MEDIUM — advisory | | Short, same-file duplicate dominated by comment or configuration-style text | Capped at LOW — advisory | +The chat LLM answers each cluster with one JSON verdict. A reply that wraps +exactly one JSON object in prose or a Markdown fence is accepted, which matters +on Bedrock and other endpoints that answer with prompt-only JSON. A reply with +no complete object or with more than one counts as a failed analysis. + If chat-LLM analysis fails for a candidate cluster, Tier 2 reports the incomplete analysis as a blocking error rather than treating the content as clean. diff --git a/src/skillevaluator/inference/client.py b/src/skillevaluator/inference/client.py index 32b68301d..8717463ef 100644 --- a/src/skillevaluator/inference/client.py +++ b/src/skillevaluator/inference/client.py @@ -340,6 +340,41 @@ def _extract_choice_content(response: Any) -> str: ) +# Malformed ``{`` candidates tolerated before recovery gives up. Each failed +# decode costs time proportional to the reply length. +_MAX_EMBEDDED_JSON_DECODE_FAILURES = 64 + + +def _embedded_json_objects(text: str) -> list[dict[str, Any]]: + """Return the complete top-level JSON objects embedded in prose. + + Scanning resumes after each decoded object, so nested objects are not + counted separately, and after the failure point of a malformed one, so an + object nested inside it is never promoted. Replies the decoder cannot + handle (excessive nesting, oversized integers) or with too many malformed + candidates yield no objects. + """ + decoder = json.JSONDecoder() + objects: list[dict[str, Any]] = [] + failures = 0 + cursor = 0 + while (start := text.find("{", cursor)) != -1: + try: + value, end = decoder.raw_decode(text, start) + except json.JSONDecodeError as exc: + failures += 1 + if failures > _MAX_EMBEDDED_JSON_DECODE_FAILURES: + return [] + cursor = max(exc.pos, start + 1) + continue + except (RecursionError, ValueError): + return [] + cursor = end + if isinstance(value, dict): + objects.append(value) + return objects + + class LLMClient: """Public-provider client for chat completions. @@ -683,7 +718,13 @@ def extract_json_from_response( response_schema: dict[str, Any] | None = None, schema_name: str = "judge_response", ) -> dict: - """Send a completion and parse JSON from the response.""" + """Send a completion and parse one unambiguous JSON object from the response. + + The whole reply, optionally in a Markdown fence, is parsed first. Models + without structured output (Bedrock, or after a schema downgrade) may + still wrap the object in prose; exactly one embedded object is then + accepted, while several objects remain an error rather than a guess. + """ raw = self.completions(system_prompt, user_prompt, response_schema=response_schema, schema_name=schema_name) cleaned = raw.strip() @@ -694,7 +735,11 @@ def extract_json_from_response( try: return json.loads(cleaned) except json.JSONDecodeError as e: - raise LLMClientError(f"LLM returned invalid JSON: {e}\nRaw: {raw[:500]}") from e + objects = _embedded_json_objects(raw) + if len(objects) == 1: + return objects[0] + detail = f"found {len(objects)} JSON objects; expected exactly one" if objects else str(e) + raise LLMClientError(f"LLM returned invalid JSON: {detail}\nRaw: {raw[:500]}") from e # -- template-method hooks (override in subclasses) ------------------- diff --git a/tests/inference/test_llm_client.py b/tests/inference/test_llm_client.py index 7dae183f5..690a6aa3d 100644 --- a/tests/inference/test_llm_client.py +++ b/tests/inference/test_llm_client.py @@ -748,6 +748,15 @@ def test_vertex_openapi_does_not_refresh_token_when_explicit_api_key_provided( assert client._resolved_config().api_key == "explicit-user-key" +def _extract_json_reply(monkeypatch: pytest.MonkeyPatch, content: str) -> dict: + monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "nv_build") + monkeypatch.setenv("NVIDIA_API_KEY", "test-key") + mock_openai = MagicMock() + mock_openai.chat.completions.create.return_value.choices = [MagicMock(message=MagicMock(content=content))] + with patch("openai.OpenAI", return_value=mock_openai): + return LLMClient().extract_json_from_response("system", "user") + + class TestExtractJsonFromResponse: def test_parses_plain_json(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "nv_build") @@ -773,6 +782,80 @@ def test_strips_markdown_fences(self, monkeypatch: pytest.MonkeyPatch) -> None: result = client.extract_json_from_response("system", "user") assert result == {"key": "value"} + def test_recovers_one_object_surrounded_by_prose(self, monkeypatch: pytest.MonkeyPatch) -> None: + content = ( + "The chunks overlap, but one summarizes what the other explains.\n\n" + '{"verdict": "INTENTIONAL_DETAIL", "confidence": 0.82, ' + '"rationale": "Summary and detail.", "suggestion": "Keep both sections."}' + "\n\nLet me know if you need more detail." + ) + + assert _extract_json_reply(monkeypatch, content) == { + "verdict": "INTENTIONAL_DETAIL", + "confidence": 0.82, + "rationale": "Summary and detail.", + "suggestion": "Keep both sections.", + } + + def test_recovers_fenced_object_after_prose_preamble(self, monkeypatch: pytest.MonkeyPatch) -> None: + content = 'Here is the result:\n```json\n{"key": "value"}\n```' + + assert _extract_json_reply(monkeypatch, content) == {"key": "value"} + + def test_nested_object_is_not_counted_as_a_second_object(self, monkeypatch: pytest.MonkeyPatch) -> None: + assert _extract_json_reply(monkeypatch, 'Result:\n{"outer": {"key": "value"}}') == {"outer": {"key": "value"}} + + def test_prose_braces_that_are_not_json_are_skipped(self, monkeypatch: pytest.MonkeyPatch) -> None: + content = 'Compare {skill_name} with ${HOME} first.\n{"key": "value"}' + + assert _extract_json_reply(monkeypatch, content) == {"key": "value"} + + def test_multiple_embedded_objects_raise(self, monkeypatch: pytest.MonkeyPatch) -> None: + with pytest.raises(LLMClientError, match="found 2 JSON objects; expected exactly one"): + _extract_json_reply(monkeypatch, 'First: {"key": "one"}\nSecond: {"key": "two"}') + + def test_object_inside_malformed_container_is_not_promoted(self, monkeypatch: pytest.MonkeyPatch) -> None: + content = 'Result: {"verdict": "RELATED_BUT_DISTINCT", "detail": {"verdict": "DUPLICATE"} "rationale": "x"}' + + with pytest.raises(LLMClientError, match="invalid JSON"): + _extract_json_reply(monkeypatch, content) + + @pytest.mark.parametrize( + "payload", + [ + pytest.param('{"a":' * 100_000 + "1" + "}" * 100_000, id="nesting-beyond-recursion-limit"), + pytest.param('{"a": ' + "1" * 5_000 + "}", id="integer-beyond-digit-limit"), + ], + ) + def test_undecodable_embedded_object_fails_closed(self, monkeypatch: pytest.MonkeyPatch, payload: str) -> None: + with pytest.raises(LLMClientError, match="invalid JSON"): + _extract_json_reply(monkeypatch, "Result: " + payload + ' {"key": "value"}') + + def test_recovery_stops_after_bounded_malformed_candidates(self, monkeypatch: pytest.MonkeyPatch) -> None: + limit = client_mod._MAX_EMBEDDED_JSON_DECODE_FAILURES + obj = '{"key": "value"}' + + assert _extract_json_reply(monkeypatch, "{x} " * limit + obj) == {"key": "value"} + with pytest.raises(LLMClientError, match="invalid JSON"): + _extract_json_reply(monkeypatch, "{x} " * (limit + 1) + obj) + + def test_bedrock_prompt_only_reply_with_preamble_is_recovered(self, monkeypatch: pytest.MonkeyPatch) -> None: + from skillevaluator.deduplication.intra_skill.llm_analyzer import VERDICT_JSON_SCHEMA + + _use_provider(monkeypatch, "bedrock", CHAT_DEFAULT_BEDROCK) + reply = ( + "Both chunks list the same setup steps.\n" + '{"verdict": "DUPLICATE", "confidence": 0.9, "rationale": "Same steps.", "suggestion": "Keep one copy."}' + ) + + with patch("litellm.completion", return_value=_openai_choice_response(reply)) as completion: + result = LLMClient().extract_json_from_response( + "system", "user", response_schema=VERDICT_JSON_SCHEMA, schema_name="dedup_verdict" + ) + + assert result["verdict"] == "DUPLICATE" + assert "response_format" not in completion.call_args.kwargs + def test_invalid_json_raises(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "nv_build") monkeypatch.setenv("NVIDIA_API_KEY", "test-key") From 45423049dc6edc591ad9fd21f7d31d15caf07251 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Thu, 29 Oct 2026 23:45:53 -0700 Subject: [PATCH 2/6] fix(inference): skip whole JSON containers when recovering a verdict 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 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 +++-- docs/tier2-deduplication.mdx | 4 +- src/skillevaluator/inference/client.py | 76 ++++++++++++++++++-------- tests/inference/test_llm_client.py | 53 ++++++++++++++---- 4 files changed, 107 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7c4c77c4..e0c48d91a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -310,12 +310,14 @@ All notable changes to SkillEvaluator are documented in this file. malformed `metadata`, and the quality score counts `metadata.author` and `metadata.tags` as missing, as it already did for other non-mapping values. - Tier 2 deduplication no longer fails a content cluster when the model wraps - its JSON verdict in prose or puts a fenced block after a short preamble. - Such replies come from prompt-only JSON, which Bedrock always uses and other - providers fall back to after rejecting the structured-output schema; they - previously failed with `LLM returned invalid JSON` and left Tier 2 - incomplete. Exactly one embedded JSON object is accepted. Replies with - several objects are still rejected instead of guessed. + its JSON verdict in prose, puts a fenced block after a short preamble, or + writes the fenced block on one line. Such replies come from prompt-only JSON, + which Bedrock always uses and other providers fall back to after rejecting + the structured-output schema; they previously failed with + `LLM returned invalid JSON` (or an `IndexError` for the one-line fence) and + left Tier 2 incomplete. Exactly one embedded JSON object is accepted. Replies + with several objects are still rejected instead of guessed, and an object + inside an array or a malformed container is never used as the verdict. ## 0.6.0 - 2026-10-20 diff --git a/docs/tier2-deduplication.mdx b/docs/tier2-deduplication.mdx index 7b393008a..c03954ead 100644 --- a/docs/tier2-deduplication.mdx +++ b/docs/tier2-deduplication.mdx @@ -152,7 +152,9 @@ Duplicate findings map to severities by confidence: The chat LLM answers each cluster with one JSON verdict. A reply that wraps exactly one JSON object in prose or a Markdown fence is accepted, which matters on Bedrock and other endpoints that answer with prompt-only JSON. A reply with -no complete object or with more than one counts as a failed analysis. +no complete object or with more than one counts as a failed analysis. An object +nested inside an array or inside a malformed container is never used as the +verdict. If chat-LLM analysis fails for a candidate cluster, Tier 2 reports the incomplete analysis as a blocking error rather than treating the content as diff --git a/src/skillevaluator/inference/client.py b/src/skillevaluator/inference/client.py index 8717463ef..938a76242 100644 --- a/src/skillevaluator/inference/client.py +++ b/src/skillevaluator/inference/client.py @@ -340,38 +340,70 @@ def _extract_choice_content(response: Any) -> str: ) -# Malformed ``{`` candidates tolerated before recovery gives up. Each failed -# decode costs time proportional to the reply length. -_MAX_EMBEDDED_JSON_DECODE_FAILURES = 64 +# Bracket depth beyond which an embedded span is not decoded. Verdicts are +# shallow, and the cap keeps the decoder well away from the recursion limit. +_MAX_EMBEDDED_JSON_NESTING = 128 +_JSON_CONTAINER_START = re.compile(r"[{\[]") + + +def _balanced_json_span_end(text: str, start: int) -> int | None: + """Return the exclusive end of the string-aware ``{...}``/``[...]`` span at *start*. + + ``None`` means the span never closes, closes with a mismatched bracket, or + nests deeper than ``_MAX_EMBEDDED_JSON_NESTING``. + """ + closers: list[str] = [] + in_string = False + escaped = False + for index in range(start, len(text)): + ch = text[index] + if in_string: + if escaped: + escaped = False + elif ch == "\\": + escaped = True + elif ch == '"': + in_string = False + elif ch == '"': + in_string = True + elif ch in "{[": + closers.append("}" if ch == "{" else "]") + if len(closers) > _MAX_EMBEDDED_JSON_NESTING: + return None + elif ch in "}]": + if not closers or closers.pop() != ch: + return None + if not closers: + return index + 1 + return None def _embedded_json_objects(text: str) -> list[dict[str, Any]]: """Return the complete top-level JSON objects embedded in prose. - Scanning resumes after each decoded object, so nested objects are not - counted separately, and after the failure point of a malformed one, so an - object nested inside it is never promoted. Replies the decoder cannot - handle (excessive nesting, oversized integers) or with too many malformed - candidates yield no objects. + Each ``{`` or ``[`` starts a string-aware balanced span that is decoded as a + whole and then skipped, so nothing nested inside a span is ever promoted: + not the members of a valid object or array, and not an object inside a + span that fails to decode. Decoded arrays are not counted, so chunk + citations such as ``[1]`` stay harmless. A span that never closes, closes + with a mismatched bracket or nests too deeply ends the scan, because its + extent is unknown. Spans never overlap, so the work stays linear in the + reply length. """ - decoder = json.JSONDecoder() objects: list[dict[str, Any]] = [] - failures = 0 cursor = 0 - while (start := text.find("{", cursor)) != -1: + while (match := _JSON_CONTAINER_START.search(text, cursor)) is not None: + start = match.start() + end = _balanced_json_span_end(text, start) + if end is None: + break try: - value, end = decoder.raw_decode(text, start) - except json.JSONDecodeError as exc: - failures += 1 - if failures > _MAX_EMBEDDED_JSON_DECODE_FAILURES: - return [] - cursor = max(exc.pos, start + 1) - continue + value = json.loads(text[start:end]) except (RecursionError, ValueError): - return [] - cursor = end + value = None if isinstance(value, dict): objects.append(value) + cursor = end return objects @@ -729,12 +761,12 @@ def extract_json_from_response( cleaned = raw.strip() if cleaned.startswith("```"): - cleaned = cleaned.split("\n", 1)[1] + cleaned = cleaned.partition("\n")[2] cleaned = cleaned.rsplit("```", 1)[0].strip() try: return json.loads(cleaned) - except json.JSONDecodeError as e: + except (RecursionError, ValueError) as e: objects = _embedded_json_objects(raw) if len(objects) == 1: return objects[0] diff --git a/tests/inference/test_llm_client.py b/tests/inference/test_llm_client.py index 690a6aa3d..f0f83114f 100644 --- a/tests/inference/test_llm_client.py +++ b/tests/inference/test_llm_client.py @@ -802,6 +802,14 @@ def test_recovers_fenced_object_after_prose_preamble(self, monkeypatch: pytest.M assert _extract_json_reply(monkeypatch, content) == {"key": "value"} + def test_recovers_single_line_fenced_object(self, monkeypatch: pytest.MonkeyPatch) -> None: + assert _extract_json_reply(monkeypatch, '```{"verdict": "DUPLICATE"}```') == {"verdict": "DUPLICATE"} + + def test_bracketed_citations_are_not_counted(self, monkeypatch: pytest.MonkeyPatch) -> None: + content = 'Chunks [1] and [2] repeat the same steps.\n{"key": "value"}' + + assert _extract_json_reply(monkeypatch, content) == {"key": "value"} + def test_nested_object_is_not_counted_as_a_second_object(self, monkeypatch: pytest.MonkeyPatch) -> None: assert _extract_json_reply(monkeypatch, 'Result:\n{"outer": {"key": "value"}}') == {"outer": {"key": "value"}} @@ -814,12 +822,34 @@ def test_multiple_embedded_objects_raise(self, monkeypatch: pytest.MonkeyPatch) with pytest.raises(LLMClientError, match="found 2 JSON objects; expected exactly one"): _extract_json_reply(monkeypatch, 'First: {"key": "one"}\nSecond: {"key": "two"}') - def test_object_inside_malformed_container_is_not_promoted(self, monkeypatch: pytest.MonkeyPatch) -> None: - content = 'Result: {"verdict": "RELATED_BUT_DISTINCT", "detail": {"verdict": "DUPLICATE"} "rationale": "x"}' - + @pytest.mark.parametrize( + "container", + [ + pytest.param( + '{"verdict": "RELATED_BUT_DISTINCT", "detail": {"verdict": "DUPLICATE"} "rationale": "x"}', + id="missing-comma-after-nested-object", + ), + pytest.param( + '{"verdict": "RELATED_BUT_DISTINCT" "detail": {"verdict": "DUPLICATE"}}', + id="missing-comma-before-nested-key", + ), + pytest.param( + '{"verdict": "RELATED_BUT_DISTINCT", {"verdict": "DUPLICATE"}}', + id="nested-object-where-key-expected", + ), + pytest.param('{verdict: {"verdict": "DUPLICATE"}}', id="unquoted-key"), + pytest.param('{"verdict": "RELATED_BUT_DISTINCT", "detail": {"verdict": "DUPLICATE"}', id="never-closes"), + pytest.param('[oops, {"verdict": "DUPLICATE"}]', id="malformed-array"), + pytest.param('[{"verdict": "DUPLICATE"}]', id="valid-array"), + ], + ) + def test_object_inside_another_container_is_not_promoted( + self, monkeypatch: pytest.MonkeyPatch, container: str + ) -> None: with pytest.raises(LLMClientError, match="invalid JSON"): - _extract_json_reply(monkeypatch, content) + _extract_json_reply(monkeypatch, "Result: " + container) + @pytest.mark.parametrize("prefix", [pytest.param("", id="whole-reply"), pytest.param("Result: ", id="in-prose")]) @pytest.mark.parametrize( "payload", [ @@ -827,17 +857,18 @@ def test_object_inside_malformed_container_is_not_promoted(self, monkeypatch: py pytest.param('{"a": ' + "1" * 5_000 + "}", id="integer-beyond-digit-limit"), ], ) - def test_undecodable_embedded_object_fails_closed(self, monkeypatch: pytest.MonkeyPatch, payload: str) -> None: + def test_undecodable_object_fails_closed(self, monkeypatch: pytest.MonkeyPatch, prefix: str, payload: str) -> None: with pytest.raises(LLMClientError, match="invalid JSON"): - _extract_json_reply(monkeypatch, "Result: " + payload + ' {"key": "value"}') + _extract_json_reply(monkeypatch, prefix + payload) - def test_recovery_stops_after_bounded_malformed_candidates(self, monkeypatch: pytest.MonkeyPatch) -> None: - limit = client_mod._MAX_EMBEDDED_JSON_DECODE_FAILURES - obj = '{"key": "value"}' + def test_undecodable_object_blocks_a_later_object(self, monkeypatch: pytest.MonkeyPatch) -> None: + payload = '{"a":' * 100_000 + "1" + "}" * 100_000 - assert _extract_json_reply(monkeypatch, "{x} " * limit + obj) == {"key": "value"} with pytest.raises(LLMClientError, match="invalid JSON"): - _extract_json_reply(monkeypatch, "{x} " * (limit + 1) + obj) + _extract_json_reply(monkeypatch, "Result: " + payload + ' {"key": "value"}') + + def test_many_malformed_spans_are_skipped(self, monkeypatch: pytest.MonkeyPatch) -> None: + assert _extract_json_reply(monkeypatch, "{x} " * 5_000 + '{"key": "value"}') == {"key": "value"} def test_bedrock_prompt_only_reply_with_preamble_is_recovered(self, monkeypatch: pytest.MonkeyPatch) -> None: from skillevaluator.deduplication.intra_skill.llm_analyzer import VERDICT_JSON_SCHEMA From 61cf8c933cc9f702f99bac77ae9db4a28aa9145b Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Tue, 3 Nov 2026 09:28:12 -0800 Subject: [PATCH 3/6] refactor(inference): share JSON span and decode hooks with the Tier 3 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 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +- docs/tier2-deduplication.mdx | 3 +- src/skillevaluator/inference/client.py | 46 ++----- .../tier3/eval_core/llm_judge.py | 92 +++----------- src/skillevaluator/utils/json_spans.py | 116 ++++++++++++++++++ tests/inference/test_llm_client.py | 36 ++++++ tests/utils/test_json_spans.py | 78 ++++++++++++ 7 files changed, 257 insertions(+), 119 deletions(-) create mode 100644 src/skillevaluator/utils/json_spans.py create mode 100644 tests/utils/test_json_spans.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 46d532ad2..db9bb3022 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -533,7 +533,10 @@ All notable changes to SkillEvaluator are documented in this file. `LLM returned invalid JSON` (or an `IndexError` for the one-line fence) and left Tier 2 incomplete. Exactly one embedded JSON object is accepted. Replies with several objects are still rejected instead of guessed, and an object - inside an array or a malformed container is never used as the verdict. + inside an array or a malformed container is never used as the verdict. As in + the Tier 3 judge, an object with a repeated key, a `NaN` or `Infinity` value + or a number that overflows a float is rejected, whether it is the whole reply + or embedded in prose. ### Security diff --git a/docs/tier2-deduplication.mdx b/docs/tier2-deduplication.mdx index e3b4277e7..4f9f94856 100644 --- a/docs/tier2-deduplication.mdx +++ b/docs/tier2-deduplication.mdx @@ -154,7 +154,8 @@ exactly one JSON object in prose or a Markdown fence is accepted, which matters on Bedrock and other endpoints that answer with prompt-only JSON. A reply with no complete object or with more than one counts as a failed analysis. An object nested inside an array or inside a malformed container is never used as the -verdict. +verdict, and neither is an object with a repeated key, a `NaN` or `Infinity` +value, or a number too large for a float. If chat-LLM analysis fails for a candidate cluster, Tier 2 reports the incomplete analysis as a blocking error rather than treating the content as diff --git a/src/skillevaluator/inference/client.py b/src/skillevaluator/inference/client.py index f68617a9f..df4a5c75e 100644 --- a/src/skillevaluator/inference/client.py +++ b/src/skillevaluator/inference/client.py @@ -19,7 +19,6 @@ class supports two usage patterns: from __future__ import annotations import io -import json import os import re import urllib.error @@ -53,6 +52,10 @@ class supports two usage patterns: is_openai_reasoning_model, resolve_llm_provider, ) +from skillevaluator.utils.json_spans import ( + balanced_json_container_end, + loads_strict_json, +) logger = get_logger(__name__) @@ -340,44 +343,9 @@ def _extract_choice_content(response: Any) -> str: ) -# Bracket depth beyond which an embedded span is not decoded. Verdicts are -# shallow, and the cap keeps the decoder well away from the recursion limit. -_MAX_EMBEDDED_JSON_NESTING = 128 _JSON_CONTAINER_START = re.compile(r"[{\[]") -def _balanced_json_span_end(text: str, start: int) -> int | None: - """Return the exclusive end of the string-aware ``{...}``/``[...]`` span at *start*. - - ``None`` means the span never closes, closes with a mismatched bracket, or - nests deeper than ``_MAX_EMBEDDED_JSON_NESTING``. - """ - closers: list[str] = [] - in_string = False - escaped = False - for index in range(start, len(text)): - ch = text[index] - if in_string: - if escaped: - escaped = False - elif ch == "\\": - escaped = True - elif ch == '"': - in_string = False - elif ch == '"': - in_string = True - elif ch in "{[": - closers.append("}" if ch == "{" else "]") - if len(closers) > _MAX_EMBEDDED_JSON_NESTING: - return None - elif ch in "}]": - if not closers or closers.pop() != ch: - return None - if not closers: - return index + 1 - return None - - def _embedded_json_objects(text: str) -> list[dict[str, Any]]: """Return the complete top-level JSON objects embedded in prose. @@ -394,11 +362,11 @@ def _embedded_json_objects(text: str) -> list[dict[str, Any]]: cursor = 0 while (match := _JSON_CONTAINER_START.search(text, cursor)) is not None: start = match.start() - end = _balanced_json_span_end(text, start) + end = balanced_json_container_end(text, start) if end is None: break try: - value = json.loads(text[start:end]) + value = loads_strict_json(text[start:end]) except (RecursionError, ValueError): value = None if isinstance(value, dict): @@ -776,7 +744,7 @@ def extract_json_from_response( cleaned = cleaned.rsplit("```", 1)[0].strip() try: - return json.loads(cleaned) + return loads_strict_json(cleaned) except (RecursionError, ValueError) as e: objects = _embedded_json_objects(raw) if len(objects) == 1: diff --git a/src/skillevaluator/tier3/eval_core/llm_judge.py b/src/skillevaluator/tier3/eval_core/llm_judge.py index 427586838..579b12e68 100644 --- a/src/skillevaluator/tier3/eval_core/llm_judge.py +++ b/src/skillevaluator/tier3/eval_core/llm_judge.py @@ -31,6 +31,14 @@ _truncate_for_behavior, ) from skillevaluator.tier3.eval_core.character_facts import append_character_facts +from skillevaluator.utils.json_spans import ( + MAX_JSON_NESTING, + balanced_json_container_end, + json_nesting_within_limit, + parse_finite_json_float, + reject_duplicate_object_pairs, + reject_nonstandard_json_constant, +) logger = logging.getLogger(__name__) @@ -294,85 +302,13 @@ def call_public_llm( _JSON_WHITESPACE = " \t\r\n" _MAX_JSON_TEXT_CHARS = 100_000 -_MAX_JSON_NESTING = 128 +_MAX_JSON_NESTING = MAX_JSON_NESTING _JSON_NUMBER_PREFIX_RE = re.compile(r"-?(?:(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]*)?|(?:0|[1-9][0-9]*)\.)?") - - -def _balanced_json_container_end(text: str, start: int) -> int | None: - """Return the exclusive end of one bounded structural container.""" - if start >= len(text) or text[start] not in "{[": - return None - stack: list[str] = [] - in_string = False - escaped = False - for i in range(start, len(text)): - ch = text[i] - if in_string: - if escaped: - escaped = False - elif ch == "\\": - escaped = True - elif ch == '"': - in_string = False - elif ch == '"': - in_string = True - elif ch in "{[": - stack.append(ch) - if len(stack) > _MAX_JSON_NESTING: - return None - elif ch in "}]": - expected = "{" if ch == "}" else "[" - if not stack or stack[-1] != expected: - return None - stack.pop() - if not stack: - return i + 1 - return None - - -def _reject_duplicate_object_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]: - """Build an object while rejecting ambiguous duplicate members.""" - result: dict[str, Any] = {} - for key, value in pairs: - if key in result: - raise ValueError("Duplicate JSON object member") - result[key] = value - return result - - -def _reject_nonstandard_json_constant(_value: str) -> None: - raise ValueError("Non-standard JSON constant") - - -def _parse_finite_json_float(value: str) -> float: - parsed = float(value) - if not math.isfinite(parsed): - raise ValueError("JSON number overflowed to a non-finite value") - return parsed - - -def _json_nesting_within_limit(text: str) -> bool: - """Bound structural nesting without recursively parsing partial JSON.""" - depth = 0 - in_string = False - escaped = False - for character in text: - if in_string: - if escaped: - escaped = False - elif character == "\\": - escaped = True - elif character == '"': - in_string = False - elif character == '"': - in_string = True - elif character in "{[": - depth += 1 - if depth > _MAX_JSON_NESTING: - return False - elif character in "}]" and depth: - depth -= 1 - return True +_balanced_json_container_end = balanced_json_container_end +_json_nesting_within_limit = json_nesting_within_limit +_reject_duplicate_object_pairs = reject_duplicate_object_pairs +_reject_nonstandard_json_constant = reject_nonstandard_json_constant +_parse_finite_json_float = parse_finite_json_float def _extract_json(text: str) -> dict[str, Any] | list[Any] | None: diff --git a/src/skillevaluator/utils/json_spans.py b/src/skillevaluator/utils/json_spans.py new file mode 100644 index 000000000..dbd103608 --- /dev/null +++ b/src/skillevaluator/utils/json_spans.py @@ -0,0 +1,116 @@ +"""Bounded JSON span scanning and strict decode hooks for LLM replies. + +The Tier 3 judge and the inference client both recover JSON that a model +wrapped in prose. They share these helpers so the two extractors agree on what +a container span is and on which decoded values are ambiguous: duplicate +object members, ``NaN``/``Infinity`` constants and numbers that overflow to a +non-finite float are all rejected. +""" + +from __future__ import annotations + +import json +import math +from typing import Any + +# Structural depth beyond which a span is not decoded. LLM verdicts are +# shallow, and the cap keeps the decoder away from recursion and C stack +# limits, which differ between Python versions and threads. +MAX_JSON_NESTING = 128 + + +def balanced_json_container_end(text: str, start: int) -> int | None: + """Return the exclusive end of the string-aware ``{...}``/``[...]`` span at *start*. + + ``None`` means *start* is not a container opener, or the span never + closes, closes with a mismatched bracket, or nests deeper than + ``MAX_JSON_NESTING``. + """ + if start >= len(text) or text[start] not in "{[": + return None + stack: list[str] = [] + in_string = False + escaped = False + for i in range(start, len(text)): + ch = text[i] + if in_string: + if escaped: + escaped = False + elif ch == "\\": + escaped = True + elif ch == '"': + in_string = False + elif ch == '"': + in_string = True + elif ch in "{[": + stack.append(ch) + if len(stack) > MAX_JSON_NESTING: + return None + elif ch in "}]": + expected = "{" if ch == "}" else "[" + if not stack or stack[-1] != expected: + return None + stack.pop() + if not stack: + return i + 1 + return None + + +def json_nesting_within_limit(text: str) -> bool: + """Bound structural nesting without recursively parsing partial JSON.""" + depth = 0 + in_string = False + escaped = False + for character in text: + if in_string: + if escaped: + escaped = False + elif character == "\\": + escaped = True + elif character == '"': + in_string = False + elif character == '"': + in_string = True + elif character in "{[": + depth += 1 + if depth > MAX_JSON_NESTING: + return False + elif character in "}]" and depth: + depth -= 1 + return True + + +def reject_duplicate_object_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + """Build an object while rejecting ambiguous duplicate members.""" + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise ValueError("Duplicate JSON object member") + result[key] = value + return result + + +def reject_nonstandard_json_constant(_value: str) -> None: + raise ValueError("Non-standard JSON constant") + + +def parse_finite_json_float(value: str) -> float: + parsed = float(value) + if not math.isfinite(parsed): + raise ValueError("JSON number overflowed to a non-finite value") + return parsed + + +def loads_strict_json(text: str) -> Any: + """Decode *text* with the shared hooks. + + Raises ``ValueError`` (including ``json.JSONDecodeError``) for invalid or + ambiguous JSON, and may raise ``RecursionError`` for deep input; callers + that need a depth bound check ``json_nesting_within_limit`` first. + """ + return json.loads( + text, + object_pairs_hook=reject_duplicate_object_pairs, + parse_constant=reject_nonstandard_json_constant, + parse_float=parse_finite_json_float, + ) diff --git a/tests/inference/test_llm_client.py b/tests/inference/test_llm_client.py index 159a650a3..55221c7bd 100644 --- a/tests/inference/test_llm_client.py +++ b/tests/inference/test_llm_client.py @@ -894,6 +894,42 @@ def test_undecodable_object_fails_closed(self, monkeypatch: pytest.MonkeyPatch, with pytest.raises(LLMClientError, match="invalid JSON"): _extract_json_reply(monkeypatch, prefix + payload) + @pytest.mark.parametrize("prefix", [pytest.param("", id="whole-reply"), pytest.param("Result: ", id="in-prose")]) + @pytest.mark.parametrize( + ("payload", "reason"), + [ + pytest.param( + '{"verdict": "DUPLICATE", "confidence": 0.9, "verdict": "RELATED_BUT_DISTINCT"}', + "Duplicate JSON object member", + id="duplicate-key", + ), + pytest.param( + '{"verdict": "DUPLICATE", "detail": {"k": 1, "k": 2}}', + "Duplicate JSON object member", + id="nested-duplicate-key", + ), + pytest.param('{"verdict": "DUPLICATE", "confidence": NaN}', "Non-standard JSON constant", id="nan"), + pytest.param( + '{"verdict": "DUPLICATE", "confidence": -Infinity}', "Non-standard JSON constant", id="infinity" + ), + pytest.param('{"verdict": "DUPLICATE", "confidence": 1e400}', "non-finite", id="float-overflow"), + ], + ) + def test_ambiguous_object_is_rejected( + self, monkeypatch: pytest.MonkeyPatch, prefix: str, payload: str, reason: str + ) -> None: + with pytest.raises(LLMClientError, match="invalid JSON") as excinfo: + _extract_json_reply(monkeypatch, prefix + payload) + + if not prefix: + # In prose the strict whole-reply error is reported; the scan found no usable object. + assert reason in str(excinfo.value) + + def test_ambiguous_object_does_not_hide_another_object(self, monkeypatch: pytest.MonkeyPatch) -> None: + content = 'Draft: {"verdict": "DUPLICATE", "verdict": "UNIQUE"}\nFinal: {"verdict": "RELATED_BUT_DISTINCT"}' + + assert _extract_json_reply(monkeypatch, content) == {"verdict": "RELATED_BUT_DISTINCT"} + def test_undecodable_object_blocks_a_later_object(self, monkeypatch: pytest.MonkeyPatch) -> None: payload = '{"a":' * 100_000 + "1" + "}" * 100_000 diff --git a/tests/utils/test_json_spans.py b/tests/utils/test_json_spans.py new file mode 100644 index 000000000..5b49687bc --- /dev/null +++ b/tests/utils/test_json_spans.py @@ -0,0 +1,78 @@ +"""Tests for the shared bounded JSON span helpers.""" + +from __future__ import annotations + +import json + +import pytest + +from skillevaluator.inference import client as client_mod +from skillevaluator.tier3.eval_core import llm_judge +from skillevaluator.utils import json_spans + + +def test_tier3_judge_and_inference_client_share_the_helpers() -> None: + assert llm_judge._balanced_json_container_end is json_spans.balanced_json_container_end + assert llm_judge._json_nesting_within_limit is json_spans.json_nesting_within_limit + assert llm_judge._reject_duplicate_object_pairs is json_spans.reject_duplicate_object_pairs + assert llm_judge._reject_nonstandard_json_constant is json_spans.reject_nonstandard_json_constant + assert llm_judge._parse_finite_json_float is json_spans.parse_finite_json_float + assert llm_judge._MAX_JSON_NESTING == json_spans.MAX_JSON_NESTING + assert client_mod.balanced_json_container_end is json_spans.balanced_json_container_end + assert client_mod.loads_strict_json is json_spans.loads_strict_json + + +@pytest.mark.parametrize( + ("text", "start", "end"), + [ + pytest.param('x {"a": "}"} y', 2, 12, id="brace-inside-string"), + pytest.param('[1, {"a": [2]}] tail', 0, 15, id="mixed-containers"), + pytest.param('{"a": "\\"}"} tail', 0, 12, id="escaped-quote"), + ], +) +def test_balanced_container_end(text: str, start: int, end: int) -> None: + assert json_spans.balanced_json_container_end(text, start) == end + + +@pytest.mark.parametrize( + ("text", "start"), + [ + pytest.param('{"a": 1', 0, id="never-closes"), + pytest.param('{"a": [1}', 0, id="mismatched-bracket"), + pytest.param("plain", 0, id="not-a-container"), + pytest.param("{}", 2, id="start-past-end"), + pytest.param( + "[" * (json_spans.MAX_JSON_NESTING + 1) + "]" * (json_spans.MAX_JSON_NESTING + 1), 0, id="too-deep" + ), + ], +) +def test_balanced_container_end_rejects(text: str, start: int) -> None: + assert json_spans.balanced_json_container_end(text, start) is None + + +def test_nesting_limit_is_inclusive() -> None: + limit = json_spans.MAX_JSON_NESTING + + assert json_spans.json_nesting_within_limit("[" * limit + "]" * limit) + assert not json_spans.json_nesting_within_limit("[" * (limit + 1) + "]" * (limit + 1)) + assert json_spans.json_nesting_within_limit('"' + "[" * (limit + 1) + '"') + + +@pytest.mark.parametrize( + ("text", "reason"), + [ + pytest.param('{"k": 1, "k": 2}', "Duplicate JSON object member", id="duplicate-key"), + pytest.param("[NaN]", "Non-standard JSON constant", id="nan"), + pytest.param("Infinity", "Non-standard JSON constant", id="infinity"), + pytest.param("1e400", "non-finite", id="float-overflow"), + ], +) +def test_loads_strict_json_rejects_ambiguous_values(text: str, reason: str) -> None: + with pytest.raises(ValueError, match=reason): + json_spans.loads_strict_json(text) + + +def test_loads_strict_json_matches_json_loads_for_ordinary_input() -> None: + text = '{"verdict": "DUPLICATE", "confidence": 0.9, "tags": [1, -2.5e3, null, true]}' + + assert json_spans.loads_strict_json(text) == json.loads(text) From c727a37b8fca4a1c28904bd1a129378780210d51 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Tue, 3 Nov 2026 09:28:24 -0800 Subject: [PATCH 4/6] fix(inference): bound JSON nesting before decoding the whole reply 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 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +++--- docs/tier2-deduplication.mdx | 2 +- src/skillevaluator/inference/client.py | 4 ++++ tests/inference/test_llm_client.py | 19 +++++++++++++++++-- 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db9bb3022..cdb939642 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -534,9 +534,9 @@ All notable changes to SkillEvaluator are documented in this file. left Tier 2 incomplete. Exactly one embedded JSON object is accepted. Replies with several objects are still rejected instead of guessed, and an object inside an array or a malformed container is never used as the verdict. As in - the Tier 3 judge, an object with a repeated key, a `NaN` or `Infinity` value - or a number that overflows a float is rejected, whether it is the whole reply - or embedded in prose. + the Tier 3 judge, an object with a repeated key, a `NaN` or `Infinity` value, + a number that overflows a float or more than 128 levels of nesting is + rejected, whether it is the whole reply or embedded in prose. ### Security diff --git a/docs/tier2-deduplication.mdx b/docs/tier2-deduplication.mdx index 4f9f94856..8131b7d1e 100644 --- a/docs/tier2-deduplication.mdx +++ b/docs/tier2-deduplication.mdx @@ -155,7 +155,7 @@ on Bedrock and other endpoints that answer with prompt-only JSON. A reply with no complete object or with more than one counts as a failed analysis. An object nested inside an array or inside a malformed container is never used as the verdict, and neither is an object with a repeated key, a `NaN` or `Infinity` -value, or a number too large for a float. +value, a number too large for a float, or more than 128 levels of nesting. If chat-LLM analysis fails for a candidate cluster, Tier 2 reports the incomplete analysis as a blocking error rather than treating the content as diff --git a/src/skillevaluator/inference/client.py b/src/skillevaluator/inference/client.py index df4a5c75e..988f68c19 100644 --- a/src/skillevaluator/inference/client.py +++ b/src/skillevaluator/inference/client.py @@ -53,7 +53,9 @@ class supports two usage patterns: resolve_llm_provider, ) from skillevaluator.utils.json_spans import ( + MAX_JSON_NESTING, balanced_json_container_end, + json_nesting_within_limit, loads_strict_json, ) @@ -744,6 +746,8 @@ def extract_json_from_response( cleaned = cleaned.rsplit("```", 1)[0].strip() try: + if not json_nesting_within_limit(cleaned): + raise ValueError(f"JSON nests deeper than {MAX_JSON_NESTING} levels") return loads_strict_json(cleaned) except (RecursionError, ValueError) as e: objects = _embedded_json_objects(raw) diff --git a/tests/inference/test_llm_client.py b/tests/inference/test_llm_client.py index 55221c7bd..22d0ec1f6 100644 --- a/tests/inference/test_llm_client.py +++ b/tests/inference/test_llm_client.py @@ -36,6 +36,7 @@ REASONING_MAX_COMPLETION_TOKENS, ProviderConfig, ) +from skillevaluator.utils.json_spans import MAX_JSON_NESTING from skillevaluator.validators.rubric_eval import RUBRIC_JSON_SCHEMA, RubricJudge @@ -781,6 +782,10 @@ def test_vertex_openapi_does_not_refresh_token_when_explicit_api_key_provided( assert client._resolved_config().api_key == "explicit-user-key" +def _nested_object(depth: int) -> str: + return '{"a":' * (depth - 1) + '{"a": 1}' + "}" * (depth - 1) + + def _extract_json_reply(monkeypatch: pytest.MonkeyPatch, content: str) -> dict: monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "nv_build") monkeypatch.setenv("NVIDIA_API_KEY", "test-key") @@ -886,14 +891,24 @@ def test_object_inside_another_container_is_not_promoted( @pytest.mark.parametrize( "payload", [ - pytest.param('{"a":' * 100_000 + "1" + "}" * 100_000, id="nesting-beyond-recursion-limit"), + pytest.param(_nested_object(MAX_JSON_NESTING + 1), id="nesting-just-beyond-limit"), + pytest.param(_nested_object(100_000), id="nesting-beyond-recursion-limit"), pytest.param('{"a": ' + "1" * 5_000 + "}", id="integer-beyond-digit-limit"), ], ) def test_undecodable_object_fails_closed(self, monkeypatch: pytest.MonkeyPatch, prefix: str, payload: str) -> None: + # The depth bound is checked before decoding, so the result does not + # depend on the Python version or thread stack size (Python 3.14 can + # decode 100,000 levels when the C stack allows it). with pytest.raises(LLMClientError, match="invalid JSON"): _extract_json_reply(monkeypatch, prefix + payload) + @pytest.mark.parametrize("prefix", [pytest.param("", id="whole-reply"), pytest.param("Result: ", id="in-prose")]) + def test_object_at_nesting_limit_is_accepted(self, monkeypatch: pytest.MonkeyPatch, prefix: str) -> None: + payload = _nested_object(MAX_JSON_NESTING) + + assert _extract_json_reply(monkeypatch, prefix + payload) == json.loads(payload) + @pytest.mark.parametrize("prefix", [pytest.param("", id="whole-reply"), pytest.param("Result: ", id="in-prose")]) @pytest.mark.parametrize( ("payload", "reason"), @@ -931,7 +946,7 @@ def test_ambiguous_object_does_not_hide_another_object(self, monkeypatch: pytest assert _extract_json_reply(monkeypatch, content) == {"verdict": "RELATED_BUT_DISTINCT"} def test_undecodable_object_blocks_a_later_object(self, monkeypatch: pytest.MonkeyPatch) -> None: - payload = '{"a":' * 100_000 + "1" + "}" * 100_000 + payload = _nested_object(100_000) with pytest.raises(LLMClientError, match="invalid JSON"): _extract_json_reply(monkeypatch, "Result: " + payload + ' {"key": "value"}') From 4cba632dc29e8f98205a9f7f53cb16e0ec73820f Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Tue, 3 Nov 2026 09:28:29 -0800 Subject: [PATCH 5/6] refactor(inference): share JSON span scanning with the Tier 3 judge 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 Signed-off-by: Narendran Raghavan --- src/skillevaluator/inference/client.py | 40 +-------- src/skillevaluator/inference/json_span.py | 81 +++++++++++++++++++ .../tier3/eval_core/llm_judge.py | 74 +++-------------- tests/inference/test_llm_client.py | 23 +++++- 4 files changed, 115 insertions(+), 103 deletions(-) create mode 100644 src/skillevaluator/inference/json_span.py diff --git a/src/skillevaluator/inference/client.py b/src/skillevaluator/inference/client.py index 938a76242..36af89af8 100644 --- a/src/skillevaluator/inference/client.py +++ b/src/skillevaluator/inference/client.py @@ -30,6 +30,7 @@ class supports two usage patterns: from skillevaluator.constants import LLM_VERIFY_TEMPERATURE from skillevaluator.inference.diagnostics import llm_failure_diagnostic +from skillevaluator.inference.json_span import STRICT_JSON_DECODE_HOOKS, balanced_json_container_end from skillevaluator.inference.retry import RetryConfig, resolve_retry_config, retry_call_with_backoff from skillevaluator.inference.types import ( EmptyLLMResponseError, @@ -340,44 +341,9 @@ def _extract_choice_content(response: Any) -> str: ) -# Bracket depth beyond which an embedded span is not decoded. Verdicts are -# shallow, and the cap keeps the decoder well away from the recursion limit. -_MAX_EMBEDDED_JSON_NESTING = 128 _JSON_CONTAINER_START = re.compile(r"[{\[]") -def _balanced_json_span_end(text: str, start: int) -> int | None: - """Return the exclusive end of the string-aware ``{...}``/``[...]`` span at *start*. - - ``None`` means the span never closes, closes with a mismatched bracket, or - nests deeper than ``_MAX_EMBEDDED_JSON_NESTING``. - """ - closers: list[str] = [] - in_string = False - escaped = False - for index in range(start, len(text)): - ch = text[index] - if in_string: - if escaped: - escaped = False - elif ch == "\\": - escaped = True - elif ch == '"': - in_string = False - elif ch == '"': - in_string = True - elif ch in "{[": - closers.append("}" if ch == "{" else "]") - if len(closers) > _MAX_EMBEDDED_JSON_NESTING: - return None - elif ch in "}]": - if not closers or closers.pop() != ch: - return None - if not closers: - return index + 1 - return None - - def _embedded_json_objects(text: str) -> list[dict[str, Any]]: """Return the complete top-level JSON objects embedded in prose. @@ -394,11 +360,11 @@ def _embedded_json_objects(text: str) -> list[dict[str, Any]]: cursor = 0 while (match := _JSON_CONTAINER_START.search(text, cursor)) is not None: start = match.start() - end = _balanced_json_span_end(text, start) + end = balanced_json_container_end(text, start) if end is None: break try: - value = json.loads(text[start:end]) + value = json.loads(text[start:end], **STRICT_JSON_DECODE_HOOKS) except (RecursionError, ValueError): value = None if isinstance(value, dict): diff --git a/src/skillevaluator/inference/json_span.py b/src/skillevaluator/inference/json_span.py new file mode 100644 index 000000000..450a82d33 --- /dev/null +++ b/src/skillevaluator/inference/json_span.py @@ -0,0 +1,81 @@ +"""Shared JSON span scanning and strict decode hooks for LLM replies. + +Both the public inference client and the Tier 3 judge recover JSON that a model +wrapped in prose. They share one span scanner and one set of decode hooks so +the two paths accept and refuse the same replies. +""" + +from __future__ import annotations + +import math +from typing import Any + +# Bracket depth beyond which a span is not decoded. Verdicts are shallow, and +# the cap keeps the decoder well away from the recursion limit. +MAX_JSON_NESTING = 128 + + +def balanced_json_container_end(text: str, start: int) -> int | None: + """Return the exclusive end of the string-aware ``{...}``/``[...]`` span at *start*. + + ``None`` means *start* is not a container opener, or the span never closes, + closes with a mismatched bracket, or nests deeper than ``MAX_JSON_NESTING``. + """ + if start >= len(text) or text[start] not in "{[": + return None + stack: list[str] = [] + in_string = False + escaped = False + for index in range(start, len(text)): + ch = text[index] + if in_string: + if escaped: + escaped = False + elif ch == "\\": + escaped = True + elif ch == '"': + in_string = False + elif ch == '"': + in_string = True + elif ch in "{[": + stack.append(ch) + if len(stack) > MAX_JSON_NESTING: + return None + elif ch in "}]": + expected = "{" if ch == "}" else "[" + if not stack or stack[-1] != expected: + return None + stack.pop() + if not stack: + return index + 1 + return None + + +def reject_duplicate_object_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + """Build an object while rejecting ambiguous duplicate members.""" + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise ValueError("Duplicate JSON object member") + result[key] = value + return result + + +def reject_nonstandard_json_constant(_value: str) -> None: + """``parse_constant`` hook that refuses ``NaN`` and ``Infinity``.""" + raise ValueError("Non-standard JSON constant") + + +def parse_finite_json_float(value: str) -> float: + """``parse_float`` hook that refuses numbers overflowing to infinity.""" + parsed = float(value) + if not math.isfinite(parsed): + raise ValueError("JSON number overflowed to a non-finite value") + return parsed + + +STRICT_JSON_DECODE_HOOKS: dict[str, Any] = { + "object_pairs_hook": reject_duplicate_object_pairs, + "parse_constant": reject_nonstandard_json_constant, + "parse_float": parse_finite_json_float, +} diff --git a/src/skillevaluator/tier3/eval_core/llm_judge.py b/src/skillevaluator/tier3/eval_core/llm_judge.py index 427586838..e96c5935a 100644 --- a/src/skillevaluator/tier3/eval_core/llm_judge.py +++ b/src/skillevaluator/tier3/eval_core/llm_judge.py @@ -16,6 +16,11 @@ import urllib.request from typing import Any +from skillevaluator.inference.json_span import ( + MAX_JSON_NESTING, + STRICT_JSON_DECODE_HOOKS, + balanced_json_container_end, +) from skillevaluator.inference.types import EmptyLLMResponseError, LLMClientTruncatedError from skillevaluator.provider_config import ( MAX_COMPLETION_TOKENS, @@ -294,63 +299,10 @@ def call_public_llm( _JSON_WHITESPACE = " \t\r\n" _MAX_JSON_TEXT_CHARS = 100_000 -_MAX_JSON_NESTING = 128 +_MAX_JSON_NESTING = MAX_JSON_NESTING _JSON_NUMBER_PREFIX_RE = re.compile(r"-?(?:(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]*)?|(?:0|[1-9][0-9]*)\.)?") -def _balanced_json_container_end(text: str, start: int) -> int | None: - """Return the exclusive end of one bounded structural container.""" - if start >= len(text) or text[start] not in "{[": - return None - stack: list[str] = [] - in_string = False - escaped = False - for i in range(start, len(text)): - ch = text[i] - if in_string: - if escaped: - escaped = False - elif ch == "\\": - escaped = True - elif ch == '"': - in_string = False - elif ch == '"': - in_string = True - elif ch in "{[": - stack.append(ch) - if len(stack) > _MAX_JSON_NESTING: - return None - elif ch in "}]": - expected = "{" if ch == "}" else "[" - if not stack or stack[-1] != expected: - return None - stack.pop() - if not stack: - return i + 1 - return None - - -def _reject_duplicate_object_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]: - """Build an object while rejecting ambiguous duplicate members.""" - result: dict[str, Any] = {} - for key, value in pairs: - if key in result: - raise ValueError("Duplicate JSON object member") - result[key] = value - return result - - -def _reject_nonstandard_json_constant(_value: str) -> None: - raise ValueError("Non-standard JSON constant") - - -def _parse_finite_json_float(value: str) -> float: - parsed = float(value) - if not math.isfinite(parsed): - raise ValueError("JSON number overflowed to a non-finite value") - return parsed - - def _json_nesting_within_limit(text: str) -> bool: """Bound structural nesting without recursively parsing partial JSON.""" depth = 0 @@ -394,16 +346,14 @@ def _extract_json(text: str) -> dict[str, Any] | list[Any] | None: if text[index] not in "{[": index += 1 continue - end = _balanced_json_container_end(text, index) + end = balanced_json_container_end(text, index) if end is None: return documents[0] if documents else None candidate = text[index:end] try: parsed = json.loads( candidate, - object_pairs_hook=_reject_duplicate_object_pairs, - parse_constant=_reject_nonstandard_json_constant, - parse_float=_parse_finite_json_float, + **STRICT_JSON_DECODE_HOOKS, ) except (json.JSONDecodeError, RecursionError, ValueError): index = end @@ -465,9 +415,7 @@ def _is_append_only_json_object_prefix(fragment: str) -> bool: return False decoder = json.JSONDecoder( - object_pairs_hook=_reject_duplicate_object_pairs, - parse_constant=_reject_nonstandard_json_constant, - parse_float=_parse_finite_json_float, + **STRICT_JSON_DECODE_HOOKS, ) def _skip_whitespace(index: int) -> int: @@ -540,9 +488,7 @@ def _salvage_behavior_results(text: str) -> list[dict[str, Any]]: return [] decoder = json.JSONDecoder( - object_pairs_hook=_reject_duplicate_object_pairs, - parse_constant=_reject_nonstandard_json_constant, - parse_float=_parse_finite_json_float, + **STRICT_JSON_DECODE_HOOKS, ) def _skip_whitespace(index: int) -> int: diff --git a/tests/inference/test_llm_client.py b/tests/inference/test_llm_client.py index f0f83114f..fdb65254a 100644 --- a/tests/inference/test_llm_client.py +++ b/tests/inference/test_llm_client.py @@ -700,7 +700,9 @@ def test_vertex_openapi_refreshes_token_on_auth_error(self, monkeypatch: pytest. monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "openai-compatible") monkeypatch.setenv("SKILL_EVAL_LLM_BASE_URL", vertex_base_url) monkeypatch.setenv("SKILL_EVAL_LLM_MODEL", "google/gemini-3.8-flash") - monkeypatch.setattr("skillevaluator.provider_config._get_google_access_token", lambda **_kwargs: "mock-refreshed-token") + monkeypatch.setattr( + "skillevaluator.provider_config._get_google_access_token", lambda **_kwargs: "mock-refreshed-token" + ) mock_openai = MagicMock() mock_auth_err = AuthenticationError("Unauthorized", response=MagicMock(status_code=401), body=None) @@ -732,7 +734,9 @@ def test_vertex_openapi_does_not_refresh_token_when_explicit_api_key_provided( monkeypatch.setenv("SKILL_EVAL_LLM_BASE_URL", vertex_base_url) monkeypatch.setenv("SKILL_EVAL_LLM_API_KEY", "explicit-user-key") monkeypatch.setenv("SKILL_EVAL_LLM_MODEL", "google/gemini-3.8-flash") - monkeypatch.setattr("skillevaluator.provider_config._get_google_access_token", lambda **_kwargs: "host-adc-token") + monkeypatch.setattr( + "skillevaluator.provider_config._get_google_access_token", lambda **_kwargs: "host-adc-token" + ) mock_openai = MagicMock() mock_auth_err = AuthenticationError("Unauthorized", response=MagicMock(status_code=401), body=None) @@ -818,6 +822,21 @@ def test_prose_braces_that_are_not_json_are_skipped(self, monkeypatch: pytest.Mo assert _extract_json_reply(monkeypatch, content) == {"key": "value"} + @pytest.mark.parametrize( + "span", + [ + pytest.param('{"verdict": "DUPLICATE", "verdict": "RELATED_BUT_DISTINCT"}', id="duplicate-key"), + pytest.param('{"verdict": "DUPLICATE", "confidence": NaN}', id="nan-constant"), + pytest.param('{"verdict": "DUPLICATE", "confidence": 1e999}', id="overflowing-float"), + ], + ) + def test_ambiguous_or_non_finite_embedded_object_is_refused( + self, monkeypatch: pytest.MonkeyPatch, span: str + ) -> None: + # Matches the Tier 3 judge: the last duplicate key must not silently win. + with pytest.raises(LLMClientError): + _extract_json_reply(monkeypatch, f"Result:\n{span}\nDone.") + def test_multiple_embedded_objects_raise(self, monkeypatch: pytest.MonkeyPatch) -> None: with pytest.raises(LLMClientError, match="found 2 JSON objects; expected exactly one"): _extract_json_reply(monkeypatch, 'First: {"key": "one"}\nSecond: {"key": "two"}') From 814986b68583d58642e11452cfeade45b3b629bc Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Tue, 3 Nov 2026 12:21:38 -0800 Subject: [PATCH 6/6] test(inference): drop the duplicated embedded-object rejection test 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 Co-Authored-By: Claude Opus 5.5 --- tests/inference/test_llm_client.py | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/tests/inference/test_llm_client.py b/tests/inference/test_llm_client.py index 68dbf3b54..4dd7986a4 100644 --- a/tests/inference/test_llm_client.py +++ b/tests/inference/test_llm_client.py @@ -860,21 +860,6 @@ def test_prose_braces_that_are_not_json_are_skipped(self, monkeypatch: pytest.Mo assert _extract_json_reply(monkeypatch, content) == {"key": "value"} - @pytest.mark.parametrize( - "span", - [ - pytest.param('{"verdict": "DUPLICATE", "verdict": "RELATED_BUT_DISTINCT"}', id="duplicate-key"), - pytest.param('{"verdict": "DUPLICATE", "confidence": NaN}', id="nan-constant"), - pytest.param('{"verdict": "DUPLICATE", "confidence": 1e999}', id="overflowing-float"), - ], - ) - def test_ambiguous_or_non_finite_embedded_object_is_refused( - self, monkeypatch: pytest.MonkeyPatch, span: str - ) -> None: - # Matches the Tier 3 judge: the last duplicate key must not silently win. - with pytest.raises(LLMClientError): - _extract_json_reply(monkeypatch, f"Result:\n{span}\nDone.") - def test_multiple_embedded_objects_raise(self, monkeypatch: pytest.MonkeyPatch) -> None: with pytest.raises(LLMClientError, match="found 2 JSON objects; expected exactly one"): _extract_json_reply(monkeypatch, 'First: {"key": "one"}\nSecond: {"key": "two"}')