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(expect): require judge for expect_chosen_preferred_over_rejected_by_judge (#1433) (#1505)

Nurkhan Esenbekd7f2b1993b4d
diff --git a/changelog.d/0.75.1/1505.fixed.md b/changelog.d/0.75.1/1505.fixed.md
new file mode 100644
index 00000000..70a2e673
--- /dev/null
+++ b/changelog.d/0.75.1/1505.fixed.md
@@ -0,0 +1,2 @@
+- **`soup expect` requires a judge for `expect_chosen_preferred_over_rejected_by_judge` instead of silently scoring 1.0 (#1433 by @kok-o in #1505).**
+ `expect_chosen_preferred_over_rejected_by_judge` gave every row 1.0 when `judge_fn` was `None`, so `soup expect` ran with no judge and passed every preference dataset at any threshold. The expectation now flags preference rows as violations when no judge is configured (exit 2). A judge can be supplied via `soup expect --judge <url>` or in suite YAML under `args: {judge: "ollama://llama3.1", threshold: 0.7}`. Callers that deliberately want to trust existing labels without running a judge can opt in with `args: {advisory: true}`.
diff --git a/docs/commands.md b/docs/commands.md
index 19d8f2b7..7cfa19d5 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -351,7 +351,7 @@ soup local-rl harvest --db <path> -o <pairs.jsonl> Harvest DPO pairs from thumb
soup local-rl train --db <path> --model <id> --once [--train-method dpo|kto|orpo] [--min-pairs N] [-o <dir>] Ad-hoc DPO/KTO/ORPO train from harvested thumbs — live (v0.71.13)
soup local-rl train --db <path> --model <id> [--scheduler-dir <dir>] [--hour H] [--minute M] [--train-method dpo|kto|orpo] [--min-pairs N] [-o <dir>] Render a systemd/launchd nightly-train scaffold (no --once) that runs `--once` with the same flags (v0.71.13)
soup build <manifest.yaml> [--dry-run] [--output-dir <dir>] dbt-for-SFT DAG: validate + plan + live materialise (v0.69.0; live v0.71.6)
-soup expect <data.jsonl> <suite.yaml> Expectations suite: PII / token-length / refusal / judge (v0.69.0)
+soup expect <data.jsonl> <suite.yaml> [--judge URL] Expectations suite: PII / token-length / refusal / judge (v0.69.0)
soup data gen-magpie --base <m> --provider ollama|vllm --target N --output <jsonl> [--base-url <url>] [--quality-filter] Magpie synthetic generator — live (v0.69.0; live v0.71.6)
soup data best-of-n (--base <m> | --provider ollama|vllm --model <m> [--base-url <url>]) --prompts <jsonl> --n 8 --judge <url> -o <sft.jsonl> [--emit-pairs <dpo.jsonl>] [--resume] [--checkpoint <journal.jsonl>] [--manifest <manifest.json>] Best-of-N rejection sampling with durable per-prompt recovery and manifest-last publication
soup data best-of-n (--base <m> [--revision <rev>] | --provider ollama|vllm --model <m>) --prompts <jsonl> --n 8 --export-candidates <jsonl> [--checkpoint <jsonl>] [--resume] Resumable sampling-only phase; no judge is constructed
diff --git a/docs/compliance.md b/docs/compliance.md
index 1b36430c..18b59c92 100644
--- a/docs/compliance.md
+++ b/docs/compliance.md
@@ -140,6 +140,11 @@ argument the expectation does not take (`max_token`), is refused when the suite
loads (exit 3), so a mistyped bound cannot silently run on the defaults. A
top-level key other than `expectations` (a `fail_fast:` or a `name:` label
beside it) is refused the same way, naming the key.
+`expect_chosen_preferred_over_rejected_by_judge` requires a judge model configured
+under `args: {judge: "ollama://llama3.1", threshold: 0.7}` or passed via CLI with
+`soup expect --judge <url>`. When both are set, `--judge` takes precedence over
+the suite's `args.judge`. Without a judge configured, the gate fails (or pass
+`args: {advisory: true}` to explicitly trust existing labels in advisory mode).
Scanned fields per format:
- ChatML / tool-calling / audio: every `messages[].content` (string or text parts), tool-call arguments (per message and top-level `tool_calls`), and `tools[].function.description`.
diff --git a/src/soup_cli/commands/expect.py b/src/soup_cli/commands/expect.py
index 45e29f82..b2d771a5 100644
--- a/src/soup_cli/commands/expect.py
+++ b/src/soup_cli/commands/expect.py
@@ -9,7 +9,7 @@ from __future__ import annotations
import json
import os
-from typing import List, Mapping
+from typing import List, Mapping, Optional
import typer
from rich.console import Console
@@ -17,7 +17,7 @@ from rich.markup import escape
from rich.panel import Panel
from rich.table import Table
-from soup_cli.utils.exit_codes import EXIT_GATE_FAILED, EXIT_USAGE_ERROR
+from soup_cli.utils.exit_codes import EXIT_GATE_FAILED, EXIT_RUNTIME_ERROR, EXIT_USAGE_ERROR
console = Console()
@@ -79,12 +79,22 @@ def _load_jsonl_rows(data_path: str) -> List[Mapping[str, object]]:
def expect_cmd(
data: str = typer.Argument(..., help="Path to JSONL dataset"),
suite: str = typer.Argument(..., help="Path to expectations suite YAML"),
+ judge: Optional[str] = typer.Option(
+ None,
+ "--judge",
+ help="Judge model URL (e.g. ollama://llama3.1, https://api.openai.com/gpt-4o-mini)",
+ ),
) -> None:
"""Run an expectations suite against a JSONL dataset.
- Exit 0 = suite passed. Exit 2 = gate failed. Exit 3 = usage/input error.
+ Exit 0 = suite passed. Exit 1 = judge unreachable.
+ Exit 2 = gate failed. Exit 3 = usage/input error.
"""
- from soup_cli.utils.expectations import load_suite_yaml, run_suite
+ from soup_cli.utils.expectations import (
+ build_pairwise_judge_fn,
+ load_suite_yaml,
+ run_suite,
+ )
try:
spec = load_suite_yaml(suite)
@@ -98,11 +108,34 @@ def expect_cmd(
console.print(f"[red]{escape(str(exc))}[/]")
raise typer.Exit(EXIT_USAGE_ERROR) from exc
+ cli_judge_fn = None
+ if judge is not None:
+ try:
+ cli_judge_fn = build_pairwise_judge_fn(judge)
+ except (ValueError, TypeError) as exc:
+ console.print(f"[red]{escape(str(exc))}[/]")
+ raise typer.Exit(EXIT_USAGE_ERROR) from exc
+ if not any(
+ e.name == "expect_chosen_preferred_over_rejected_by_judge"
+ for e in spec.expectations
+ ):
+ console.print(
+ "[yellow]note: --judge was specified, but the suite contains "
+ "no judge expectation[/]"
+ )
+
try:
- report = run_suite(rows, spec)
+ report = run_suite(rows, spec, judge_fn=cli_judge_fn)
except (TypeError, ValueError) as exc:
console.print(f"[red]{escape(str(exc))}[/]")
raise typer.Exit(EXIT_USAGE_ERROR) from exc
+ except Exception as exc:
+ from soup_cli.eval.judge import JudgeUnavailableError
+
+ if isinstance(exc, JudgeUnavailableError):
+ console.print(f"[red]{escape(str(exc))}[/]")
+ raise typer.Exit(EXIT_RUNTIME_ERROR) from exc
+ raise
table = Table(title=f"soup expect — {escape(data)}")
table.add_column("Expectation")
@@ -119,6 +152,11 @@ def expect_cmd(
)
console.print(table)
+ for result in report.results:
+ if result.passed and result.details:
+ for d in result.details:
+ console.print(f"[yellow]{escape(d)}[/]")
+
if not report.passed:
for result in report.results:
if not result.passed and result.details:
diff --git a/src/soup_cli/utils/expectations.py b/src/soup_cli/utils/expectations.py
index 312be9e3..b11cf9a3 100644
--- a/src/soup_cli/utils/expectations.py
+++ b/src/soup_cli/utils/expectations.py
@@ -36,7 +36,11 @@ _EXPECTATION_ARGS: dict[str, dict[str, Any]] = {
"expect_no_pii": {},
"expect_token_length_between": {"min_tokens": 1, "max_tokens": _MAX_TOKEN_BOUND},
"expect_no_refusal_pattern": {},
- "expect_chosen_preferred_over_rejected_by_judge": {"threshold": 0.7},
+ "expect_chosen_preferred_over_rejected_by_judge": {
+ "threshold": 0.7,
+ "judge": None,
+ "advisory": False,
+ },
}
_SUPPORTED_EXPECTATIONS = tuple(_EXPECTATION_ARGS)
SUPPORTED_EXPECTATIONS: frozenset = frozenset(_SUPPORTED_EXPECTATIONS)
@@ -46,6 +50,57 @@ _ENTRY_KEYS = ("name", "args")
JudgeFn = Callable[[Mapping[str, Any]], float]
+def _extract_row_text_for_judge(val: Any) -> str:
+ if isinstance(val, str):
+ return val
+ if isinstance(val, list):
+ parts = []
+ for item in val:
+ if isinstance(item, Mapping) and "content" in item:
+ parts.append(str(item["content"]))
+ elif isinstance(item, str):
+ parts.append(item)
+ return "\n".join(parts)
+ return str(val) if val is not None else ""
+
+
+def build_pairwise_judge_fn(judge: Any) -> JudgeFn:
+ """Build a JudgeFn from a judge URL string, PairwiseJudge instance, or callable."""
+ if callable(judge) and not hasattr(judge, "compare_pair"):
+ return judge
+ if isinstance(judge, str):
+ if not judge.strip():
+ raise ValueError("judge URL must be non-empty")
+ from soup_cli.eval.gate import _parse_judge_url
+ from soup_cli.eval.judge import JudgeEvaluator
+
+ provider, model, api_base = _parse_judge_url(judge)
+ evaluator = JudgeEvaluator(
+ provider=provider,
+ model=model,
+ api_base=api_base,
+ )
+ elif hasattr(judge, "compare_pair"):
+ evaluator = judge
+ else:
+ raise TypeError("judge must be a URL string, PairwiseJudge instance, or callable")
+
+ from soup_cli.eval.judge import pairwise_compare
+
+ def pairwise_judge_fn(row: Mapping[str, Any]) -> float:
+ prompt = _extract_row_text_for_judge(row.get("prompt"))
+ resp_a = _extract_row_text_for_judge(row.get("chosen"))
+ resp_b = _extract_row_text_for_judge(row.get("rejected"))
+ verdict = pairwise_compare(prompt, resp_a, resp_b, evaluator, swap=True)
+ if verdict == 0:
+ return 1.0
+ if verdict == 1:
+ return 0.0
+ return 0.5
+
+ return pairwise_judge_fn
+
+
@dataclass(frozen=True)
class ExpectationResult:
"""Outcome of one expectation."""
@@ -658,17 +713,21 @@ def expect_chosen_preferred_over_rejected_by_judge(
*,
judge_fn: Optional[JudgeFn] = None,
threshold: float = 0.7,
+ advisory: bool = False,
) -> ExpectationResult:
"""Fail when ``judge_fn(row) < threshold`` on a preference row.
Rows must carry both ``chosen`` and ``rejected``. ``judge_fn`` returns a
score in [0, 1]; 1.0 means the judge fully prefers chosen over rejected.
- When ``judge_fn`` is omitted the suite runs in *advisory* mode (every row
- gets the default score 1.0, i.e. trust the labelling); production callers
- should always supply a real judge.
+ When ``judge_fn`` is omitted and ``advisory=False``, every preference row
+ is flagged as a violation for missing judge configuration (#1433).
+ To explicitly trust existing labels without running a judge, set
+ ``advisory=True``.
"""
t = _check_threshold(threshold, field="threshold")
+ if not isinstance(advisory, bool):
+ raise TypeError("advisory must be bool")
if judge_fn is not None and not callable(judge_fn):
raise TypeError("judge_fn must be callable or None")
materialised = _check_rows(rows)
@@ -690,12 +749,26 @@ def expect_chosen_preferred_over_rejected_by_judge(
)
continue
if judge_fn is None:
- # No judge supplied — assume chosen wins (advisory pass).
- score: float = 1.0
+ if advisory:
+ score: float = 1.0
+ else:
+ num_violations += 1
+ if len(details) < _MAX_DETAILS_PER_RESULT:
+ details.append(
+ _truncate_detail(
+ f"rows[{index}]: no judge configured: set args.judge "
+ "(e.g. ollama://llama3.1) or pass --judge, or remove this expectation"
+ )
+ )
+ continue
else:
try:
raw = judge_fn(row)
- except Exception: # noqa: BLE001 — one bad row mustn't crash the suite
+ except Exception as exc: # noqa: BLE001 - one bad row mustn't crash the suite
+ from soup_cli.eval.judge import JudgeUnavailableError
+
+ if isinstance(exc, JudgeUnavailableError):
+ raise
num_violations += 1
if len(details) < _MAX_DETAILS_PER_RESULT:
details.append(
@@ -723,6 +796,8 @@ def expect_chosen_preferred_over_rejected_by_judge(
f"rows[{index}]: judge score {score:.3f} < {t:.3f}"
)
)
+ if judge_fn is None and advisory and not details:
+ details.append(f"advisory: no judge ran; {len(materialised)} rows not scored")
return ExpectationResult(
name="expect_chosen_preferred_over_rejected_by_judge",
passed=num_violations == 0,
@@ -776,6 +851,19 @@ def _validate_args(index: int, name: str, args: Mapping[str, Any]) -> None:
_check_token_bounds(merged["min_tokens"], merged["max_tokens"])
elif name == "expect_chosen_preferred_over_rejected_by_judge":
_check_threshold(merged["threshold"], field="threshold")
+ if merged.get("judge") is not None:
+ if not isinstance(merged["judge"], str):
+ raise TypeError(f"expectations[{index}]: judge must be a string")
+ if not merged["judge"].strip():
+ raise ValueError(f"expectations[{index}]: judge must be non-empty")
+ from soup_cli.eval.gate import _parse_judge_url
+
+ try:
+ _parse_judge_url(merged["judge"])
+ except ValueError as exc:
+ raise ValueError(f"expectations[{index}]: {exc}") from exc
+ if not isinstance(merged.get("advisory", False), bool):
+ raise TypeError(f"expectations[{index}]: advisory must be a boolean")
def parse_suite_spec(raw: Any) -> SuiteSpec:
@@ -879,10 +967,14 @@ def _dispatch_expectation(
if name == "expect_no_refusal_pattern":
return expect_no_refusal_pattern(rows)
if name == "expect_chosen_preferred_over_rejected_by_judge":
+ effective_judge = judge_fn
+ if effective_judge is None and args.get("judge"):
+ effective_judge = build_pairwise_judge_fn(args["judge"])
return expect_chosen_preferred_over_rejected_by_judge(
rows,
- judge_fn=judge_fn,
+ judge_fn=effective_judge,
threshold=args["threshold"],
+ advisory=args["advisory"],
)
raise ValueError(f"unhandled expectation: {name!r}") # pragma: no cover
@@ -914,6 +1006,7 @@ __all__ = [
"SUPPORTED_EXPECTATIONS",
"SuiteReport",
"SuiteSpec",
+ "build_pairwise_judge_fn",
"expect_chosen_preferred_over_rejected_by_judge",
"expect_no_pii",
"expect_no_refusal_pattern",
diff --git a/tests/test_issue1433_expect_judge.py b/tests/test_issue1433_expect_judge.py
new file mode 100644
index 00000000..93cd1716
--- /dev/null
+++ b/tests/test_issue1433_expect_judge.py
@@ -0,0 +1,392 @@
+"""Tests for Issue #1433: expect_chosen_preferred_over_rejected_by_judge requires a judge.
+
+Without a judge configured, the expectation must not silently pass every row with 1.0.
+Supports --judge on CLI, args: {judge: ...} in suite YAML, and explicit advisory: True opt-in.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from unittest import mock
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from soup_cli.utils.expectations import (
+ build_pairwise_judge_fn,
+ expect_chosen_preferred_over_rejected_by_judge,
+ parse_suite_yaml,
+)
+
+
+def _plain(text: str) -> str:
+ import re
+
+ cleaned = re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", "", text)
+ return " ".join(cleaned.split())
+
+
+def _write_prefs(tmp_path: Path, rows: list[dict]) -> Path:
+ p = tmp_path / "prefs.jsonl"
+ p.write_text("\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8")
+ return p
+
+
+def _write_suite(tmp_path: Path, content: str) -> Path:
+ p = tmp_path / "suite.yaml"
+ p.write_text(content, encoding="utf-8")
+ return p
+
+
+SAMPLE_ROWS = [
+ {"prompt": "What is 2+2?", "chosen": "banana", "rejected": "4"},
+ {"prompt": "Capital of France?", "chosen": "", "rejected": "Paris"},
+]
+
+CLEAN_ROWS = [
+ {"prompt": "What is 2+2?", "chosen": "4", "rejected": "banana"},
+ {"prompt": "Capital of France?", "chosen": "Paris", "rejected": "London"},
+]
+
+
+class TestExpectJudgeDirectFunction:
+ def test_missing_judge_fails_by_default(self) -> None:
+ result = expect_chosen_preferred_over_rejected_by_judge(SAMPLE_ROWS)
+ assert result.passed is False
+ assert result.num_rows_checked == 2
+ assert result.num_violations == 2
+ assert any("no judge configured" in d for d in result.details)
+
+ def test_advisory_mode_passes(self) -> None:
+ result = expect_chosen_preferred_over_rejected_by_judge(SAMPLE_ROWS, advisory=True)
+ assert result.passed is True
+ assert result.num_rows_checked == 2
+ assert result.num_violations == 0
+
+ def test_callable_judge_invoked(self) -> None:
+ calls = []
+
+ def counting_judge(row: dict) -> float:
+ calls.append(row["prompt"])
+ return 1.0
+
+ result = expect_chosen_preferred_over_rejected_by_judge(
+ CLEAN_ROWS, judge_fn=counting_judge, threshold=0.7
+ )
+ assert result.passed is True
+ assert len(calls) == 2
+ assert calls == ["What is 2+2?", "Capital of France?"]
+
+ def test_callable_judge_below_threshold_fails(self) -> None:
+ result = expect_chosen_preferred_over_rejected_by_judge(
+ CLEAN_ROWS, judge_fn=lambda r: 0.0, threshold=0.7
+ )
+ assert result.passed is False
+ assert result.num_violations == 2
+ assert any("< 0.700" in d for d in result.details)
+
+ def test_invalid_advisory_type_rejected(self) -> None:
+ with pytest.raises(TypeError, match="advisory must be bool"):
+ expect_chosen_preferred_over_rejected_by_judge(CLEAN_ROWS, advisory="yes") # type: ignore[arg-type]
+
+
+class TestExpectSuiteParse:
+ def test_suite_with_judge_arg_parses(self) -> None:
+ yaml_text = (
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args:\n"
+ " judge: ollama://llama3.1\n"
+ " threshold: 0.8\n"
+ )
+ spec = parse_suite_yaml(yaml_text)
+ assert spec.expectations[0].args["judge"] == "ollama://llama3.1"
+ assert spec.expectations[0].args["threshold"] == 0.8
+
+ def test_suite_with_invalid_judge_scheme_refused_at_parse(self) -> None:
+ yaml_text = (
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args:\n"
+ " judge: ftp://unsupported.host/model\n"
+ )
+ with pytest.raises(ValueError, match="unsupported scheme"):
+ parse_suite_yaml(yaml_text)
+
+ def test_suite_with_non_string_judge_refused_at_parse(self) -> None:
+ yaml_text = (
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args:\n"
+ " judge: 12345\n"
+ )
+ with pytest.raises(TypeError, match="judge must be a string"):
+ parse_suite_yaml(yaml_text)
+
+ def test_suite_with_empty_judge_refused_at_parse(self) -> None:
+ yaml_text = (
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args:\n"
+ " judge: ' '\n"
+ )
+ with pytest.raises(ValueError, match="judge must be non-empty"):
+ parse_suite_yaml(yaml_text)
+
+ def test_suite_with_advisory_opt_in_parses(self) -> None:
+ yaml_text = (
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args:\n"
+ " advisory: true\n"
+ )
+ spec = parse_suite_yaml(yaml_text)
+ assert spec.expectations[0].args["advisory"] is True
+
+
+class TestBuildPairwiseJudgeFn:
+ def test_callable_passes_through(self) -> None:
+ def stub_judge(row: dict) -> float:
+ return 0.8
+
+ built = build_pairwise_judge_fn(stub_judge)
+ assert built({"prompt": "p"}) == 0.8
+
+ def test_pairwise_judge_evaluator_dispatch(self) -> None:
+ calls = []
+
+ class StubEvaluator:
+ def compare_pair(self, prompt: str, resp_a: str, resp_b: str) -> int:
+ calls.append((prompt, resp_a, resp_b))
+ # When ans_a is resp_a, ans_a (position 0) wins.
+ # When ans_a is resp_b (swapped), ans_a (position 1) wins.
+ return 0 if resp_a == "ans_a" else 1
+
+ judge_fn = build_pairwise_judge_fn(StubEvaluator())
+ score = judge_fn({"prompt": "q", "chosen": "ans_a", "rejected": "ans_b"})
+ assert score == 1.0
+ assert len(calls) == 2 # swap=True checks both (A, B) and (B, A)
+
+ def test_pairwise_judge_loss(self) -> None:
+ class RejectWinsEvaluator:
+ def compare_pair(self, prompt: str, resp_a: str, resp_b: str) -> int:
+ # ans_b (rejected) always wins
+ return 0 if resp_a == "ans_b" else 1
+
+ judge_fn = build_pairwise_judge_fn(RejectWinsEvaluator())
+ score = judge_fn({"prompt": "q", "chosen": "ans_a", "rejected": "ans_b"})
+ assert score == 0.0
+
+ def test_invalid_type_rejected(self) -> None:
+ with pytest.raises(TypeError, match="judge must be a URL string"):
+ build_pairwise_judge_fn(12345)
+
+
+class TestCliExpectJudge:
+ def test_unconfigured_judge_exits_2_with_violation_details(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ data = _write_prefs(tmp_path, SAMPLE_ROWS)
+ suite = _write_suite(
+ tmp_path,
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args: {threshold: 1.0}\n",
+ )
+ result = CliRunner().invoke(app, ["expect", str(data), str(suite)])
+ out = _plain(result.output)
+ assert result.exit_code == 2
+ assert "FAIL" in out
+ assert "no judge configured" in out
+
+ def test_cli_advisory_mode_exits_0(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ data = _write_prefs(tmp_path, SAMPLE_ROWS)
+ suite = _write_suite(
+ tmp_path,
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args: {threshold: 1.0, advisory: true}\n",
+ )
+ result = CliRunner().invoke(app, ["expect", str(data), str(suite)])
+ out = _plain(result.output)
+ assert result.exit_code == 0
+ assert "PASS" in out
+
+ def test_cli_flag_judge_scores_and_exits_0_on_clean_data(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ data = _write_prefs(tmp_path, CLEAN_ROWS)
+ suite = _write_suite(
+ tmp_path,
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args: {threshold: 0.7}\n",
+ )
+ calls = []
+
+ class PerfectJudge:
+ def compare_pair(self, prompt: str, resp_a: str, resp_b: str) -> int:
+ calls.append((prompt, resp_a, resp_b))
+ return 0 if resp_a in ("4", "Paris") else 1
+
+ with mock.patch("soup_cli.utils.expectations.build_pairwise_judge_fn") as mock_build:
+ mock_build.return_value = build_pairwise_judge_fn(PerfectJudge())
+ result = CliRunner().invoke(
+ app, ["expect", str(data), str(suite), "--judge", "ollama://llama3.1"]
+ )
+ out = _plain(result.output)
+ assert result.exit_code == 0
+ assert "PASS" in out
+ assert len(calls) == 4 # 2 rows * 2 calls each for swap-debiasing
+
+ def test_cli_flag_judge_fails_when_judge_prefers_rejected(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ data = _write_prefs(tmp_path, SAMPLE_ROWS)
+ suite = _write_suite(
+ tmp_path,
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args: {threshold: 0.7}\n",
+ )
+
+ class HarshJudge:
+ def compare_pair(self, prompt: str, resp_a: str, resp_b: str) -> int:
+ return 1 if resp_a in ("banana", "") else 0
+
+ with mock.patch("soup_cli.utils.expectations.build_pairwise_judge_fn") as mock_build:
+ mock_build.return_value = build_pairwise_judge_fn(HarshJudge())
+ result = CliRunner().invoke(
+ app, ["expect", str(data), str(suite), "--judge", "ollama://llama3.1"]
+ )
+ out = _plain(result.output)
+ assert result.exit_code == 2
+ assert "FAIL" in out
+
+ def test_cli_invalid_judge_url_exits_3_before_running_suite(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ data = _write_prefs(tmp_path, SAMPLE_ROWS)
+ suite = _write_suite(
+ tmp_path,
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n",
+ )
+ result = CliRunner().invoke(
+ app, ["expect", str(data), str(suite), "--judge", "ftp://bad-url"]
+ )
+ assert result.exit_code == 3
+ assert "unsupported scheme" in _plain(result.output)
+
+ def test_suite_judge_arg_is_used_at_run_time(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ _write_prefs(tmp_path, CLEAN_ROWS)
+ _write_suite(
+ tmp_path,
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args: {judge: 'ollama://llama3.1', threshold: 0.7}\n",
+ )
+ calls = []
+
+ def fake_compare(self, prompt, resp_a, resp_b):
+ calls.append((self.provider, self.model))
+ return 0 if resp_a in ("4", "Paris") else 1
+
+ monkeypatch.setattr("soup_cli.eval.judge.JudgeEvaluator.compare_pair", fake_compare)
+ result = CliRunner().invoke(app, ["expect", "prefs.jsonl", "suite.yaml"])
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ assert calls == [("ollama", "llama3.1")] * 4 # 2 rows, both orders
+
+ def test_advisory_pass_says_no_judge_ran(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ _write_prefs(tmp_path, CLEAN_ROWS)
+ _write_suite(
+ tmp_path,
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args: {advisory: true}\n",
+ )
+ result = CliRunner().invoke(app, ["expect", "prefs.jsonl", "suite.yaml"])
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ assert "advisory" in " ".join(_plain(result.output).split()).lower()
+
+ @pytest.mark.parametrize("value", ["'false'", "'no'", "1"])
+ def test_non_bool_advisory_refused_at_load(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, value: str
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ _write_prefs(tmp_path, CLEAN_ROWS)
+ _write_suite(
+ tmp_path,
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ f" args: {{advisory: {value}}}\n",
+ )
+ result = CliRunner().invoke(app, ["expect", "prefs.jsonl", "suite.yaml"])
+ assert result.exit_code == 3, (result.output, repr(result.exception))
+ assert "advisory must be a boolean" in " ".join(_plain(result.output).split())
+
+ def test_cli_judge_takes_precedence_over_suite_judge(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ _write_prefs(tmp_path, CLEAN_ROWS)
+ _write_suite(
+ tmp_path,
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args: {judge: 'ollama://suite-model', threshold: 0.7}\n",
+ )
+ calls = []
+
+ def fake_compare(self, prompt, resp_a, resp_b):
+ calls.append((self.provider, self.model))
+ return 0 if resp_a in ("4", "Paris") else 1
+
+ monkeypatch.setattr("soup_cli.eval.judge.JudgeEvaluator.compare_pair", fake_compare)
+ result = CliRunner().invoke(
+ app,
+ ["expect", "prefs.jsonl", "suite.yaml", "--judge", "ollama://cli-model"],
+ )
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ assert calls == [("ollama", "cli-model")] * 4
+
+ def test_unreachable_judge_exits_1_without_evaluating_remaining_rows(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ _write_prefs(tmp_path, CLEAN_ROWS)
+ _write_suite(
+ tmp_path,
+ "expectations:\n"
+ " - name: expect_chosen_preferred_over_rejected_by_judge\n"
+ " args: {judge: 'ollama://llama3.1', threshold: 0.7}\n",
+ )
+ from soup_cli.eval.judge import JudgeUnavailableError
+
+ call_count = 0
+
+ def dead_judge(self, prompt, resp_a, resp_b):
+ nonlocal call_count
+ call_count += 1
+ raise JudgeUnavailableError("connection refused", url="http://localhost:11434")
+
+ monkeypatch.setattr("soup_cli.eval.judge.JudgeEvaluator.compare_pair", dead_judge)
+ result = CliRunner().invoke(app, ["expect", "prefs.jsonl", "suite.yaml"])
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ assert call_count == 1
+ assert "judge unavailable" in _plain(result.output).lower()
diff --git a/tests/test_v0690_part_b.py b/tests/test_v0690_part_b.py
index 1cbbe6e8..5e3a8793 100644
--- a/tests/test_v0690_part_b.py
+++ b/tests/test_v0690_part_b.py
@@ -455,10 +455,25 @@ class TestRunSuite:
}
)
rows = [{"prompt": "Q", "chosen": "good", "rejected": "bad"}]
- # No judge fn supplied = neutral pass (operator must inject for live).
+ # No judge fn supplied and advisory=False -> fails (#1433)
report = expectations.run_suite(rows, spec)
- # Default judge returns 1.0 (no judge → assume chosen wins).
- assert report.passed is True
+ assert report.passed is False
+ assert report.results[0].num_violations == 1
+ assert "no judge configured" in report.results[0].details[0]
+
+ # Explicit advisory=True passes without a judge
+ advisory_spec = expectations.parse_suite_spec(
+ {
+ "expectations": [
+ {
+ "name": "expect_chosen_preferred_over_rejected_by_judge",
+ "args": {"threshold": 0.5, "advisory": True},
+ }
+ ]
+ }
+ )
+ advisory_report = expectations.run_suite(rows, advisory_spec)
+ assert advisory_report.passed is True
def test_report_frozen(self) -> None:
spec = expectations.parse_suite_spec(