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,train,eval): print evidence, ids, paths and error text through for_terminal (#1647)

Alpamys Makazhanffcb5537e96a
diff --git a/changelog.d/0.75.1/1647.fixed.md b/changelog.d/0.75.1/1647.fixed.md
new file mode 100644
index 00000000..9968c859
--- /dev/null
+++ b/changelog.d/0.75.1/1647.fixed.md
@@ -0,0 +1,12 @@
+- `soup diagnose`, `soup train --diagnose-gate` and `soup eval unlearning`
+ print text they did not write through the shared `for_terminal` helper
+ instead of `escape()` alone, so ESC, DEL and the C1 control range
+ (U+0080-U+009F) are stripped before the text reaches the terminal: the
+ evidence line of every score or metric (from `--evidence` /
+ `--diagnose-gate` JSON or a live run), the adapter name and run id in the
+ table titles and the overall panel, the `--output` and `--badge` paths,
+ the `--attach-to-registry` id, and the exception text in their error
+ lines. The `--diagnose-gate failed` line of `soup train` printed its
+ exception text as Rich markup: an evidence file whose refused `verdict`
+ contained `[/]` ended the command with a `MarkupError` traceback instead
+ of the message (#1647).
diff --git a/src/soup_cli/commands/_eval_v0610.py b/src/soup_cli/commands/_eval_v0610.py
index 0408e184..5660f9f4 100644
--- a/src/soup_cli/commands/_eval_v0610.py
+++ b/src/soup_cli/commands/_eval_v0610.py
@@ -17,6 +17,8 @@ from rich.console import Console
from rich.markup import escape
from rich.table import Table
+from soup_cli.utils.terminal import for_terminal
+
def register(app: typer.Typer, console: Console) -> None:
"""Attach v0.61.0 subcommands to ``app``."""
@@ -63,7 +65,7 @@ def register(app: typer.Typer, console: Console) -> None:
try:
bench = validate_benchmark_name(benchmark)
except (TypeError, ValueError) as exc:
- console.print(f"[red]Invalid benchmark:[/] {escape(str(exc))}")
+ console.print(f"[red]Invalid benchmark:[/] {for_terminal(exc)}")
raise typer.Exit(2) from exc
evidence_data = None
@@ -75,11 +77,11 @@ def register(app: typer.Typer, console: Console) -> None:
# FIRST so we can label the message specifically (review
# MEDIUM M10 — was unreachable after the broader except).
console.print(
- f"[red]Evidence file is not valid JSON:[/] {escape(str(exc))}"
+ f"[red]Evidence file is not valid JSON:[/] {for_terminal(exc)}"
)
raise typer.Exit(2) from exc
except (FileNotFoundError, ValueError, TypeError, OSError) as exc:
- console.print(f"[red]Cannot read evidence:[/] {escape(str(exc))}")
+ console.print(f"[red]Cannot read evidence:[/] {for_terminal(exc)}")
raise typer.Exit(2) from exc
try:
@@ -89,11 +91,11 @@ def register(app: typer.Typer, console: Console) -> None:
evidence=evidence_data,
)
except (TypeError, ValueError) as exc:
- console.print(f"[red]Eval failed:[/] {escape(str(exc))}")
+ console.print(f"[red]Eval failed:[/] {for_terminal(exc)}")
raise typer.Exit(2) from exc
# Render the table.
- table = Table(title=f"Unlearn eval — {escape(bench)} — {escape(run_id)}")
+ table = Table(title=f"Unlearn eval — {escape(bench)} — {for_terminal(run_id)}")
table.add_column("metric", style="bold")
table.add_column("score", justify="right")
table.add_column("verdict")
@@ -108,7 +110,7 @@ def register(app: typer.Typer, console: Console) -> None:
escape(m.name),
f"{m.score:.3f}",
f"[{colour}]{escape(m.verdict)}[/]",
- escape(m.evidence),
+ for_terminal(m.evidence),
)
console.print(table)
overall_colour = {
@@ -125,9 +127,9 @@ def register(app: typer.Typer, console: Console) -> None:
try:
write_unlearn_report(report, output)
except (TypeError, ValueError, OSError) as exc:
- console.print(f"[red]Cannot write report:[/] {escape(str(exc))}")
+ console.print(f"[red]Cannot write report:[/] {for_terminal(exc)}")
raise typer.Exit(2) from exc
- console.print(f"Wrote report -> {escape(output)}")
+ console.print(f"Wrote report -> {for_terminal(output)}")
# Optional registry attach.
if attach_to_registry is not None:
@@ -144,11 +146,11 @@ def register(app: typer.Typer, console: Console) -> None:
kind="eval_results",
)
console.print(
- f"Attached eval_results -> registry {escape(attach_to_registry)}"
+ f"Attached eval_results -> registry {for_terminal(attach_to_registry)}"
)
except Exception as exc: # noqa: BLE001
console.print(
- f"[yellow]Registry attach failed:[/] {escape(str(exc))}"
+ f"[yellow]Registry attach failed:[/] {for_terminal(exc)}"
)
# Exit code: 0 on OK / MINOR; 2 on MAJOR (matches v0.56.0 diagnose
diff --git a/src/soup_cli/commands/diagnose.py b/src/soup_cli/commands/diagnose.py
index f9f926e9..4e7aed3c 100644
--- a/src/soup_cli/commands/diagnose.py
+++ b/src/soup_cli/commands/diagnose.py
@@ -45,6 +45,7 @@ from soup_cli.utils.diagnose.runner import (
)
from soup_cli.utils.exit_codes import EXIT_USAGE_ERROR
from soup_cli.utils.paths import enforce_under_cwd_and_no_symlink
+from soup_cli.utils.terminal import for_terminal
console = Console()
@@ -79,7 +80,7 @@ def _exit_for(report: FailureReport, allow_not_run: bool) -> None:
def _render_report(report: FailureReport) -> None:
- table = Table(title=f"soup diagnose: {escape(report.adapter or report.run_id)}")
+ table = Table(title=f"soup diagnose: {for_terminal(report.adapter or report.run_id)}")
table.add_column("Mode", style="bold")
table.add_column("Score", justify="right")
table.add_column("Verdict")
@@ -93,13 +94,13 @@ def _render_report(report: FailureReport) -> None:
# 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),
+ for_terminal(score.evidence),
)
console.print(table)
console.print(
Panel.fit(
f"[bold {_verdict_style(report.overall)}]{report.overall}[/] — "
- f"run [bold]{escape(report.run_id)}[/]",
+ f"run [bold]{for_terminal(report.run_id)}[/]",
title="overall",
)
)
@@ -208,12 +209,12 @@ def _attach_to_registry(report: FailureReport, registry_id: str, output: str) ->
attach_artifact(registry_id, "diagnose_report", output)
console.print(
f"[green]Attached[/] diagnose_report to registry entry "
- f"[bold]{escape(registry_id)}[/]"
+ f"[bold]{for_terminal(registry_id)}[/]"
)
except Exception as exc: # noqa: BLE001
console.print(
f"[yellow]Warning:[/] could not attach to registry: "
- f"{escape(type(exc).__name__)}: {escape(str(exc))}"
+ f"{escape(type(exc).__name__)}: {for_terminal(exc)}"
)
@@ -230,11 +231,11 @@ def _emit_report(
if output:
try:
write_report(report, output)
- console.print(f"[green]Wrote[/] {escape(output)}")
+ console.print(f"[green]Wrote[/] {for_terminal(output)}")
except (OSError, ValueError) as exc:
console.print(
f"[red]Error:[/] cannot write --output: "
- f"{escape(type(exc).__name__)}: {escape(str(exc))}"
+ f"{escape(type(exc).__name__)}: {for_terminal(exc)}"
)
raise typer.Exit(code=1) from exc
@@ -242,11 +243,11 @@ def _emit_report(
try:
svg = render_badge_svg(report)
_write_badge(badge, svg)
- console.print(f"[green]Badge written[/] to {escape(badge)}")
+ console.print(f"[green]Badge written[/] to {for_terminal(badge)}")
except (OSError, ValueError, TypeError) as exc:
console.print(
f"[red]Error:[/] cannot write --badge: "
- f"{escape(type(exc).__name__)}: {escape(str(exc))}"
+ f"{escape(type(exc).__name__)}: {for_terminal(exc)}"
)
raise typer.Exit(code=1) from exc
@@ -350,7 +351,7 @@ def diagnose(
resolved_citation_style = validate_citation_style(citation_style)
except (TypeError, ValueError) as exc:
console.print(
- f"[red]Invalid --citation-style:[/] {escape(str(exc))}"
+ f"[red]Invalid --citation-style:[/] {for_terminal(exc)}"
)
raise typer.Exit(code=2) from exc
@@ -364,7 +365,7 @@ def diagnose(
try:
tokenizer_arg = _common.resolve_tokenizer(tokenizer)
except (TypeError, ValueError) as exc:
- console.print(f"[red]Error:[/] {escape(str(exc))}")
+ console.print(f"[red]Error:[/] {for_terminal(exc)}")
raise typer.Exit(code=EXIT_USAGE_ERROR) from exc
try:
@@ -383,7 +384,7 @@ def diagnose(
except (ValueError, TypeError, OSError, RuntimeError) as exc:
console.print(
f"[red]Error:[/] live diagnose failed: "
- f"{escape(type(exc).__name__)}: {escape(str(exc))}"
+ f"{escape(type(exc).__name__)}: {for_terminal(exc)}"
)
raise typer.Exit(code=1) from exc
_emit_report(report, output=output, badge=badge, attach_to_registry=attach_to_registry)
diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.py
index 1e413a4e..3eb23645 100644
--- a/src/soup_cli/commands/train.py
+++ b/src/soup_cli/commands/train.py
@@ -1889,17 +1889,9 @@ def train(
# --- v0.56.0 --diagnose-gate: post-training failure-mode check ---
if diagnose_gate and _should_run_diagnose_gate_on_rank():
- try:
- _run_diagnose_gate(
- diagnose_gate, run_id, cfg.base, result["output_dir"]
- )
- except typer.Exit:
- raise
- except (OSError, ValueError) as exc:
- console.print(
- f"[red]--diagnose-gate failed:[/] {type(exc).__name__}: {exc}"
- )
- raise typer.Exit(1) from exc
+ _run_diagnose_gate_or_exit(
+ diagnose_gate, run_id, cfg.base, result["output_dir"]
+ )
# --- v0.71.3 #180 --track-energy: print the measured energy/CO2 -------
energy_measurement = (
@@ -2211,6 +2203,7 @@ def _run_diagnose_gate(
from soup_cli.utils.diagnose.report import FAILURE_MODES, FailureScore
from soup_cli.utils.diagnose.runner import build_report
from soup_cli.utils.paths import enforce_under_cwd_and_no_symlink
+ from soup_cli.utils.terminal import for_terminal
enforce_under_cwd_and_no_symlink(evidence_path, "--diagnose-gate evidence")
# 16 MiB cap on evidence JSON (security review HIGH — symmetric with
@@ -2259,7 +2252,7 @@ def _run_diagnose_gate(
for mode in FAILURE_MODES:
sc = report.scores[mode]
if sc.verdict == "MAJOR":
- console.print(f" [red]MAJOR[/] {mode}: {markup_escape(sc.evidence)}")
+ console.print(f" [red]MAJOR[/] {mode}: {for_terminal(sc.evidence)}")
raise typer.Exit(2)
if report.overall == "NOT_RUN":
# An unmeasured mode is not a pass (#1435); same exit as `soup diagnose`.
@@ -2270,7 +2263,7 @@ def _run_diagnose_gate(
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)}")
+ console.print(f" [yellow]NOT_RUN[/] {mode}: {for_terminal(sc.evidence)}")
raise typer.Exit(EXIT_USAGE_ERROR)
console.print(
f"[green]--diagnose-gate: {report.overall}[/] across "
@@ -2278,6 +2271,23 @@ def _run_diagnose_gate(
)
+def _run_diagnose_gate_or_exit(
+ evidence_path: str, run_id: str, base: str, adapter: str
+) -> None:
+ """Run the gate; an unreadable or refused evidence file is reported and exits 1."""
+ from soup_cli.utils.terminal import for_terminal
+
+ try:
+ _run_diagnose_gate(evidence_path, run_id, base, adapter)
+ except typer.Exit:
+ raise
+ except (OSError, ValueError) as exc:
+ console.print(
+ f"[red]--diagnose-gate failed:[/] {type(exc).__name__}: {for_terminal(exc)}"
+ )
+ raise typer.Exit(1) from exc
+
+
def _resolve_deepspeed(deepspeed: str) -> str:
"""Resolve DeepSpeed config: named preset or path to JSON file."""
import soup_cli.utils.deepspeed as ds
diff --git a/tests/test_diagnose_evidence_terminal_output.py b/tests/test_diagnose_evidence_terminal_output.py
new file mode 100644
index 00000000..ab35588c
--- /dev/null
+++ b/tests/test_diagnose_evidence_terminal_output.py
@@ -0,0 +1,419 @@
+"""Text that ``soup diagnose`` did not write reaches the terminal as text.
+
+``soup diagnose`` interpolates strings from outside the program into Rich
+markup: the evidence line of every score (from the ``--evidence`` JSON, or on a
+live run from a model reply, a dataset row or a probe's exception text), the
+run id, the adapter name, the ``--output`` / ``--badge`` paths, the registry
+entry id, and the text of the exceptions it reports. Each went through
+``rich.markup.escape`` alone, which neutralises ``[...]`` tags and leaves ESC,
+DEL and the C1 range U+0080-U+009F in place. Each now goes through
+``soup_cli.utils.terminal.for_terminal``.
+
+Every test drives the real ``soup diagnose`` command line, with the module's
+console swapped for ``Console(file=StringIO(), color_system=None)`` so Rich
+emits no styling of its own: any control byte in the capture came from the
+value. Control characters are asserted on the UTF-8 bytes of the capture.
+Non-ASCII characters are built with ``chr()`` so this file stays ASCII.
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+import sys
+import types
+from io import StringIO
+from pathlib import Path
+
+import pytest
+from rich.console import Console
+from typer.testing import CliRunner
+
+import soup_cli.commands.diagnose as diagnose_mod
+import soup_cli.registry.attach as attach_mod
+import soup_cli.utils.citation_faithful as citation_mod
+import soup_cli.utils.diagnose.live as live_mod
+from soup_cli.cli import app
+from soup_cli.utils.diagnose.report import FAILURE_MODES, FailureScore
+from soup_cli.utils.diagnose.runner import build_report
+from soup_cli.utils.exit_codes import EXIT_USAGE_ERROR
+from tests.conftest import strip_ansi
+
+runner = CliRunner()
+
+ESC = chr(27)
+BEL = chr(7)
+BACKSPACE = chr(8)
+CARRIAGE_RETURN = chr(13)
+DEL = chr(0x7F)
+CSI_C1 = chr(0x9B)
+ST_C1 = chr(0x9C)
+OSC_C1 = chr(0x9D)
+BACKSLASH = chr(92)
+
+MARKUP = "[red]x[/red][link=http://h/]y[/link][/]"
+
+#: name -> (text as stored in the file, text the terminal must show)
+SEQUENCES = {
+ "csi-colour": ("ZQ" + ESC + "[31mQZ", "ZQ[31mQZ"),
+ "osc-title": ("ZQ" + ESC + "]0;T" + BEL + "QZ", "ZQ]0;TQZ"),
+ "osc-hyperlink": (
+ "ZQ" + ESC + "]8;;http://h/" + ESC + BACKSLASH + "QZ",
+ "ZQ]8;;http://h/" + BACKSLASH + "QZ",
+ ),
+ "bel": ("ZQ" + BEL + "QZ", "ZQQZ"),
+ "backspace": ("ZQ" + BACKSPACE + "QZ", "ZQQZ"),
+ "carriage-return": ("ZQ" + CARRIAGE_RETURN + "QZ", "ZQQZ"),
+ "del": ("ZQ" + DEL + "QZ", "ZQQZ"),
+ "c1-csi": ("ZQ" + CSI_C1 + "2JQZ", "ZQ2JQZ"),
+ "c1-osc": ("ZQ" + OSC_C1 + "0;T" + ST_C1 + "QZ", "ZQ0;TQZ"),
+}
+
+#: One value carrying every sequence above plus tag pairs and a bare closing tag.
+FILE_TEXT = (
+ "ZQ"
+ + ESC + "[31m"
+ + ESC + "]0;T" + BEL
+ + ESC + "]8;;http://h/" + ESC + BACKSLASH
+ + "-" + BACKSPACE + CARRIAGE_RETURN + DEL
+ + CSI_C1 + "2J"
+ + OSC_C1 + "0;T" + ST_C1
+ + MARKUP
+ + "QZ"
+)
+
+#: What the terminal must show for it: controls gone, brackets literal.
+SHOWN = "ZQ[31m]0;T]8;;http://h/" + BACKSLASH + "-2J0;T" + MARKUP + "QZ"
+
+#: Raw byte strings that must never be in a capture.
+RAW_CONTROLS = {
+ "ESC": ESC.encode("utf-8"),
+ "BEL": BEL.encode("utf-8"),
+ "BACKSPACE": BACKSPACE.encode("utf-8"),
+ "CARRIAGE RETURN": CARRIAGE_RETURN.encode("utf-8"),
+ "DEL": DEL.encode("utf-8"),
+ "C1 CSI": CSI_C1.encode("utf-8"),
+ "C1 ST": ST_C1.encode("utf-8"),
+ "C1 OSC": OSC_C1.encode("utf-8"),
+}
+
+
+def _is_control(char: str) -> bool:
+ code = ord(char)
+ return (code < 0x20 and char not in "\t\n") or 0x7F <= code <= 0x9F
+
+
+def _assert_no_control_bytes(out: str) -> None:
+ raw = out.encode("utf-8")
+ found = [name for name, needle in RAW_CONTROLS.items() if needle in raw]
+ assert not found, (found, raw)
+ stray = sorted({f"U+{ord(char):04X}" for char in out if _is_control(char)})
+ assert not stray, (stray, raw)
+
+
+def _flat(out: str) -> str:
+ """Drop all whitespace: a table title wraps to the table's width."""
+ return "".join(out.split())
+
+
+def _assert_shown_literally(out: str, *, times: int = 1) -> None:
+ _assert_no_control_bytes(out)
+ assert _flat(out).count(SHOWN) == times, out
+
+
+def _run(monkeypatch, tmp_path, *args, evidence=None, ensure_ascii=True):
+ """Invoke ``soup diagnose`` in ``tmp_path``; return (result, console capture)."""
+ monkeypatch.chdir(tmp_path)
+ argv = ["diagnose", *args]
+ if evidence is not None:
+ (tmp_path / "ev.json").write_text(
+ json.dumps(evidence, ensure_ascii=ensure_ascii), encoding="utf-8"
+ )
+ argv += ["--evidence", "ev.json"]
+ buffer = StringIO()
+ monkeypatch.setattr(
+ diagnose_mod, "console", Console(file=buffer, color_system=None, width=400)
+ )
+ result = runner.invoke(app, argv)
+ return result, buffer.getvalue()
+
+
+def _evidence_for(mode: str, text: str) -> dict:
+ return {"scores": {mode: {"score": 1.0, "evidence": text}}}
+
+
+def _ok(result) -> None:
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+
+
+# ---------------------------------------------------------------------------
+# The evidence column of the report table
+# ---------------------------------------------------------------------------
+
+
[email protected]("name", sorted(SEQUENCES))
+def test_evidence_line_drops_each_control_sequence(monkeypatch, tmp_path, name):
+ stored, shown = SEQUENCES[name]
+ result, out = _run(
+ monkeypatch, tmp_path, "run1", evidence=_evidence_for("forgetting", stored)
+ )
+ _ok(result)
+ _assert_no_control_bytes(out)
+ assert out.count(shown) == 1, out
+
+
+def test_evidence_line_of_every_mode_is_shown_literally(monkeypatch, tmp_path):
+ evidence = {
+ "scores": {mode: {"score": 1.0, "evidence": FILE_TEXT} for mode in FAILURE_MODES}
+ }
+ result, out = _run(monkeypatch, tmp_path, "run1", evidence=evidence)
+ _ok(result)
+ _assert_shown_literally(out, times=len(FAILURE_MODES))
+
+
+ "markup",
+ [
+ "[red]x[/red]",
+ "[link=http://h/]y[/link]",
+ "[bold]never closed",
+ "closed but never opened[/]",
+ "[/red]",
+ ],
+)
+def test_evidence_line_prints_markup_as_literal_text(monkeypatch, tmp_path, markup):
+ result, out = _run(
+ monkeypatch, tmp_path, "run1", evidence=_evidence_for("refusal", "ZQ" + markup + "QZ")
+ )
+ _ok(result)
+ assert out.count("ZQ" + markup + "QZ") == 1, out
+
+
+def test_evidence_line_keeps_ordinary_non_ascii_text(monkeypatch, tmp_path):
+ # e-acute, inverted exclamation mark (first code point after the C1 range),
+ # a Cyrillic and a CJK letter, and a character outside the BMP.
+ text = "caf" + chr(0xE9) + chr(0xA1) + chr(0x416) + chr(0x65E5) + chr(0x1D11E) + "~end"
+ result, out = _run(
+ monkeypatch,
+ tmp_path,
+ "run1",
+ evidence=_evidence_for("format", text),
+ ensure_ascii=False,
+ )
+ _ok(result)
+ assert out.count(text) == 1, out
+ _assert_no_control_bytes(out)
+
+
+def test_evidence_line_of_a_live_report_is_shown_literally(monkeypatch, tmp_path):
+ """A live run's evidence quotes model replies, dataset rows and exception text."""
+
+ def _live(**kwargs):
+ scores = {
+ "memorization": FailureScore(
+ mode="memorization", score=1.0, verdict="OK", evidence=FILE_TEXT
+ )
+ }
+ return build_report(
+ run_id=kwargs["run_id"],
+ base=kwargs["base"],
+ adapter="",
+ scores=scores,
+ soup_version="0",
+ )
+
+ monkeypatch.setattr(live_mod, "run_live_diagnose", _live)
+ result, out = _run(monkeypatch, tmp_path, "run1", "--base-model", "org/m")
+ _ok(result)
+ _assert_shown_literally(out)
+
+
+# ---------------------------------------------------------------------------
+# The table title and the overall panel
+# ---------------------------------------------------------------------------
+
+
+def test_table_title_shows_the_adapter_name_literally(monkeypatch, tmp_path):
+ result, out = _run(monkeypatch, tmp_path, "run1", "--adapter", FILE_TEXT)
+ _ok(result)
+ _assert_shown_literally(out)
+
+
+def test_overall_panel_shows_the_run_id_literally(monkeypatch, tmp_path):
+ result, out = _run(monkeypatch, tmp_path, FILE_TEXT, "--adapter", "plain")
+ _ok(result)
+ _assert_shown_literally(out)
+
+
+def test_table_title_falls_back_to_the_run_id(monkeypatch, tmp_path):
+ result, out = _run(monkeypatch, tmp_path, FILE_TEXT)
+ _ok(result)
+ _assert_shown_literally(out, times=2)
+
+
+# ---------------------------------------------------------------------------
+# --output, --badge and --attach-to-registry lines
+# ---------------------------------------------------------------------------
+
+
+def test_wrote_line_shows_the_output_path_literally(monkeypatch, tmp_path):
+ monkeypatch.setattr(diagnose_mod, "write_report", lambda report, path: path)
+ result, out = _run(monkeypatch, tmp_path, "run1", "--output", FILE_TEXT)
+ _ok(result)
+ _assert_shown_literally(out)
+ assert "Wrote" in out
+
+
+def test_output_error_shows_the_exception_text_literally(monkeypatch, tmp_path):
+ def _refuse(report, path):
+ raise ValueError(f"diagnose report path {path} must stay under cwd")
+
+ monkeypatch.setattr(diagnose_mod, "write_report", _refuse)
+ result, out = _run(monkeypatch, tmp_path, "run1", "--output", FILE_TEXT)
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ assert "cannot write --output: ValueError: diagnose report path" in out
+ _assert_shown_literally(out)
+
+
+def test_badge_line_shows_the_badge_path_literally(monkeypatch, tmp_path):
+ monkeypatch.setattr(diagnose_mod, "_write_badge", lambda badge_path, svg: None)
+ result, out = _run(monkeypatch, tmp_path, "run1", "--badge", FILE_TEXT)
+ _ok(result)
+ _assert_shown_literally(out)
+ assert "Badge written" in out
+
+
+def test_badge_error_shows_the_exception_text_literally(monkeypatch, tmp_path):
+ def _refuse(badge_path, svg):
+ raise ValueError(f"badge path {badge_path} must stay under cwd")
+
+ monkeypatch.setattr(diagnose_mod, "_write_badge", _refuse)
+ result, out = _run(monkeypatch, tmp_path, "run1", "--badge", FILE_TEXT)
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ assert "cannot write --badge: ValueError: badge path" in out
+ _assert_shown_literally(out)
+
+
+def test_attached_line_shows_the_registry_id_literally(monkeypatch, tmp_path):
+ monkeypatch.setattr(attach_mod, "attach_artifact", lambda entry_id, kind, path: None)
+ result, out = _run(
+ monkeypatch, tmp_path, "run1", "--output", "report.json", "--attach-to-registry", FILE_TEXT
+ )
+ _ok(result)
+ assert "Attached" in out
+ _assert_shown_literally(out)
+
+
+def test_attach_warning_shows_the_exception_text_literally(monkeypatch, tmp_path):
+ def _missing(entry_id, kind, path):
+ raise ValueError(f"registry entry not found: {entry_id}")
+
+ monkeypatch.setattr(attach_mod, "attach_artifact", _missing)
+ result, out = _run(
+ monkeypatch, tmp_path, "run1", "--output", "report.json", "--attach-to-registry", FILE_TEXT
+ )
+ _ok(result)
+ assert "could not attach to registry: ValueError: registry entry not found:" in out
+ _assert_shown_literally(out)
+
+
+# ---------------------------------------------------------------------------
+# Input errors reported before the report is built
+# ---------------------------------------------------------------------------
+
+
+def test_citation_style_error_shows_the_exception_text_literally(monkeypatch, tmp_path):
+ def _reject(value):
+ raise ValueError(f"unknown citation_style {value}")
+
+ monkeypatch.setattr(citation_mod, "validate_citation_style", _reject)
+ result, out = _run(monkeypatch, tmp_path, "run1", "--citation-style", FILE_TEXT)
+ assert result.exit_code == 2, (result.output, repr(result.exception))
+ assert "Invalid --citation-style: unknown citation_style" in out
+ _assert_shown_literally(out)
+
+
+def test_citation_style_error_from_the_real_validator_has_no_control_bytes(
+ monkeypatch, tmp_path
+):
+ # The validator caps the name at 32 characters and quotes it with repr().
+ value = "Z" + ESC + "[31m" + CSI_C1 + DEL + "[b]x[/b]Q"
+ result, out = _run(monkeypatch, tmp_path, "run1", "--citation-style", value)
+ assert result.exit_code == 2, (result.output, repr(result.exception))
+ assert "Invalid --citation-style: unknown citation_style" in out
+ _assert_no_control_bytes(out)
+ assert "[b]x[/b]Q" in out, out
+
+
+def test_tokenizer_error_shows_the_loader_text_literally(monkeypatch, tmp_path):
+ """The loader's own message repeats the id as given; the wrapper quotes it too."""
+
+ def _from_pretrained(name, *args, **kwargs):
+ raise OSError(f"{name} is not a local folder and is not a valid model identifier")
+
+ transformers = types.ModuleType("transformers")
+ transformers.AutoTokenizer = types.SimpleNamespace(from_pretrained=_from_pretrained)
+ monkeypatch.setitem(sys.modules, "transformers", transformers)
+ monkeypatch.setattr(
+ live_mod,
+ "run_live_diagnose",
+ lambda **kwargs: pytest.fail("the model must not load after a tokenizer error"),
+ )
+ result, out = _run(
+ monkeypatch, tmp_path, "run1", "--base-model", "org/m", "--tokenizer", FILE_TEXT
+ )
+ assert result.exit_code == EXIT_USAGE_ERROR, (result.output, repr(result.exception))
+ assert "could not load tokenizer" in out
+ _assert_shown_literally(out)
+
+
+def test_live_failure_shows_the_exception_text_literally(monkeypatch, tmp_path):
+ def _fail(**kwargs):
+ raise RuntimeError(f"row 3 of d.jsonl: {FILE_TEXT}")
+
+ monkeypatch.setattr(live_mod, "run_live_diagnose", _fail)
+ result, out = _run(monkeypatch, tmp_path, "run1", "--base-model", "org/m")
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ assert "live diagnose failed: RuntimeError: row 3 of d.jsonl:" in out
+ _assert_shown_literally(out)
+
+
+# ---------------------------------------------------------------------------
+# Evidence values quoted in a usage error (printed by Typer, not by the module)
+# ---------------------------------------------------------------------------
+
+
[email protected]("field", ["score", "verdict"])
+def test_rejected_evidence_value_is_quoted_with_repr(monkeypatch, tmp_path, field):
+ """These messages quote the value with ``repr()`` and Typer prints them as text."""
+ value = "Z" + ESC + "]0;T" + BEL + CSI_C1 + DEL + BACKSPACE + "[red]x[/red]Q"
+ entry = {"score": 1.0, "evidence": "plain"}
+ entry[field] = value
+ result, _ = _run(monkeypatch, tmp_path, "run1", evidence={"scores": {"forgetting": entry}})
+ assert result.exit_code == 2, (result.output, repr(result.exception))
+ for char in (BEL, CSI_C1, DEL, BACKSPACE):
+ assert char not in result.output, repr(result.output)
+ assert ESC + "]0;T" not in result.output, repr(result.output)
+ shown = "".join(strip_ansi(result.output).replace(chr(0x2502), "").split())
+ assert "[red]x[/red]Q" in shown, result.output
+ assert BACKSLASH + "x1b]0;T" in shown, result.output
+
+
+# ---------------------------------------------------------------------------
+# What is left on rich.markup.escape
+# ---------------------------------------------------------------------------
+
+
+def test_plain_escape_is_left_only_on_text_the_program_wrote():
+ """A mode name is a constant and an exception class name is an identifier."""
+ tree = ast.parse(Path(diagnose_mod.__file__).read_text(encoding="utf-8"))
+ arguments = sorted(
+ {
+ ast.unparse(node.args[0])
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "escape"
+ }
+ )
+ assert arguments == ["mode", "type(exc).__name__"], arguments
diff --git a/tests/test_eval_unlearning_terminal_output.py b/tests/test_eval_unlearning_terminal_output.py
new file mode 100644
index 00000000..8ba41934
--- /dev/null
+++ b/tests/test_eval_unlearning_terminal_output.py
@@ -0,0 +1,325 @@
+"""``soup eval unlearning`` prints text it did not write as text.
+
+The command interpolates the run id, the ``--output`` path, the registry entry
+id, the evidence line of every metric and the text of the exceptions it
+reports into Rich markup. Each went through ``rich.markup.escape`` alone,
+which neutralises ``[...]`` tags and leaves ESC, DEL and the C1 range
+U+0080-U+009F in place. Each now goes through
+``soup_cli.utils.terminal.for_terminal``.
+
+Every test drives the real command line: the command is registered on a fresh
+Typer app with ``Console(file=StringIO(), color_system=None)``, so Rich emits
+no styling of its own and any control byte in the capture came from the value.
+Control characters are asserted on the UTF-8 bytes of the capture. Non-ASCII
+characters are built with ``chr()`` so this file stays ASCII.
+"""
+
+from __future__ import annotations
+
+import ast
+import dataclasses
+import json
+from io import StringIO
+from pathlib import Path
+
+import pytest
+import typer
+from rich.console import Console
+from typer.testing import CliRunner
+
+import soup_cli.commands._eval_v0610 as unlearning_cmd
+import soup_cli.registry.attach as attach_mod
+import soup_cli.utils.unlearning_eval as unlearning_eval
+
+runner = CliRunner()
+
+ESC = chr(27)
+BEL = chr(7)
+BACKSPACE = chr(8)
+CARRIAGE_RETURN = chr(13)
+DEL = chr(0x7F)
+CSI_C1 = chr(0x9B)
+ST_C1 = chr(0x9C)
+OSC_C1 = chr(0x9D)
+BACKSLASH = chr(92)
+
+MARKUP = "[red]x[/red][link=http://h/]y[/link][/]"
+
+#: name -> (text as given, text the terminal must show)
+SEQUENCES = {
+ "csi-colour": ("ZQ" + ESC + "[31mQZ", "ZQ[31mQZ"),
+ "osc-title": ("ZQ" + ESC + "]0;T" + BEL + "QZ", "ZQ]0;TQZ"),
+ "osc-hyperlink": (
+ "ZQ" + ESC + "]8;;http://h/" + ESC + BACKSLASH + "QZ",
+ "ZQ]8;;http://h/" + BACKSLASH + "QZ",
+ ),
+ "bel": ("ZQ" + BEL + "QZ", "ZQQZ"),
+ "backspace": ("ZQ" + BACKSPACE + "QZ", "ZQQZ"),
+ "carriage-return": ("ZQ" + CARRIAGE_RETURN + "QZ", "ZQQZ"),
+ "del": ("ZQ" + DEL + "QZ", "ZQQZ"),
+ "c1-csi": ("ZQ" + CSI_C1 + "2JQZ", "ZQ2JQZ"),
+ "c1-osc": ("ZQ" + OSC_C1 + "0;T" + ST_C1 + "QZ", "ZQ0;TQZ"),
+}
+
+#: One value carrying every sequence above plus tag pairs and a bare closing tag.
+FILE_TEXT = (
+ "ZQ"
+ + ESC + "[31m"
+ + ESC + "]0;T" + BEL
+ + ESC + "]8;;http://h/" + ESC + BACKSLASH
+ + "-" + BACKSPACE + CARRIAGE_RETURN + DEL
+ + CSI_C1 + "2J"
+ + OSC_C1 + "0;T" + ST_C1
+ + MARKUP
+ + "QZ"
+)
+
+#: What the terminal must show for it: controls gone, brackets literal.
+SHOWN = "ZQ[31m]0;T]8;;http://h/" + BACKSLASH + "-2J0;T" + MARKUP + "QZ"
+
+#: Raw byte strings that must never be in a capture.
+RAW_CONTROLS = {
+ "ESC": ESC.encode("utf-8"),
+ "BEL": BEL.encode("utf-8"),
+ "BACKSPACE": BACKSPACE.encode("utf-8"),
+ "CARRIAGE RETURN": CARRIAGE_RETURN.encode("utf-8"),
+ "DEL": DEL.encode("utf-8"),
+ "C1 CSI": CSI_C1.encode("utf-8"),
+ "C1 ST": ST_C1.encode("utf-8"),
+ "C1 OSC": OSC_C1.encode("utf-8"),
+}
+
+
+def _is_control(char: str) -> bool:
+ code = ord(char)
+ return (code < 0x20 and char not in "\t\n") or 0x7F <= code <= 0x9F
+
+
+def _assert_no_control_bytes(out: str) -> None:
+ raw = out.encode("utf-8")
+ found = [name for name, needle in RAW_CONTROLS.items() if needle in raw]
+ assert not found, (found, raw)
+ stray = sorted({f"U+{ord(char):04X}" for char in out if _is_control(char)})
+ assert not stray, (stray, raw)
+
+
+def _flat(out: str) -> str:
+ """Drop all whitespace: a table title wraps to the table's width."""
+ return "".join(out.split())
+
+
+def _assert_shown_literally(out: str, *, times: int = 1) -> None:
+ _assert_no_control_bytes(out)
+ assert _flat(out).count(SHOWN) == times, out
+
+
+def _run(monkeypatch, tmp_path, *args):
+ """Invoke ``unlearning`` in ``tmp_path``; return (result, console capture)."""
+ monkeypatch.chdir(tmp_path)
+ buffer = StringIO()
+ eval_app = typer.Typer()
+
+ @eval_app.callback()
+ def _root() -> None:
+ """Keep ``unlearning`` a named subcommand, as under ``soup eval``."""
+
+ unlearning_cmd.register(eval_app, Console(file=buffer, color_system=None, width=400))
+ result = runner.invoke(eval_app, ["unlearning", *args])
+ return result, buffer.getvalue()
+
+
+def _exit(result, code: int) -> None:
+ assert result.exit_code == code, (result.output, repr(result.exception))
+
+
+def _with_evidence_text(monkeypatch, text: str) -> None:
+ """Make every metric of the report carry ``text`` as its evidence line."""
+ real = unlearning_eval.run_unlearn_eval
+
+ def _run_eval(**kwargs):
+ report = real(**kwargs)
+ metrics = tuple(dataclasses.replace(m, evidence=text) for m in report.metrics)
+ return dataclasses.replace(report, metrics=metrics)
+
+ monkeypatch.setattr(unlearning_eval, "run_unlearn_eval", _run_eval)
+
+
+# ---------------------------------------------------------------------------
+# The report table
+# ---------------------------------------------------------------------------
+
+
[email protected]("name", sorted(SEQUENCES))
+def test_table_title_drops_each_control_sequence_of_the_run_id(monkeypatch, tmp_path, name):
+ given, shown = SEQUENCES[name]
+ result, out = _run(monkeypatch, tmp_path, given)
+ _exit(result, 0)
+ _assert_no_control_bytes(out)
+ assert _flat(out).count(shown) == 1, out
+
+
+def test_table_title_shows_the_run_id_literally(monkeypatch, tmp_path):
+ result, out = _run(monkeypatch, tmp_path, FILE_TEXT)
+ _exit(result, 0)
+ _assert_shown_literally(out)
+
+
+def test_evidence_column_is_shown_literally(monkeypatch, tmp_path):
+ _with_evidence_text(monkeypatch, FILE_TEXT)
+ result, out = _run(monkeypatch, tmp_path, "run1")
+ _exit(result, 0)
+ _assert_shown_literally(out, times=3)
+
+
+ "markup",
+ [
+ "[red]x[/red]",
+ "[link=http://h/]y[/link]",
+ "[bold]never closed",
+ "closed but never opened[/]",
+ "[/red]",
+ ],
+)
+def test_evidence_column_prints_markup_as_literal_text(monkeypatch, tmp_path, markup):
+ _with_evidence_text(monkeypatch, "ZQ" + markup + "QZ")
+ result, out = _run(monkeypatch, tmp_path, "run1")
+ _exit(result, 0)
+ assert out.count("ZQ" + markup + "QZ") == 3, out
+
+
+def test_evidence_column_keeps_ordinary_non_ascii_text(monkeypatch, tmp_path):
+ # e-acute, inverted exclamation mark (first code point after the C1 range),
+ # a Cyrillic and a CJK letter, and a character outside the BMP.
+ text = "caf" + chr(0xE9) + chr(0xA1) + chr(0x416) + chr(0x65E5) + chr(0x1D11E) + "~end"
+ _with_evidence_text(monkeypatch, text)
+ result, out = _run(monkeypatch, tmp_path, "run1")
+ _exit(result, 0)
+ assert out.count(text) == 3, out
+ _assert_no_control_bytes(out)
+
+
+# ---------------------------------------------------------------------------
+# Input errors
+# ---------------------------------------------------------------------------
+
+
+def test_benchmark_error_shows_the_exception_text_literally(monkeypatch, tmp_path):
+ def _reject(value):
+ raise ValueError(f"unknown benchmark {value}")
+
+ monkeypatch.setattr(unlearning_eval, "validate_benchmark_name", _reject)
+ result, out = _run(monkeypatch, tmp_path, "run1", "--benchmark", FILE_TEXT)
+ _exit(result, 2)
+ assert "Invalid benchmark: unknown benchmark" in out
+ _assert_shown_literally(out)
+
+
+def test_benchmark_error_from_the_real_validator_has_no_control_bytes(monkeypatch, tmp_path):
+ # The validator caps the name at a short length and quotes it with repr().
+ value = "Z" + ESC + "[31m" + CSI_C1 + DEL + "[b]x[/b]Q"
+ result, out = _run(monkeypatch, tmp_path, "run1", "--benchmark", value)
+ _exit(result, 2)
+ assert "Invalid benchmark: unknown benchmark" in out
+ _assert_no_control_bytes(out)
+ assert "[b]x[/b]Q" in out, out
+
+
+def test_invalid_json_error_shows_the_exception_text_literally(monkeypatch, tmp_path):
+ def _load(path):
+ raise json.JSONDecodeError(f"cannot parse {path}", "{", 0)
+
+ monkeypatch.setattr(unlearning_eval, "load_evidence_file", _load)
+ result, out = _run(monkeypatch, tmp_path, "run1", "--evidence", FILE_TEXT)
+ _exit(result, 2)
+ assert "Evidence file is not valid JSON: cannot parse" in out
+ _assert_shown_literally(out)
+
+
+def test_evidence_read_error_shows_the_exception_text_literally(monkeypatch, tmp_path):
+ def _load(path):
+ raise ValueError(f"evidence path must stay under cwd: {path}")
+
+ monkeypatch.setattr(unlearning_eval, "load_evidence_file", _load)
+ result, out = _run(monkeypatch, tmp_path, "run1", "--evidence", FILE_TEXT)
+ _exit(result, 2)
+ assert "Cannot read evidence: evidence path must stay under cwd:" in out
+ _assert_shown_literally(out)
+
+
+def test_eval_failure_shows_the_exception_text_literally(monkeypatch, tmp_path):
+ def _fail(**kwargs):
+ raise ValueError(f"cannot score run {kwargs['run_id']}")
+
+ monkeypatch.setattr(unlearning_eval, "run_unlearn_eval", _fail)
+ result, out = _run(monkeypatch, tmp_path, FILE_TEXT)
+ _exit(result, 2)
+ assert "Eval failed: cannot score run" in out
+ _assert_shown_literally(out)
+
+
+# ---------------------------------------------------------------------------
+# --output and --attach-to-registry lines
+# ---------------------------------------------------------------------------
+
+
+def test_wrote_line_shows_the_output_path_literally(monkeypatch, tmp_path):
+ monkeypatch.setattr(unlearning_eval, "write_unlearn_report", lambda report, path: path)
+ result, out = _run(monkeypatch, tmp_path, "run1", "--output", FILE_TEXT)
+ _exit(result, 0)
+ assert "Wrote report ->" in out
+ _assert_shown_literally(out)
+
+
+def test_write_error_shows_the_exception_text_literally(monkeypatch, tmp_path):
+ def _refuse(report, path):
+ raise ValueError(f"report path {path} must stay under cwd")
+
+ monkeypatch.setattr(unlearning_eval, "write_unlearn_report", _refuse)
+ result, out = _run(monkeypatch, tmp_path, "run1", "--output", FILE_TEXT)
+ _exit(result, 2)
+ assert "Cannot write report: report path" in out
+ _assert_shown_literally(out)
+
+
+def test_attached_line_shows_the_registry_id_literally(monkeypatch, tmp_path):
+ monkeypatch.setattr(attach_mod, "attach_artifact", lambda **kwargs: None)
+ result, out = _run(
+ monkeypatch, tmp_path, "run1", "--output", "report.json", "--attach-to-registry", FILE_TEXT
+ )
+ _exit(result, 0)
+ assert "Attached eval_results -> registry" in out
+ _assert_shown_literally(out)
+
+
+def test_attach_failure_shows_the_exception_text_literally(monkeypatch, tmp_path):
+ def _missing(**kwargs):
+ raise ValueError(f"registry entry not found: {kwargs['entry_id']}")
+
+ monkeypatch.setattr(attach_mod, "attach_artifact", _missing)
+ result, out = _run(
+ monkeypatch, tmp_path, "run1", "--output", "report.json", "--attach-to-registry", FILE_TEXT
+ )
+ _exit(result, 0)
+ assert "Registry attach failed: registry entry not found:" in out
+ _assert_shown_literally(out)
+
+
+# ---------------------------------------------------------------------------
+# What is left on rich.markup.escape
+# ---------------------------------------------------------------------------
+
+
+def test_plain_escape_is_left_only_on_values_from_closed_sets():
+ """Benchmark, metric name and verdicts are validated against fixed tuples."""
+ tree = ast.parse(Path(unlearning_cmd.__file__).read_text(encoding="utf-8"))
+ arguments = sorted(
+ {
+ ast.unparse(node.args[0])
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "escape"
+ }
+ )
+ assert arguments == ["bench", "m.name", "m.verdict", "report.overall"], arguments
diff --git a/tests/test_train_diagnose_gate_terminal_output.py b/tests/test_train_diagnose_gate_terminal_output.py
new file mode 100644
index 00000000..7e05afc7
--- /dev/null
+++ b/tests/test_train_diagnose_gate_terminal_output.py
@@ -0,0 +1,248 @@
+"""``soup train --diagnose-gate`` prints evidence-file text as text.
+
+The gate reads a JSON evidence file after training and prints the evidence
+line of every MAJOR / NOT_RUN mode, or the reason the file was refused. The
+evidence lines went through ``rich.markup.escape`` alone, which leaves ESC,
+DEL and the C1 range U+0080-U+009F in place; the refusal line interpolated the
+exception text into Rich markup with no escaping at all, so a ``[...]`` tag
+quoted in the message was read as markup. All three now go through
+``soup_cli.utils.terminal.for_terminal``.
+
+The tests call the gate helpers of ``soup_cli.commands.train`` directly, with
+the module's console swapped for ``Console(file=StringIO(), color_system=None)``
+so Rich emits no styling of its own: any control byte in the capture came from
+the value. Control characters are asserted on the UTF-8 bytes of the capture.
+Non-ASCII characters are built with ``chr()`` so this file stays ASCII.
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+from io import StringIO
+from pathlib import Path
+
+import pytest
+import typer
+from rich.console import Console
+
+import soup_cli.commands.train as train_mod
+from soup_cli.utils.exit_codes import EXIT_USAGE_ERROR
+
+ESC = chr(27)
+BEL = chr(7)
+BACKSPACE = chr(8)
+CARRIAGE_RETURN = chr(13)
+DEL = chr(0x7F)
+CSI_C1 = chr(0x9B)
+ST_C1 = chr(0x9C)
+OSC_C1 = chr(0x9D)
+BACKSLASH = chr(92)
+
+MARKUP = "[red]x[/red][link=http://h/]y[/link][/]"
+
+#: name -> (text as stored in the file, text the terminal must show)
+SEQUENCES = {
+ "csi-colour": ("ZQ" + ESC + "[31mQZ", "ZQ[31mQZ"),
+ "osc-title": ("ZQ" + ESC + "]0;T" + BEL + "QZ", "ZQ]0;TQZ"),
+ "osc-hyperlink": (
+ "ZQ" + ESC + "]8;;http://h/" + ESC + BACKSLASH + "QZ",
+ "ZQ]8;;http://h/" + BACKSLASH + "QZ",
+ ),
+ "bel": ("ZQ" + BEL + "QZ", "ZQQZ"),
+ "backspace": ("ZQ" + BACKSPACE + "QZ", "ZQQZ"),
+ "carriage-return": ("ZQ" + CARRIAGE_RETURN + "QZ", "ZQQZ"),
+ "del": ("ZQ" + DEL + "QZ", "ZQQZ"),
+ "c1-csi": ("ZQ" + CSI_C1 + "2JQZ", "ZQ2JQZ"),
+ "c1-osc": ("ZQ" + OSC_C1 + "0;T" + ST_C1 + "QZ", "ZQ0;TQZ"),
+}
+
+#: One value carrying every sequence above plus tag pairs and a bare closing tag.
+FILE_TEXT = (
+ "ZQ"
+ + ESC + "[31m"
+ + ESC + "]0;T" + BEL
+ + ESC + "]8;;http://h/" + ESC + BACKSLASH
+ + "-" + BACKSPACE + CARRIAGE_RETURN + DEL
+ + CSI_C1 + "2J"
+ + OSC_C1 + "0;T" + ST_C1
+ + MARKUP
+ + "QZ"
+)
+
+#: What the terminal must show for it: controls gone, brackets literal.
+SHOWN = "ZQ[31m]0;T]8;;http://h/" + BACKSLASH + "-2J0;T" + MARKUP + "QZ"
+
+#: Raw byte strings that must never be in a capture.
+RAW_CONTROLS = {
+ "ESC": ESC.encode("utf-8"),
+ "BEL": BEL.encode("utf-8"),
+ "BACKSPACE": BACKSPACE.encode("utf-8"),
+ "CARRIAGE RETURN": CARRIAGE_RETURN.encode("utf-8"),
+ "DEL": DEL.encode("utf-8"),
+ "C1 CSI": CSI_C1.encode("utf-8"),
+ "C1 ST": ST_C1.encode("utf-8"),
+ "C1 OSC": OSC_C1.encode("utf-8"),
+}
+
+#: verdict -> (a score FailureScore accepts for it, the gate's exit code)
+GATED = {"MAJOR": (0.1, 2), "NOT_RUN": (0.0, EXIT_USAGE_ERROR)}
+
+
+def _is_control(char: str) -> bool:
+ code = ord(char)
+ return (code < 0x20 and char not in "\t\n") or 0x7F <= code <= 0x9F
+
+
+def _assert_no_control_bytes(out: str) -> None:
+ raw = out.encode("utf-8")
+ found = [name for name, needle in RAW_CONTROLS.items() if needle in raw]
+ assert not found, (found, raw)
+ stray = sorted({f"U+{ord(char):04X}" for char in out if _is_control(char)})
+ assert not stray, (stray, raw)
+
+
+def _capture(monkeypatch) -> StringIO:
+ buffer = StringIO()
+ monkeypatch.setattr(
+ train_mod, "console", Console(file=buffer, color_system=None, width=400)
+ )
+ return buffer
+
+
+def _gate(monkeypatch, tmp_path, verdict: str, text: str, *, ensure_ascii: bool = True):
+ """Run the gate on one ``format`` entry; return (exit code, console capture)."""
+ monkeypatch.chdir(tmp_path)
+ score, _ = GATED[verdict]
+ entry = {"score": score, "verdict": verdict, "evidence": text}
+ (tmp_path / "ev.json").write_text(
+ json.dumps({"scores": {"format": entry}}, ensure_ascii=ensure_ascii),
+ encoding="utf-8",
+ )
+ buffer = _capture(monkeypatch)
+ with pytest.raises(typer.Exit) as excinfo:
+ train_mod._run_diagnose_gate("ev.json", "run1", "base", "adapter")
+ return excinfo.value.exit_code, buffer.getvalue()
+
+
+# ---------------------------------------------------------------------------
+# The evidence line of a MAJOR / NOT_RUN mode
+# ---------------------------------------------------------------------------
+
+
[email protected]("verdict", sorted(GATED))
[email protected]("name", sorted(SEQUENCES))
+def test_gate_evidence_line_drops_each_control_sequence(monkeypatch, tmp_path, verdict, name):
+ stored, shown = SEQUENCES[name]
+ code, out = _gate(monkeypatch, tmp_path, verdict, stored)
+ assert code == GATED[verdict][1], out
+ _assert_no_control_bytes(out)
+ assert out.count(f"{verdict} format: {shown}\n") == 1, out
+
+
[email protected]("verdict", sorted(GATED))
+def test_gate_evidence_line_is_shown_literally(monkeypatch, tmp_path, verdict):
+ code, out = _gate(monkeypatch, tmp_path, verdict, FILE_TEXT)
+ assert code == GATED[verdict][1], out
+ _assert_no_control_bytes(out)
+ assert out.count(f"{verdict} format: {SHOWN}\n") == 1, out
+
+
[email protected]("verdict", sorted(GATED))
+ "markup",
+ [
+ "[red]x[/red]",
+ "[link=http://h/]y[/link]",
+ "[bold]never closed",
+ "closed but never opened[/]",
+ "[/red]",
+ ],
+)
+def test_gate_evidence_line_prints_markup_as_literal_text(
+ monkeypatch, tmp_path, verdict, markup
+):
+ code, out = _gate(monkeypatch, tmp_path, verdict, "ZQ" + markup + "QZ")
+ assert code == GATED[verdict][1], out
+ assert out.count(f"{verdict} format: ZQ{markup}QZ\n") == 1, out
+
+
[email protected]("verdict", sorted(GATED))
+def test_gate_evidence_line_keeps_ordinary_non_ascii_text(monkeypatch, tmp_path, verdict):
+ # e-acute, inverted exclamation mark (first code point after the C1 range),
+ # a Cyrillic and a CJK letter, and a character outside the BMP.
+ text = "caf" + chr(0xE9) + chr(0xA1) + chr(0x416) + chr(0x65E5) + chr(0x1D11E) + "~end"
+ code, out = _gate(monkeypatch, tmp_path, verdict, text, ensure_ascii=False)
+ assert code == GATED[verdict][1], out
+ assert out.count(f"{verdict} format: {text}\n") == 1, out
+ _assert_no_control_bytes(out)
+
+
+# ---------------------------------------------------------------------------
+# The "--diagnose-gate failed" line
+# ---------------------------------------------------------------------------
+
+
+def test_gate_failure_line_quotes_a_refused_verdict_literally(monkeypatch, tmp_path):
+ """The refusal quotes the verdict with repr(); its brackets are not markup."""
+ monkeypatch.chdir(tmp_path)
+ verdict = "ZQ" + ESC + "]0;T" + BEL + CSI_C1 + MARKUP + "QZ"
+ entry = {"score": 1.0, "verdict": verdict, "evidence": "plain"}
+ (tmp_path / "ev.json").write_text(
+ json.dumps({"scores": {"format": entry}}), encoding="utf-8"
+ )
+ buffer = _capture(monkeypatch)
+ with pytest.raises(typer.Exit) as excinfo:
+ train_mod._run_diagnose_gate_or_exit("ev.json", "run1", "base", "adapter")
+ out = buffer.getvalue()
+ assert excinfo.value.exit_code == 1, out
+ assert "--diagnose-gate failed: ValueError: verdict must be one of" in out
+ _assert_no_control_bytes(out)
+ assert out.count(MARKUP + "QZ'") == 1, out
+
+
[email protected]("error", [ValueError, OSError])
+def test_gate_failure_line_shows_the_exception_text_literally(monkeypatch, error):
+ def _refuse(evidence_path, run_id, base, adapter):
+ raise error(f"cannot use {evidence_path}")
+
+ monkeypatch.setattr(train_mod, "_run_diagnose_gate", _refuse)
+ buffer = _capture(monkeypatch)
+ with pytest.raises(typer.Exit) as excinfo:
+ train_mod._run_diagnose_gate_or_exit(FILE_TEXT, "run1", "base", "adapter")
+ out = buffer.getvalue()
+ assert excinfo.value.exit_code == 1, out
+ _assert_no_control_bytes(out)
+ assert out.count(f"--diagnose-gate failed: {error.__name__}: cannot use {SHOWN}\n") == 1, out
+
+
[email protected]("verdict", sorted(GATED))
+def test_gate_exit_code_passes_through_the_failure_handler(monkeypatch, tmp_path, verdict):
+ monkeypatch.chdir(tmp_path)
+ score, code = GATED[verdict]
+ entry = {"score": score, "verdict": verdict, "evidence": "plain"}
+ (tmp_path / "ev.json").write_text(
+ json.dumps({"scores": {"format": entry}}), encoding="utf-8"
+ )
+ buffer = _capture(monkeypatch)
+ with pytest.raises(typer.Exit) as excinfo:
+ train_mod._run_diagnose_gate_or_exit("ev.json", "run1", "base", "adapter")
+ assert excinfo.value.exit_code == code, buffer.getvalue()
+ assert "--diagnose-gate failed" not in buffer.getvalue()
+
+
+def test_train_runs_the_gate_through_the_failure_handler():
+ """``train`` is too heavy to drive here; pin which helper it calls."""
+ tree = ast.parse(Path(train_mod.__file__).read_text(encoding="utf-8"))
+ train_def = next(
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef) and node.name == "train"
+ )
+ called = {
+ node.func.id
+ for node in ast.walk(train_def)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
+ }
+ assert "_run_diagnose_gate_or_exit" in called
+ assert "_run_diagnose_gate" not in called