Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(eval): stop a judged run when the judge is down instead of backing off per row (#1522) (#1563)

Yang Baie6fd615e468d
diff --git a/changelog.d/0.75.1/1563.fixed.md b/changelog.d/0.75.1/1563.fixed.md
new file mode 100644
index 00000000..ce51549f
--- /dev/null
+++ b/changelog.d/0.75.1/1563.fixed.md
@@ -0,0 +1,14 @@
+- **A judge that is down no longer costs 3 s of backoff for every row (#1522
+ by @ybai08 in #1563).** Each judged row retried on its own, so `soup eval
+ judge` over 10,000 rows slept for more than 8 hours against a host that
+ never answered, and `soup data from-traces --judge` did the same and then
+ wrote an empty file with exit 0. An evaluator now counts the requests in a
+ row that spent their retries unanswered and raises `JudgeDownError`, a
+ `JudgeUnavailableError`, at the third. `soup eval judge` stops there, prints
+ one message naming the judge URL and how many items were not judged, shows
+ the scores from before the outage without saving them, and exits 1;
+ `from-traces --judge` exits 1 and writes nothing; `soup data best-of-n` and
+ `soup ship --task-mode pairwise` say how many prompts or pairs were left.
+ One reply resets the count, and a 4xx or an unusable reply counts as a
+ reply. A judge-ranked training run is unchanged: it keeps asking and resumes
+ on the first reply.
diff --git a/docs/evaluation.md b/docs/evaluation.md
index 43148700..740289d2 100644
--- a/docs/evaluation.md
+++ b/docs/evaluation.md
@@ -410,7 +410,7 @@ soup ship --base <m> --adapter ./out --task-eval tasks.jsonl \
# 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.
+# that answers "tie" still scores 0.5. The error says how many pairs were not judged (#1522).
# Leg-2 via lm-eval benchmarks, base scores supplied by --baseline
soup ship --base <m> --tuned ./out --task-eval tasks.jsonl \
@@ -703,6 +703,15 @@ soup eval judge --target responses.jsonl --model gpt-4o-mini --provider openai
soup 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).
+# A judge that is down stops the run: once 3 requests in a row have spent their retries
+# unanswered, `soup eval judge` prints one message naming the judge URL and how many items
+# were not judged, shows the scores from before the outage without saving them, and exits 1,
+# so a long run costs 9 s of backoff, not 3 s per row. One reply resets the count, and a 4xx
+# or an unusable reply counts as a reply. `soup data from-traces --judge` stops the same way
+# and writes no output; `soup data best-of-n` and `soup ship --task-mode pairwise`, which
+# already stopped at the first unanswered request, now say how many prompts or pairs were
+# left. A judge-ranked training run is unchanged: it keeps asking, and resumes on the first
+# reply (#1522).
# Auto-eval after training (configure in soup.yaml)
soup eval auto --config soup.yaml
diff --git a/src/soup_cli/commands/data.py b/src/soup_cli/commands/data.py
index fdd99bab..b7c58303 100644
--- a/src/soup_cli/commands/data.py
+++ b/src/soup_cli/commands/data.py
@@ -2172,7 +2172,7 @@ def from_traces_cmd(
if judge:
# v0.40.3 (#33 (a)) — LLM-judge confidence filter.
from soup_cli.data.traces.quality import judge_filter_pairs
- from soup_cli.eval.judge import VALID_PROVIDERS, JudgeEvaluator
+ from soup_cli.eval.judge import VALID_PROVIDERS, JudgeDownError, JudgeEvaluator
# Friendly early validation matches the existing CLI conventions —
# fall through to the constructor only after the obvious typo is caught.
@@ -2205,6 +2205,9 @@ def from_traces_cmd(
filtered, report = judge_filter_pairs(
pairs, judge=judge_evaluator, min_confidence=min_confidence,
)
+ except JudgeDownError as exc:
+ console.print(f"[red]--judge stopped:[/] {for_terminal(exc)}")
+ raise typer.Exit(1) from exc
except (TypeError, ValueError) as exc:
console.print(f"[red]--judge runtime error:[/] {_escape(str(exc))}")
raise typer.Exit(1) from exc
@@ -3995,6 +3998,13 @@ def best_of_n(
checkpoint_path, index=index, sft=row, dpo=pair
)
except bon.BestOfNRuntimeError as exc:
+ from soup_cli.eval.judge import JudgeUnavailableError
+
+ if isinstance(exc.__cause__, JudgeUnavailableError):
+ lost = exc.__cause__.for_rows(
+ len(prompt_list) - index, len(prompt_list), "prompts"
+ )
+ console.print(f"[red]{for_terminal(lost)}[/]")
console.print(
f"[red]Best-of-N stopped after {index}/{len(prompt_list)} prompts.[/]\n"
f"Resume with [bold]--resume[/]; checkpoint: "
diff --git a/src/soup_cli/commands/eval.py b/src/soup_cli/commands/eval.py
index d05eed32..34879f78 100644
--- a/src/soup_cli/commands/eval.py
+++ b/src/soup_cli/commands/eval.py
@@ -500,6 +500,7 @@ def judge(
):
"""Evaluate model outputs using LLM-as-a-judge."""
from soup_cli.eval.judge import (
+ JudgeDownError,
JudgeEvaluator,
JudgeUnavailableError,
load_rubric,
@@ -577,6 +578,7 @@ def judge(
judge_scores = []
skipped_count = 0
+ down = None
progress = Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
@@ -594,6 +596,10 @@ def judge(
category=item.get("category", "default"),
)
judge_scores.append(score)
+ except JudgeDownError as exc:
+ # #1522: it has stopped answering, so the rest would fail alike.
+ down = exc.for_rows(len(items) - len(judge_scores), len(items), "items")
+ break
except (ValueError, OSError, KeyError, JudgeUnavailableError) as exc:
skipped_count += 1
console.print(
@@ -601,6 +607,18 @@ def judge(
)
progress.advance(task_bar)
+ if down is not None:
+ console.print(f"[red]Judging stopped: {for_terminal(down)}[/]")
+ if judge_scores:
+ # Not saved to the tracker: a mean over the rows before the outage
+ # is not this benchmark's score.
+ results = JudgeResults(scores=judge_scores)
+ results.compute()
+ _display_judge_results(results)
+ else:
+ console.print("[red]All items failed. Check judge configuration.[/]")
+ raise typer.Exit(1)
+
if skipped_count > 0:
console.print(
f"[yellow]{skipped_count}/{len(items)} items skipped "
diff --git a/src/soup_cli/data/traces/quality.py b/src/soup_cli/data/traces/quality.py
index 3821258a..ebad2746 100644
--- a/src/soup_cli/data/traces/quality.py
+++ b/src/soup_cli/data/traces/quality.py
@@ -71,8 +71,12 @@ def judge_filter_pairs(
weighted score is normalised to ``[0, 1]`` against the rubric scale;
pairs with ``chosen_norm - rejected_norm >= min_confidence`` are kept.
Any per-pair exception from the judge backend (network error, parse
- failure) drops the pair and increments the report's ``errors`` field.
+ failure) drops the pair and increments the report's ``errors`` field,
+ except ``JudgeDownError``: a judge that has stopped answering ends the
+ filter, and the error says how many pairs were not judged (#1522).
"""
+ from soup_cli.eval.judge import JudgeDownError
+
threshold = _validate_threshold(min_confidence)
# Lazy materialise: peek at most _MAX_BATCH+1 to detect overflow without
@@ -96,6 +100,12 @@ def judge_filter_pairs(
rejected_score = float(
judge.evaluate(pair.prompt, pair.rejected).weighted_score
)
+ except JudgeDownError as exc:
+ # #1522: it has stopped answering, so every later pair would only
+ # add to ``errors``. Stop, and say how much was left.
+ raise exc.for_rows(
+ len(pair_list) - len(kept) - dropped, len(pair_list), "pairs"
+ ) from exc
except Exception as exc: # noqa: BLE001 — judge backends raise many shapes
# Mirror v0.33.0 #47 / v0.35.0 policy: log at DEBUG so production
# silent-degradation is inspectable, but do not crash the harvest.
diff --git a/src/soup_cli/eval/judge.py b/src/soup_cli/eval/judge.py
index 7306ec0c..8118ee4b 100644
--- a/src/soup_cli/eval/judge.py
+++ b/src/soup_cli/eval/judge.py
@@ -21,6 +21,10 @@ logger = logging.getLogger(__name__)
# #1447: one bounded retry policy for every judge request.
JUDGE_MAX_RETRIES = 2
JUDGE_MAX_BACKOFF_SECONDS = 30.0
+# #1522: this many requests in a row with their retries spent, and the judge is
+# down. The evaluator says so, and a caller working through rows stops there
+# instead of backing off again for every row.
+JUDGE_DOWN_AFTER = 3
_sleep = time.sleep # patched by tests
@@ -46,19 +50,45 @@ class JudgeUnavailableError(RuntimeError):
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.
+
+ ``retries_spent`` is True when the request was retried to the bound and never
+ answered usefully (a transport error, 429 or 5xx every time), which is what a
+ judge that is down looks like. A 4xx or an unusable reply is an answer.
"""
- def __init__(self, detail: str, *, url: str) -> None:
+ def __init__(self, detail: str, *, url: str, retries_spent: bool = False) -> None:
self.detail = detail
self.url = _redact_url(url)
+ self.retries_spent = retries_spent
super().__init__(f"judge unavailable at {self.url}: {detail}")
+ def for_rows(self, lost: int, total: int, unit: str = "rows") -> "JudgeUnavailableError":
+ """The same error, saying how much of the caller's work it ended."""
+ return type(self)(
+ f"{self.detail}; {lost} of {total} {unit} not judged",
+ url=self.url,
+ retries_spent=self.retries_spent,
+ )
+
def __reduce__(self): # keyword-only ``url`` otherwise breaks pickle / copy
- return (_rebuild_unavailable, (self.detail, self.url))
+ return (_rebuild_unavailable, (type(self), self.detail, self.url, self.retries_spent))
-def _rebuild_unavailable(detail: str, url: str) -> "JudgeUnavailableError":
- return JudgeUnavailableError(detail, url=url)
+class JudgeDownError(JudgeUnavailableError):
+ """``JUDGE_DOWN_AFTER`` requests in a row went unanswered: stop the run (#1522).
+
+ Raised by the request that completes the run of failures and by each
+ unanswered one after it. The evaluator keeps asking, so a caller that
+ skips a failed row and carries on must let this one through; a caller that
+ maps a failure to a score (the Online DPO adapters) resumes on the first
+ reply.
+ """
+
+
+def _rebuild_unavailable(
+ cls: type, detail: str, url: str, retries_spent: bool
+) -> "JudgeUnavailableError":
+ return cls(detail, url=url, retries_spent=retries_spent)
class PairwiseJudge(Protocol):
@@ -348,6 +378,9 @@ def _compute_weighted_score(scores: dict[str, float], rubric: dict) -> float:
class JudgeEvaluator:
"""Configurable LLM-as-a-judge evaluator."""
+ # #1522: requests in a row whose retries were spent.
+ _spent_in_a_row = 0
+
def __init__(
self,
rubric: Optional[dict] = None,
@@ -456,7 +489,23 @@ class JudgeEvaluator:
"max_tokens": 1024,
}
- return _judge_request(url, payload, headers)
+ try:
+ reply = _judge_request(url, payload, headers)
+ except JudgeUnavailableError as exc:
+ if not exc.retries_spent:
+ self._spent_in_a_row = 0 # a refusal or a bad reply is an answer
+ raise
+ self._spent_in_a_row += 1
+ if self._spent_in_a_row >= JUDGE_DOWN_AFTER:
+ raise JudgeDownError(
+ f"{self._spent_in_a_row} requests in a row failed, the last with "
+ f"{exc.detail}",
+ url=url,
+ retries_spent=True,
+ ) from exc
+ raise
+ self._spent_in_a_row = 0
+ return reply
def _retry_delay(retry_after: Optional[str], attempt: int) -> float:
@@ -523,7 +572,9 @@ def _judge_request(url: str, payload: dict, headers: dict, *, timeout: float = 1
failure, attempt + 1, JUDGE_MAX_RETRIES, delay,
)
_sleep(delay)
- raise JudgeUnavailableError(f"{failure} ({JUDGE_MAX_RETRIES + 1} attempts)", url=url)
+ raise JudgeUnavailableError(
+ f"{failure} ({JUDGE_MAX_RETRIES + 1} attempts)", url=url, retries_spent=True
+ )
# ---------------------------------------------------------------------------
@@ -611,8 +662,11 @@ def pairwise_winrate(
if not pairs:
return 0.5
total = 0.0
- for prompt, base_resp, tuned_resp in pairs:
- verdict = pairwise_compare(prompt, base_resp, tuned_resp, evaluator, swap=True)
+ for index, (prompt, base_resp, tuned_resp) in enumerate(pairs):
+ try:
+ verdict = pairwise_compare(prompt, base_resp, tuned_resp, evaluator, swap=True)
+ except JudgeUnavailableError as exc:
+ raise exc.for_rows(len(pairs) - index, len(pairs), "pairs") from exc
if verdict == 1:
total += 1.0
elif verdict == -1:
diff --git a/tests/test_issue1522_judge_down.py b/tests/test_issue1522_judge_down.py
new file mode 100644
index 00000000..a057ad41
--- /dev/null
+++ b/tests/test_issue1522_judge_down.py
@@ -0,0 +1,412 @@
+"""Regression tests for #1522: a judge that is down stops the run, not each row.
+
+#1484 made an unreachable judge raise ``JudgeUnavailableError`` after a bounded
+retry, but every row retried on its own: 3 s of backoff per row, for the whole
+dataset, against a host that never answered once. An evaluator now remembers
+that its last requests all went unanswered and stops asking.
+
+``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 pickle
+from pathlib import Path
+from unittest import mock
+
+import httpx
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.eval import judge as judge_mod
+from soup_cli.eval.judge import (
+ JUDGE_DOWN_AFTER,
+ JudgeDownError,
+ JudgeEvaluator,
+ JudgeUnavailableError,
+ make_judge_reward_func,
+ 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",
+ }
+ )
+ }
+ }
+ ]
+}
+ATTEMPTS = judge_mod.JUDGE_MAX_RETRIES + 1
+# What one unanswered request sleeps before it gives up: 1 s, then 2 s.
+ONE_REQUEST_BACKOFF = [float(2 ** attempt) for attempt in range(judge_mod.JUDGE_MAX_RETRIES)]
+
+
+def _reply(status: int, body: object) -> httpx.Response:
+ return httpx.Response(status, json=body, request=REQ)
+
+
+def _refused(*args, **kwargs):
+ raise httpx.ConnectError("connection refused", request=REQ)
+
+
+def _script(*steps):
+ """A fake ``httpx.post`` that plays ``steps`` in order, then refuses."""
+ remaining = list(steps)
+
+ def post(*args, **kwargs):
+ step = remaining.pop(0) if remaining else _refused
+ return step() if callable(step) else step
+
+ return post
+
+
+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)
+
+
+def _judge_rows(evaluator: JudgeEvaluator, rows: int) -> list[Exception]:
+ errors: list[Exception] = []
+ for index in range(rows):
+ try:
+ evaluator.evaluate(f"q{index}", "a")
+ except JudgeUnavailableError as exc:
+ errors.append(exc)
+ return errors
+
+
+# ---------------------------------------------------------------------------
+# The counter
+# ---------------------------------------------------------------------------
+
+
+class TestJudgeDownCounter:
+ def test_a_dead_judge_costs_the_first_rows_backoff_and_no_more(self, evaluator, no_sleep):
+ # The way every row-by-row caller uses it: a failed row is skipped, and
+ # the run stops at the first JudgeDownError.
+ skipped = 0
+ with mock.patch("httpx.post", side_effect=_refused) as post:
+ with pytest.raises(JudgeDownError):
+ for index in range(1000):
+ try:
+ evaluator.evaluate(f"q{index}", "a")
+ except JudgeDownError:
+ raise
+ except JudgeUnavailableError:
+ skipped += 1
+
+ assert skipped == JUDGE_DOWN_AFTER - 1
+ assert post.call_count == JUDGE_DOWN_AFTER * ATTEMPTS
+ assert no_sleep == ONE_REQUEST_BACKOFF * JUDGE_DOWN_AFTER
+
+ def test_the_error_names_the_redacted_url_and_the_run_of_failures(self, no_sleep):
+ evaluator = JudgeEvaluator(
+ provider="server", model="judge", api_base="https://user:[email protected]"
+ )
+ with mock.patch("httpx.post", side_effect=_refused):
+ errors = _judge_rows(evaluator, JUDGE_DOWN_AFTER)
+
+ down = errors[-1]
+ assert isinstance(down, JudgeDownError)
+ assert "https://judge.example.com/v1/chat/completions" in str(down)
+ assert "hunter2" not in str(down)
+ assert f"{JUDGE_DOWN_AFTER} requests in a row" in str(down)
+ assert "ConnectError" in str(down)
+
+ def test_one_reply_resets_the_count(self, evaluator, no_sleep):
+ unanswered = [_refused] * ATTEMPTS
+ steps = [*unanswered, *unanswered, _reply(200, SCORED), *unanswered, *unanswered]
+ with mock.patch("httpx.post", side_effect=_script(*steps)) as post:
+ errors = []
+ scored = 0
+ for index in range(5):
+ try:
+ evaluator.evaluate(f"q{index}", "a")
+ scored += 1
+ except JudgeUnavailableError as exc:
+ errors.append(exc)
+
+ assert scored == 1
+ assert len(errors) == 4
+ assert not any(isinstance(exc, JudgeDownError) for exc in errors)
+ assert post.call_count == len(steps)
+
+ @pytest.mark.parametrize(
+ "answer",
+ [_reply(400, {"error": "prompt too long"}), _reply(200, {"choices": []})],
+ ids=["4xx", "unusable-200"],
+ )
+ def test_a_judge_that_answers_badly_is_not_down(self, evaluator, no_sleep, answer):
+ with mock.patch("httpx.post", return_value=answer) as post:
+ errors = _judge_rows(evaluator, 10)
+
+ assert len(errors) == 10
+ assert not any(isinstance(exc, JudgeDownError) for exc in errors)
+ assert post.call_count == 10
+ assert no_sleep == []
+
+ def test_a_bad_answer_between_outages_resets_the_count(self, evaluator, no_sleep):
+ unanswered = [_refused] * ATTEMPTS
+ steps = [*unanswered, *unanswered, _reply(400, {"error": "no"}), *unanswered]
+ with mock.patch("httpx.post", side_effect=_script(*steps)):
+ errors = _judge_rows(evaluator, 4)
+
+ assert len(errors) == 4
+ assert not any(isinstance(exc, JudgeDownError) for exc in errors)
+
+ def test_pairwise_and_pointwise_calls_share_the_count(self, evaluator, no_sleep):
+ with mock.patch("httpx.post", side_effect=_refused):
+ for _ in range(JUDGE_DOWN_AFTER - 1):
+ with pytest.raises(JudgeUnavailableError) as excinfo:
+ evaluator.evaluate("q", "a")
+ assert not isinstance(excinfo.value, JudgeDownError)
+ with pytest.raises(JudgeDownError):
+ evaluator.compare_pair("q", "a", "b")
+
+ def test_each_evaluator_counts_its_own_judge(self, no_sleep):
+ dead = JudgeEvaluator(provider="server", model="judge", api_base=JUDGE_BASE)
+ other = JudgeEvaluator(provider="server", model="judge", api_base="http://localhost:9000")
+ with mock.patch("httpx.post", side_effect=_refused):
+ _judge_rows(dead, JUDGE_DOWN_AFTER)
+ with mock.patch("httpx.post", return_value=_reply(200, SCORED)):
+ assert other.evaluate("q", "a").weighted_score == 4.0
+
+ def test_a_judge_that_stays_down_is_still_asked(self, evaluator, no_sleep):
+ # No cooldown: a caller that carries on gets a real request each time,
+ # so the first reply after an outage is seen.
+ with mock.patch("httpx.post", side_effect=_refused) as post:
+ errors = _judge_rows(evaluator, JUDGE_DOWN_AFTER + 2)
+
+ assert post.call_count == (JUDGE_DOWN_AFTER + 2) * ATTEMPTS
+ assert all(isinstance(exc, JudgeDownError) for exc in errors[JUDGE_DOWN_AFTER - 1:])
+ assert f"{JUDGE_DOWN_AFTER + 2} requests in a row" in str(errors[-1])
+
+ def test_down_error_is_an_unavailable_error_and_survives_pickle(self):
+ err = JudgeDownError("3 requests in a row failed", url=f"{JUDGE_BASE}/v1/chat/completions")
+ told = err.for_rows(7, 10, "pairs")
+ assert isinstance(told, JudgeDownError) and isinstance(told, JudgeUnavailableError)
+ assert "7 of 10 pairs not judged" in str(told)
+ clone = pickle.loads(pickle.dumps(told))
+ assert type(clone) is JudgeDownError
+ assert str(clone) == str(told) and clone.url == told.url
+
+
+# ---------------------------------------------------------------------------
+# Online DPO: a failure is a score, so a short outage must not outlast itself
+# ---------------------------------------------------------------------------
+
+
+def test_a_short_outage_does_not_leave_a_judge_ranked_run_unranked(evaluator, no_sleep):
+ ok = _reply(200, SCORED)
+ # three requests in a row are refused, then the judge answers every request
+ steps = [*[_refused] * (JUDGE_DOWN_AFTER * ATTEMPTS), *[ok] * 20]
+ reward = make_judge_reward_func(evaluator)
+ with mock.patch("httpx.post", side_effect=_script(*steps)):
+ scores = reward(["q"] * 10, ["a"] * 10)
+ assert scores[:3] == [0.0, 0.0, 0.0]
+ assert scores[3:] == [4.0] * 7, scores
+
+
+# ---------------------------------------------------------------------------
+# soup eval judge
+# ---------------------------------------------------------------------------
+
+
+def _write_rows(path: Path, n: int) -> 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")
+
+
+class TestEvalJudgeCli:
+ def test_a_dead_judge_stops_the_run_with_one_message(self, tmp_path, monkeypatch, no_sleep):
+ from soup_cli.cli import app
+
+ monkeypatch.chdir(tmp_path)
+ _write_rows(tmp_path / "t.jsonl", 1000)
+ with mock.patch("httpx.post", side_effect=_refused) as post:
+ result = CliRunner().invoke(
+ app, ["eval", "judge", "--target", "t.jsonl", "--provider", "server"],
+ )
+ out = " ".join(strip_ansi(result.output).split())
+ assert result.exit_code == 1, (out, repr(result.exception))
+ assert result.exception is None or isinstance(result.exception, SystemExit)
+ assert post.call_count == JUDGE_DOWN_AFTER * ATTEMPTS
+ assert no_sleep == ONE_REQUEST_BACKOFF * JUDGE_DOWN_AFTER
+ assert JUDGE_BASE in out
+ assert "1000 of 1000 items not judged" in out
+ # The rows before the stop still warn; the 997 after it print nothing.
+ assert out.count("Warning: judge failed") == JUDGE_DOWN_AFTER - 1
+
+ def test_scores_from_before_the_outage_are_shown_and_the_run_still_fails(
+ self, tmp_path, monkeypatch, no_sleep
+ ):
+ from soup_cli.cli import app
+
+ monkeypatch.chdir(tmp_path)
+ _write_rows(tmp_path / "t.jsonl", 50)
+ steps = [_reply(200, SCORED)] * 5
+ with mock.patch("httpx.post", side_effect=_script(*steps)):
+ result = CliRunner().invoke(
+ app, ["eval", "judge", "--target", "t.jsonl", "--provider", "server"],
+ )
+ out = " ".join(strip_ansi(result.output).split())
+ assert result.exit_code == 1, (out, repr(result.exception))
+ assert "45 of 50 items not judged" in out
+ assert "Judge Evaluation Results" in out
+
+
+# ---------------------------------------------------------------------------
+# soup data from-traces --judge (the pair filter)
+# ---------------------------------------------------------------------------
+
+
+class TestPairFilter:
+ def _pairs(self, n: int):
+ from soup_cli.data.traces.pair_builder import PreferencePair
+
+ return [
+ PreferencePair(prompt=f"q{i}", chosen="good", rejected="bad", source="t")
+ for i in range(n)
+ ]
+
+ def test_a_dead_judge_stops_the_filter(self, evaluator, no_sleep):
+ from soup_cli.data.traces.quality import judge_filter_pairs
+
+ with mock.patch("httpx.post", side_effect=_refused) as post:
+ with pytest.raises(JudgeDownError) as excinfo:
+ judge_filter_pairs(self._pairs(1000), judge=evaluator)
+
+ assert post.call_count == JUDGE_DOWN_AFTER * ATTEMPTS
+ assert no_sleep == ONE_REQUEST_BACKOFF * JUDGE_DOWN_AFTER
+ assert JUDGE_BASE in str(excinfo.value)
+ assert "1000 of 1000 pairs not judged" in str(excinfo.value)
+
+ def test_one_failing_pair_is_still_only_counted(self, evaluator, no_sleep):
+ from soup_cli.data.traces.quality import judge_filter_pairs
+
+ steps = [*[_refused] * ATTEMPTS, *[_reply(200, SCORED)] * 4]
+ with mock.patch("httpx.post", side_effect=_script(*steps)):
+ kept, report = judge_filter_pairs(self._pairs(3), judge=evaluator)
+
+ assert report.errors == 1
+ assert report.kept + report.dropped == 2
+
+ def test_from_traces_exits_1_naming_the_judge(self, tmp_path, monkeypatch, no_sleep):
+ from soup_cli.cli import app
+
+ monkeypatch.chdir(tmp_path)
+ with (tmp_path / "traces.jsonl").open("w", encoding="utf-8") as fh:
+ for i in range(20):
+ for text, score in (("good", 1), ("bad", 0)):
+ fh.write(json.dumps({
+ "inputs": {"input": f"q{i}"},
+ "outputs": {"output": text},
+ "feedback": [{"key": "thumbs", "score": score}],
+ }) + "\n")
+ with mock.patch("httpx.post", side_effect=_refused) as post:
+ result = CliRunner().invoke(
+ app,
+ ["data", "from-traces", "--logs", "traces.jsonl", "--format", "langchain",
+ "--signal", "thumbs_up", "--output", "prefs.jsonl", "--judge",
+ "--judge-provider", "server", "--judge-api-base", JUDGE_BASE],
+ )
+ out = " ".join(strip_ansi(result.output).split())
+ assert result.exit_code == 1, (out, repr(result.exception))
+ assert result.exception is None or isinstance(result.exception, SystemExit)
+ assert post.call_count == JUDGE_DOWN_AFTER * ATTEMPTS
+ assert JUDGE_BASE in out
+ assert "20 of 20 pairs not judged" in out
+ assert not (tmp_path / "prefs.jsonl").exists()
+
+
+# ---------------------------------------------------------------------------
+# soup ship --task-mode pairwise, and best-of-n
+# ---------------------------------------------------------------------------
+
+
+class TestPairwiseWinrate:
+ def test_the_error_says_how_many_pairs_were_not_judged(self, evaluator, no_sleep):
+ pairs = [(f"p{i}", "base answer", "tuned answer") for i in range(8)]
+ # Three pairs judged (two calls each, tuned wins), then nothing answers.
+ steps = []
+ for _ in range(3):
+ steps += [
+ _reply(200, {"choices": [{"message": {"content": '{"winner": "B"}'}}]}),
+ _reply(200, {"choices": [{"message": {"content": '{"winner": "A"}'}}]}),
+ ]
+ with mock.patch("httpx.post", side_effect=_script(*steps)):
+ with pytest.raises(JudgeUnavailableError) as excinfo:
+ pairwise_winrate(pairs, evaluator)
+
+ assert JUDGE_BASE in str(excinfo.value)
+ assert "5 of 8 pairs not judged" in str(excinfo.value)
+
+ def test_ship_names_the_judge_and_the_pairs_lost(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(4):
+ 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 = " ".join(strip_ansi(result.output).split())
+ assert result.exit_code == 1, (out, repr(result.exception))
+ assert "DON'T SHIP" not in out
+ assert JUDGE_BASE in out
+ assert "4 of 4 pairs not judged" in out
+
+
+class TestBestOfNCli:
+ def test_the_stop_names_the_judge_and_the_prompts_lost(self, tmp_path, monkeypatch, no_sleep):
+ from soup_cli.commands.data import app
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "prompts.jsonl").write_text(
+ "".join(json.dumps({"prompt": f"prompt {i}"}) + "\n" for i in range(4)),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(
+ "soup_cli.utils.magpie.make_magpie_generate_fn",
+ lambda *a, **k: (lambda prompt: "a candidate"),
+ )
+ with mock.patch("httpx.post", side_effect=_refused):
+ result = CliRunner().invoke(
+ app,
+ ["best-of-n", "--provider", "ollama", "--model", "sampler",
+ "--prompts", "prompts.jsonl", "--n", "3", "--judge", "ollama://judge",
+ "--output", "sft.jsonl"],
+ )
+ out = " ".join(strip_ansi(result.output).split())
+ assert result.exit_code == 1, (out, repr(result.exception))
+ assert "http://localhost:11434/v1/chat/completions" in out
+ assert "4 of 4 prompts not judged" in out
+ assert "--resume" in out