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(diagnose): report unmeasured probes as NOT_RUN instead of OK (#1489)

Bakdauletf562f79d4af4
diff --git a/changelog.d/0.75.1/1489.changed.md b/changelog.d/0.75.1/1489.changed.md
new file mode 100644
index 00000000..35d5f00a
--- /dev/null
+++ b/changelog.d/0.75.1/1489.changed.md
@@ -0,0 +1 @@
+- **`soup diagnose` no longer scores a probe that never ran as OK 1.00 (#1435 by @bakdauletbaktygaliyev in [#1489](https://github.com/MakazhanAlpamys/Soup/pull/1489)).** A live probe that was requested but produced no measurement, such as a `--dataset` with no usable rows or a probe that raised, now reports the new `NOT_RUN` verdict (grey in the badge and the table, ranked between MINOR and MAJOR) and keeps the exception text in its evidence. `soup diagnose` exits `3` when the overall verdict is `NOT_RUN`; pass `--allow-not-run` to keep exit `0` for runs that knowingly skip probes. MAJOR still exits `2`. `soup train --diagnose-gate` now also refuses a `NOT_RUN` report (exit `3`), and a bad `--tokenizer` is an input error (exit `3`) raised before any model loads. Probes that do not apply, and modes omitted from an `--evidence` file, stay a neutral OK.
diff --git a/docs/evaluation.md b/docs/evaluation.md
index 26e20c9d..8e49aec4 100644
--- a/docs/evaluation.md
+++ b/docs/evaluation.md
@@ -319,7 +319,7 @@ Default threshold 0.2 matches v0.43.0 KL-delta quant-check thresholds. Webhooks
## Diagnose (Post-Training Report Card)
-`soup diagnose` scores seven independent failure modes for a trained adapter and renders an OK / MINOR / MAJOR verdict per mode plus an overall headline — same taxonomy as Quant-Lobotomy. Useful for catching adapter regressions that a loss curve cannot distinguish from a healthy run.
+`soup diagnose` scores seven independent failure modes for a trained adapter and renders an OK / MINOR / MAJOR / NOT_RUN verdict per mode (see `NOT_RUN` below) plus an overall headline — same taxonomy as Quant-Lobotomy. Useful for catching adapter regressions that a loss curve cannot distinguish from a healthy run.
```bash
# Neutral report (no model load — runs as a sanity check)
@@ -340,6 +340,9 @@ soup diagnose my-run-id --evidence evidence.json --output diag.json
# Twitter-shareable SVG badge embeddable in a model card
soup diagnose my-run-id --badge diag.svg
+# Live run that knowingly skips probes: keep exit 0 instead of 3 on NOT_RUN
+soup diagnose my-run-id --base-model HuggingFaceTB/SmolLM2-135M --allow-not-run
+
# Attach the report to a Model Registry entry as a first-class artifact
soup diagnose my-run-id --output diag.json --attach-to-registry abc123
```
@@ -362,9 +365,11 @@ a built-in probe set; `format` only fires when the dataset's own targets look li
| `contamination` | Training data overlapping public benchmarks | 1 − contamination_rate |
| `citation` | RAFT model stopped citing the supporting `[doc-N]` (v0.71.10) | fraction of answers citing the golden doc |
-**Verdict pill colours:** OK (≥ 0.85) green / MINOR (≥ 0.60) amber / MAJOR (< 0.60) red. `soup diagnose` exits 2 when the overall verdict is MAJOR — wire into CI to fail the build on regression.
+**Verdict pill colours:** OK (≥ 0.85) green / MINOR (≥ 0.60) amber / MAJOR (< 0.60) red. `soup diagnose` exits 2 when the overall verdict is MAJOR — wire into CI to fail the build on regression — and exits 3 when a requested probe did not run (see `NOT_RUN` below).
+
+**`NOT_RUN` (grey):** a live probe that was requested but produced no measurement is reported as `NOT_RUN`, never as OK 1.00. That covers a `--dataset` with no usable prompt/answer rows and a probe that raised; the evidence column keeps the reason, including the exception text. `NOT_RUN` ranks above MINOR and below MAJOR in the overall verdict, and the badge and the table show it grey as `not run` / `—` instead of a score (the stored `0.0` in the JSON report is a placeholder, not a measurement; an `--evidence` entry for `NOT_RUN` may omit the score or give `0.0`). `soup diagnose` exits 3 when the overall verdict is `NOT_RUN`; pass `--allow-not-run` to keep exit 0 for runs that knowingly skip probes. MAJOR still exits 2. Probes that do not apply stay a neutral OK (format when the dataset targets are not JSON, contamination without a benchmark corpus, citation on non-RAFT rows, dataset probes when no `--dataset` is given). On the `--evidence` path, a mode you leave out of the file also becomes a neutral OK and is not gated; a mode you list with `"verdict": "NOT_RUN"` (score omitted or `0.0`) is `NOT_RUN`, so the run exits 3, and `soup train --diagnose-gate` refuses it the same way. A bad `--tokenizer` is an input error (exit 3) raised before any model loads. For `--dataset`, the live probes currently read rows with a prompt key (`prompt`, `instruction`, `input`, `question` or `query`) plus an answer key (`response`, `completion`, `output`, `answer`, `chosen` or `text`), or a `messages` list; other shapes (ShareGPT `conversations`, LLaVA, plaintext) make the dataset probes `NOT_RUN`. Memorization additionally needs a `text`, `content`, `prompt`, `instruction` or `messages` field, and is `NOT_RUN` when none of the first rows has one.
-**Post-training gate:** `soup train --diagnose-gate <evidence.json>` runs the same scorer after training finishes and refuses to mark the run successful when any mode comes back MAJOR. Composes with `--gate <eval-suite>` (v0.26) — the eval gate catches accuracy regressions vs a baseline; the diagnose gate catches behaviour regressions the eval suite is blind to.
+**Post-training gate:** `soup train --diagnose-gate <evidence.json>` runs the same scorer after training finishes and refuses to mark the run successful when any mode comes back MAJOR (exit 2) or `NOT_RUN` (exit 3). Composes with `--gate <eval-suite>` (v0.26) — the eval gate catches accuracy regressions vs a baseline; the diagnose gate catches behaviour regressions the eval suite is blind to.
## Ship Verdict (`soup ship`)
diff --git a/src/soup_cli/commands/diagnose.py b/src/soup_cli/commands/diagnose.py
index c5daeb31..c4c8181c 100644
--- a/src/soup_cli/commands/diagnose.py
+++ b/src/soup_cli/commands/diagnose.py
@@ -32,12 +32,18 @@ from rich.table import Table
from soup_cli import __version__
from soup_cli.utils.diagnose import FailureReport, compose_report
from soup_cli.utils.diagnose.badge import render_badge_svg
-from soup_cli.utils.diagnose.report import FAILURE_MODES, FailureScore, classify_score
+from soup_cli.utils.diagnose.report import (
+ FAILURE_MODES,
+ FailureScore,
+ classify_score,
+ evidence_default_score,
+)
from soup_cli.utils.diagnose.runner import (
build_report,
neutral_score,
write_report,
)
+from soup_cli.utils.exit_codes import EXIT_USAGE_ERROR
from soup_cli.utils.paths import enforce_under_cwd_and_no_symlink
console = Console()
@@ -48,9 +54,28 @@ _MAX_EVIDENCE_BYTES = 16 * 1024 * 1024
def _verdict_style(verdict: str) -> str:
- return {"OK": "green", "MINOR": "yellow", "MAJOR": "red"}.get(
- verdict, "white"
- )
+ return {
+ "OK": "green",
+ "MINOR": "yellow",
+ "MAJOR": "red",
+ "NOT_RUN": "bright_black",
+ }.get(verdict, "white")
+
+
+def _exit_for(report: FailureReport, allow_not_run: bool) -> None:
+ """Exit 2 on MAJOR; exit 3 when a requested probe did not run (#1435).
+
+ MAJOR wins: a known regression is reported as such even if another probe did
+ not run. ``--allow-not-run`` keeps exit 0 for runs that knowingly skip probes.
+ """
+ if report.overall == "MAJOR":
+ raise typer.Exit(code=2)
+ if report.overall == "NOT_RUN" and not allow_not_run:
+ console.print(
+ "[yellow]One or more requested probes did not run, so the verdict is "
+ "not a pass. Fix the input, or pass --allow-not-run to accept it.[/]"
+ )
+ raise typer.Exit(code=EXIT_USAGE_ERROR)
def _render_report(report: FailureReport) -> None:
@@ -65,7 +90,8 @@ def _render_report(report: FailureReport) -> None:
continue
table.add_row(
escape(mode),
- f"{score.score:.3f}",
+ # A NOT_RUN score is a stored 0.0 placeholder, not a measurement.
+ "\u2014" if score.verdict == "NOT_RUN" else f"{score.score:.3f}",
f"[{_verdict_style(score.verdict)}]{score.verdict}[/]",
escape(score.evidence),
)
@@ -116,7 +142,7 @@ def _scores_from_evidence(payload: dict) -> dict:
continue
if not isinstance(entry, dict):
raise typer.BadParameter(f"scores.{mode} must be an object")
- score = entry.get("score", 1.0)
+ score = entry.get("score", evidence_default_score(entry))
# Validate numeric before float() — a non-numeric score otherwise raised
# ValueError that exited 1 with zero output. BadParameter prints a clear
# message.
@@ -126,12 +152,15 @@ def _scores_from_evidence(payload: dict) -> dict:
)
evidence = entry.get("evidence", "supplied by --evidence")
verdict = entry.get("verdict") or classify_score(score)
- out[mode] = FailureScore(
- mode=mode,
- score=float(score),
- verdict=verdict,
- evidence=str(evidence),
- )
+ try:
+ out[mode] = FailureScore(
+ mode=mode,
+ score=float(score),
+ verdict=verdict,
+ evidence=str(evidence),
+ )
+ except (ValueError, TypeError) as exc:
+ raise typer.BadParameter(f"scores.{mode} is invalid: {exc}") from exc
return out
@@ -279,6 +308,14 @@ def diagnose(
"style the model was trained to emit. (v0.71.17 #254)"
),
),
+ allow_not_run: bool = typer.Option(
+ False,
+ "--allow-not-run",
+ help=(
+ "Exit 0 even when a requested probe did not run (verdict NOT_RUN). "
+ "Without it such a run exits 3."
+ ),
+ ),
shuffle_seed: Optional[int] = typer.Option(
None,
"--shuffle-seed",
@@ -312,8 +349,18 @@ def diagnose(
raise typer.Exit(code=2) from exc
if base_model is not None:
+ from soup_cli.utils.diagnose import _common
from soup_cli.utils.diagnose.live import run_live_diagnose
+ # Resolve --tokenizer before any model loads; a bad id is an input error.
+ tokenizer_arg: object = tokenizer
+ if tokenizer is not None:
+ try:
+ tokenizer_arg = _common.resolve_tokenizer(tokenizer)
+ except (TypeError, ValueError) as exc:
+ console.print(f"[red]Error:[/] {escape(str(exc))}")
+ raise typer.Exit(code=EXIT_USAGE_ERROR) from exc
+
try:
report = run_live_diagnose(
run_id=run_id,
@@ -321,7 +368,7 @@ def diagnose(
adapter=adapter or None,
dataset_path=dataset,
device=device,
- tokenizer=tokenizer,
+ tokenizer=tokenizer_arg,
soup_version=__version__,
citation_style=resolved_citation_style,
shuffle_seed=shuffle_seed,
@@ -333,8 +380,7 @@ def diagnose(
)
raise typer.Exit(code=1) from exc
_emit_report(report, output=output, badge=badge, attach_to_registry=attach_to_registry)
- if report.overall == "MAJOR":
- raise typer.Exit(code=2)
+ _exit_for(report, allow_not_run)
return
scores = {}
@@ -375,9 +421,7 @@ def diagnose(
extras=extras,
)
_emit_report(report, output=output, badge=badge, attach_to_registry=attach_to_registry)
-
- if report.overall == "MAJOR":
- raise typer.Exit(code=2)
+ _exit_for(report, allow_not_run)
# Compose a tiny helper so the CLI module is callable from tests.
diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.py
index 42947fe2..39530c99 100644
--- a/src/soup_cli/commands/train.py
+++ b/src/soup_cli/commands/train.py
@@ -575,7 +575,7 @@ def train(
help=(
"After training, run `soup diagnose` against the supplied evidence "
"JSON (or scratch evidence). Refuses to mark the run successful "
- "if any of the 6 v0.56.0 failure modes returns MAJOR."
+ "if any failure mode returns MAJOR (exit 2) or NOT_RUN (exit 3)."
),
),
annex_xi: str = typer.Option(
@@ -2112,8 +2112,8 @@ def _run_diagnose_gate(
"""Post-training failure-mode gate (v0.56.0).
Loads a JSON ``evidence`` file with optional per-mode scores and
- refuses to mark the run successful if any mode comes back MAJOR.
- Missing modes fall back to a neutral OK score so partial evidence
+ refuses to mark the run successful if any mode comes back MAJOR (exit 2)
+ or NOT_RUN (exit 3, #1435). Missing modes fall back to a neutral OK score so partial evidence
still produces a useful report card. The train command only calls
this helper on the chief worker (RANK==0 in a multi-node launch, else
LOCAL_RANK==0) so distributed runs execute the gate once per cluster,
@@ -2141,7 +2141,8 @@ def _run_diagnose_gate(
if not isinstance(raw_scores, dict):
raise ValueError("evidence.scores must be an object")
- from soup_cli.utils.diagnose.report import classify_score
+ from soup_cli.utils.diagnose.report import classify_score, evidence_default_score
+ from soup_cli.utils.exit_codes import EXIT_USAGE_ERROR
scores: dict = {}
for mode in FAILURE_MODES:
@@ -2150,7 +2151,9 @@ def _run_diagnose_gate(
continue
if not isinstance(entry, dict):
raise ValueError(f"scores.{mode} must be an object")
- score = entry.get("score", 1.0)
+ score = entry.get("score", evidence_default_score(entry))
+ if isinstance(score, bool) or not isinstance(score, (int, float)):
+ raise ValueError(f"scores.{mode}.score must be a number")
verdict = entry.get("verdict") or classify_score(score)
scores[mode] = FailureScore(
mode=mode,
@@ -2169,8 +2172,19 @@ def _run_diagnose_gate(
for mode in FAILURE_MODES:
sc = report.scores[mode]
if sc.verdict == "MAJOR":
- console.print(f" [red]MAJOR[/] {mode}: {sc.evidence}")
+ console.print(f" [red]MAJOR[/] {mode}: {markup_escape(sc.evidence)}")
raise typer.Exit(2)
+ if report.overall == "NOT_RUN":
+ # An unmeasured mode is not a pass (#1435); same exit as `soup diagnose`.
+ console.print(
+ "[yellow]--diagnose-gate: one or more modes did not run (NOT_RUN); "
+ "the run is not verified.[/]"
+ )
+ for mode in FAILURE_MODES:
+ sc = report.scores[mode]
+ if sc.verdict == "NOT_RUN":
+ console.print(f" [yellow]NOT_RUN[/] {mode}: {markup_escape(sc.evidence)}")
+ raise typer.Exit(EXIT_USAGE_ERROR)
console.print(
f"[green]--diagnose-gate: {report.overall}[/] across "
f"{len(FAILURE_MODES)} modes."
diff --git a/src/soup_cli/mcp_server/registry.py b/src/soup_cli/mcp_server/registry.py
index 0719980d..9f9bd402 100644
--- a/src/soup_cli/mcp_server/registry.py
+++ b/src/soup_cli/mcp_server/registry.py
@@ -514,7 +514,12 @@ def tool_profile(args: dict) -> dict:
def tool_diagnose_evidence(args: dict) -> dict:
"""`soup diagnose --evidence` — failure-mode report card from pre-computed scores."""
from soup_cli import __version__
- from soup_cli.utils.diagnose.report import FAILURE_MODES, FailureScore, classify_score
+ from soup_cli.utils.diagnose.report import (
+ FAILURE_MODES,
+ FailureScore,
+ classify_score,
+ evidence_default_score,
+ )
from soup_cli.utils.diagnose.runner import build_report
run_id = _require_str(args, "run_id")
@@ -532,7 +537,7 @@ def tool_diagnose_evidence(args: dict) -> dict:
continue
if not isinstance(entry, dict):
raise McpToolError(f"evidence.scores.{mode} must be an object")
- score = entry.get("score", 1.0)
+ score = entry.get("score", evidence_default_score(entry))
if isinstance(score, bool) or not isinstance(score, (int, float)):
raise McpToolError(f"evidence.scores.{mode}.score must be a number")
# classify_score rejects a score outside [0, 1] / non-finite, and
@@ -1063,7 +1068,9 @@ def _readonly_specs() -> list[ToolSpec]:
title="Diagnose (evidence)",
description=(
"Post-training failure-mode report card from a pre-computed "
- "evidence JSON (no model load)."
+ "evidence JSON (no model load). `overall` is OK / MINOR / MAJOR / "
+ "NOT_RUN; only OK or MINOR is a pass (NOT_RUN means a probe did "
+ "not run)."
),
input_schema={
"type": "object",
diff --git a/src/soup_cli/utils/diagnose/badge.py b/src/soup_cli/utils/diagnose/badge.py
index c92b39d2..733dca0d 100644
--- a/src/soup_cli/utils/diagnose/badge.py
+++ b/src/soup_cli/utils/diagnose/badge.py
@@ -15,6 +15,7 @@ _VERDICT_COLOUR = {
"OK": "#3fb950", # green
"MINOR": "#d29922", # amber
"MAJOR": "#f85149", # red
+ "NOT_RUN": "#8b949e", # grey: a probe that never ran is not a pass (#1435)
}
@@ -43,7 +44,13 @@ def render_badge_svg(report: FailureReport) -> str:
label = _safe(mode.replace("_", " "), max_len=14)
# Defence-in-depth — even the formatted float passes through
# `_safe` so a crafted FailureScore subclass cannot inject SVG.
- score_text = _safe(f"{score.score:.2f}" if score is not None else "—", max_len=8)
+ if score is None:
+ shown = "—"
+ elif score.verdict == "NOT_RUN":
+ shown = "not run" # the stored 0.00 is a placeholder, not a measurement
+ else:
+ shown = f"{score.score:.2f}"
+ score_text = _safe(shown, max_len=8)
cells.append(
f'<rect x="{x}" y="40" width="56" height="36" rx="6" fill="{colour}" />'
f'<text x="{x + 28}" y="60" font-size="11" fill="#ffffff" '
diff --git a/src/soup_cli/utils/diagnose/live.py b/src/soup_cli/utils/diagnose/live.py
index 9a564d0e..f55f715b 100644
--- a/src/soup_cli/utils/diagnose/live.py
+++ b/src/soup_cli/utils/diagnose/live.py
@@ -24,18 +24,19 @@ from collections.abc import Mapping, Sequence
from typing import TYPE_CHECKING, Dict, List, Optional
from soup_cli.utils.diagnose.report import FAILURE_MODES
-from soup_cli.utils.diagnose.runner import build_report, neutral_score
+from soup_cli.utils.diagnose.runner import build_report, neutral_score, not_run_score
from soup_cli.utils.live_eval import token_f1
from soup_cli.utils.paths import enforce_under_cwd_and_no_symlink
if TYPE_CHECKING:
- from soup_cli.utils.diagnose.report import FailureReport
+ from soup_cli.utils.diagnose.report import FailureReport, FailureScore
# Bounds — keep the live diagnose run small on a 4 GB box.
_MAX_DATASET_ROWS = 5000
_PROBE_PROMPTS = 12
_MODE_COLLAPSE_PROMPTS = 6
_MEMORIZATION_ROWS = 32
+_MAX_FAILURE_REASON = 200
# Tiny built-in refusal probe set. The bundled v0.65 behaviour fixtures ship
# REDACTED placeholders (deliberately can't elicit a refusal), so the diagnose
@@ -54,6 +55,15 @@ _REFUSAL_BENIGN = (
)
+def _probe_failed(mode: str, exc: BaseException) -> "FailureScore":
+ """NOT_RUN score for a probe that raised, keeping the (sanitised) error text.
+
+ A raised probe used to read OK 1.00 with the exception thrown away (#1435).
+ """
+ message = " ".join(str(exc).replace("\x00", "").split())[:_MAX_FAILURE_REASON]
+ return not_run_score(mode, f"probe failed: {type(exc).__name__}: {message}")
+
+
def _row_input(row: object) -> str:
if not isinstance(row, Mapping):
return ""
@@ -217,17 +227,27 @@ def run_live_diagnose(
* **contamination** — pure data overlap (no model; empty benchmark corpus
→ neutral when none is supplied).
- Any probe whose inputs are unavailable falls back to a neutral OK score
- with a reason, matching the v0.56.0 ``build_report`` policy.
+ A probe that was requested but produced no measurement (no usable dataset rows,
+ or it raised) reports ``NOT_RUN`` with the reason. Only a probe that does not
+ apply (no ``--dataset``, non-JSON format targets, no benchmark corpus) falls
+ back to a neutral OK score, matching the v0.56.0 ``build_report`` policy.
"""
if not isinstance(base, str) or not base.strip():
raise ValueError("base must be a non-empty string")
+ from soup_cli.utils.diagnose._common import extract_row_text
from soup_cli.utils.diagnose.forgetting import score_forgetting
from soup_cli.utils.diagnose.format import score_format
from soup_cli.utils.diagnose.memorization import score_memorization
from soup_cli.utils.diagnose.mode_collapse import score_mode_collapse
from soup_cli.utils.diagnose.refusal import score_refusal
+ # Resolve a --tokenizer id before any model loads: a typo used to cost a full
+ # run and then pass silently (#1435). Objects pass through unchanged.
+ if isinstance(tokenizer, str):
+ from soup_cli.utils.diagnose import _common
+
+ tokenizer = _common.resolve_tokenizer(tokenizer)
+
rows: List[Mapping[str, object]] = []
if dataset_path:
rows = _load_dataset_rows(dataset_path)
@@ -247,8 +267,8 @@ def run_live_diagnose(
base_gen,
adapter_gen,
)
- except (ValueError, TypeError):
- scores["refusal"] = neutral_score("refusal", "probe failed")
+ except (ValueError, TypeError) as exc:
+ scores["refusal"] = _probe_failed("refusal", exc)
# The dataset-driven probes need rows.
pairs = [
@@ -270,15 +290,15 @@ def run_live_diagnose(
{"heldout": base_acc / n},
{"heldout": adp_acc / n},
)
- except (ValueError, TypeError, ZeroDivisionError):
- scores["forgetting"] = neutral_score("forgetting", "probe failed")
+ except (ValueError, TypeError, ZeroDivisionError) as exc:
+ scores["forgetting"] = _probe_failed("forgetting", exc)
# --- format (only when the dataset targets look like JSON) ---
if _looks_like_json_dataset(rows):
try:
scores["format"] = score_format(prompts, adapter_gen, kind="json")
- except (ValueError, TypeError):
- scores["format"] = neutral_score("format", "probe failed")
+ except (ValueError, TypeError) as exc:
+ scores["format"] = _probe_failed("format", exc)
else:
scores["format"] = neutral_score(
"format", "dataset targets are not JSON"
@@ -289,16 +309,32 @@ def run_live_diagnose(
scores["mode_collapse"] = score_mode_collapse(
prompts[:_MODE_COLLAPSE_PROMPTS], adapter_multi, k=4
)
- except (ValueError, TypeError):
- scores["mode_collapse"] = neutral_score("mode_collapse", "probe failed")
+ except (ValueError, TypeError) as exc:
+ scores["mode_collapse"] = _probe_failed("mode_collapse", exc)
# --- memorization (training-prefix echo) ---
- try:
- scores["memorization"] = score_memorization(
- rows[:_MEMORIZATION_ROWS], adapter_gen, tokenizer=tokenizer
+ # score_memorization reads only text/content/prompt/instruction/messages, while
+ # the pair builder also accepts question/answer, query/response and
+ # input/output rows; for those it answers "nothing to check" with OK 1.00.
+ if not any(extract_row_text(row) for row in rows[:_MEMORIZATION_ROWS]):
+ scores["memorization"] = not_run_score(
+ "memorization",
+ "none of the first rows has a text, content, prompt, instruction "
+ "or messages field to split",
)
- except (ValueError, TypeError):
- scores["memorization"] = neutral_score("memorization", "probe failed")
+ else:
+ try:
+ scores["memorization"] = score_memorization(
+ rows[:_MEMORIZATION_ROWS], adapter_gen, tokenizer=tokenizer
+ )
+ except (ValueError, TypeError) as exc:
+ scores["memorization"] = _probe_failed("memorization", exc)
+ elif dataset_path:
+ # A dataset was supplied but nothing in it could be turned into a probe
+ # input: the dataset probes were requested and did not run (#1435).
+ reason = "no usable prompt/answer rows in --dataset"
+ for mode in ("forgetting", "format", "mode_collapse", "memorization"):
+ scores[mode] = not_run_score(mode, reason)
# --- contamination (no benchmark corpus supplied → neutral) ---
scores.setdefault(
@@ -318,8 +354,8 @@ def run_live_diagnose(
citation_style=citation_style,
shuffle_seed=shuffle_seed,
)
- except (ValueError, TypeError):
- scores["citation"] = neutral_score("citation", "probe failed")
+ except (ValueError, TypeError) as exc:
+ scores["citation"] = _probe_failed("citation", exc)
# Fill any still-missing modes (no dataset → forgetting/format/etc neutral).
for mode in FAILURE_MODES:
diff --git a/src/soup_cli/utils/diagnose/report.py b/src/soup_cli/utils/diagnose/report.py
index b28408ef..6ea085d4 100644
--- a/src/soup_cli/utils/diagnose/report.py
+++ b/src/soup_cli/utils/diagnose/report.py
@@ -23,7 +23,10 @@ FAILURE_MODES: Tuple[str, ...] = (
"citation",
)
-VERDICTS: Tuple[str, ...] = ("OK", "MINOR", "MAJOR")
+# ``NOT_RUN`` = a requested probe produced no measurement (#1435). It is not a
+# pass: it ranks above MINOR in ``overall_verdict`` so an unmeasured probe can
+# never read as OK.
+VERDICTS: Tuple[str, ...] = ("OK", "MINOR", "MAJOR", "NOT_RUN")
# Thresholds (lower bound for verdict). Score >= 0.85 → OK; >= 0.60 → MINOR.
_OK_THRESHOLD: float = 0.85
@@ -59,7 +62,11 @@ def classify_score(score: float) -> str:
@dataclass(frozen=True)
class FailureScore:
- """Per-mode score with an OK / MINOR / MAJOR verdict + evidence line."""
+ """Per-mode score with an OK / MINOR / MAJOR / NOT_RUN verdict + evidence line.
+
+ ``NOT_RUN`` carries ``score == 0.0`` (no measurement was made) and is exempt
+ from the score/verdict agreement check.
+ """
mode: str
score: float
@@ -75,7 +82,10 @@ class FailureScore:
expected = classify_score(self.score)
if not isinstance(self.verdict, str) or self.verdict not in VERDICTS:
raise ValueError(f"verdict must be one of {VERDICTS}, got {self.verdict!r}")
- if self.verdict != expected:
+ if self.verdict == "NOT_RUN":
+ if float(self.score) != 0.0:
+ raise ValueError("a NOT_RUN score must be 0.0 (no measurement was made)")
+ elif self.verdict != expected:
raise ValueError(
f"verdict {self.verdict!r} disagrees with score "
f"{self.score} (expected {expected!r})"
@@ -88,15 +98,26 @@ class FailureScore:
raise ValueError("evidence too long (max 4096 chars)")
+def evidence_default_score(entry: Mapping[str, object]) -> float:
+ """Score assumed when an evidence entry omits ``score``.
+
+ ``NOT_RUN`` entries carry no measurement, so they default to 0.0 (the only
+ score ``FailureScore`` accepts for them); everything else defaults to 1.0.
+ Shared by the CLI, ``train --diagnose-gate`` and the MCP evidence parsers.
+ """
+ return 0.0 if entry.get("verdict") == "NOT_RUN" else 1.0
+
+
def overall_verdict(scores: Mapping[str, FailureScore]) -> str:
"""Worst-case across all modes; empty → ``OK``.
- Used as the headline badge value. MAJOR wins, then MINOR, then OK.
+ Used as the headline badge value. MAJOR wins, then NOT_RUN (an unmeasured
+ probe is worse than a known MINOR), then MINOR, then OK.
"""
if not isinstance(scores, Mapping):
raise TypeError("scores must be Mapping[str, FailureScore]")
worst = "OK"
- rank = {"OK": 0, "MINOR": 1, "MAJOR": 2}
+ rank = {"OK": 0, "MINOR": 1, "NOT_RUN": 2, "MAJOR": 3}
for value in scores.values():
if not isinstance(value, FailureScore):
raise TypeError("every entry must be FailureScore")
diff --git a/src/soup_cli/utils/diagnose/runner.py b/src/soup_cli/utils/diagnose/runner.py
index a85911f4..c7bf72df 100644
--- a/src/soup_cli/utils/diagnose/runner.py
+++ b/src/soup_cli/utils/diagnose/runner.py
@@ -38,6 +38,21 @@ def neutral_score(mode: str, reason: str = "skipped") -> FailureScore:
)
+def not_run_score(mode: str, reason: str) -> FailureScore:
+ """Score for a probe that was requested but produced no measurement (#1435).
+
+ Unlike :func:`neutral_score` (by-design "not applicable", reads OK), this is
+ ``NOT_RUN``: it never passes a gate. ``reason`` should say why, including the
+ exception text when a probe raised.
+ """
+ return FailureScore(
+ mode=mode,
+ score=0.0,
+ verdict="NOT_RUN",
+ evidence=f"probe not run ({reason})",
+ )
+
+
def build_report(
*,
run_id: str,
diff --git a/tests/test_issue1435_diagnose_not_run.py b/tests/test_issue1435_diagnose_not_run.py
new file mode 100644
index 00000000..d26bedd1
--- /dev/null
+++ b/tests/test_issue1435_diagnose_not_run.py
@@ -0,0 +1,449 @@
+"""Tests for Issue #1435 (PR 1): a probe that never ran must not score OK 1.00.
+
+Covers the ``NOT_RUN`` verdict, its ranking, the live-path sites that used to fall
+back to ``neutral_score``, the exit code / ``--allow-not-run`` flag, the badge colour,
+and resolving ``--tokenizer`` before any model is loaded.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from unittest import mock
+
+import pytest
+from typer.testing import CliRunner
+
+import soup_cli.utils.diagnose.live as live
+from soup_cli.cli import app
+from soup_cli.utils.diagnose.report import (
+ VERDICTS,
+ FailureReport,
+ FailureScore,
+ overall_verdict,
+)
+from tests.conftest import strip_ansi
+
+DATASET_MODES = ("forgetting", "format", "mode_collapse", "memorization")
+
+RECOGNISED = [
+ {"prompt": f"Write story number {i}.", "completion": f"Once upon a time {i}."}
+ for i in range(12)
+]
+# No key any row builder reads, now or after the PR 2 converter rewrite.
+UNRECOGNISED = [{"foo": f"bar {i}"} for i in range(12)]
+
+
+def _gens(**overrides):
+ gens = {
+ "base_gen": lambda prompt: "ok",
+ "adapter_gen": lambda prompt: "ok",
+ "base_multi": lambda prompt, k: [f"base{i} x{i}y z{i}w" for i in range(k)],
+ "adapter_multi": lambda prompt, k: [f"adapter{i} p{i}q r{i}s" for i in range(k)],
+ }
+ gens.update(overrides)
+ return gens
+
+
+def _write_rows(tmp_path: Path, rows) -> None:
+ (tmp_path / "d.jsonl").write_text(
+ "\n".join(json.dumps(row) for row in rows), encoding="utf-8"
+ )
+
+
+def _run_live(tmp_path, monkeypatch, rows, gens, **kwargs):
+ """Run ``run_live_diagnose`` with a stand-in model pair; returns (report, load_calls)."""
+ monkeypatch.chdir(tmp_path)
+ _write_rows(tmp_path, rows)
+ calls: list = []
+
+ def fake_pair(base, adapter=None, **kw):
+ calls.append(base)
+ return gens
+
+ monkeypatch.setattr(live, "load_adapter_pair", fake_pair)
+ kwargs.setdefault("dataset_path", "d.jsonl")
+ report = live.run_live_diagnose(run_id="r", base="b", adapter="a", **kwargs)
+ return report, calls
+
+
+def _cli(tmp_path, monkeypatch, rows, gens, *extra):
+ monkeypatch.chdir(tmp_path)
+ _write_rows(tmp_path, rows)
+ calls: list = []
+
+ def fake_pair(base, adapter=None, **kw):
+ calls.append(base)
+ return gens
+
+ monkeypatch.setattr(live, "load_adapter_pair", fake_pair)
+ args = ["diagnose", "r", "--base-model", "b", "--adapter", "a", "--dataset", "d.jsonl"]
+ result = CliRunner().invoke(app, [*args, *extra])
+ return result, strip_ansi(result.output), calls
+
+
+# ---------------------------------------------------------------------------
+# Verdict taxonomy
+# ---------------------------------------------------------------------------
+
+
+class TestNotRunVerdict:
+ def test_verdicts_include_not_run_and_keep_the_old_three(self):
+ assert "NOT_RUN" in VERDICTS
+ assert {"OK", "MINOR", "MAJOR"} <= set(VERDICTS)
+
+ def test_not_run_score_helper(self):
+ from soup_cli.utils.diagnose.runner import neutral_score, not_run_score
+
+ score = not_run_score("memorization", "no usable rows")
+ assert score.verdict == "NOT_RUN"
+ assert score.score == 0.0
+ assert "probe not run" in score.evidence
+ assert "no usable rows" in score.evidence
+ # The by-design "not applicable" helper keeps its documented behaviour.
+ assert neutral_score("memorization", "x").verdict == "OK"
+
+ def test_failure_score_accepts_not_run_only_with_zero_score(self):
+ ok = FailureScore(mode="format", score=0.0, verdict="NOT_RUN", evidence="probe not run")
+ assert ok.verdict == "NOT_RUN"
+ with pytest.raises(ValueError):
+ FailureScore(mode="format", score=0.5, verdict="NOT_RUN", evidence="x")
+
+ def test_old_verdicts_still_validate(self):
+ assert FailureScore(mode="format", score=0.9, verdict="OK", evidence="x").verdict == "OK"
+ with pytest.raises(ValueError, match="disagrees"):
+ FailureScore(mode="format", score=0.9, verdict="MAJOR", evidence="x")
+
+ @pytest.mark.parametrize(
+ ("verdicts", "expected"),
+ [
+ (("OK", "NOT_RUN"), "NOT_RUN"),
+ (("MINOR", "NOT_RUN"), "NOT_RUN"),
+ (("MAJOR", "NOT_RUN"), "MAJOR"),
+ (("OK", "MINOR"), "MINOR"),
+ ],
+ )
+ def test_overall_ranking(self, verdicts, expected):
+ modes = ["forgetting", "format", "mode_collapse"]
+ scores = {}
+ for mode, verdict in zip(modes, verdicts):
+ value = {"OK": 1.0, "MINOR": 0.7, "MAJOR": 0.1, "NOT_RUN": 0.0}[verdict]
+ scores[mode] = FailureScore(mode=mode, score=value, verdict=verdict, evidence="x")
+ assert overall_verdict(scores) == expected
+
+ def test_report_serialises_not_run(self):
+ from soup_cli.utils.diagnose.runner import build_report, not_run_score
+
+ report = build_report(
+ run_id="r", base="b", adapter="a", scores={"format": not_run_score("format", "why")}
+ )
+ assert isinstance(report, FailureReport)
+ assert report.overall == "NOT_RUN"
+ assert report.to_dict()["scores"]["format"]["verdict"] == "NOT_RUN"
+
+
+# ---------------------------------------------------------------------------
+# Live path
+# ---------------------------------------------------------------------------
+
+
+class TestLivePath:
+ def test_dataset_without_usable_pairs_is_not_run(self, tmp_path, monkeypatch):
+ report, _ = _run_live(tmp_path, monkeypatch, UNRECOGNISED, _gens())
+ for mode in DATASET_MODES:
+ assert report.scores[mode].verdict == "NOT_RUN", mode
+ assert report.overall == "NOT_RUN"
+
+ def test_probe_exception_is_not_run_and_keeps_the_reason(self, tmp_path, monkeypatch):
+ def boom(prompt, k):
+ raise ValueError("generator exploded")
+
+ report, _ = _run_live(
+ tmp_path, monkeypatch, RECOGNISED, _gens(adapter_multi=boom)
+ )
+ score = report.scores["mode_collapse"]
+ assert score.verdict == "NOT_RUN"
+ assert "ValueError" in score.evidence
+ assert "generator exploded" in score.evidence
+ assert report.overall == "NOT_RUN"
+
+ def test_exception_text_is_sanitised_and_capped(self, tmp_path, monkeypatch):
+ def boom(prompt, k):
+ raise ValueError("a\x00b" + "x" * 5000)
+
+ report, _ = _run_live(
+ tmp_path, monkeypatch, RECOGNISED, _gens(adapter_multi=boom)
+ )
+ evidence = report.scores["mode_collapse"].evidence
+ assert "\x00" not in evidence
+ assert len(evidence) < 400
+
+ def test_major_outranks_not_run(self, tmp_path, monkeypatch):
+ collapsed = _gens(adapter_multi=lambda prompt, k: ["same reply"] * k)
+ with mock.patch(
+ "soup_cli.utils.diagnose.memorization.score_memorization",
+ side_effect=ValueError("probe broke"),
+ ):
+ report, _ = _run_live(tmp_path, monkeypatch, RECOGNISED, collapsed)
+ assert report.scores["mode_collapse"].verdict == "MAJOR"
+ assert report.scores["memorization"].verdict == "NOT_RUN"
+ assert report.overall == "MAJOR"
+
+ def test_not_applicable_probes_stay_neutral_ok(self, tmp_path, monkeypatch):
+ report, _ = _run_live(tmp_path, monkeypatch, RECOGNISED, _gens())
+ assert report.scores["format"].verdict == "OK"
+ assert "not JSON" in report.scores["format"].evidence
+ assert report.scores["contamination"].verdict == "OK"
+ assert report.scores["citation"].verdict == "OK"
+
+ def test_no_dataset_keeps_dataset_probes_neutral(self, tmp_path, monkeypatch):
+ report, _ = _run_live(
+ tmp_path, monkeypatch, RECOGNISED, _gens(), dataset_path=None
+ )
+ for mode in DATASET_MODES:
+ assert report.scores[mode].verdict == "OK", mode
+ assert "NOT_RUN" not in {score.verdict for score in report.scores.values()}
+
+ def test_bad_tokenizer_fails_before_any_model_load(self, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ _write_rows(tmp_path, RECOGNISED)
+ calls: list = []
+ monkeypatch.setattr(
+ live, "load_adapter_pair", lambda base, adapter=None, **kw: calls.append(base)
+ )
+ with mock.patch(
+ "soup_cli.utils.diagnose._common.resolve_tokenizer",
+ side_effect=ValueError("could not load tokenizer 'typo/tok'"),
+ ):
+ with pytest.raises(ValueError, match="could not load tokenizer"):
+ live.run_live_diagnose(
+ run_id="r", base="b", dataset_path="d.jsonl", tokenizer="typo/tok"
+ )
+ assert calls == []
+
+
+# ---------------------------------------------------------------------------
+# CLI: exit code, opt-out flag, badge, tokenizer
+# ---------------------------------------------------------------------------
+
+
+class TestCli:
+ def test_not_run_exits_3(self, tmp_path, monkeypatch):
+ result, out, _ = _cli(tmp_path, monkeypatch, UNRECOGNISED, _gens())
+ assert result.exit_code == 3
+ assert "NOT_RUN" in out
+
+ def test_allow_not_run_exits_0(self, tmp_path, monkeypatch):
+ result, out, _ = _cli(
+ tmp_path, monkeypatch, UNRECOGNISED, _gens(), "--allow-not-run"
+ )
+ assert result.exit_code == 0
+ assert "NOT_RUN" in out # still visible, only the exit code changes
+
+ def test_major_still_exits_2_with_not_run_present(self, tmp_path, monkeypatch):
+ collapsed = _gens(adapter_multi=lambda prompt, k: ["same reply"] * k)
+ with mock.patch(
+ "soup_cli.utils.diagnose.memorization.score_memorization",
+ side_effect=ValueError("probe broke"),
+ ):
+ result, _, _ = _cli(tmp_path, monkeypatch, RECOGNISED, collapsed)
+ assert result.exit_code == 2
+
+ def test_allow_not_run_does_not_hide_a_major(self, tmp_path, monkeypatch):
+ collapsed = _gens(adapter_multi=lambda prompt, k: ["same reply"] * k)
+ with mock.patch(
+ "soup_cli.utils.diagnose.memorization.score_memorization",
+ side_effect=ValueError("probe broke"),
+ ):
+ result, _, _ = _cli(
+ tmp_path, monkeypatch, RECOGNISED, collapsed, "--allow-not-run"
+ )
+ assert result.exit_code == 2
+
+ def test_badge_is_grey_not_green_for_not_run(self, tmp_path, monkeypatch):
+ result, _, _ = _cli(
+ tmp_path, monkeypatch, UNRECOGNISED, _gens(), "--badge", "b.svg", "--allow-not-run"
+ )
+ assert result.exit_code == 0
+ svg = (tmp_path / "b.svg").read_text(encoding="utf-8")
+ assert "NOT_RUN" in svg # the overall pill
+ assert "#8b949e" in svg
+ # The four dataset probes show "not run", never a stored 0.00 placeholder.
+ assert svg.count("not run") == 4
+ assert "0.00" not in svg
+ # Only refusal, contamination and citation are OK (green); the pill is grey.
+ assert svg.count("#3fb950") == 3
+
+ def test_bad_tokenizer_exits_3_before_model_load(self, tmp_path, monkeypatch):
+ with mock.patch(
+ "soup_cli.utils.diagnose._common.resolve_tokenizer",
+ side_effect=ValueError("could not load tokenizer 'typo/tok'"),
+ ):
+ result, out, calls = _cli(
+ tmp_path, monkeypatch, RECOGNISED, _gens(), "--tokenizer", "typo/tok"
+ )
+ assert result.exit_code == 3
+ assert "could not load tokenizer" in out
+ assert calls == []
+
+ def test_evidence_only_path_is_unchanged(self, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ result = CliRunner().invoke(app, ["diagnose", "r1"])
+ assert result.exit_code == 0
+ assert "NOT_RUN" not in strip_ansi(result.output)
+
+
+# ---------------------------------------------------------------------------
+# Evidence files carrying NOT_RUN (CLI + MCP)
+# ---------------------------------------------------------------------------
+
+
+def _evidence_file(tmp_path: Path, scores: dict) -> str:
+ (tmp_path / "ev.json").write_text(json.dumps({"scores": scores}), encoding="utf-8")
+ return "ev.json"
+
+
+class TestEvidenceNotRun:
+ def test_cli_evidence_not_run_exits_3(self, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ path = _evidence_file(tmp_path, {"format": {"verdict": "NOT_RUN", "evidence": "never"}})
+ result = CliRunner().invoke(app, ["diagnose", "r", "--evidence", path])
+ assert result.exit_code == 3
+ assert "NOT_RUN" in strip_ansi(result.output)
+
+ def test_cli_evidence_not_run_allowed_exits_0(self, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ path = _evidence_file(tmp_path, {"format": {"verdict": "NOT_RUN", "evidence": "never"}})
+ result = CliRunner().invoke(app, ["diagnose", "r", "--evidence", path, "--allow-not-run"])
+ assert result.exit_code == 0
+
+ def test_cli_not_run_with_a_score_is_a_clear_error(self, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ path = _evidence_file(
+ tmp_path, {"format": {"verdict": "NOT_RUN", "score": 0.4, "evidence": "x"}}
+ )
+ result = CliRunner().invoke(app, ["diagnose", "r", "--evidence", path])
+ # A usage error (2/3) with a message, not a ValueError traceback (exit 1).
+ assert result.exit_code in (2, 3)
+ assert isinstance(result.exception, SystemExit)
+ assert "NOT_RUN score must be 0.0" in strip_ansi(result.output)
+
+ def test_not_run_entry_needs_no_score(self):
+ from soup_cli.utils.diagnose.report import evidence_default_score
+
+ assert evidence_default_score({"verdict": "NOT_RUN"}) == 0.0
+ assert evidence_default_score({"verdict": "OK"}) == 1.0
+ assert evidence_default_score({}) == 1.0
+
+ def test_mcp_evidence_round_trips_not_run(self, tmp_path, monkeypatch):
+ from soup_cli.mcp_server.registry import tool_diagnose_evidence
+
+ monkeypatch.chdir(tmp_path)
+ path = _evidence_file(tmp_path, {"format": {"verdict": "NOT_RUN", "evidence": "never"}})
+ out = tool_diagnose_evidence({"run_id": "r", "evidence": path})
+ assert out["overall"] == "NOT_RUN"
+ assert out["scores"]["format"]["verdict"] == "NOT_RUN"
+
+
+# ---------------------------------------------------------------------------
+# Every probe site reports NOT_RUN, and a probe with nothing to measure is not OK
+# ---------------------------------------------------------------------------
+
+JSON_ROWS = [
+ {"prompt": f"Return object {i}.", "completion": f'{{"id": {i}}}'} for i in range(12)
+]
+RAFT_ROWS = [
+ {
+ "query": f"question {i}?",
+ "golden_doc": f"golden doc {i}",
+ "answer": f"answer {i} [doc-1]",
+ "text": f"document {i} has several separate words that can be split",
+ }
+ for i in range(12)
+]
+# Pairs exist (the pair builder reads these keys) but score_memorization reads none of them
+# and used to answer "nothing to check" with OK 1.00.
+QUESTION_ANSWER = [
+ {"question": f"What is topic {i} about in detail?", "answer": f"Topic {i} is about things."}
+ for i in range(12)
+]
+QUERY_RESPONSE = [
+ {"query": f"Tell me about topic {i} in detail.", "response": f"Topic {i} is about things."}
+ for i in range(12)
+]
+INPUT_OUTPUT = [
+ {"input": f"translate sentence number {i} to French", "output": f"phrase {i}"}
+ for i in range(12)
+]
+
+PROBE_SITES = [
+ ("refusal", "soup_cli.utils.diagnose.refusal.score_refusal", RECOGNISED),
+ ("forgetting", "soup_cli.utils.diagnose.forgetting.score_forgetting", RECOGNISED),
+ ("format", "soup_cli.utils.diagnose.format.score_format", JSON_ROWS),
+ ("mode_collapse", "soup_cli.utils.diagnose.mode_collapse.score_mode_collapse", RECOGNISED),
+ ("memorization", "soup_cli.utils.diagnose.memorization.score_memorization", RECOGNISED),
+ ("citation", "soup_cli.utils.diagnose.citation.score_citation", RAFT_ROWS),
+]
+
+
+class TestEveryProbeSite:
+ @pytest.mark.parametrize(
+ ("mode", "target", "rows"), PROBE_SITES, ids=[site[0] for site in PROBE_SITES]
+ )
+ def test_a_probe_that_raises_is_not_run_with_its_reason(
+ self, tmp_path, monkeypatch, mode, target, rows
+ ):
+ with mock.patch(target, side_effect=ValueError("probe exploded")):
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ score = report.scores[mode]
+ assert score.verdict == "NOT_RUN", (mode, score)
+ assert "ValueError: probe exploded" in score.evidence
+ assert report.overall == "NOT_RUN"
+
+ @pytest.mark.parametrize(
+ "rows",
+ [QUESTION_ANSWER, QUERY_RESPONSE, INPUT_OUTPUT],
+ ids=["question_answer", "query_response", "input_output"],
+ )
+ def test_memorization_with_no_splittable_text_is_not_run(self, tmp_path, monkeypatch, rows):
+ report, _ = _run_live(tmp_path, monkeypatch, rows, _gens())
+ score = report.scores["memorization"]
+ assert score.verdict == "NOT_RUN", score
+ assert "text, content" in score.evidence # the new guard, not "no usable rows"
+ assert report.scores["forgetting"].verdict != "NOT_RUN" # the rows do form pairs
+ assert report.overall == "NOT_RUN"
+
+
+# ---------------------------------------------------------------------------
+# Review follow-ups: table cell, empty --tokenizer, grey style
+# ---------------------------------------------------------------------------
+
+
+class TestReviewFollowUps:
+ def test_table_shows_a_dash_not_a_zero_score_for_not_run(self, tmp_path, monkeypatch):
+ result, out, _ = _cli(
+ tmp_path, monkeypatch, UNRECOGNISED, _gens(), "--allow-not-run"
+ )
+ assert result.exit_code == 0
+ modes = ("forgetting", "format", "mode_collapse", "memorization")
+ rows = [
+ line for line in out.splitlines()
+ if "NOT_RUN" in line and any(mode in line for mode in modes)
+ ]
+ assert len(rows) == 4 # one table row per NOT_RUN probe, not the overall panel
+ for line in rows:
+ assert "\u2014" in line
+ assert "0.000" not in line
+
+ def test_empty_tokenizer_is_an_input_error(self, tmp_path, monkeypatch):
+ result, out, calls = _cli(
+ tmp_path, monkeypatch, RECOGNISED, _gens(), "--tokenizer", ""
+ )
+ assert result.exit_code == 3
+ assert "non-empty" in out
+ assert calls == []
+
+ def test_not_run_is_styled_grey(self):
+ from soup_cli.commands.diagnose import _verdict_style
+
+ assert _verdict_style("NOT_RUN") == "bright_black"
diff --git a/tests/test_v0560.py b/tests/test_v0560.py
index 8f54f54b..934e4a70 100644
--- a/tests/test_v0560.py
+++ b/tests/test_v0560.py
@@ -709,6 +709,91 @@ class TestTrainDiagnoseGate:
from soup_cli.commands.train import _run_diagnose_gate
_run_diagnose_gate(str(evidence), "run1", "base", "adapter")
+ def test_run_diagnose_gate_helper_not_run_exits_3(self, tmp_path: Path) -> None:
+ import typer
+
+ # #1435: an unmeasured mode must not pass the gate.
+ os.chdir(tmp_path)
+ evidence = tmp_path / "ev.json"
+ evidence.write_text(
+ json.dumps(
+ {
+ "scores": {
+ "format": {
+ "score": 0.0,
+ "verdict": "NOT_RUN",
+ "evidence": "probe not run (no rows)",
+ }
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ from soup_cli.commands.train import _run_diagnose_gate
+
+ with pytest.raises(typer.Exit) as excinfo:
+ _run_diagnose_gate(str(evidence), "run1", "base", "adapter")
+ assert excinfo.value.exit_code == 3
+
+ def test_run_diagnose_gate_major_beats_not_run(self, tmp_path: Path) -> None:
+ import typer
+
+ os.chdir(tmp_path)
+ evidence = tmp_path / "ev.json"
+ evidence.write_text(
+ json.dumps(
+ {
+ "scores": {
+ "format": {"verdict": "NOT_RUN", "evidence": "never ran"},
+ "refusal": {"score": 0.1, "verdict": "MAJOR", "evidence": "worse"},
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ from soup_cli.commands.train import _run_diagnose_gate
+
+ with pytest.raises(typer.Exit) as excinfo:
+ _run_diagnose_gate(str(evidence), "run1", "base", "adapter")
+ assert excinfo.value.exit_code == 2
+
+ @pytest.mark.parametrize("verdict", ["NOT_RUN", "MAJOR"])
+ def test_run_diagnose_gate_escapes_evidence_markup(
+ self, tmp_path: Path, verdict: str
+ ) -> None:
+ import typer
+
+ os.chdir(tmp_path)
+ evidence = tmp_path / "ev.json"
+ score = 0.0 if verdict == "NOT_RUN" else 0.1
+ evidence.write_text(
+ json.dumps(
+ {"scores": {"format": {"score": score, "verdict": verdict,
+ "evidence": "[/bad] [red]x"}}}
+ ),
+ encoding="utf-8",
+ )
+ from soup_cli.commands.train import _run_diagnose_gate
+
+ # An unescaped "[/bad]" would raise rich.errors.MarkupError, not typer.Exit.
+ with pytest.raises(typer.Exit):
+ _run_diagnose_gate(str(evidence), "run1", "base", "adapter")
+
+ @pytest.mark.parametrize("bad_score", [None, True, "0.5"])
+ def test_run_diagnose_gate_rejects_non_numeric_score(
+ self, tmp_path: Path, bad_score: object
+ ) -> None:
+ os.chdir(tmp_path)
+ evidence = tmp_path / "ev.json"
+ evidence.write_text(
+ json.dumps({"scores": {"format": {"score": bad_score, "verdict": "OK"}}}),
+ encoding="utf-8",
+ )
+ from soup_cli.commands.train import _run_diagnose_gate
+
+ with pytest.raises(ValueError, match="must be a number"):
+ _run_diagnose_gate(str(evidence), "run1", "base", "adapter")
+
def test_diagnose_gate_skips_nonzero_local_rank(self, monkeypatch: pytest.MonkeyPatch) -> None:
from soup_cli.commands.train import _should_run_diagnose_gate_on_rank