Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(eval): retry judge requests and report an unreachable judge instead of scoring it as a tie (#1447) (#1484)
Srinivasan Ra07d6ba2f9a1
diff --git a/changelog.d/0.75.1/1484.fixed.md b/changelog.d/0.75.1/1484.fixed.mdnew file mode 100644index 00000000..444d29bc--- /dev/null+++ b/changelog.d/0.75.1/1484.fixed.md@@ -0,0 +1 @@+- **A judge that cannot be reached is reported as unavailable, not scored as a tie (#1447 by @Srinivasan8888 in #1484).** Every LLM-judge request now goes through one helper that retries 429, 5xx and transport errors within a bound (honouring `Retry-After`), fails at once on a 4xx that will not heal, treats a reply with no usable content as a judge error, and raises `JudgeUnavailableError` naming the judge URL once the retries are spent. `soup ship --task-mode pairwise` exits 1 with that message instead of scoring a dead judge as a measured 0.5 win-rate and printing DON'T SHIP; `soup eval judge` skips and counts the failing row and still scores, shows and saves the rest; a training eval gate still fails closed, and its log line says which task could not be scored and why instead of calling it a regression. The Online DPO adapter keeps leaving a failed pair unranked, as #1225 designed.diff --git a/docs/evaluation.md b/docs/evaluation.mdindex 8e49aec4..e16a06ff 100644--- a/docs/evaluation.md+++ b/docs/evaluation.md@@ -258,7 +258,7 @@ tasks:`judge_model` accepts `ollama://<model>`, `http://localhost:<port>/<model>` or `https://<host>/<model>`. An `https://` judge URL uses `OPENAI_API_KEY` only when its host is `api.openai.com`; other hosts are called as an OpenAI-compatible server without that key.-Baselines may be a registry reference (`registry://<name-or-id>`), a file path, or omitted for the first run. A registry baseline uses the newest eval row for each benchmark — re-measuring a benchmark replaces its baseline score — and warns, per benchmark, when that row's scorer stamp is missing or from a different scorer revision. Any structured exception (`ValueError`, `FileNotFoundError`, `OSError`) during the gate is treated as a regression under `on_regression: stop`.+Baselines may be a registry reference (`registry://<name-or-id>`), a file path, or omitted for the first run. A registry baseline uses the newest eval row for each benchmark — re-measuring a benchmark replaces its baseline score — and warns, per benchmark, when that row's scorer stamp is missing or from a different scorer revision. A task whose evaluation raises (`ValueError`, `FileNotFoundError`, `OSError`, or a judge that stays unreachable) gets no score and fails the gate closed under `on_regression: stop`; the log line lists it as a task that could not be scored, with the error, rather than as a regression (#1447).## Sequential A/B Harness (`soup ab`)@@ -404,6 +404,10 @@ soup ship --base <m> --adapter ./out --task-eval tasks.jsonl \# base vs tuned per prompt (swap-debiased); base = 0.5 coin-flip, won <=> winrate > 0.5soup ship --base <m> --adapter ./out --task-eval tasks.jsonl \--task-mode pairwise --judge-model ollama://llama3.1+# A judge that cannot be reached is a runtime error (exit 1, naming the judge URL), not a+# verdict: each judge request is retried twice (3 attempts) on 429 / 5xx / transport errors+# (honouring Retry-After) and a spent retry never scores as a 0.5 tie (#1447). A judge+# that answers "tie" still scores 0.5.# Leg-2 via lm-eval benchmarks, base scores supplied by --baselinesoup ship --base <m> --tuned ./out --task-eval tasks.jsonl \@@ -694,6 +698,8 @@ soup eval custom --tasks eval_tasks.jsonl --model ./output# LLM-as-a-judge (score model outputs using GPT-4o, Ollama, etc.)soup eval judge --target responses.jsonl --model gpt-4o-mini --provider openaisoup eval judge --target responses.jsonl --model llama3.1 --provider ollama+# A row whose judge call keeps failing (429 after the retries, a timeout, a reply with no+# choices) is skipped and counted; the other rows are still scored, shown and saved (#1447).# Auto-eval after training (configure in soup.yaml)soup eval auto --config soup.yamldiff --git a/src/soup_cli/commands/eval.py b/src/soup_cli/commands/eval.pyindex 859f761f..e19cd8a8 100644--- a/src/soup_cli/commands/eval.py+++ b/src/soup_cli/commands/eval.py@@ -501,6 +501,7 @@ def judge("""Evaluate model outputs using LLM-as-a-judge."""from soup_cli.eval.judge import (JudgeEvaluator,+ JudgeUnavailableError,load_rubric,validate_judge_api_base,)@@ -593,10 +594,10 @@ def judge(category=item.get("category", "default"),)judge_scores.append(score)- except (ValueError, OSError, KeyError) as exc:+ except (ValueError, OSError, KeyError, JudgeUnavailableError) as exc:skipped_count += 1console.print(- f"[yellow]Warning: judge failed for prompt: {exc}[/]"+ f"[yellow]Warning: judge failed for prompt: {for_terminal(exc)}[/]")progress.advance(task_bar)diff --git a/src/soup_cli/eval/judge.py b/src/soup_cli/eval/judge.pyindex 0b709760..5d277185 100644--- a/src/soup_cli/eval/judge.py+++ b/src/soup_cli/eval/judge.py@@ -7,6 +7,7 @@ import loggingimport mathimport osimport re+import timefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import TYPE_CHECKING, Optional, Protocol@@ -17,6 +18,48 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)+# #1447: one bounded retry policy for every judge request.+JUDGE_MAX_RETRIES = 2+JUDGE_MAX_BACKOFF_SECONDS = 30.0+_sleep = time.sleep # patched by tests+++def _redact_url(url: str) -> str:+ """``url`` without userinfo, query or fragment, safe to print and log."""+ from urllib.parse import urlsplit, urlunsplit++ try:+ parts = urlsplit(str(url))+ host = parts.hostname or ""+ if ":" in host:+ host = f"[{host}]"+ netloc = host + (f":{parts.port}" if parts.port else "")+ return urlunsplit((parts.scheme, netloc, parts.path, "", ""))+ except ValueError:+ return "<unparseable judge url>"+++class JudgeUnavailableError(RuntimeError):+ """The judge could not be reached, kept failing, or answered in an unusable shape.++ ``url`` is the request URL with any userinfo, query or fragment removed: the+ message is printed per skipped row, stored in ``GateTaskResult.error`` and+ logged by the training callback, and ``validate_judge_api_base`` accepts+ ``https://user:pass@host`` and ``?api_key=`` bases.+ """++ def __init__(self, detail: str, *, url: str) -> None:+ self.detail = detail+ self.url = _redact_url(url)+ super().__init__(f"judge unavailable at {self.url}: {detail}")++ def __reduce__(self): # keyword-only ``url`` otherwise breaks pickle / copy+ return (_rebuild_unavailable, (self.detail, self.url))+++def _rebuild_unavailable(detail: str, url: str) -> "JudgeUnavailableError":+ return JudgeUnavailableError(detail, url=url)+class PairwiseJudge(Protocol):"""Anything that can compare two responses -> 0 (A) / 1 (B) / -1 (tie)."""@@ -370,21 +413,19 @@ class JudgeEvaluator:return resultsdef compare_pair(self, prompt: str, resp_a: str, resp_b: str) -> int:- """One pairwise A/B judgment -> 0 (A) / 1 (B) / -1 (tie / parse fail)."""+ """One pairwise A/B judgment -> 0 (A) / 1 (B) / -1 (tie / unparseable reply).++ A judge that cannot be reached raises :class:`JudgeUnavailableError`+ (#1447). A failed call is not a tie: scoring it as one turned a dead+ judge into a measured 0.5 win-rate and a DON'T SHIP verdict.+ """judge_prompt = _PAIRWISE_INSTRUCTIONS.format(prompt=prompt, resp_a=resp_a, resp_b=resp_b)- try:- reply = self._call_llm(judge_prompt)- except Exception as exc: # noqa: BLE001 — network/parse variety -> tie- logger.debug("pairwise judge call failed: %s", exc)- return -1- return _parse_pairwise(reply)+ return _parse_pairwise(self._call_llm(judge_prompt))def _call_llm(self, prompt: str) -> str:"""Call the judge LLM. Uses OpenAI-compatible API for all providers."""- import httpx-if self.provider == "ollama":base = self.api_base or "http://localhost:11434"url = f"{base}/v1/chat/completions"@@ -406,11 +447,74 @@ class JudgeEvaluator:"max_tokens": 1024,}- resp = httpx.post(url, json=payload, headers=headers, timeout=120.0)- resp.raise_for_status()+ return _judge_request(url, payload, headers)++def _retry_delay(retry_after: Optional[str], attempt: int) -> float:+ """Seconds to pause before retry ``attempt`` (0-based), capped.++ A numeric ``Retry-After`` wins; an HTTP-date one, or none, falls back to+ exponential backoff.+ """+ if retry_after:+ try:+ seconds = float(retry_after)+ except ValueError:+ seconds = math.nan+ if math.isfinite(seconds): # nan and inf would reach time.sleep+ return min(max(seconds, 0.0), JUDGE_MAX_BACKOFF_SECONDS)+ return min(float(2 ** attempt), JUDGE_MAX_BACKOFF_SECONDS)+++def _reply_content(resp, url: str) -> str:+ """The judge's text from an OpenAI-shaped reply, or ``JudgeUnavailableError``."""+ try:data = resp.json()- return data["choices"][0]["message"]["content"]+ except ValueError as exc:+ raise JudgeUnavailableError(f"reply is not JSON: {exc}", url=url) from exc+ choices = data.get("choices") if isinstance(data, dict) else None+ first = choices[0] if isinstance(choices, list) and choices else None+ message = first.get("message") if isinstance(first, dict) else None+ content = message.get("content") if isinstance(message, dict) else None+ if not isinstance(content, str):+ raise JudgeUnavailableError("reply has no choices[0].message.content", url=url)+ return content+++def _judge_request(url: str, payload: dict, headers: dict, *, timeout: float = 120.0) -> str:+ """POST one judge request; retry 429 / 5xx / transport errors within a bound (#1447).++ Every judge call goes through here, so every caller sees one failure shape:+ ``JudgeUnavailableError`` naming the URL, raised once the retries are spent,+ at once for a 4xx that will not heal or an undecodable reply, and for a 200+ with no usable content.+ """+ import httpx++ failure = ""+ for attempt in range(JUDGE_MAX_RETRIES + 1):+ retry_after: Optional[str] = None+ try:+ resp = httpx.post(url, json=payload, headers=headers, timeout=timeout)+ except httpx.TransportError as exc:+ failure = f"{type(exc).__name__}: {exc}"+ except httpx.RequestError as exc: # e.g. DecodingError: not transient, no retry+ raise JudgeUnavailableError(f"{type(exc).__name__}: {exc}", url=url) from exc+ else:+ if resp.status_code < 400:+ return _reply_content(resp, url)+ failure = f"HTTP {resp.status_code}"+ if resp.status_code != 429 and resp.status_code < 500:+ raise JudgeUnavailableError(failure, url=url)+ retry_after = resp.headers.get("Retry-After")+ if attempt < JUDGE_MAX_RETRIES:+ delay = _retry_delay(retry_after, attempt)+ logger.debug(+ "judge request failed (%s); retry %d/%d in %.1fs",+ failure, attempt + 1, JUDGE_MAX_RETRIES, delay,+ )+ _sleep(delay)+ raise JudgeUnavailableError(f"{failure} ({JUDGE_MAX_RETRIES + 1} attempts)", url=url)# ---------------------------------------------------------------------------@@ -465,8 +569,8 @@ def pairwise_compare(When ``swap`` is True the pair is judged in BOTH orders (A,B and B,A) and awinner is returned ONLY if the two runs produce the same definite verdict —the standard defence against a judge's positional bias. Anything else — a- tie, a failure (``compare_pair`` returns -1 for both), or a disagreement —- yields -1, so a single un-cross-checked verdict is never trusted. This+ tie or a disagreement — yields -1, so a single un-cross-checked verdict is+ never trusted; a judge that cannot be reached raises instead (#1447). Thisdoubles the judge calls per pair vs a one-shot random-flip; the strongerguarantee is intentional."""@@ -607,6 +711,12 @@ def make_soup_pairwise_judge(evaluator: "PairwiseJudge") -> "BasePairwiseJudge":(:func:`soup_cli.trainer.online_dpo_ranking.make_ranked_pairs_trainer`)leaves those pairs out of the loss; any other caller must handle ``-1``itself.++ This is the one caller that keeps mapping a failed judge call to ``-1``+ (#1447): the ranking trainer leaves ``-1`` pairs out of the loss, logs+ ``judge/invalid_rate`` and stops the run with an error naming the judge once+ it has ranked nothing for too long (#1225), so a judge that is down ends the+ run through that accounting, not a traceback."""base_cls = _base_pairwise_judge_cls()@@ -625,12 +735,15 @@ def make_soup_pairwise_judge(evaluator: "PairwiseJudge") -> "BasePairwiseJudge":if not isinstance(pair, (list, tuple)) or len(pair) != 2:out.append(-1)continue- out.append(- pairwise_compare(+ try:+ rank = pairwise_compare(prompt, pair[0], pair[1], self.evaluator,swap=shuffle_order,)- )+ except Exception as exc: # noqa: BLE001 — unranked; #1225 stops the run+ logger.warning("online DPO judge call failed, pair left unranked: %s", exc)+ rank = -1+ out.append(rank)return outreturn _SoupPairwiseJudge(evaluator)diff --git a/src/soup_cli/monitoring/callback.py b/src/soup_cli/monitoring/callback.pyindex a63793e7..c4b57a3f 100644--- a/src/soup_cli/monitoring/callback.py+++ b/src/soup_cli/monitoring/callback.py@@ -78,6 +78,27 @@ def _get_trainer_callback_base():return object+def _gate_failure_summary(result) -> str:+ """Name what failed the gate: regressions, and tasks that could not be scored.++ A task with ``error`` set never ran to a score (a judge that was down, a+ missing prompts file); it fails the gate closed, but it is not a regression+ and the log must not call it one (#1447).+ """+ failed = [r for r in result.task_results if not r.passed]+ unscored = [r for r in failed if r.error]+ regressed = len(failed) - len(unscored)+ parts = []+ if regressed or not unscored:+ parts.append(f"{regressed} task(s) regressed")+ if unscored:+ parts.append(+ f"{len(unscored)} task(s) could not be scored: "+ + "; ".join(f"{r.name}: {r.error}" for r in unscored)+ )+ return ", ".join(parts)++class _SoupTrainerCallback_body: # noqa: N801"""Bridges HF Trainer events to Soup's Rich live display and experiment tracker."""@@ -533,13 +554,13 @@ class _SoupTrainerCallback_body: # noqa: N801if on_reg == "stop":control.should_training_stop = Truelogger.warning(- "eval gate FAILED (%d task(s) regressed); stopping training",- sum(1 for r in result.task_results if not r.passed),+ "eval gate FAILED (%s); stopping training",+ _gate_failure_summary(result),)elif on_reg == "warn":logger.warning(- "eval gate FAILED (%d task(s) regressed); continuing per policy",- sum(1 for r in result.task_results if not r.passed),+ "eval gate FAILED (%s); continuing per policy",+ _gate_failure_summary(result),)# on_reg == "continue": silent per user policydiff --git a/tests/test_issue1447_judge_unavailable.py b/tests/test_issue1447_judge_unavailable.pynew file mode 100644index 00000000..e01a33f1--- /dev/null+++ b/tests/test_issue1447_judge_unavailable.py@@ -0,0 +1,500 @@+"""Regression tests for #1447: a judge that fails is unavailable, not a tie.++Before the fix the pairwise path scored every judge exception as a 0.5 tie, so+``soup ship --task-mode pairwise`` printed a measured DON'T SHIP with the judge+down; ``soup eval judge`` aborted on the first transport error and lost the+scores already collected; nothing was ever retried; and a training eval gate+called an unreachable judge a regression.++``httpx.post`` is patched throughout, so no judge server is needed, and the+retry pause is captured instead of slept.+"""++from __future__ import annotations++import json+import logging+import math+import pickle+from pathlib import Path+from unittest import mock+from unittest.mock import MagicMock++import httpx+import pytest+from typer.testing import CliRunner++from soup_cli.eval import judge as judge_mod+from soup_cli.eval.judge import JudgeEvaluator, JudgeUnavailableError, pairwise_winrate+from tests.conftest import strip_ansi++JUDGE_BASE = "http://localhost:8000"+REQ = httpx.Request("POST", f"{JUDGE_BASE}/v1/chat/completions")+SCORED = {+ "choices": [+ {+ "message": {+ "content": json.dumps(+ {+ "scores": {"helpfulness": 4, "accuracy": 4, "safety": 4},+ "reasoning": "ok",+ }+ )+ }+ }+ ]+}+++def _reply(status: int, body: object, headers: dict | None = None) -> httpx.Response:+ return httpx.Response(status, json=body, headers=headers, request=REQ)+++def _content(text: str) -> httpx.Response:+ return _reply(200, {"choices": [{"message": {"content": text}}]})+++def _refused(*args, **kwargs):+ raise httpx.ConnectError("connection refused", request=REQ)+++def _timed_out(*args, **kwargs):+ raise httpx.ReadTimeout("read timed out", request=REQ)+++def no_sleep(monkeypatch):+ """Capture the retry pauses instead of sleeping them."""+ delays: list[float] = []+ monkeypatch.setattr(judge_mod, "_sleep", delays.append)+ return delays+++def evaluator() -> JudgeEvaluator:+ return JudgeEvaluator(provider="server", model="judge", api_base=JUDGE_BASE)+++ATTEMPTS = judge_mod.JUDGE_MAX_RETRIES + 1+++# ---------------------------------------------------------------------------+# Pairwise: a failure is not a tie+# ---------------------------------------------------------------------------+++class TestPairwiseFailureIsNotATie:+ def test_dead_judge_raises_instead_of_scoring_half(self, evaluator, no_sleep):+ pairs = [("p", "base answer", "tuned answer")] * 5+ with mock.patch("httpx.post", side_effect=_refused) as post:+ with pytest.raises(JudgeUnavailableError) as excinfo:+ pairwise_winrate(pairs, evaluator)+ # The message names the judge, and the first pair aborts the run after+ # the bounded retries: no further pairs are attempted.+ assert JUDGE_BASE in str(excinfo.value)+ assert post.call_count == ATTEMPTS++ def test_judge_that_answers_tie_still_scores_half(self, evaluator):+ pairs = [("p", "base answer", "tuned answer")] * 3+ with mock.patch("httpx.post", return_value=_content("I cannot decide")):+ assert pairwise_winrate(pairs, evaluator) == 0.5++ def test_judge_that_picks_tuned_scores_one(self, evaluator):+ # Base is A and tuned is B in the first order; the swapped order must+ # agree, so the fake answers by position.+ def post(url, json, headers, timeout):+ body = json["messages"][0]["content"]+ winner = "B" if body.index("tuned answer") > body.index("base answer") else "A"+ return _content(f'{{"winner": "{winner}"}}')++ with mock.patch("httpx.post", side_effect=post):+ assert pairwise_winrate([("p", "base answer", "tuned answer")], evaluator) == 1.0++ def test_compare_pair_lets_the_error_propagate(self, evaluator, monkeypatch):+ def boom(prompt):+ raise JudgeUnavailableError("down", url=REQ.url)++ monkeypatch.setattr(evaluator, "_call_llm", boom)+ with pytest.raises(JudgeUnavailableError):+ evaluator.compare_pair("p", "x", "y")+++ def test_online_dpo_adapter_keeps_a_down_judge_unranked(self, evaluator, no_sleep):+ # #1225's contract: the ranking trainer counts -1 pairs and stops the run+ # itself with an error naming the judge, so this one adapter must not raise.+ from soup_cli.eval.judge import make_soup_pairwise_judge++ try:+ judge = make_soup_pairwise_judge(evaluator)+ except ImportError:+ pytest.skip("installed trl has no BasePairwiseJudge")+ with mock.patch("httpx.post", side_effect=_refused) as post:+ assert judge.judge(["p"], [["first", "second"]]) == [-1]+ # the first order spent its bounded retries; the swapped order was never asked+ assert post.call_count == ATTEMPTS+++# ---------------------------------------------------------------------------+# One request helper: bounded retry, Retry-After, reply-shape validation+# ---------------------------------------------------------------------------+++class TestRetry:+ def test_429_then_200_is_scored_after_one_retry(self, evaluator, no_sleep):+ replies = iter([_reply(429, {"error": "rate limited"}, {"Retry-After": "3"}),+ _reply(200, SCORED)])+ with mock.patch("httpx.post", side_effect=lambda *a, **k: next(replies)) as post:+ score = evaluator.evaluate("q", "a")+ assert score.weighted_score == 4.0+ assert post.call_count == 2+ assert no_sleep == [3.0]++ def test_transport_error_then_200_is_scored(self, evaluator, no_sleep):+ replies = iter([_timed_out, _reply(200, SCORED)])++ def post(*args, **kwargs):+ item = next(replies)+ return item(*args, **kwargs) if callable(item) else item++ with mock.patch("httpx.post", side_effect=post) as post_mock:+ assert evaluator.evaluate("q", "a").weighted_score == 4.0+ assert post_mock.call_count == 2+ assert len(no_sleep) == 1++ def test_persistent_503_is_bounded_and_raises(self, evaluator, no_sleep):+ with mock.patch("httpx.post", return_value=_reply(503, {"error": "down"})) as post:+ with pytest.raises(JudgeUnavailableError, match="503"):+ evaluator.evaluate("q", "a")+ assert post.call_count == ATTEMPTS+ assert len(no_sleep) == judge_mod.JUDGE_MAX_RETRIES++ def test_backoff_without_retry_after_grows_and_is_capped(self, evaluator, no_sleep):+ with mock.patch("httpx.post", return_value=_reply(429, {"error": "rate limited"})):+ with pytest.raises(JudgeUnavailableError):+ evaluator.evaluate("q", "a")+ assert no_sleep == sorted(no_sleep)+ assert all(0 < d <= judge_mod.JUDGE_MAX_BACKOFF_SECONDS for d in no_sleep)++ def test_retry_after_is_capped(self, evaluator, no_sleep):+ with mock.patch(+ "httpx.post", return_value=_reply(429, {}, {"Retry-After": "86400"})+ ):+ with pytest.raises(JudgeUnavailableError):+ evaluator.evaluate("q", "a")+ assert no_sleep == [judge_mod.JUDGE_MAX_BACKOFF_SECONDS] * judge_mod.JUDGE_MAX_RETRIES++ @pytest.mark.parametrize("status", [400, 401, 403, 404])+ def test_client_errors_are_not_retried(self, evaluator, no_sleep, status):+ with mock.patch("httpx.post", return_value=_reply(status, {"error": "no"})) as post:+ with pytest.raises(JudgeUnavailableError, match=str(status)):+ evaluator.evaluate("q", "a")+ assert post.call_count == 1+ assert no_sleep == []++ @pytest.mark.parametrize(+ "body",+ [+ {"choices": []},+ {"choices": [{"message": {}}]},+ {"choices": [{"message": {"content": None}}]},+ {"error": "no choices"},+ ["not", "a", "dict"],+ ],+ ids=["empty-choices", "no-content", "null-content", "no-choices-key", "not-a-dict"],+ )+ def test_malformed_200_reply_is_a_judge_error(self, evaluator, no_sleep, body):+ with mock.patch("httpx.post", return_value=_reply(200, body)) as post:+ with pytest.raises(JudgeUnavailableError):+ evaluator.evaluate("q", "a")+ assert post.call_count == 1++ def test_non_json_200_reply_is_a_judge_error(self, evaluator, no_sleep):+ reply = httpx.Response(200, text="<html>gateway</html>", request=REQ)+ with mock.patch("httpx.post", return_value=reply):+ with pytest.raises(JudgeUnavailableError):+ evaluator.evaluate("q", "a")++ def test_error_names_the_url_and_the_attempt_count(self, evaluator, no_sleep):+ with mock.patch("httpx.post", side_effect=_refused):+ with pytest.raises(JudgeUnavailableError) as excinfo:+ evaluator.evaluate("q", "a")+ message = str(excinfo.value)+ assert f"{JUDGE_BASE}/v1/chat/completions" in message+ assert f"{ATTEMPTS} attempt" in message+ assert "ConnectError" in message+ assert excinfo.value.url == f"{JUDGE_BASE}/v1/chat/completions"+++# ---------------------------------------------------------------------------+# Review round 1: hostile Retry-After, absolute bounds, undecodable replies,+# credentials in the judge URL, pickling+# ---------------------------------------------------------------------------++[email protected]("value", ["nan", "NaN", "-5", "-inf", "inf", "1e400", "abc", ""])+def test_hostile_retry_after_never_yields_a_bad_pause(evaluator, no_sleep, value):+ with mock.patch("httpx.post", return_value=_reply(429, {}, {"Retry-After": value})):+ with pytest.raises(JudgeUnavailableError):+ evaluator.evaluate("q", "a")+ assert no_sleep+ # time.sleep(nan) and time.sleep(-1) both raise ValueError+ assert all(+ math.isfinite(d) and 0 <= d <= judge_mod.JUDGE_MAX_BACKOFF_SECONDS for d in no_sleep+ )+++def test_the_bounds_are_absolute_not_derived_from_themselves():+ assert judge_mod.JUDGE_MAX_RETRIES <= 5+ assert judge_mod.JUDGE_MAX_BACKOFF_SECONDS <= 60+++def test_undecodable_reply_is_a_judge_error_not_a_raw_httpx_error(evaluator, no_sleep):+ def boom(*args, **kwargs):+ raise httpx.DecodingError("bad reply", request=REQ)++ with mock.patch("httpx.post", side_effect=boom) as post:+ with pytest.raises(JudgeUnavailableError, match="DecodingError"):+ evaluator.evaluate("q", "a")+ assert post.call_count == 1 # not transient: no retry+ assert no_sleep == []+++ "base, secret",+ [+ ("https://user:[email protected]", "hunter2"),+ ("https://judge.example.com/?api_key=SECRET123", "SECRET123"),+ ],+)+def test_error_text_carries_no_credentials(no_sleep, base, secret):+ evaluator = JudgeEvaluator(provider="server", model="judge", api_base=base)+ with mock.patch("httpx.post", side_effect=_refused) as post:+ with pytest.raises(JudgeUnavailableError) as excinfo:+ evaluator.evaluate("q", "a")+ assert secret not in str(excinfo.value)+ assert secret not in excinfo.value.url+ assert "judge.example.com" in str(excinfo.value)+ # the request itself still went to the real URL+ assert secret in post.call_args.args[0]+++def test_ipv6_judge_host_is_kept_readable():+ err = JudgeUnavailableError("down", url="http://[::1]:8000/v1/chat/completions")+ assert err.url == "http://[::1]:8000/v1/chat/completions"+++def test_unavailable_error_survives_pickle():+ err = JudgeUnavailableError("down", url="http://localhost:8000/v1/chat/completions")+ clone = pickle.loads(pickle.dumps(err))+ assert str(clone) == str(err) and clone.url == err.url+++# ---------------------------------------------------------------------------+# soup eval judge: a failing row is skipped and counted, the rest are saved+# ---------------------------------------------------------------------------+++def _write_rows(path: Path, n: int = 3) -> None:+ with path.open("w", encoding="utf-8") as fh:+ for i in range(n):+ fh.write(json.dumps({"prompt": f"q{i}", "response": f"a{i}"}) + "\n")+++def _failing_row(prompt_marker: str, failure):+ """A fake ``httpx.post`` that fails only for the row whose prompt has the marker."""++ def post(url, json, headers, timeout):+ if prompt_marker in json["messages"][0]["content"]:+ if callable(failure):+ return failure()+ return failure+ return _reply(200, SCORED)++ return post+++class TestEvalJudgeCli:+ @pytest.mark.parametrize(+ "failure",+ [+ _reply(429, {"error": "rate limited"}),+ _timed_out,+ _reply(200, {"choices": []}),+ ],+ ids=["429-after-retries", "read-timeout", "empty-choices"],+ )+ def test_one_failing_row_is_skipped_and_the_rest_scored(self, tmp_path, monkeypatch,+ no_sleep, failure):+ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ _write_rows(tmp_path / "t.jsonl")+ with mock.patch("httpx.post", side_effect=_failing_row("q1", failure)):+ result = CliRunner().invoke(+ app, ["eval", "judge", "--target", "t.jsonl", "--provider", "server"],+ )+ out = strip_ansi(result.output)+ assert result.exit_code == 0, (out, repr(result.exception))+ assert "1/3 items skipped" in out+ assert "Judge Evaluation Results" in out++ def test_failure_text_is_shown_literally_and_control_bytes_are_dropped(+ self, tmp_path, monkeypatch, no_sleep+ ):+ # The per-row warning interpolates the judge's error text; a hostile+ # transport message must neither be read as Rich markup nor reach the+ # terminal as a control sequence.+ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ _write_rows(tmp_path / "t.jsonl")++ def hostile():+ raise httpx.ConnectError("[red]boom[/] \x1b[2J gone", request=REQ)++ with mock.patch("httpx.post", side_effect=_failing_row("q1", hostile)):+ result = CliRunner().invoke(+ app, ["eval", "judge", "--target", "t.jsonl", "--provider", "server"],+ )+ out = strip_ansi(result.output)+ assert result.exit_code == 0, (out, repr(result.exception))+ assert "[red]boom[/]" in out+ assert "\x1b[2J" not in result.output++ def test_every_row_failing_exits_1_naming_the_judge(self, tmp_path, monkeypatch, no_sleep):+ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ _write_rows(tmp_path / "t.jsonl")+ with mock.patch("httpx.post", side_effect=_refused):+ result = CliRunner().invoke(+ app, ["eval", "judge", "--target", "t.jsonl", "--provider", "server"],+ )+ out = strip_ansi(result.output)+ assert result.exit_code == 1, (out, repr(result.exception))+ assert result.exception is None or isinstance(result.exception, SystemExit)+ assert JUDGE_BASE in out+ assert "All items failed" in out+++# ---------------------------------------------------------------------------+# soup ship --task-mode pairwise: exit 1 naming the judge, never DON'T SHIP+# ---------------------------------------------------------------------------+++class TestShipPairwiseCli:+ def test_dead_judge_is_a_runtime_error_not_a_verdict(self, tmp_path, monkeypatch, no_sleep):+ from soup_cli.commands import ship as ship_cmd++ monkeypatch.chdir(tmp_path)+ with (tmp_path / "tasks.jsonl").open("w", encoding="utf-8") as fh:+ for i in range(2):+ fh.write(json.dumps({"prompt": f"task {i}", "expected": "x"}) + "\n")+ monkeypatch.setattr(+ ship_cmd, "_resolve_generators",+ lambda *a, **k: (lambda p: "base answer", lambda p: "tuned answer"),+ )+ with mock.patch("httpx.post", side_effect=_refused):+ result = CliRunner().invoke(+ ship_cmd.app,+ ["--base", "m", "--tuned", "t", "--task-eval", "tasks.jsonl",+ "--task-mode", "pairwise", "--judge-model", f"{JUDGE_BASE}/judge-m"],+ )+ out = strip_ansi(result.output)+ assert result.exit_code == 1, (out, repr(result.exception))+ assert "DON'T SHIP" not in out+ assert JUDGE_BASE in out+ assert "JudgeUnavailableError" in out+++# ---------------------------------------------------------------------------+# Eval gate: still fails closed, and says the judge was unavailable+# ---------------------------------------------------------------------------+++class TestEvalGate:+ def test_run_gate_records_the_judge_as_unavailable(self, tmp_path, monkeypatch, no_sleep):+ from soup_cli.eval.gate import EvalSuite, GateTask, run_gate++ monkeypatch.chdir(tmp_path)+ (tmp_path / "prompts.jsonl").write_text(+ json.dumps({"prompt": "summarise"}) + "\n", encoding="utf-8"+ )+ suite = EvalSuite(+ suite="s",+ tasks=[GateTask(type="judge", name="quality", threshold=0.7,+ prompts="prompts.jsonl", judge_model=f"{JUDGE_BASE}/m")],+ )+ with mock.patch("httpx.post", side_effect=_refused):+ result = run_gate(suite, generate_fn=lambda prompt: "x")+ assert result.passed is False+ (task,) = result.task_results+ assert task.score is None+ assert task.passed is False+ assert "judge unavailable" in task.error.lower()+ assert JUDGE_BASE in task.error++ @pytest.mark.parametrize("policy", ["stop", "warn"])+ def test_callback_log_says_unavailable_not_regressed(self, caplog, policy):+ from soup_cli.eval.gate import EvalSuite, GateResult, GateTaskResult+ from soup_cli.monitoring.callback import SoupTrainerCallback++ cb = SoupTrainerCallback(+ display=MagicMock(), tracker=None, run_id="test_run",+ eval_gate_config=MagicMock(+ enabled=True, every_n_epochs=1, on_regression=policy,+ regression_threshold=0.05, suite="dummy.yaml", baseline=None,+ ),+ )+ cb._gate_suite = EvalSuite(suite="s", tasks=[])+ cb._gate_generate_fn = lambda prompt: "x"+ error = (+ f"judge unavailable at {JUDGE_BASE}/v1/chat/completions: "+ "ConnectError: connection refused (3 attempts)"+ )+ cb._gate_run_fn = lambda suite, generate_fn, baseline, regression_threshold: GateResult(+ passed=False, regression=False,+ task_results=[GateTaskResult(name="quality", score=None, threshold=0.7,+ baseline=None, delta=None, passed=False,+ error=error)],+ )+ control = MagicMock(should_training_stop=False)+ with caplog.at_level(logging.WARNING, logger="soup_cli.monitoring.callback"):+ cb.on_epoch_end(MagicMock(), MagicMock(epoch=1.0, global_step=100), control)+ assert control.should_training_stop is (policy == "stop")+ gate_lines = [+ r.getMessage() for r in caplog.records if "eval gate FAILED" in r.getMessage()+ ]+ assert len(gate_lines) == 1, caplog.text+ assert "regressed" not in gate_lines[0]+ assert "judge unavailable" in gate_lines[0]+ assert "quality" in gate_lines[0]++ def test_callback_log_still_counts_a_real_regression(self, caplog):+ from soup_cli.eval.gate import EvalSuite, GateResult, GateTaskResult+ from soup_cli.monitoring.callback import SoupTrainerCallback++ cb = SoupTrainerCallback(+ display=MagicMock(), tracker=None, run_id="test_run",+ eval_gate_config=MagicMock(+ enabled=True, every_n_epochs=1, on_regression="stop",+ regression_threshold=0.05, suite="dummy.yaml", baseline=None,+ ),+ )+ cb._gate_suite = EvalSuite(suite="s", tasks=[])+ cb._gate_generate_fn = lambda prompt: "x"+ cb._gate_run_fn = lambda suite, generate_fn, baseline, regression_threshold: GateResult(+ passed=False, regression=True,+ task_results=[GateTaskResult(name="math", score=0.5, threshold=0.8,+ baseline=0.9, delta=-0.4, passed=False)],+ )+ control = MagicMock(should_training_stop=False)+ with caplog.at_level(logging.WARNING, logger="soup_cli.monitoring.callback"):+ cb.on_epoch_end(MagicMock(), MagicMock(epoch=1.0, global_step=100), control)+ assert control.should_training_stop is True+ gate_lines = [+ r.getMessage() for r in caplog.records if "eval gate FAILED" in r.getMessage()+ ]+ assert gate_lines == [+ "eval gate FAILED (1 task(s) regressed); stopping training"+ ]diff --git a/tests/test_judge_key_scoping.py b/tests/test_judge_key_scoping.pyindex 08dd7f77..036fee69 100644--- a/tests/test_judge_key_scoping.py+++ b/tests/test_judge_key_scoping.py@@ -19,6 +19,7 @@ def _auth_header_for(url: str):provider, model, base = _parse_judge_url(url)evaluator = JudgeEvaluator(provider=provider, model=model, api_base=base)with mock.patch("httpx.post") as post:+ post.return_value.status_code = 200post.return_value.json.return_value = {"choices": [{"message": {"content": '{"winner": "A"}'}}]}diff --git a/tests/test_v07131.py b/tests/test_v07131.pyindex 2c247dff..bb2dfe1d 100644--- a/tests/test_v07131.py+++ b/tests/test_v07131.py@@ -171,16 +171,19 @@ class TestCompareePairMethod:monkeypatch.setattr(ev, "_call_llm", lambda prompt: '{"winner": "B"}')assert ev.compare_pair("p", "x", "y") == 1- def test_compare_pair_llm_failure_is_tie(self, monkeypatch):- from soup_cli.eval.judge import JudgeEvaluator+ def test_compare_pair_llm_failure_propagates(self, monkeypatch):+ # #1447: a failed judge call is not a tie. It used to return -1 here,+ # which scored a dead judge as a measured 0.5 win-rate downstream.+ from soup_cli.eval.judge import JudgeEvaluator, JudgeUnavailableErrorev = JudgeEvaluator(provider="ollama", model="m")def _boom(prompt):- raise RuntimeError("network down")+ raise JudgeUnavailableError("network down", url="http://localhost:11434")monkeypatch.setattr(ev, "_call_llm", _boom)- assert ev.compare_pair("p", "x", "y") == -1+ with pytest.raises(JudgeUnavailableError):+ ev.compare_pair("p", "x", "y")# ---------------------------------------------------------------------------