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(tier1): retry an invalid rubric judge reply once and name the problem (#415)

Narendran Raghavan4afd3d04ea00
diff --git a/CHANGELOG.md b/CHANGELOG.md
index efbd6394..264d0191 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -475,6 +475,24 @@ All notable changes to SkillEvaluator are documented in this file.
the dataset-size status in `result.json` and the `tier3 evaluate` summary. It
is taken from the agent with the best baseline score, as in the reports.
+- `rubric-eval` now asks the judge once more, naming the problem, when its
+ reply is not valid JSON or its criterion evidence cannot be scored: a
+ criterion is missing, repeated or unknown, or has a score outside 0 to 10 or
+ a pass flag that is not a boolean. In 0.8.0 the first such reply failed
+ Tier 1 with a HIGH `llm_invalid_response` or `llm_unavailable` finding; now
+ only a second one does. The LLM client still retries transient provider
+ errors as set by `SKILL_EVAL_LLM_MAX_RETRIES`; a request that still fails
+ after those retries, a refusal or a truncated reply is not asked again. The
+ JSON report records `judge_attempts`, the number of times the judge was
+ asked (1, or 2 after a rejected reply, not counting the client's retries),
+ in the skill's `rubric_eval` success detail or `llm_*` finding and, for a
+ single skill, also in the `rubric_eval` object. It is left out when the
+ first request fails, for example with no provider configured.
+
+- Rubric retry diagnostics redact judge-supplied credentials before logging or truncating the rejection reason.
+
+- Rubric retry guidance links to the published environment-variable documentation route.
+
- A default Tier 3 run with a baseline can reach a PASS or NEUTRAL publication
verdict in BENCHMARK.md again. The baseline arm has no skill under test, so
it records `skill_execution` and `skill_efficiency` as not applicable and has
diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx
index 9facc87d..14dc18fa 100644
--- a/docs/tier1-validation.mdx
+++ b/docs/tier1-validation.mdx
@@ -411,6 +411,10 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `lice
Each criterion is scored from 0 to 10. The local evaluator, not the model's boolean, treats 7 or higher as passing. The overall score is an importance-weighted mean, and the rubric passes only when that score reaches `--min-score` and every criterion passes.
+ If the judge's reply is not valid JSON, misses, repeats or invents a criterion, or gives a criterion a score outside 0 to 10 or a pass flag that is not a boolean, `rubric-eval` asks the judge once more and names the problem, keeping the first 500 characters of it. A second such reply fails the rubric with a HIGH `llm_invalid_response` finding, or `llm_unavailable` when it is still not JSON. A rate limit, server error or other transient provider error is retried by the LLM client as set by `SKILL_EVAL_LLM_MAX_RETRIES` (see [LLM retries and judge time budget](/skills/skillevaluator/environment-variables#llm-retries-and-judge-time-budget)). A request that still fails after those retries, a refusal or a truncated reply is not asked again.
+
+ The JSON report records `judge_attempts`, the number of times `rubric-eval` asked the judge (1, or 2 after a rejected reply), in the skill's `rubric_eval` success detail or `llm_invalid_response` / `llm_unavailable` finding and, for a single skill, also in the `rubric_eval` object. The client's own retries are not counted. When the first request fails, for example because no provider is configured, no reply came back and `judge_attempts` is left out.
+
The JSON report names the provider and model that gave each score as `llm_provider` and `llm_model_used` in the skill's `rubric_eval` success detail and, for a single skill, also in the `rubric_eval` object. For a Claude 5.5 or later model on the native Claude API, the model is the one the reply names; otherwise it is the configured model, unless a server-side `fallback` block in the reply names another model. A Claude 5.5 or later model's refusal can be answered by the server-side fallback model, and the API can send a repeat of that request straight to it; the report then names the fallback model, not the configured model.
```bash title="Rubric evaluation"
diff --git a/src/skillevaluator/validators/rubric_eval.py b/src/skillevaluator/validators/rubric_eval.py
index f9816766..88e6b619 100644
--- a/src/skillevaluator/validators/rubric_eval.py
+++ b/src/skillevaluator/validators/rubric_eval.py
@@ -35,9 +35,10 @@ from skillevaluator.constants import (
SKILL_MANIFEST_VARIANTS,
)
from skillevaluator.inference.client import LLMClient
-from skillevaluator.inference.diagnostics import safe_llm_labels
+from skillevaluator.inference.diagnostics import llm_failure_diagnostic, safe_llm_labels
from skillevaluator.logging_config import get_logger
from skillevaluator.models.result import Finding, Severity, ValidationResult
+from skillevaluator.utils.redaction import redact_sensitive_text
from skillevaluator.utils.secure_fs import SecureRoot
from skillevaluator.validators.base import ValidatorBase
from skillevaluator.validators.markdown import markdown_link_targets, normalized_local_path
@@ -50,6 +51,9 @@ _MAX_SKILL_CONTENT_BYTES = 1024 * 1024
_MAX_SUPPLEMENTARY_FILE_BYTES = 3000
_MAX_SUPPLEMENTARY_TOTAL_BYTES = 30000
_MAX_LINKED_MARKDOWN_FILES = 256
+# A rejected judge reply's problem text kept in the log line and retry note.
+# 500 characters hold every missing and some unexpected criterion ids.
+_MAX_RETRY_PROBLEM_CHARS = 500
class _UnsafeRubricInputError(ValueError):
@@ -107,20 +111,21 @@ def _read_bounded_rubric_file(
return text, len(bounded)
-def _normalize_rubric_checks(checks: Any) -> tuple[list[dict], str | None]:
+def _normalize_rubric_checks(checks: Any, criteria: list[dict] | None = None) -> tuple[list[dict], str | None]:
"""Validate criterion evidence and return it in rubric-schema order.
The judge is authoritative only for each criterion's bounded score, pass
flag, and notes. Criterion identity/order and description come from the
local rubric schema so duplicate, missing, or invented criteria cannot
- influence the aggregate.
+ influence the aggregate. ``criteria`` defaults to ``RUBRIC_CRITERIA``.
"""
+ criteria = RUBRIC_CRITERIA if criteria is None else criteria
if not isinstance(checks, list):
return [], "LLM judge returned invalid rubric evidence: checks must be a list"
if not checks:
return (
[],
- f"LLM judge returned incomplete rubric evidence: expected {len(RUBRIC_CRITERIA)} criteria, received 0",
+ f"LLM judge returned incomplete rubric evidence: expected {len(criteria)} criteria, received 0",
)
returned_ids: list[str] = []
@@ -132,7 +137,7 @@ def _normalize_rubric_checks(checks: Any) -> tuple[list[dict], str | None]:
return [], f"LLM judge returned invalid rubric evidence: criterion at index {index} must have a string id"
returned_ids.append(criterion_id)
- expected_ids = [criterion["id"] for criterion in RUBRIC_CRITERIA]
+ expected_ids = [criterion["id"] for criterion in criteria]
expected_id_set = set(expected_ids)
id_counts = Counter(returned_ids)
duplicates = sorted(criterion_id for criterion_id, count in id_counts.items() if count > 1)
@@ -150,7 +155,7 @@ def _normalize_rubric_checks(checks: Any) -> tuple[list[dict], str | None]:
checks_by_id = {check["id"]: check for check in checks}
normalized: list[dict] = []
- for criterion in RUBRIC_CRITERIA:
+ for criterion in criteria:
criterion_id = criterion["id"]
check = checks_by_id[criterion_id]
score = check.get("score")
@@ -198,6 +203,26 @@ def _aggregate_rubric_score(checks: list[dict]) -> float:
return round(weighted_score / total_weight * 10, 1)
+def _rubric_report_problem(report: Any, criteria: list[dict]) -> str | None:
+ """Return why a parsed judge reply cannot be scored against ``criteria``, or ``None`` when it can."""
+ if not isinstance(report, dict):
+ return "LLM judge returned invalid rubric evidence: response must be an object"
+ _checks, problem = _normalize_rubric_checks(report.get("checks"), criteria)
+ return problem
+
+
+def _bounded_problem(problem: str) -> str:
+ """Shorten a rejection reason for the log line and the retry note.
+
+ The reason quotes the judge's own text, such as an invented criterion id,
+ which has no length limit.
+ """
+ problem = redact_sensitive_text(problem)
+ if len(problem) <= _MAX_RETRY_PROBLEM_CHARS:
+ return problem
+ return f"{problem[:_MAX_RETRY_PROBLEM_CHARS]} ... [truncated]"
+
+
class _UnavailableRubricReport(dict):
"""Internal marker distinguishing transport fallback from model evidence."""
@@ -240,6 +265,9 @@ class RubricJudge(LLMClient):
default_reasoning_effort: str | None = RUBRIC_REASONING_EFFORT
response_schema: dict[str, Any] | None = RUBRIC_JSON_SCHEMA
schema_name: str = "rubric_evaluation"
+ # Times the last process() call asked the judge: 1, or 2 after a rejected
+ # reply; 0 when the first request failed, so no reply came back.
+ last_attempts: int = 0
_SYSTEM_PROMPT = (
"You are evaluating an AI Agent Skill documentation file (SKILL.md).\n"
@@ -310,6 +338,65 @@ class RubricJudge(LLMClient):
def parse_response(self, response_text: str, **_kwargs: Any) -> dict:
return _extract_json(response_text)
+ def process(self, **kwargs: Any) -> Any:
+ """Ask the judge, and ask once more, naming the problem, if its reply cannot be scored.
+
+ A reply that ``json`` cannot parse (any ``ValueError`` or
+ ``RecursionError`` from :func:`_extract_json`), or whose ``checks``
+ miss, repeat or invent a criterion of ``criteria``
+ (``RUBRIC_CRITERIA`` unless given) or break a criterion's score or
+ pass flag, gets one more request: the same
+ prompts plus the problem, cut to ``_MAX_RETRY_PROBLEM_CHARS``. The
+ second reply is returned as parsed, so the validator still fails
+ closed when it is invalid too. A provider error that the client's own
+ transient-error retries do not clear (a failed request, a refusal or
+ a truncated reply) is not asked again: as in :meth:`LLMClient.process`,
+ ``last_failure`` records it and the fallback is returned. A truncated
+ reply is never salvaged. ``last_attempts`` counts the times the judge
+ was asked, not the client's retries, and stays 0 when the first
+ request fails.
+ """
+ self.last_failure = None
+ self.last_attempts = 0
+ try:
+ system_prompt = self.get_system_prompt()
+ user_prompt = self.create_user_prompt(**kwargs)
+ raw = self._request_rubric(system_prompt, user_prompt)
+ self.last_attempts = 1
+ try:
+ report = self.parse_response(raw, **kwargs)
+ except (ValueError, RecursionError) as exc:
+ # json.JSONDecodeError is a ValueError. json.loads also raises a
+ # plain ValueError (an integer past the digit limit) or a
+ # RecursionError (nesting too deep) for a reply it cannot parse.
+ problem = exc.msg if isinstance(exc, json.JSONDecodeError) else str(exc) or type(exc).__name__
+ else:
+ problem = _rubric_report_problem(report, kwargs.get("criteria", RUBRIC_CRITERIA))
+ if problem is None:
+ return report
+ problem = _bounded_problem(problem)
+ logger.warning("Rubric judge reply rejected (%s) - asking once more", problem)
+ retry_prompt = (
+ f"{user_prompt}\nYOUR PREVIOUS REPLY WAS REJECTED: {problem}. "
+ "Reply again with ONLY one JSON object in the shape described above.\n"
+ )
+ self.last_attempts = 2
+ return self.parse_response(self._request_rubric(system_prompt, retry_prompt), **kwargs)
+ except NotImplementedError:
+ raise
+ except Exception as exc:
+ self.last_failure = llm_failure_diagnostic(exc)
+ logger.warning("LLM call failed (%s) - using fallback response", self.last_failure)
+ return self.get_fallback_response(**kwargs)
+
+ def _request_rubric(self, system_prompt: str, user_prompt: str) -> str:
+ return self.completions(
+ system_prompt,
+ user_prompt,
+ response_schema=self.response_schema,
+ schema_name=self.schema_name,
+ )
+
def get_fallback_response(self, **_kwargs: Any) -> dict:
return _UnavailableRubricReport(
{
@@ -570,6 +657,11 @@ class RubricEvalValidator(ValidatorBase):
provider, model = safe_llm_labels(self._judge.provider, self._judge.model_used)
return {"llm_provider": provider, "llm_model_used": model}
+ def _judge_attempts(self) -> dict[str, int]:
+ """Count the times the judge was asked for this skill, once a first reply came back."""
+ attempts = self._judge.last_attempts
+ return {"judge_attempts": attempts} if attempts else {}
+
@staticmethod
def _record_judge_failure(
result: ValidationResult,
@@ -580,6 +672,7 @@ class RubricEvalValidator(ValidatorBase):
message: str,
check_name: str,
suggestion: str,
+ judge_attempts: dict[str, int] | None = None,
) -> ValidationResult:
judge_report = report if isinstance(report, dict) else {}
result.metadata["rubric_eval"] = {
@@ -592,6 +685,7 @@ class RubricEvalValidator(ValidatorBase):
"judge_overall_pass": judge_report.get("overall_pass"),
"skill_name": skill_path.name,
"checks": [],
+ **(judge_attempts or {}),
}
result.add_finding(
Finding(
@@ -601,6 +695,7 @@ class RubricEvalValidator(ValidatorBase):
message=message,
file_path=str(manifest),
suggestion=suggestion,
+ metadata=dict(judge_attempts or {}),
)
)
return result
@@ -667,6 +762,7 @@ class RubricEvalValidator(ValidatorBase):
skill_content=content,
supplementary_content=supplementary,
)
+ judge_attempts = self._judge_attempts()
if not isinstance(report, dict):
return self._record_judge_failure(
@@ -677,6 +773,7 @@ class RubricEvalValidator(ValidatorBase):
message="LLM judge returned invalid rubric evidence: response must be an object",
check_name="llm_invalid_response",
suggestion="Retry rubric evaluation; the judge response was malformed",
+ judge_attempts=judge_attempts,
)
if isinstance(report, _UnavailableRubricReport):
@@ -689,6 +786,7 @@ class RubricEvalValidator(ValidatorBase):
message=f"LLM judge unavailable; rubric evaluation did not run{cause}",
check_name="llm_unavailable",
suggestion="Configure a public LLM provider to enable LLM rubric evaluation",
+ judge_attempts=judge_attempts,
)
checks, validation_error = _normalize_rubric_checks(report.get("checks"))
@@ -701,6 +799,7 @@ class RubricEvalValidator(ValidatorBase):
message=validation_error,
check_name="llm_invalid_response",
suggestion="Retry rubric evaluation; the judge response did not contain valid complete criterion evidence",
+ judge_attempts=judge_attempts,
)
overall_score = _aggregate_rubric_score(checks)
@@ -769,16 +868,18 @@ class RubricEvalValidator(ValidatorBase):
"requires_all_criteria_pass": True,
},
**judge_labels,
+ **judge_attempts,
}
- # The success detail also names the model, so each skill of a folder
- # run keeps its own.
+ # The success detail also names the model and counts the times the
+ # judge was asked, so each skill of a folder run keeps its own.
result.add_success(
check_name="rubric_eval",
message=f"LLM Rubric Score: {overall_score}/100",
overall_score=overall_score,
overall_pass=overall_pass,
**judge_labels,
+ **judge_attempts,
)
return result
diff --git a/tests/inference/test_llm_client.py b/tests/inference/test_llm_client.py
index 96fd068a..2394c8d9 100644
--- a/tests/inference/test_llm_client.py
+++ b/tests/inference/test_llm_client.py
@@ -13,6 +13,7 @@ from unittest.mock import MagicMock, patch
import pytest
+from skillevaluator.constants import RUBRIC_CRITERIA
from skillevaluator.inference import (
EmptyLLMResponseError,
FindingVerifier,
@@ -1074,13 +1075,23 @@ class TestReasoningModelRequests:
self, monkeypatch: pytest.MonkeyPatch
) -> None:
_use_provider(monkeypatch, "anthropic", "claude-opus-5-5")
+ reply = {
+ "overall_pass": True,
+ "score": 90,
+ "summary": "ok",
+ "checks": [
+ {"id": criterion["id"], "criterion": criterion["criterion"], "pass": True, "score": 9, "notes": "ok"}
+ for criterion in RUBRIC_CRITERIA
+ ],
+ }
mock_anthropic = MagicMock()
- mock_anthropic.messages.create.return_value = _anthropic_response('{"checks": []}')
+ mock_anthropic.messages.create.return_value = _anthropic_response(json.dumps(reply))
with patch("anthropic.Anthropic", return_value=mock_anthropic):
report = RubricJudge().process(skill_name="demo", skill_content="# Demo")
- assert report == {"checks": []}
+ assert report == reply
+ assert mock_anthropic.messages.create.call_count == 1
call_kwargs = mock_anthropic.messages.create.call_args.kwargs
assert call_kwargs["max_tokens"] == MAX_COMPLETION_TOKENS
assert call_kwargs["output_config"] == {
diff --git a/tests/validators/test_rubric_eval.py b/tests/validators/test_rubric_eval.py
index a575cf22..83565aa4 100644
--- a/tests/validators/test_rubric_eval.py
+++ b/tests/validators/test_rubric_eval.py
@@ -5,6 +5,7 @@
import json
import os
+import sys
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -15,8 +16,11 @@ from skillevaluator.constants import (
RUBRIC_MAX_TOKENS,
RUBRIC_REASONING_MAX_TOKENS,
)
+from skillevaluator.inference.types import LLMClientError, LLMClientRefusedError, LLMClientTruncatedError
from skillevaluator.reporting import HTMLReporter
+from skillevaluator.validators import rubric_eval
from skillevaluator.validators.rubric_eval import (
+ RUBRIC_JSON_SCHEMA,
RubricEvalValidator,
RubricJudge,
_collect_supplementary_content,
@@ -1066,3 +1070,453 @@ class TestRubricEvalValidator:
assert data["rubric_eval"]["llm_model_used"] == answered_by
(success,) = data["results"][0]["success_details"]
assert success["metadata"]["llm_model_used"] == answered_by
+
+
+_RETRY_MARKER = "YOUR PREVIOUS REPLY WAS REJECTED: "
+_RETRY_TAIL = "Reply again with ONLY one JSON object in the shape described above.\n"
+_FIRST_ID = RUBRIC_CRITERIA[0]["id"]
+_LAST_ID = RUBRIC_CRITERIA[-1]["id"]
+
+
+def _reply(checks: list[dict] | None = None) -> str:
+ """Serialize a judge reply whose own totals disagree with its criterion scores."""
+ return json.dumps(
+ {
+ "overall_pass": False,
+ "score": 0,
+ "summary": "judge summary",
+ "checks": _complete_checks() if checks is None else checks,
+ }
+ )
+
+
+def _invalid_checks(case: str) -> list[dict]:
+ checks = _complete_checks()
+ if case == "missing":
+ checks.pop()
+ elif case == "duplicate":
+ checks[-1]["id"] = _FIRST_ID
+ elif case == "unexpected":
+ checks.append({**checks[0], "id": "made_up_criterion"})
+ elif case == "score_above_range":
+ checks[0]["score"] = 11
+ elif case == "nonboolean_pass":
+ checks[0]["pass"] = "yes"
+ else:
+ assert case == "empty"
+ checks = []
+ return checks
+
+
+class _ScriptedCompletions:
+ """Stand in for ``RubricJudge.completions``: return or raise each scripted reply in turn."""
+
+ def __init__(self, *replies: str | Exception) -> None:
+ self._replies = list(replies)
+ self.requests: list[dict] = []
+
+ def __call__(self, system_prompt: str, user_prompt: str, **kwargs) -> str:
+ self.requests.append({"system": system_prompt, "user": user_prompt, **kwargs})
+ reply = self._replies.pop(0)
+ if isinstance(reply, Exception):
+ raise reply
+ return reply
+
+
+def _validate_with(tmp_path: Path, *replies: str | Exception):
+ scripted = _ScriptedCompletions(*replies)
+ with patch.object(RubricJudge, "completions", new=scripted):
+ result = RubricEvalValidator(min_score=70).validate(_write_skill(tmp_path))
+ return result, scripted.requests
+
+
+def _llm_findings(result) -> list:
+ return [finding for finding in result.findings if finding.check_name.startswith("llm_")]
+
+
+def _use_anthropic(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "anthropic")
+ monkeypatch.setenv("SKILL_EVAL_LLM_MODEL", "claude-opus-5-5")
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ for name in ("SKILL_EVAL_LLM_BASE_URL", "ANTHROPIC_BASE_URL"):
+ monkeypatch.delenv(name, raising=False)
+
+
+def _anthropic_message(index: int, model: str, text: str) -> dict:
+ return {
+ "id": f"msg_test_{index}",
+ "type": "message",
+ "role": "assistant",
+ "model": model,
+ "content": [{"type": "text", "text": text}],
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 1, "output_tokens": 1},
+ }
+
+
+class TestInvalidReplyRetry:
+ """One judge reply that cannot be scored gets one more request that names the problem."""
+
+ @pytest.mark.parametrize("padding", ["", "x" * 410 + " "])
+ def test_retry_problem_redacts_credentials_before_logging_and_truncation(
+ self, tmp_path, padding, caplog, monkeypatch
+ ):
+ secret = "sk-syntheticcredential123456789"
+ checks = _complete_checks()
+ checks.append({**checks[0], "id": padding + secret})
+
+ monkeypatch.setattr(rubric_eval.logger, "propagate", True)
+ result, requests = _validate_with(tmp_path, _reply(checks), _reply())
+
+ assert "Rubric judge reply rejected" in caplog.text
+ assert "sk-synthetic" not in caplog.text
+ assert "sk-synthetic" not in requests[1]["user"].removeprefix(requests[0]["user"])
+ assert result.passed
+
+ @pytest.mark.parametrize(
+ ("first_reply", "problem"),
+ [
+ (_reply(_invalid_checks("missing")), f"missing criterion ids: {_LAST_ID}"),
+ (_reply(_invalid_checks("duplicate")), f"duplicate criterion ids: {_FIRST_ID}"),
+ (_reply(_invalid_checks("unexpected")), "unexpected criterion ids: made_up_criterion"),
+ (
+ _reply(_invalid_checks("score_above_range")),
+ f"criterion {_FIRST_ID} score must be a finite number between 0 and 10",
+ ),
+ (_reply(_invalid_checks("nonboolean_pass")), f"criterion {_FIRST_ID} pass must be a boolean"),
+ (_reply(_invalid_checks("empty")), f"expected {len(RUBRIC_CRITERIA)} criteria, received 0"),
+ ("Here is my assessment of the skill.", "Could not extract valid JSON from LLM response (35 chars)"),
+ ('{"summary": "cut", "checks": [', "Could not extract valid JSON from LLM response"),
+ ],
+ ids=["missing", "duplicate", "unexpected", "score", "pass", "empty", "prose", "unclosed-json"],
+ )
+ def test_invalid_reply_is_retried_once_with_the_problem_then_scored(self, tmp_path, first_reply, problem):
+ result, requests = _validate_with(tmp_path, first_reply, _reply())
+
+ assert len(requests) == 2
+ first, retry = requests
+ assert _RETRY_MARKER not in first["user"]
+ assert retry["user"].startswith(first["user"])
+ retry_note = retry["user"][len(first["user"]) :]
+ assert retry_note.startswith(f"\n{_RETRY_MARKER}")
+ assert problem in retry_note
+ assert retry_note.endswith(f". {_RETRY_TAIL}")
+ for request in requests:
+ assert request["system"] == RubricJudge().get_system_prompt()
+ assert request["response_schema"] == RUBRIC_JSON_SCHEMA
+ assert request["schema_name"] == "rubric_evaluation"
+
+ rubric = result.metadata["rubric_eval"]
+ assert result.passed
+ assert _llm_findings(result) == []
+ assert rubric["execution_status"] == "succeeded"
+ assert rubric["overall_score"] == 90.0
+ assert rubric["overall_pass"] is True
+ assert rubric["judge_score"] == 0
+ assert rubric["judge_attempts"] == 2
+ (success,) = result.success_details
+ assert success.metadata["judge_attempts"] == 2
+
+ def test_reply_with_an_integer_past_the_digit_limit_is_retried(self, tmp_path):
+ limit = sys.get_int_max_str_digits()
+ if not limit:
+ pytest.skip("integer string conversion is unlimited in this interpreter")
+ first_reply = f'{{"checks": [{{"id": "{_FIRST_ID}", "score": 1{"0" * limit}}}]}}'
+ with pytest.raises(ValueError) as parse_error:
+ json.loads(first_reply)
+ assert not isinstance(parse_error.value, json.JSONDecodeError)
+
+ result, requests = _validate_with(tmp_path, first_reply, _reply())
+
+ assert len(requests) == 2
+ first, retry = requests
+ assert retry["user"] == f"{first['user']}\n{_RETRY_MARKER}{parse_error.value}. {_RETRY_TAIL}"
+ rubric = result.metadata["rubric_eval"]
+ assert result.passed
+ assert _llm_findings(result) == []
+ assert rubric["overall_score"] == 90.0
+ assert rubric["judge_attempts"] == 2
+
+ @pytest.mark.parametrize(
+ ("message", "problem"),
+ [
+ (
+ "maximum recursion depth exceeded while decoding a JSON array from a unicode string",
+ "maximum recursion depth exceeded while decoding a JSON array from a unicode string",
+ ),
+ ("", "RecursionError"),
+ ],
+ ids=["message", "no-message"],
+ )
+ def test_reply_nested_too_deep_to_parse_is_retried(
+ self, tmp_path, monkeypatch: pytest.MonkeyPatch, message, problem
+ ):
+ # json.loads raises RecursionError for nesting deeper than the interpreter
+ # allows. That depth differs by Python version and platform, so a stand-in
+ # parser raises it for this one reply.
+ nested_reply = '{"checks": [[[[]]]]}'
+
+ def extract_json(content: str) -> dict:
+ if content == nested_reply:
+ raise RecursionError(message)
+ return _extract_json(content)
+
+ monkeypatch.setattr(rubric_eval, "_extract_json", extract_json)
+
+ result, requests = _validate_with(tmp_path, nested_reply, _reply())
+
+ assert len(requests) == 2
+ first, retry = requests
+ assert retry["user"] == f"{first['user']}\n{_RETRY_MARKER}{problem}. {_RETRY_TAIL}"
+ rubric = result.metadata["rubric_eval"]
+ assert result.passed
+ assert _llm_findings(result) == []
+ assert rubric["judge_attempts"] == 2
+
+ def test_valid_first_reply_is_not_retried(self, tmp_path):
+ result, requests = _validate_with(tmp_path, _reply())
+
+ assert len(requests) == 1
+ assert result.passed
+ assert result.metadata["rubric_eval"]["judge_attempts"] == 1
+
+ @pytest.mark.parametrize(
+ ("first_reply", "second_case", "problem"),
+ [
+ (_reply(_invalid_checks("missing")), "missing", f"missing criterion ids: {_LAST_ID}"),
+ ("not json", "unexpected", "unexpected criterion ids: made_up_criterion"),
+ ],
+ ids=["missing-twice", "prose-then-unexpected"],
+ )
+ def test_second_invalid_reply_fails_closed(self, tmp_path, first_reply, second_case, problem):
+ result, requests = _validate_with(tmp_path, first_reply, _reply(_invalid_checks(second_case)))
+
+ assert len(requests) == 2
+ rubric = result.metadata["rubric_eval"]
+ assert not result.passed
+ assert rubric["execution_status"] == "failed"
+ assert rubric["overall_score"] is None
+ assert rubric["checks"] == []
+ assert rubric["judge_attempts"] == 2
+ assert problem in rubric["summary"]
+ (finding,) = _llm_findings(result)
+ assert finding.check_name == "llm_invalid_response"
+ assert finding.severity.value == "high"
+ assert finding.metadata == {"judge_attempts": 2}
+ assert problem in finding.message
+
+ def test_second_unparseable_reply_reports_unavailable(self, tmp_path):
+ result, requests = _validate_with(tmp_path, _reply(_invalid_checks("missing")), "still not json")
+
+ assert len(requests) == 2
+ rubric = result.metadata["rubric_eval"]
+ assert not result.passed
+ assert rubric["execution_status"] == "failed"
+ assert rubric["judge_attempts"] == 2
+ (finding,) = _llm_findings(result)
+ assert finding.check_name == "llm_unavailable"
+ assert finding.severity.value == "high"
+ assert finding.metadata == {"judge_attempts": 2}
+ assert "LLM configuration or response was invalid" in finding.message
+
+ @pytest.mark.parametrize(
+ ("error", "diagnostic"),
+ [
+ (LLMClientError("no provider configured"), "LLM configuration or response was invalid"),
+ (LLMClientRefusedError("declined"), "safety refusal"),
+ (LLMClientTruncatedError("cut off", _reply()), "output-token limit"),
+ ],
+ ids=["request-error", "refusal", "truncated"],
+ )
+ def test_provider_errors_are_not_retried(self, tmp_path, error, diagnostic):
+ result, requests = _validate_with(tmp_path, error, _reply())
+
+ assert len(requests) == 1
+ rubric = result.metadata["rubric_eval"]
+ assert not result.passed
+ assert rubric["execution_status"] == "failed"
+ assert "judge_attempts" not in rubric
+ (finding,) = _llm_findings(result)
+ assert finding.check_name == "llm_unavailable"
+ assert finding.metadata == {}
+ assert diagnostic in finding.message
+
+ def test_no_provider_sends_no_request_and_records_no_attempts(self, tmp_path, monkeypatch: pytest.MonkeyPatch):
+ from skillevaluator.reporting import JSONReporter
+
+ for name in (
+ "SKILL_EVAL_LLM_PROVIDER",
+ "SKILL_EVAL_LLM_MODEL",
+ "SKILL_EVAL_LLM_API_KEY",
+ "SKILL_EVAL_LLM_BASE_URL",
+ "NVIDIA_API_KEY",
+ "OPENAI_API_KEY",
+ "OPENAI_BASE_URL",
+ "ANTHROPIC_API_KEY",
+ "ANTHROPIC_BASE_URL",
+ ):
+ monkeypatch.delenv(name, raising=False)
+
+ with patch.object(RubricJudge, "_get_client") as get_client:
+ result = RubricEvalValidator().validate(_write_skill(tmp_path))
+
+ get_client.assert_not_called()
+ data = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+ assert data["rubric_eval"]["execution_status"] == "failed"
+ assert "judge_attempts" not in data["rubric_eval"]
+ (finding,) = [item for item in data["results"][0]["findings"] if item["check_name"].startswith("llm_")]
+ assert finding["check_name"] == "llm_unavailable"
+ assert "did not run" in finding["message"]
+ assert "judge_attempts" not in (finding.get("metadata") or {})
+
+ def test_provider_error_on_the_retry_reports_unavailable(self, tmp_path):
+ result, requests = _validate_with(
+ tmp_path, _reply(_invalid_checks("missing")), LLMClientRefusedError("declined"), _reply()
+ )
+
+ assert len(requests) == 2
+ assert result.metadata["rubric_eval"]["judge_attempts"] == 2
+ (finding,) = _llm_findings(result)
+ assert finding.check_name == "llm_unavailable"
+ assert finding.metadata == {"judge_attempts": 2}
+ assert "safety refusal" in finding.message
+
+ def test_retry_note_keeps_a_bounded_part_of_a_long_problem(self, tmp_path):
+ long_id = "x" * 20_000
+ checks = _complete_checks()
+ checks.append({**checks[0], "id": long_id})
+ with patch("skillevaluator.validators.rubric_eval.logger") as log:
+ result, requests = _validate_with(tmp_path, _reply(checks), _reply())
+
+ assert len(requests) == 2
+ first, retry = requests
+ retry_note = retry["user"][len(first["user"]) :]
+ problem = retry_note.removeprefix(f"\n{_RETRY_MARKER}").removesuffix(f". {_RETRY_TAIL}")
+ assert problem.startswith("LLM judge returned invalid rubric evidence: unexpected criterion ids: xxx")
+ assert problem.endswith("x ... [truncated]")
+ # The log line and the retry note keep the first 500 characters.
+ assert len(problem) == 500 + len(" ... [truncated]")
+ (rejected,) = [call for call in log.warning.call_args_list if "rejected" in call.args[0]]
+ assert rejected.args[1:] == (problem,)
+ assert result.metadata["rubric_eval"]["judge_attempts"] == 2
+ assert result.passed
+
+ @pytest.mark.parametrize(
+ ("replies", "expected_requests"),
+ [(("valid",), 1), (("missing", "valid"), 2)],
+ ids=["valid", "missing-then-valid"],
+ )
+ def test_custom_criteria_are_checked_against_the_given_list(self, replies, expected_requests):
+ criteria = [
+ {"id": "custom_a", "criterion": "Custom A", "importance": "high"},
+ {"id": "custom_b", "criterion": "Custom B", "importance": "low"},
+ ]
+ checks = [
+ {"id": criterion["id"], "criterion": criterion["criterion"], "pass": True, "score": 9, "notes": "ok"}
+ for criterion in criteria
+ ]
+ scripted_replies = {"valid": _reply(checks), "missing": _reply(checks[:1])}
+ scripted = _ScriptedCompletions(*(scripted_replies[reply] for reply in replies))
+
+ with patch.object(RubricJudge, "completions", new=scripted):
+ report = RubricJudge().process(skill_name="demo", skill_content="# Demo", criteria=criteria)
+
+ assert len(scripted.requests) == expected_requests
+ assert report == json.loads(scripted_replies["valid"])
+ if expected_requests == 2:
+ retry_note = scripted.requests[1]["user"][len(scripted.requests[0]["user"]) :]
+ assert "missing criterion ids: custom_b." in retry_note
+ assert not any(criterion["id"] in retry_note for criterion in RUBRIC_CRITERIA)
+
+ def test_judge_returns_the_second_reply_as_parsed(self):
+ second = {"summary": "still incomplete", "checks": _invalid_checks("missing")}
+ scripted = _ScriptedCompletions(_reply(_invalid_checks("missing")), json.dumps(second))
+ judge = RubricJudge()
+ judge.last_failure = "stale failure"
+
+ with patch.object(RubricJudge, "completions", new=scripted):
+ report = judge.process(skill_name="demo", skill_content="# Demo")
+
+ assert report == second
+ assert judge.last_attempts == 2
+ assert judge.last_failure is None
+
+ def test_each_skill_in_a_folder_records_its_own_attempts(self, tmp_path):
+ for name in ("skill-a", "skill-b", "skill-c"):
+ _write_skill(tmp_path, name)
+ scripted = _ScriptedCompletions(
+ _reply(_invalid_checks("missing")),
+ _reply(),
+ _reply(),
+ _reply(_invalid_checks("missing")),
+ _reply(_invalid_checks("missing")),
+ )
+
+ with patch.object(RubricJudge, "completions", new=scripted):
+ result = RubricEvalValidator(min_score=70).validate(tmp_path)
+
+ assert not result.passed
+ assert len(scripted.requests) == 5
+ successes = {detail.check_name: detail.metadata["judge_attempts"] for detail in result.success_details}
+ assert successes == {"[skill-a] rubric_eval": 2, "[skill-b] rubric_eval": 1}
+ (finding,) = _llm_findings(result)
+ assert finding.file_path.startswith("[skill-c] ")
+ assert finding.metadata == {"judge_attempts": 2}
+
+ def test_report_names_the_model_that_answered_the_retry(self, tmp_path, monkeypatch: pytest.MonkeyPatch):
+ pytest.importorskip("anthropic")
+ httpx = pytest.importorskip("httpx")
+ from skillevaluator.reporting import JSONReporter
+
+ _use_anthropic(monkeypatch)
+ replies = [("claude-opus-5-5", _reply(_invalid_checks("missing"))), ("claude-opus-4-8", _reply())]
+ bodies: list[dict] = []
+
+ def handler(request):
+ bodies.append(json.loads(request.content))
+ model, text = replies[len(bodies) - 1]
+ return httpx.Response(200, json=_anthropic_message(len(bodies), model, text))
+
+ validator = RubricEvalValidator()
+ with httpx.Client(transport=httpx.MockTransport(handler)) as http_client:
+ validator._judge = RubricJudge(http_client=http_client)
+ result = validator.validate(_write_skill(tmp_path))
+
+ assert len(bodies) == 2
+ assert _RETRY_MARKER not in json.dumps(bodies[0]["messages"])
+ problem = f"LLM judge returned invalid rubric evidence: missing criterion ids: {_LAST_ID}."
+ assert f"{_RETRY_MARKER}{problem}" in bodies[1]["messages"][-1]["content"]
+ assert bodies[1]["output_config"]["format"] == bodies[0]["output_config"]["format"]
+ data = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+ assert data["rubric_eval"]["execution_status"] == "succeeded"
+ assert data["rubric_eval"]["judge_attempts"] == 2
+ assert data["rubric_eval"]["llm_model_used"] == "claude-opus-4-8"
+
+ def test_client_retry_of_a_transient_error_is_not_counted(self, tmp_path, monkeypatch: pytest.MonkeyPatch):
+ pytest.importorskip("anthropic")
+ httpx = pytest.importorskip("httpx")
+
+ _use_anthropic(monkeypatch)
+ bodies: list[dict] = []
+
+ def handler(request):
+ bodies.append(json.loads(request.content))
+ if len(bodies) == 1:
+ return httpx.Response(
+ 503, json={"type": "error", "error": {"type": "overloaded_error", "message": "busy"}}
+ )
+ return httpx.Response(200, json=_anthropic_message(len(bodies), "claude-opus-5-5", _reply()))
+
+ validator = RubricEvalValidator()
+ with httpx.Client(transport=httpx.MockTransport(handler)) as http_client:
+ validator._judge = RubricJudge(
+ http_client=http_client, max_retries=1, retry_base_delay=0, retry_max_delay=0
+ )
+ result = validator.validate(_write_skill(tmp_path))
+
+ assert len(bodies) == 2
+ assert bodies[1] == bodies[0]
+ rubric = result.metadata["rubric_eval"]
+ assert rubric["execution_status"] == "succeeded"
+ assert rubric["judge_attempts"] == 1