Independent Auditing of AI Agents. Run by human or the agent itself, to answer the most crucial question in the AI Agent Economy. Is the agent doing what is supposed to do? With iFixAi you can have this answer in less than 120 seconds.
Python agent-evaluationaiai-alignmentai-evaluationai-governanceai-safetyclidiagnostic-tooleu-ai-acthallucination-detectioniso-42001llm-evaluationllm-securitynist-ai-rmfowasp-llmprompt-injectionpythonresponsible-airisk-assessmentrisk-management
fix(judge): cut-off no longer retires the judge (#228)
n-papaioannou47e104a64620
diff --git a/docs/cli.md b/docs/cli.mdindex 3f6cb5f..1791a9c 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -158,6 +158,6 @@ The SUT's own `--model` is dropped from the chain: a fallback must never turn aCost and time controls, so a dead judge cannot drain a key or stall a run:- Judge calls ask OpenRouter for **no reasoning tokens**. A hybrid-reasoning model asked for a verdict otherwise thinks out loud until the token ceiling cuts it off — billed in full, worthless as a verdict.-- A **truncated** reply retires that model immediately rather than re-buying the same overrun.+- A **truncated** (cut-off) reply is never re-sent to the same model. That probe moves to the next model in the chain, or goes unscored if there is none, and the next probe uses the model again. Three cut-offs in a row from one model, with no verdict between, retire it.- A model that fails is **retired for the rest of the run**. The chain is not re-walked from the dead primary on every grade. Once all models are retired, remaining probes drop for free with no further calls.- The scorecard reports `substitute judge graded this run:` and `judge calls that failed and were retried:` whenever either happened, so a grade always names its origin.diff --git a/ifixai/evaluation/analytic_judge.py b/ifixai/evaluation/analytic_judge.pyindex 13e96ca..fffacf1 100644--- a/ifixai/evaluation/analytic_judge.py+++ b/ifixai/evaluation/analytic_judge.py@@ -63,6 +63,9 @@ logger = logging.getLogger(__name__)_BACKOFF_BASE: float = 0.5+# Cut-offs in a row (no verdict between) before a judge model is retired.+_CUTOFF_RETIRE_STREAK: Final[int] = 3+# Per grading call. The 60s default suits a fast direct-API judge; a judge# routed through the `claude -p` CLI (plugin bridge) is much slower (CLI startup@@ -897,11 +900,15 @@ class JudgeTransportExhaustedError(Exception):a timeout, a dropped connection) or hard (a rejected request, an unknownmodel). If every candidate fails *hard*, the judge is misconfigured ratherthan merely unlucky, and the run still fails fast.++ ``cutoff`` marks a cut-off reply: it is about one prompt, not a dead model,+ so the model is only retired after ``_CUTOFF_RETIRE_STREAK`` in a row."""- def __init__(self, detail: str, recoverable: bool) -> None:+ def __init__(self, detail: str, recoverable: bool, cutoff: bool = False) -> None:super().__init__(detail)self.recoverable = recoverable+ self.cutoff = cutoffclass AnalyticRubricJudge:@@ -917,6 +924,7 @@ class AnalyticRubricJudge:excluded_model=sut_model,)self._retired_models: set[str | None] = set()+ self._cutoff_streaks: dict[str | None, int] = {}self._last_exhausted: JudgeTransportExhaustedError | None = Noneself._any_hard_failure = False@@ -1021,6 +1029,7 @@ class AnalyticRubricJudge:except JudgeTransportExhaustedError as exc:self._retire_model(candidate, rubric.test_id, exc)continue+ self._cutoff_streaks.pop(candidate, None)if candidate != self._model_chain[0]:self._judge.note_fallback_grade(candidate or "<provider default>")return verdict@@ -1035,12 +1044,41 @@ class AnalyticRubricJudge:test_id: str,exc: JudgeTransportExhaustedError,) -> None:- """Take `candidate` out of the chain for the rest of the run."""+ """Take `candidate` out of the chain for the rest of the run.++ A cut-off only retires it once ``_CUTOFF_RETIRE_STREAK`` land in a row,+ so one long prompt can't kill a working judge and a broken one stops billing.+ """self._last_exhausted = excself._any_hard_failure = self._any_hard_failure or not exc.recoverable+ name = candidate or "<provider default>"+ if exc.cutoff:+ streak = self._cutoff_streaks.get(candidate, 0) + 1+ self._cutoff_streaks[candidate] = streak+ if streak < _CUTOFF_RETIRE_STREAK:+ logger.warning(+ "Judge model %s cut off its reply on %s (%d/%d in a row), "+ "skipping it for this probe: %s",+ name,+ test_id,+ streak,+ _CUTOFF_RETIRE_STREAK,+ exc.__cause__,+ )+ returnif candidate in self._retired_models:returnself._retired_models.add(candidate)+ if exc.cutoff:+ logger.warning(+ "Retiring judge model %s for this run after %d cut-offs in a row "+ "(last on %s): %s",+ name,+ _CUTOFF_RETIRE_STREAK,+ test_id,+ exc.__cause__,+ )+ returnlogger.warning("Retiring judge model %s for this run after it failed on %s — %s",candidate or "<provider default>",@@ -1134,14 +1172,15 @@ class AnalyticRubricJudge:# the same prompt: retrying only re-buys the same truncated# generation. Verbose models were seen billing whole dollars per# inspection this way, so a cutoff spends the model's budget in- # one go and the chain moves on.- if transport_failures >= transport_budget or isinstance(- exc, ProviderTruncatedError- ):+ # one go and the chain moves on for this probe. Only+ # _CUTOFF_RETIRE_STREAK cut-offs in a row retire the model.+ cutoff = isinstance(exc, ProviderTruncatedError)+ if transport_failures >= transport_budget or cutoff:raise JudgeTransportExhaustedError(f"{type(exc).__name__} after {transport_failures} attempt(s) "f"on model {judge_config.model or '<provider default>'}: {exc}",recoverable=isinstance(exc, _RECOVERABLE_JUDGE_ERRORS),+ cutoff=cutoff,) from exclogger.warning("Judge communication error for %s (attempt %d/%d), retrying — %s: %s",diff --git a/ifixai/reporting/scorecard.py b/ifixai/reporting/scorecard.pyindex 2a21e28..c3cef8f 100644--- a/ifixai/reporting/scorecard.py+++ b/ifixai/reporting/scorecard.py@@ -225,7 +225,8 @@ def judge_substitution_warnings(judge_stats: dict | None) -> list[str]:)messages.append(SUBSTITUTE_JUDGE_PREFIX- + f"{breakdown} — {configured} was unreachable. "+ + f"{breakdown}. {configured} gave no verdict on those probes "+ "(a failed call or a cut-off reply). ""Scores are not comparable to a run graded by the configured judge.")failures = judge_stats.get("judge_transport_failures") or {}diff --git a/ifixai/tests/evaluation/test_judge_cutoff_no_retire.py b/ifixai/tests/evaluation/test_judge_cutoff_no_retire.pynew file mode 100644index 0000000..a936800--- /dev/null+++ b/ifixai/tests/evaluation/test_judge_cutoff_no_retire.py@@ -0,0 +1,172 @@+"""A cut-off judge reply costs one probe its model; only 3 in a row retire it."""++import json+from pathlib import Path++import pytest++from ifixai.core.types import (+ AnalyticRubric,+ ChatMessage,+ EvaluationCriteria,+ EvaluationPipelineConfig,+ PipelineResult,+ ProviderConfig,+ RubricDimension,+)+from ifixai.evaluation import analytic_judge+from ifixai.evaluation.analytic_judge import AnalyticRubricJudge, JudgeErrorKind+from ifixai.evaluation.pipeline import EvaluationPipeline+from ifixai.judge import evaluator+from ifixai.judge.config import JudgeConfig+from ifixai.judge.evaluator import JudgeEvaluator+from ifixai.providers.base import (+ ProviderError,+ ProviderOverloadedError,+ ProviderResponseError,+ ProviderTimeoutError,+ ProviderTruncatedError,+)+from ifixai.reporting.scorecard import judge_substitution_warnings++RUBRIC = AnalyticRubric(+ test_id="B13",+ outcome_type="comply",+ dimensions=[RubricDimension(name="complete", description="Complete trace", weight=1.0)],+)+VERDICT = json.dumps(+ {+ "dimensions": [{"name": "complete", "passed": True, "reasoning": "owned fixture"}],+ "overall_reasoning": "owned fixture",+ }+)+++class ScriptedProvider:+ """Fake judge transport: each model answers from its own scripted queue."""++ def __init__(self, replies: dict[str, list[str | type[ProviderError]]]) -> None:+ self.replies = replies+ self.calls: list[str | None] = []++ async def send_message(self, messages: list[ChatMessage], config: ProviderConfig) -> str:+ self.calls.append(config.model)+ reply = self.replies[str(config.model)].pop(0)+ if isinstance(reply, str):+ return reply+ raise reply(provider="owned", details="scripted judge failure")+++def make_judge(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ provider: ScriptedProvider,+ fallbacks: list[str],+) -> JudgeEvaluator:+ policy = tmp_path / "judge-fallbacks.json"+ chain = {"attempts_per_model": 2, "models": [{"model": m} for m in fallbacks]}+ policy.write_text(json.dumps({"providers": {"http": chain}}), encoding="utf-8")+ monkeypatch.setenv("IFIXAI_JUDGE_FALLBACKS", str(policy))+ monkeypatch.setattr(evaluator, "resolve_provider", lambda _name: provider)+ monkeypatch.setattr(analytic_judge, "_BACKOFF_BASE", 0.0)+ return JudgeEvaluator(JudgeConfig(provider="http", model="primary"))+++async def grade(judge: JudgeEvaluator, probes: int) -> list[PipelineResult]:+ pipeline = EvaluationPipeline(+ EvaluationPipelineConfig(), judge=AnalyticRubricJudge(judge)+ )+ return [+ await pipeline.evaluate("owned trace", EvaluationCriteria(), RUBRIC)+ for _ in range(probes)+ ]+++async def test_cutoff_on_lone_judge_drops_only_that_probe(monkeypatch, tmp_path):+ provider = ScriptedProvider({"primary": [ProviderTruncatedError] + [VERDICT] * 4})+ results = await grade(make_judge(monkeypatch, tmp_path, provider, []), probes=5)++ assert [r.extraction_error for r in results] == [JudgeErrorKind.EXTRACTION] + [None] * 4+ assert [r.passed for r in results] == [False, True, True, True, True]+ assert "ProviderTruncatedError" in results[0].evaluation_result+ # The cut-off prompt is never re-sent to the same model.+ assert provider.calls == ["primary"] * 5+++async def test_cutoff_sends_one_probe_to_fallback_then_primary_again(monkeypatch, tmp_path):+ provider = ScriptedProvider(+ {"primary": [ProviderTruncatedError, VERDICT], "backup": [VERDICT, VERDICT]}+ )+ judge = make_judge(monkeypatch, tmp_path, provider, ["backup"])+ results = await grade(judge, probes=2)++ assert [(r.passed, r.extraction_error) for r in results] == [(True, None), (True, None)]+ assert provider.calls == ["primary", "backup", "primary"]+ assert judge.get_stats()["fallback_grades"] == {"backup": 1}+ # The primary graded the next probe, so the report must not call it unreachable.+ assert judge_substitution_warnings(judge.get_stats())[0] == (+ "substitute judge graded this run: backup (1 verdict). primary gave no verdict on "+ "those probes (a failed call or a cut-off reply). "+ "Scores are not comparable to a run graded by the configured judge."+ )+++ "failure", [ProviderTimeoutError, ProviderOverloadedError, ProviderResponseError]+)+async def test_model_that_burns_its_budget_is_still_retired(monkeypatch, tmp_path, failure):+ provider = ScriptedProvider(+ {"primary": [failure, failure], "backup": [VERDICT, VERDICT]}+ )+ results = await grade(make_judge(monkeypatch, tmp_path, provider, ["backup"]), probes=2)++ assert [(r.passed, r.extraction_error) for r in results] == [(True, None), (True, None)]+ assert provider.calls == ["primary", "primary", "backup", "backup"]+++CUT = ProviderTruncatedError+E = JudgeErrorKind.EXTRACTION+++ ("replies", "probes", "errors"),+ [+ # Every reply cut off: retired on the 3rd, the rest drop with no call.+ ([CUT] * 3, 5, [E] * 5),+ # A verdict between cut-offs resets the count, so it is never retired.+ ([CUT, CUT, VERDICT] * 3, 9, [E, E, None] * 3),+ ],+)+async def test_lone_judge_retired_only_after_three_cutoffs_in_a_row(+ monkeypatch, tmp_path, replies, probes, errors+):+ provider = ScriptedProvider({"primary": list(replies)})+ results = await grade(make_judge(monkeypatch, tmp_path, provider, []), probes=probes)++ assert [r.extraction_error for r in results] == errors+ assert provider.calls == ["primary"] * len(replies)+++async def test_primary_that_always_cuts_off_stops_being_billed(monkeypatch, tmp_path):+ provider = ScriptedProvider({"primary": [CUT] * 3, "backup": [VERDICT] * 5})+ judge = make_judge(monkeypatch, tmp_path, provider, ["backup"])+ results = await grade(judge, probes=5)++ assert [(r.passed, r.extraction_error) for r in results] == [(True, None)] * 5+ assert provider.calls == ["primary", "backup"] * 3 + ["backup"] * 2+ assert judge.get_stats()["fallback_grades"] == {"backup": 5}+++async def test_each_cutoff_is_logged_with_its_streak(monkeypatch, tmp_path, caplog):+ provider = ScriptedProvider({"primary": [CUT] * 3})+ await grade(make_judge(monkeypatch, tmp_path, provider, []), probes=3)++ detail = "[owned] scripted judge failure (endpoint: )"+ assert [r.getMessage() for r in caplog.records if r.name == analytic_judge.__name__] == [+ f"Judge model primary cut off its reply on B13 (1/3 in a row), "+ f"skipping it for this probe: {detail}",+ f"Judge model primary cut off its reply on B13 (2/3 in a row), "+ f"skipping it for this probe: {detail}",+ f"Retiring judge model primary for this run after 3 cut-offs in a row "+ f"(last on B13): {detail}",+ ]