Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,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.

### Security

Expand Down
8 changes: 8 additions & 0 deletions docs/tier2-deduplication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,14 @@ 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. 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.
Expand Down
60 changes: 55 additions & 5 deletions src/skillevaluator/inference/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ 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 (
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,
Expand Down Expand Up @@ -340,6 +346,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.

Expand Down Expand Up @@ -694,18 +732,30 @@ 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()
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) -------------------

Expand Down
109 changes: 109 additions & 0 deletions src/skillevaluator/inference/json_span.py
Original file line number Diff line number Diff line change
@@ -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,
}
100 changes: 12 additions & 88 deletions src/skillevaluator/tier3/eval_core/llm_judge.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@
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,
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading