Skip to content

Commit fc29403

Browse files
davanstrienclaude
andauthored
fix: harden judge failure handling and verdict aggregation (#28)
Four related fixes so judge failures can neither corrupt the ELO nor abort a run: - Exclude 0/0 jury verdicts from results. When every judge in a jury failed, aggregate_jury_votes returns {winner: tie, agreement: 0/0} — a non-empty dict that passed the failure filter in _convert_results and entered Bradley-Terry as a genuine tie, dragging down models that had actually won their real comparisons. - Protect the sequential judge path. The default --concurrency 1 path had no error handling (unlike the concurrent path), so one non-retryable API error late in an adaptive run discarded every completed batch. Failures now log and yield {} like the concurrent path. - Make parse_judge_output robust to valid-JSON-but-wrong-shape output (null/list winner, bare string/array). These raised AttributeError/ TypeError that escaped the retry wrapper; they now return {} like other parse failures. - Judge at temperature 0.0 on HF Inference Endpoints, matching every other judge backend. 0.7 made verdicts non-reproducible on that path. Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
1 parent fcdb3c5 commit fc29403

6 files changed

Lines changed: 132 additions & 10 deletions

File tree

‎src/ocr_bench/backends.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,14 @@ def judge(self, comparisons: list[Comparison]) -> list[dict[str, str]]:
7575
or an empty dict on failure.
7676
"""
7777
if self.concurrency <= 1 or len(comparisons) <= 1:
78-
return [self._call_single(comp) for comp in comparisons]
78+
results = []
79+
for i, comp in enumerate(comparisons):
80+
try:
81+
results.append(self._call_single(comp))
82+
except Exception as exc:
83+
logger.warning("judge_call_failed", idx=i, error=str(exc))
84+
results.append({})
85+
return results
7986

8087
# Concurrent execution preserving order
8188
results: list[dict[str, str]] = [{}] * len(comparisons)
@@ -202,7 +209,7 @@ def parse_judge_spec(
202209
model=model_name,
203210
api_key=token,
204211
max_tokens=max_tokens,
205-
temperature=0.7,
212+
temperature=0.0,
206213
extra_body={"chat_template_kwargs": {"enable_thinking": False}},
207214
concurrency=concurrency,
208215
)

‎src/ocr_bench/cli.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,9 @@ def _convert_results(
191191
"""Convert judged comparisons + aggregated outputs into ComparisonResult list."""
192192
results: list[ComparisonResult] = []
193193
for comp, result in zip(comparisons, aggregated):
194-
if not result:
194+
# Skip failures: empty dict (single judge failed) and 0/0 "ties"
195+
# (every judge in a jury failed) — neither is a real verdict.
196+
if not result or result.get("agreement") == "0/0":
195197
continue
196198
results.append(
197199
ComparisonResult(

‎src/ocr_bench/judge.py‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -278,12 +278,22 @@ def parse_judge_output(text: str) -> dict[str, str]:
278278
text = text.split("\n", 1)[1].rsplit("```", 1)[0].strip()
279279
try:
280280
result = json.loads(text)
281-
winner = result.get("winner", "tie").upper().strip()
282-
if winner == "TIE":
283-
winner = "tie"
284-
if winner not in ("A", "B", "tie"):
285-
winner = "tie"
286-
return {"winner": winner, "reason": result.get("reason", "")}
287281
except json.JSONDecodeError:
288282
logger.warning("Failed to parse judge output: %s", text[:200])
289283
return {}
284+
if not isinstance(result, dict):
285+
logger.warning("Judge output is not a JSON object: %s", text[:200])
286+
return {}
287+
winner = result.get("winner", "tie")
288+
if not isinstance(winner, str):
289+
logger.warning("Judge output has non-string winner: %s", text[:200])
290+
return {}
291+
winner = winner.upper().strip()
292+
if winner == "TIE":
293+
winner = "tie"
294+
if winner not in ("A", "B", "tie"):
295+
winner = "tie"
296+
reason = result.get("reason", "")
297+
if not isinstance(reason, str):
298+
reason = json.dumps(reason)
299+
return {"winner": winner, "reason": reason}

‎tests/test_backends.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from ocr_bench.backends import (
1010
InferenceProviderJudge,
11+
JudgeBackend,
1112
OpenAICompatibleJudge,
1213
_is_retryable,
1314
aggregate_jury_votes,
@@ -127,13 +128,50 @@ def test_hf_endpoint_url(self, mock_get_token):
127128
assert isinstance(backend, OpenAICompatibleJudge)
128129
assert "endpoints.huggingface" in backend.name
129130
assert backend.name.endswith("/v1")
131+
assert backend.temperature == 0.0
130132

131133
def test_non_hf_url_still_openai(self):
132134
"""Non-HF URLs still route to OpenAICompatibleJudge."""
133135
backend = parse_judge_spec("https://my-vllm-server.example.com/v1")
134136
assert isinstance(backend, OpenAICompatibleJudge)
135137

136138

139+
# ---------------------------------------------------------------------------
140+
# JudgeBackend.judge error handling
141+
# ---------------------------------------------------------------------------
142+
143+
144+
class _FlakyJudge(JudgeBackend):
145+
"""Judge whose _call_single raises on sample_idx 1."""
146+
147+
name = "flaky"
148+
149+
def __init__(self, concurrency: int = 1):
150+
self.concurrency = concurrency
151+
152+
def _call_single(self, comp: Comparison) -> dict[str, str]:
153+
if comp.sample_idx == 1:
154+
raise RuntimeError("boom")
155+
return {"winner": "A", "reason": "ok"}
156+
157+
158+
class TestJudgeErrorHandling:
159+
def test_sequential_failure_yields_empty_dict(self):
160+
"""A failed call on the default sequential path must not abort the run."""
161+
comps = [_make_comparison(i) for i in range(3)]
162+
results = _FlakyJudge(concurrency=1).judge(comps)
163+
assert results[0] == {"winner": "A", "reason": "ok"}
164+
assert results[1] == {}
165+
assert results[2] == {"winner": "A", "reason": "ok"}
166+
167+
def test_concurrent_failure_yields_empty_dict(self):
168+
comps = [_make_comparison(i) for i in range(3)]
169+
results = _FlakyJudge(concurrency=2).judge(comps)
170+
assert results[0] == {"winner": "A", "reason": "ok"}
171+
assert results[1] == {}
172+
assert results[2] == {"winner": "A", "reason": "ok"}
173+
174+
137175
# ---------------------------------------------------------------------------
138176
# aggregate_jury_votes
139177
# ---------------------------------------------------------------------------

‎tests/test_cli.py‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
from openai import OpenAIError
99

1010
from ocr_bench import cli
11-
from ocr_bench.cli import _resolve_results_repo, build_parser
11+
from ocr_bench.cli import _convert_results, _resolve_results_repo, build_parser
12+
from ocr_bench.judge import Comparison
1213

1314

1415
class TestBuildParser:
@@ -157,3 +158,48 @@ def test_no_publish_returns_none(self):
157158
def test_no_publish_overrides_explicit(self):
158159
result = _resolve_results_repo("user/my-dataset", "user/custom", True)
159160
assert result is None
161+
162+
163+
def _make_comparison(idx: int = 0) -> Comparison:
164+
return Comparison(
165+
sample_idx=idx,
166+
model_a="model-a",
167+
model_b="model-b",
168+
col_a="col_a",
169+
col_b="col_b",
170+
swapped=False,
171+
messages=[{"role": "user", "content": "test"}],
172+
)
173+
174+
175+
class TestConvertResults:
176+
def test_valid_result_kept(self):
177+
results = _convert_results(
178+
[_make_comparison()],
179+
[{"winner": "A", "reason": "better", "agreement": "3/3"}],
180+
)
181+
assert len(results) == 1
182+
assert results[0].winner == "A"
183+
assert results[0].agreement == "3/3"
184+
185+
def test_empty_result_skipped(self):
186+
results = _convert_results([_make_comparison()], [{}])
187+
assert results == []
188+
189+
def test_all_judges_failed_tie_skipped(self):
190+
"""A 0/0 'tie' means every judge in the jury failed — it must not
191+
enter the ELO computation as a real verdict."""
192+
failed = {"winner": "tie", "reason": "no valid votes", "agreement": "0/0"}
193+
results = _convert_results([_make_comparison()], [failed])
194+
assert results == []
195+
196+
def test_mixed_results_keep_only_valid(self):
197+
comps = [_make_comparison(i) for i in range(3)]
198+
aggregated = [
199+
{"winner": "A", "reason": "ok", "agreement": "2/3"},
200+
{},
201+
{"winner": "tie", "reason": "no valid votes", "agreement": "0/0"},
202+
]
203+
results = _convert_results(comps, aggregated)
204+
assert len(results) == 1
205+
assert results[0].sample_idx == 0

‎tests/test_judge.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,25 @@ def test_missing_reason(self):
126126
assert result["winner"] == "A"
127127
assert result["reason"] == ""
128128

129+
def test_null_winner_returns_empty(self):
130+
"""Valid JSON with a non-string winner is a failure, not a crash."""
131+
result = parse_judge_output('{"winner": null, "reason": "unsure"}')
132+
assert result == {}
133+
134+
def test_list_winner_returns_empty(self):
135+
result = parse_judge_output('{"winner": ["A"], "reason": "odd"}')
136+
assert result == {}
137+
138+
def test_non_object_json_returns_empty(self):
139+
assert parse_judge_output('"A"') == {}
140+
assert parse_judge_output("[1, 2, 3]") == {}
141+
assert parse_judge_output("42") == {}
142+
143+
def test_non_string_reason_coerced(self):
144+
result = parse_judge_output('{"winner": "A", "reason": {"note": "x"}}')
145+
assert result["winner"] == "A"
146+
assert isinstance(result["reason"], str)
147+
129148

130149
class TestComparison:
131150
def test_text_fields_default_empty(self):

0 commit comments

Comments
 (0)