Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

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

Narendran Raghavan61ca935c6a9c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a36cdd85..b3481a81 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1005,6 +1005,18 @@ All notable changes to SkillEvaluator are documented in this file.
edited skill whose name, description, or (with `--full-body`) `SKILL.md`
changed is still compared with its old entry; build the catalog from the tree
you screen.
+- Tier 2 deduplication no longer fails a content cluster when the model wraps
+ 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. As in
+ 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.
- Ctrl+C during `tier3 evaluate` now stops the run. The interrupt reached only
the coordinating thread, so running Harbor jobs kept going in their own
process groups, agents waiting for a `--max-agents` slot still started, and
diff --git a/docs/tier2-deduplication.mdx b/docs/tier2-deduplication.mdx
index 88246076..4f0d0882 100644
--- a/docs/tier2-deduplication.mdx
+++ b/docs/tier2-deduplication.mdx
@@ -164,6 +164,14 @@ A cluster that is still over 64,000 characters stops the scan as incomplete
counts the rest; its `source_files` metadata in the JSON report lists every
file.
+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. 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, 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
clean.
diff --git a/src/skillevaluator/inference/client.py b/src/skillevaluator/inference/client.py
index ed9b1a3e..694d4862 100644
--- a/src/skillevaluator/inference/client.py
+++ b/src/skillevaluator/inference/client.py
@@ -31,6 +31,12 @@ from urllib.parse import urlsplit
from skillevaluator.constants import LLM_VERIFY_TEMPERATURE
from skillevaluator.inference.diagnostics import llm_failure_diagnostic
+from skillevaluator.inference.json_span import (
+ MAX_JSON_NESTING,
+ STRICT_JSON_DECODE_HOOKS,
+ balanced_json_container_end,
+ json_nesting_within_limit,
+)
from skillevaluator.inference.retry import RetryConfig, resolve_retry_config, retry_call_with_backoff
from skillevaluator.inference.types import (
EmptyLLMResponseError,
@@ -365,6 +371,38 @@ def _extract_choice_content(response: Any) -> str:
)
+_JSON_CONTAINER_START = re.compile(r"[{\[]")
+
+
+def _embedded_json_objects(text: str) -> list[dict[str, Any]]:
+ """Return the complete top-level JSON objects embedded in prose.
+
+ 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.
+ """
+ objects: list[dict[str, Any]] = []
+ cursor = 0
+ while (match := _JSON_CONTAINER_START.search(text, cursor)) is not None:
+ start = match.start()
+ end = balanced_json_container_end(text, start)
+ if end is None:
+ break
+ try:
+ value = json.loads(text[start:end], **STRICT_JSON_DECODE_HOOKS)
+ except (RecursionError, ValueError):
+ value = None
+ if isinstance(value, dict):
+ objects.append(value)
+ cursor = end
+ return objects
+
+
class LLMClient:
"""Public-provider client for chat completions.
@@ -746,18 +784,30 @@ class LLMClient:
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()
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:
- raise LLMClientError(f"LLM returned invalid JSON: {e}\nRaw: {raw[:500]}") from e
+ if not json_nesting_within_limit(cleaned):
+ raise ValueError(f"JSON nests deeper than {MAX_JSON_NESTING} levels")
+ return json.loads(cleaned, **STRICT_JSON_DECODE_HOOKS)
+ except (RecursionError, ValueError) as 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/src/skillevaluator/inference/json_span.py b/src/skillevaluator/inference/json_span.py
new file mode 100644
index 00000000..0e355374
--- /dev/null
+++ b/src/skillevaluator/inference/json_span.py
@@ -0,0 +1,109 @@
+"""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 json_nesting_within_limit(text: str) -> bool:
+ """Bound structural nesting of *text* without recursively parsing it.
+
+ Checked before decoding a whole reply, because the decoder's own depth
+ limit depends on the Python version and the thread's C stack size.
+ """
+ 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:
+ """``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 bc63bd79..9004cc81 100644
--- a/src/skillevaluator/tier3/eval_core/llm_judge.py
+++ b/src/skillevaluator/tier3/eval_core/llm_judge.py
@@ -16,6 +16,12 @@ import urllib.error
import urllib.request
from typing import Any
+from skillevaluator.inference.json_span import (
+ MAX_JSON_NESTING,
+ STRICT_JSON_DECODE_HOOKS,
+ balanced_json_container_end,
+ json_nesting_within_limit,
+)
from skillevaluator.inference.types import EmptyLLMResponseError, LLMClientTruncatedError
from skillevaluator.provider_config import (
MAX_COMPLETION_TOKENS,
@@ -294,85 +300,9 @@ 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
+_json_nesting_within_limit = json_nesting_within_limit
def _extract_json(text: str) -> dict[str, Any] | list[Any] | None:
@@ -394,16 +324,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 +393,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 +466,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_json_span.py b/tests/inference/test_json_span.py
new file mode 100644
index 00000000..dbf21f6c
--- /dev/null
+++ b/tests/inference/test_json_span.py
@@ -0,0 +1,76 @@
+"""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.inference import json_span
+from skillevaluator.tier3.eval_core import llm_judge
+
+
+def test_tier3_judge_and_inference_client_share_the_helpers() -> None:
+ assert llm_judge.balanced_json_container_end is json_span.balanced_json_container_end
+ assert llm_judge._json_nesting_within_limit is json_span.json_nesting_within_limit
+ assert llm_judge.STRICT_JSON_DECODE_HOOKS is json_span.STRICT_JSON_DECODE_HOOKS
+ assert llm_judge._MAX_JSON_NESTING == json_span.MAX_JSON_NESTING
+ assert client_mod.balanced_json_container_end is json_span.balanced_json_container_end
+ assert client_mod.json_nesting_within_limit is json_span.json_nesting_within_limit
+ assert client_mod.STRICT_JSON_DECODE_HOOKS is json_span.STRICT_JSON_DECODE_HOOKS
+
+
+ ("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_span.balanced_json_container_end(text, start) == end
+
+
+ ("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_span.MAX_JSON_NESTING + 1) + "]" * (json_span.MAX_JSON_NESTING + 1), 0, id="too-deep"),
+ ],
+)
+def test_balanced_container_end_rejects(text: str, start: int) -> None:
+ assert json_span.balanced_json_container_end(text, start) is None
+
+
+def test_nesting_limit_is_inclusive() -> None:
+ limit = json_span.MAX_JSON_NESTING
+
+ assert json_span.json_nesting_within_limit("[" * limit + "]" * limit)
+ assert not json_span.json_nesting_within_limit("[" * (limit + 1) + "]" * (limit + 1))
+ assert json_span.json_nesting_within_limit('"' + "[" * (limit + 1) + '"')
+ assert json_span.json_nesting_within_limit('"\\"' + "[" * (limit + 1) + '"')
+
+
+ ("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_strict_decode_hooks_reject_ambiguous_values(text: str, reason: str) -> None:
+ with pytest.raises(ValueError, match=reason):
+ json.loads(text, **json_span.STRICT_JSON_DECODE_HOOKS)
+
+
+def test_strict_decode_hooks_match_json_loads_for_ordinary_input() -> None:
+ text = '{"verdict": "DUPLICATE", "confidence": 0.9, "tags": [1, -2.5e3, null, true]}'
+
+ assert json.loads(text, **json_span.STRICT_JSON_DECODE_HOOKS) == json.loads(text)
diff --git a/tests/inference/test_llm_client.py b/tests/inference/test_llm_client.py
index 17a8e202..ae691e6f 100644
--- a/tests/inference/test_llm_client.py
+++ b/tests/inference/test_llm_client.py
@@ -24,6 +24,7 @@ from skillevaluator.inference import (
)
from skillevaluator.inference import client as client_mod
from skillevaluator.inference.client import _is_native_openai_endpoint, _token_limit_kwargs
+from skillevaluator.inference.json_span import MAX_JSON_NESTING
from skillevaluator.provider_config import (
ANTHROPIC_REFUSAL_FALLBACK_MODEL,
ANTHROPIC_SERVER_SIDE_FALLBACK_BETA,
@@ -734,7 +735,9 @@ class TestCompletions:
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)
@@ -766,7 +769,9 @@ class TestCompletions:
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)
@@ -782,6 +787,19 @@ class TestCompletions:
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")
+ 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")
@@ -807,6 +825,157 @@ class TestExtractJsonFromResponse:
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_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"}}
+
+ 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"}')
+
+ @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, "Result: " + container)
+
+ @pytest.mark.parametrize("prefix", [pytest.param("", id="whole-reply"), pytest.param("Result: ", id="in-prose")])
+ @pytest.mark.parametrize(
+ "payload",
+ [
+ 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"),
+ [
+ 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 = _nested_object(100_000)
+
+ with pytest.raises(LLMClientError, match="invalid JSON"):
+ _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
+
+ _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")