Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(cli): exit non-zero when nothing succeeded in sweep, cmaes merge, drift-alarm, eval auto and loop watch --detach (#1905)
ndablizovf2e762b4fc64
diff --git a/changelog.d/0.76.0/1905.fixed.md b/changelog.d/0.76.0/1905.fixed.mdnew file mode 100644index 00000000..0fda2049--- /dev/null+++ b/changelog.d/0.76.0/1905.fixed.md@@ -0,0 +1 @@+- Five commands no longer exit 0 when nothing succeeded or nothing was compared: `soup sweep` exits 1 when every arm failed (one completed arm still exits 0); a CMA-ES merge in which every evaluation failed raises instead of writing a "converged" merge of the first sample, `converged` requires a real score, and `soup adapters merge --strategy cmaes` exits non-zero and writes no adapter (its missing-`--eval` message now says `.jsonl`); `soup drift-alarm` exits 1 and shows no OK panel when it could read no live or reference row, naming the file and the keys it reads (`output`, `response`, `text`); `soup eval auto` exits 1 when no leg evaluated anything, with the same code whichever leg failed; `soup loop watch --detach` validates `--poll-interval` / `--max-iterations` in the parent and spawns no child when they are invalid (#1808 by @ndablizov in #1905)diff --git a/docs/evaluation.md b/docs/evaluation.mdindex 6af3a689..eab1987b 100644--- a/docs/evaluation.md+++ b/docs/evaluation.md@@ -341,6 +341,8 @@ soup drift-alarm --reference ft-time.jsonl --live yesterday.jsonl --threshold 0.Default threshold 0.2 matches v0.43.0 KL-delta quant-check thresholds. Webhooks are SSRF-validated (loopback HTTP only, RFC1918 / 169.254.x / `100.64.0.0/10` / `fec0::/10` / 0.0.0.0 rejected). On drift the CLI exits with code 3 — cron-friendly automation.+Each JSONL row's text is read from `output`, `response` or `text`. A file in which no row carries one of those keys (a live log keyed `completion`, an empty file, all-malformed JSON) is not a passing gate: nothing was compared, so the command exits 1 naming the file and the keys instead of printing OK with `n_live: 0` (#1808).+## Diagnose (Post-Training Report Card)diff --git a/src/soup_cli/commands/adapters.py b/src/soup_cli/commands/adapters.pyindex 2f5efdc1..7cd8e795 100644--- a/src/soup_cli/commands/adapters.py+++ b/src/soup_cli/commands/adapters.py@@ -433,7 +433,7 @@ def merge(if eval_suite is None:console.print("[red]--strategy cmaes requires --eval <suite> "- "(path to a YAML/JSONL eval).[/]"+ "(path to a .jsonl eval suite; the loader accepts .jsonl only).[/]")raise typer.Exit(2)if canary is not None or strict_verdict:diff --git a/src/soup_cli/commands/eval.py b/src/soup_cli/commands/eval.pyindex 5a7cc71d..cff05cbe 100644--- a/src/soup_cli/commands/eval.py+++ b/src/soup_cli/commands/eval.py@@ -730,6 +730,10 @@ def auto(border_style="blue",))+ # #1808: a leg that could not run used to be swallowed, and "Auto-eval+ # complete." exited 0 even when it was the only leg. Count what ran.+ legs_ran = 0+# Run standard benchmarks if specifiedif bench_list:console.print("\n[bold]Standard Benchmarks[/]")@@ -749,6 +753,8 @@ def auto(# benchmark failure aborted the whole auto-eval instead of falling# through to the custom eval below.console.print("[yellow]Benchmark eval skipped (see above).[/]")+ else:+ legs_ran += 1# Run custom eval if specifiedif tasks_file:@@ -767,8 +773,20 @@ def auto(output=None,trust_remote_code=trust_remote_code,)- except SystemExit:+ except (typer.Exit, SystemExit):+ # The same pair as the benchmark leg (#1808): custom() also fails+ # with typer.Exit, which `except SystemExit` alone never caught, so+ # the exit code depended on which leg had failed.console.print("[yellow]Custom eval skipped (see above).[/]")+ else:+ legs_ran += 1++ if legs_ran == 0:+ console.print(+ "\n[red]Auto-eval failed: nothing was evaluated.[/] Every leg was skipped "+ "(see above); fix the cause and run again."+ )+ raise typer.Exit(1)console.print("\n[green]Auto-eval complete.[/]")diff --git a/src/soup_cli/commands/loop.py b/src/soup_cli/commands/loop.pyindex c5dc42ff..830fdf06 100644--- a/src/soup_cli/commands/loop.py+++ b/src/soup_cli/commands/loop.py@@ -249,6 +249,14 @@ def watch_cmd("never read it; run `soup loop watch --pre-wired` to harvest it")if detach:+ # #1808: the child validates these in WatchConfig.__post_init__ and exits+ # 2 with its output on /dev/null, while the parent printed "watch+ # detached". Run the same checks here, before anything is spawned.+ try:+ WatchConfig(poll_interval_sec=poll_interval, max_iterations=max_iterations)+ except (TypeError, ValueError) as exc:+ console.print(f"[red]invalid watch config:[/] {escape(str(exc))}")+ raise typer.Exit(code=2)argv = [sys.executable,"-m",diff --git a/src/soup_cli/commands/sweep.py b/src/soup_cli/commands/sweep.pyindex bdb8f5c6..5089551d 100644--- a/src/soup_cli/commands/sweep.py+++ b/src/soup_cli/commands/sweep.py@@ -289,6 +289,17 @@ def sweep(if skipped:console.print(f"\n[yellow]Early stopping: {skipped} run(s) skipped.[/]")+ # #1808: a sweep in which no arm completed used to return normally, so a+ # script chaining on the exit code read a table of "failed" rows as success.+ # One completed arm is still a sweep; none is a failure, named as such.+ completed_count = sum(1 for r in results if r["status"] == "completed")+ if results and completed_count == 0:+ console.print(+ f"\n[red]No sweep run completed: {len(results)} of {len(results)} "+ f"run(s) failed.[/] The first error is printed above each run."+ )+ raise typer.Exit(1)+def _parse_sweep_params(params: list[str]) -> dict[str, list]:"""Parse sweep parameter strings into a dict of {key: [values]}."""diff --git a/src/soup_cli/utils/cmaes_merge.py b/src/soup_cli/utils/cmaes_merge.pyindex 17602f05..489beb0b 100644--- a/src/soup_cli/utils/cmaes_merge.py+++ b/src/soup_cli/utils/cmaes_merge.py@@ -287,25 +287,36 @@ def _softmax(logits: Sequence[float]) -> Tuple[float, ...]:def _eval_safely(eval_fn: Callable[[Tuple[float, ...]], float],weights: Tuple[float, ...],+ failures: Optional[list[str]] = None,) -> float:"""Call ``eval_fn`` with sentinel-low score on exception.Failure isolation mirrors v0.40.3 #33 / v0.48 / v0.53.7 #106 policy:- one bad eval must not crash the whole run.+ one bad eval must not crash the whole run. When ``failures`` is given, the+ reason each failed evaluation was dropped is appended to it, so the caller+ can tell a search in which EVERY evaluation failed from one that converged+ (#1808): the sentinel alone cannot, since a flat sentinel history reads as+ a plateau."""++ def _failed(reason: str) -> float:+ if failures is not None:+ failures.append(reason)+ return _FAILED_EVAL_SENTINEL+try:score = eval_fn(weights)except (KeyboardInterrupt, SystemExit):raise- except Exception: # noqa: BLE001 — eval_fn surface is operator-controlled- return _FAILED_EVAL_SENTINEL+ except Exception as exc: # noqa: BLE001 — eval_fn surface is operator-controlled+ return _failed(f"{type(exc).__name__}: {exc}")if isinstance(score, bool):- return _FAILED_EVAL_SENTINEL+ return _failed(f"score was a bool ({score!r}), not a number")if not isinstance(score, (int, float)):- return _FAILED_EVAL_SENTINEL+ return _failed(f"score was {type(score).__name__}, not a number")s = float(score)if not math.isfinite(s):- return _FAILED_EVAL_SENTINEL+ return _failed(f"score {s!r} is not finite")return s@@ -359,6 +370,7 @@ def run_cmaes_merge(evaluations = 0converged = Falseplateau_run = 0+ failures: list[str] = []for gen in range(plan.max_generations):if (time.monotonic() - start) >= plan.budget_seconds:@@ -374,7 +386,7 @@ def run_cmaes_merge(# span the full simplex.logits = sample + [0.0]weights = _softmax(logits)- score = _eval_safely(eval_fn, weights)+ score = _eval_safely(eval_fn, weights, failures)evaluations += 1candidates.append((sample, weights, score))if score > best_score:@@ -400,10 +412,14 @@ def run_cmaes_merge(# Clamp to a sensible floor; CMA-ES typically blends with prior# but for ≤16-adapter case the simple rank-mu update converges.new_sigma.append(max(math.sqrt(var), 1e-4))- # Plateau detection+ # Plateau detection. A generation in which every candidate failed has a+ # sentinel "best"; a run of those is a flat history, not a plateau+ # (#1808), so it neither extends nor counts as convergence.gen_best = candidates[0][2]history.append(gen_best)- if len(history) >= 2:+ if gen_best <= _FAILED_EVAL_SENTINEL:+ plateau_run = 0+ elif len(history) >= 2:delta = abs(history[-1] - history[-2])if delta < convergence_tol:plateau_run += 1@@ -416,6 +432,18 @@ def run_cmaes_merge(sigma = new_sigmawall_clock = time.monotonic() - start+ if evaluations > 0 and len(failures) == evaluations:+ # #1808: every evaluation failed. Before this the sentinel scores read+ # as a converged search and the caller wrote a merge with the first+ # random sample's weights. Nothing was measured, so nothing can be+ # merged on the strength of it.+ first = failures[0]+ raise RuntimeError(+ f"every evaluation failed: {evaluations} evaluation(s) over "+ f"{generations_run} generation(s), none returned a finite score. "+ f"First failure: {first}. No merge is written; fix the eval suite or the "+ f"scorer and run again."+ )if best_score == -math.inf:# Defensive — should not happen because we always sample at least oncebest_score = 0.0diff --git a/src/soup_cli/utils/drift_alarm.py b/src/soup_cli/utils/drift_alarm.pyindex 91ad2d7f..b9a115bb 100644--- a/src/soup_cli/utils/drift_alarm.py+++ b/src/soup_cli/utils/drift_alarm.py@@ -227,6 +227,17 @@ def run_drift_check(ref_rows = _read_jsonl_outputs(reference_path)live_rows = _read_jsonl_outputs(live_path)+ # #1808: with nothing on one side the KL is 0.0 by construction, which read+ # as a green OK with n_live 0. Nothing was compared, so refuse by name: the+ # file, and the keys the reader takes a row's text from.+ for label, path, rows in (("reference", reference_path, ref_rows),+ ("live", live_path, live_rows)):+ if not rows:+ raise ValueError(+ f"{label} file {os.path.basename(path)!r} has 0 readable rows: each line "+ f"must be a JSON object with its text under 'output', 'response' or "+ f"'text'. Nothing was compared, so no drift verdict is possible."+ )ref_dist = compute_token_distribution(ref_rows)live_dist = compute_token_distribution(live_rows)kl = rolling_kl(live_dist, ref_dist) if (ref_dist and live_dist) else 0.0diff --git a/tests/test_cmaes_merge_all_evals_failed.py b/tests/test_cmaes_merge_all_evals_failed.pynew file mode 100644index 00000000..d507548f--- /dev/null+++ b/tests/test_cmaes_merge_all_evals_failed.py@@ -0,0 +1,198 @@+"""#1808 — a CMA-ES merge in which every evaluation failed is a failure, not a converged merge.++``_eval_safely`` turned every failed evaluation into the ``-1e9`` sentinel; the+plateau rule then saw a flat history, set ``converged=True``, and+``soup adapters merge --strategy cmaes`` wrote a merge with the first random+sample's weights, printed ``Converged: True`` in green and exited 0. The+missing-``--eval`` message also asked for "a YAML/JSONL eval" while the loader+accepts ``.jsonl`` only, which is one way to make every evaluation fail.+"""++from __future__ import annotations++import json+import math+from pathlib import Path++import pytest+from typer.testing import CliRunner++import soup_cli.utils.cmaes_merge as cm+from soup_cli.utils.cmaes_merge import CmaesPlan, run_cmaes_merge++from .conftest import strip_ansi+++def _plain(text: str) -> str:+ return " ".join(strip_ansi(text).split())+++def _plan(**overrides) -> CmaesPlan:+ kwargs = dict(adapters=("a", "b"), eval_suite="suite.jsonl", budget_seconds=600,+ population_size=4, max_generations=20, seed=0)+ kwargs.update(overrides)+ return CmaesPlan(**kwargs)+++# ---------------------------------------------------------------------------+# run_cmaes_merge+# ---------------------------------------------------------------------------+++ "eval_fn,reason",+ [+ pytest.param(lambda w: 1 / 0, "ZeroDivisionError", id="raises"),+ pytest.param(lambda w: float("nan"), "not finite", id="nan"),+ pytest.param(lambda w: None, "NoneType", id="none"),+ pytest.param(lambda w: True, "bool", id="bool"),+ ],+)+def test_every_evaluation_failing_raises_instead_of_converging(eval_fn, reason) -> None:+ with pytest.raises(RuntimeError) as exc:+ run_cmaes_merge(_plan(), eval_fn=eval_fn)+ msg = str(exc.value)+ assert "every evaluation failed" in msg.lower() or "all " in msg.lower()+ assert reason in msg # the first failure's reason is on screen+++def test_the_count_of_failed_evaluations_is_named() -> None:+ with pytest.raises(RuntimeError, match=r"\b\d+ evaluation"):+ run_cmaes_merge(_plan(population_size=3, max_generations=2), eval_fn=lambda w: 1 / 0)+++def test_control_one_real_score_among_failures_still_returns_a_result() -> None:+ calls = {"n": 0}++ def flaky(weights):+ calls["n"] += 1+ if calls["n"] == 2:+ return 0.7+ raise RuntimeError("scorer down")++ result = run_cmaes_merge(_plan(max_generations=3), eval_fn=flaky)+ assert result.best_score == pytest.approx(0.7)+ assert result.evaluations >= 2+++def test_convergence_needs_a_real_score_not_a_flat_sentinel_history() -> None:+ # Two generations of pure failures followed by real scores: the flat sentinel+ # stretch at the start must not count towards the plateau run.+ calls = {"n": 0}++ def late(weights):+ calls["n"] += 1+ if calls["n"] <= 8:+ raise RuntimeError("warming up")+ return 0.5++ result = run_cmaes_merge(_plan(population_size=4, max_generations=4), eval_fn=late)+ assert result.best_score == pytest.approx(0.5)+ assert result.converged is False+++def test_four_failed_generations_do_not_stop_the_search_as_converged() -> None:+ # The plateau reset on a sentinel generation (#1905 review): 16 failed+ # evaluations are four all-failed generations, enough for plateau_run to reach 3+ # if the sentinel counted as "no improvement". Without the reset the search+ # stops there as converged and never sees the real score that follows.+ calls = {"n": 0}++ def late(weights):+ calls["n"] += 1+ if calls["n"] <= 16:+ raise RuntimeError("warming up")+ return 0.5++ result = run_cmaes_merge(_plan(population_size=4, max_generations=8), eval_fn=late)+ assert result.best_score == pytest.approx(0.5)+ assert calls["n"] > 16+++def test_control_a_steady_scorer_still_converges() -> None:+ result = run_cmaes_merge(_plan(max_generations=10), eval_fn=lambda w: 0.6)+ assert result.converged is True+ assert math.isfinite(result.best_score)+++# ---------------------------------------------------------------------------+# soup adapters merge --strategy cmaes+# ---------------------------------------------------------------------------+++def _make_adapter(dir_path: Path) -> str:+ import numpy as np+ from safetensors.numpy import save_file++ dir_path.mkdir(parents=True, exist_ok=True)+ rng = np.random.default_rng(0)+ tensors = {+ "base_model.model.layers.0.self_attn.q_proj.lora_A.weight":+ rng.standard_normal((8, 16)).astype("float32"),+ "base_model.model.layers.0.self_attn.q_proj.lora_B.weight":+ rng.standard_normal((16, 8)).astype("float32"),+ }+ save_file(tensors, str(dir_path / "adapter_model.safetensors"))+ (dir_path / "adapter_config.json").write_text(json.dumps({+ "peft_type": "LORA", "r": 8, "lora_alpha": 16,+ "base_model_name_or_path": "hf-internal-testing/tiny-random-gpt2",+ }), encoding="utf-8")+ return str(dir_path)+++def two_adapters(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.chdir(tmp_path)+ a = _make_adapter(tmp_path / "a")+ b = _make_adapter(tmp_path / "b")+ suite = tmp_path / "eval.jsonl"+ suite.write_text('{"prompt": "p", "expected": "e"}\n', encoding="utf-8")+ return a, b, str(suite), tmp_path / "merged"+++def _merge(a, b, suite, out, *extra):+ from soup_cli.commands.adapters import app++ return CliRunner().invoke(app, [+ "merge", a, b, "--strategy", "cmaes", "--eval", suite, "--budget", "60s",+ "--population", "4", "--max-generations", "3", "-o", str(out), *extra,+ ])+++def test_cli_exits_non_zero_and_writes_nothing_when_every_evaluation_fails(+ two_adapters, monkeypatch+) -> None:+ def broken_scorer(merged_dir, suite):+ raise RuntimeError("scorer could not load the base")++ monkeypatch.setattr(cm, "_CMAES_SCORER_OVERRIDE", broken_scorer)+ a, b, suite, out = two_adapters+ result = _merge(a, b, suite, out)+ plain = _plain(result.output)+ assert result.exit_code == 2, (result.exit_code, plain)+ assert not out.exists(), "no merged adapter may be written"+ assert "Converged: True" not in plain+ assert "scorer could not load the base" in plain+++def test_cli_control_a_working_scorer_still_writes_the_merge(two_adapters, monkeypatch) -> None:+ monkeypatch.setattr(cm, "_CMAES_SCORER_OVERRIDE", lambda d, s: 0.6)+ a, b, suite, out = two_adapters+ result = _merge(a, b, suite, out)+ assert result.exit_code == 0, _plain(result.output)+ assert (out / "adapter_model.safetensors").is_file()+++def test_the_missing_eval_message_names_the_format_the_loader_accepts(+ two_adapters,+) -> None:+ from soup_cli.commands.adapters import app++ a, b, _, out = two_adapters+ result = CliRunner().invoke(app, [+ "merge", a, b, "--strategy", "cmaes", "-o", str(out), "--allow-unscanned",+ ])+ plain = _plain(result.output)+ assert result.exit_code == 2+ assert ".jsonl" in plain+ assert "YAML" not in plaindiff --git a/tests/test_drift_alarm_no_rows.py b/tests/test_drift_alarm_no_rows.pynew file mode 100644index 00000000..e452f7db--- /dev/null+++ b/tests/test_drift_alarm_no_rows.py@@ -0,0 +1,92 @@+"""#1808 — ``soup drift-alarm`` with nothing to compare is not OK.++With no readable live (or reference) row the KL was 0.0, so the command showed a+green OK with ``n_live: 0``, sent no webhook and exited 0; a live log keyed+``completion`` (or ``messages`` / ``choices``), an empty file or all-malformed+JSON all passed the gate. Now zero rows on either side exits 1 with a message+that names the file and the keys the reader looks for.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.utils.drift_alarm import run_drift_check++from .conftest import strip_ansi+++def _plain(text: str) -> str:+ return " ".join(strip_ansi(text).split())+++def _write(path: Path, key: str, texts: list[str]) -> str:+ path.write_text("".join(json.dumps({key: t}) + "\n" for t in texts), encoding="utf-8")+ return str(path.name)+++def files(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.chdir(tmp_path)+ ref = _write(tmp_path / "ref.jsonl", "output", [f"The answer is {i}." for i in range(20)])+ return tmp_path, ref+++def test_live_rows_under_an_unread_key_exit_non_zero_and_name_the_keys(files) -> None:+ tmp_path, ref = files+ live = _write(tmp_path / "live.jsonl", "completion", ["Something else entirely."] * 20)+ result = CliRunner().invoke(app, ["drift-alarm", "--reference", ref, "--live", live])+ out = _plain(result.output)+ assert result.exit_code == 1, (result.exit_code, out)+ assert "OK" not in out.split("drift-alarm")[-1][:40]+ assert "live.jsonl" in out+ for key in ("output", "response", "text"):+ assert key in out+ assert "0 readable" in out or "no readable" in out.lower()+++def test_reference_rows_under_an_unread_key_exit_non_zero_too(files) -> None:+ tmp_path, _ = files+ ref = _write(tmp_path / "ref2.jsonl", "completion", ["The answer is 1."] * 20)+ live = _write(tmp_path / "live.jsonl", "output", ["The answer is 1."] * 20)+ result = CliRunner().invoke(app, ["drift-alarm", "--reference", ref, "--live", live])+ out = _plain(result.output)+ assert result.exit_code == 1, (result.exit_code, out)+ assert "ref2.jsonl" in out+++def test_an_empty_live_file_exits_non_zero(files) -> None:+ tmp_path, ref = files+ (tmp_path / "live.jsonl").write_text("", encoding="utf-8")+ result = CliRunner().invoke(app, ["drift-alarm", "--reference", ref, "--live", "live.jsonl"])+ assert result.exit_code == 1, _plain(result.output)+++def test_the_library_call_raises_rather_than_reporting_kl_zero(files) -> None:+ tmp_path, ref = files+ live = _write(tmp_path / "live.jsonl", "completion", ["x"] * 3)+ with pytest.raises(ValueError, match="live.jsonl"):+ run_drift_check(reference_path=ref, live_path=live, threshold=0.2)+++def test_control_same_text_under_output_is_ok_exit_zero(files) -> None:+ tmp_path, ref = files+ live = _write(tmp_path / "live.jsonl", "output", [f"The answer is {i}." for i in range(20)])+ result = CliRunner().invoke(app, ["drift-alarm", "--reference", ref, "--live", live])+ out = _plain(result.output)+ assert result.exit_code == 0, (result.exit_code, out)+ assert "OK" in out+++def test_control_different_text_under_output_is_drift_exit_three(files) -> None:+ tmp_path, ref = files+ live = _write(tmp_path / "live.jsonl", "output", ["Something else entirely."] * 20)+ result = CliRunner().invoke(app, ["drift-alarm", "--reference", ref, "--live", live])+ out = _plain(result.output)+ assert result.exit_code == 3, (result.exit_code, out)+ assert "DRIFT" in outdiff --git a/tests/test_eval_auto_no_leg_ran.py b/tests/test_eval_auto_no_leg_ran.pynew file mode 100644index 00000000..b6fcbf7c--- /dev/null+++ b/tests/test_eval_auto_no_leg_ran.py@@ -0,0 +1,109 @@+"""#1808 — ``soup eval auto`` exits non-zero when no leg evaluated anything.++A benchmark leg that could not run was swallowed and "Auto-eval complete."+exited 0 when it was the only leg. The custom leg's ``except SystemExit`` could+not catch ``typer.Exit`` (a ``RuntimeError``), so a custom-only failure exited 1+with a traceback-style abort: the exit code depended on which leg failed. Now+both legs are caught the same way, "Auto-eval complete." is printed only when a+leg ran, and nothing having run exits 1 whichever leg it was.+"""++from __future__ import annotations++from pathlib import Path++import pytest+import typer+from typer.testing import CliRunner++import soup_cli.commands.eval as eval_mod+from soup_cli.cli import app++from .conftest import strip_ansi+++def _plain(text: str) -> str:+ return " ".join(strip_ansi(text).split())+++def workdir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ monkeypatch.chdir(tmp_path)+ (tmp_path / "out").mkdir()+ (tmp_path / "out" / "adapter_config.json").write_text(+ '{"base_model_name_or_path": "HuggingFaceTB/SmolLM2-135M"}', encoding="utf-8"+ )+ (tmp_path / "eval.yaml").write_text(+ "base: HuggingFaceTB/SmolLM2-135M\ntask: sft\ndata:\n train: ./missing.jsonl\n"+ "output: out\n",+ encoding="utf-8",+ )+ (tmp_path / "tasks.jsonl").write_text('{"prompt": "p", "expected": "e"}\n', encoding="utf-8")+ return tmp_path+++def _failing(*args, **kwargs):+ raise typer.Exit(1)+++def _ran(*args, **kwargs):+ return None+++def _auto(*extra: str):+ return CliRunner().invoke(app, ["eval", "auto", "-c", "eval.yaml", *extra])+++def test_benchmark_only_leg_that_cannot_run_exits_non_zero(workdir, monkeypatch) -> None:+ monkeypatch.setattr(eval_mod, "benchmark", _failing)+ result = _auto("--benchmarks", "mmlu")+ out = _plain(result.output)+ assert result.exit_code == 1, (result.exit_code, out)+ assert "Auto-eval complete." not in out+ assert "nothing was evaluated" in out.lower()+++def test_custom_only_leg_that_cannot_run_exits_the_same_code(workdir, monkeypatch) -> None:+ monkeypatch.setattr(eval_mod, "custom", _failing)+ result = _auto("--tasks", "tasks.jsonl")+ out = _plain(result.output)+ assert result.exit_code == 1, (result.exit_code, out)+ assert "Custom eval skipped" in out # caught like the benchmark leg, not aborted+ assert "Auto-eval complete." not in out+++def test_both_legs_failing_exits_non_zero(workdir, monkeypatch) -> None:+ monkeypatch.setattr(eval_mod, "benchmark", _failing)+ monkeypatch.setattr(eval_mod, "custom", _failing)+ result = _auto("--benchmarks", "mmlu", "--tasks", "tasks.jsonl")+ assert result.exit_code == 1, _plain(result.output)+++def test_control_one_of_two_legs_running_still_completes(workdir, monkeypatch) -> None:+ monkeypatch.setattr(eval_mod, "benchmark", _failing)+ monkeypatch.setattr(eval_mod, "custom", _ran)+ result = _auto("--benchmarks", "mmlu", "--tasks", "tasks.jsonl")+ out = _plain(result.output)+ assert result.exit_code == 0, (result.exit_code, out)+ assert "Benchmark eval skipped" in out+ assert "Auto-eval complete." in out+++def test_control_a_leg_that_runs_exits_zero(workdir, monkeypatch) -> None:+ monkeypatch.setattr(eval_mod, "custom", _ran)+ result = _auto("--tasks", "tasks.jsonl")+ out = _plain(result.output)+ assert result.exit_code == 0, (result.exit_code, out)+ assert "Auto-eval complete." in out+++def test_control_a_benchmark_leg_that_runs_exits_zero(workdir, monkeypatch) -> None:+ # The benchmark leg's own `legs_ran += 1`: with no tasks file the benchmark leg+ # is the only one, so if it ran and is not counted the command would say+ # "nothing was evaluated" (#1905 review).+ monkeypatch.setattr(eval_mod, "benchmark", _ran)+ result = _auto("--benchmarks", "mmlu")+ out = _plain(result.output)+ assert result.exit_code == 0, (result.exit_code, out)+ assert "Auto-eval complete." in out+ assert "nothing was evaluated" not in out.lower()diff --git a/tests/test_loop_watch_detach_validates.py b/tests/test_loop_watch_detach_validates.pynew file mode 100644index 00000000..7c0c236e--- /dev/null+++ b/tests/test_loop_watch_detach_validates.py@@ -0,0 +1,81 @@+"""#1808 — ``soup loop watch --detach`` validates the daemon's options before it forks.++The parent spawned the child with stdout and stderr on ``/dev/null`` and printed+"watch detached" without checking the options the child validates at startup+(``WatchConfig.__post_init__``), so a ``--poll-interval 86400`` or+``--max-iterations -1`` reported success while the child exited 2 unseen. The+parent now builds the same config first and fails with the same message.+"""++from __future__ import annotations++from pathlib import Path+from unittest import mock++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app++from .conftest import strip_ansi+++def _plain(text: str) -> str:+ return " ".join(strip_ansi(text).split())+++def initialised(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ monkeypatch.chdir(tmp_path)+ result = CliRunner().invoke(+ app, ["loop", "init", "m", "--eval", "e.json", "--baseline", "b"]+ )+ assert result.exit_code == 0, result.output+ return tmp_path+++def _detach(*extra: str):+ with mock.patch("soup_cli.commands.loop.subprocess.Popen") as popen:+ popen.return_value.pid = 123+ result = CliRunner().invoke(app, ["loop", "watch", "--detach", *extra])+ return result, popen+++ "extra,message",+ [+ pytest.param(["--poll-interval", "86400"], "poll_interval_sec must be in [1, 3600]",+ id="poll-interval"),+ pytest.param(["--poll-interval", "0.5"], "poll_interval_sec must be in [1, 3600]",+ id="poll-interval-low"),+ pytest.param(["--max-iterations", "-1"], "max_iterations must be a non-negative int",+ id="max-iterations"),+ ],+)+def test_invalid_options_fail_in_the_parent_and_spawn_no_child(initialised, extra, message):+ result, popen = _detach(*extra)+ out = _plain(result.output)+ assert result.exit_code == 2, (result.exit_code, out)+ assert "invalid watch config" in out+ assert message in out+ assert "watch detached" not in out+ popen.assert_not_called()+++def test_control_valid_options_still_detach(initialised):+ result, popen = _detach("--poll-interval", "60", "--max-iterations", "1")+ out = _plain(result.output)+ assert result.exit_code == 0, (result.exit_code, out)+ assert "watch detached pid=123" in out+ popen.assert_called_once()+ argv = popen.call_args.args[0]+ assert "--foreground" in argv and "--poll-interval" in argv+++def test_control_the_foreground_path_keeps_its_own_message(initialised):+ result = CliRunner().invoke(+ app, ["loop", "watch", "--foreground", "--poll-interval", "86400"]+ )+ out = _plain(result.output)+ assert result.exit_code == 2, (result.exit_code, out)+ assert "poll_interval_sec must be in [1, 3600]" in outdiff --git a/tests/test_sweep_all_arms_failed.py b/tests/test_sweep_all_arms_failed.pynew file mode 100644index 00000000..999dd8d5--- /dev/null+++ b/tests/test_sweep_all_arms_failed.py@@ -0,0 +1,83 @@+"""#1808 — ``soup sweep`` exits non-zero when every arm failed.++Each failing arm was recorded as ``failed`` and the loop went on; after the+summary the command returned normally, so a sweep in which no arm completed+exited 0 with a table of ``failed`` rows. A script chaining on the exit code+read that as success.+"""++from __future__ import annotations++from pathlib import Path++import pytest+from typer.testing import CliRunner++import soup_cli.commands.sweep as sweep_mod+from soup_cli.cli import app++from .conftest import strip_ansi+++def _plain(text: str) -> str:+ return " ".join(strip_ansi(text).split())+++def config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> str:+ monkeypatch.chdir(tmp_path)+ path = tmp_path / "soup.yaml"+ path.write_text("base: some-model\ndata:\n train: ./d.jsonl\n", encoding="utf-8")+ return str(path)+++def _sweep(config: str, params: list[str]):+ argv = ["sweep", "--config", config, "--yes"]+ for param in params:+ argv += ["--param", param]+ return CliRunner().invoke(app, argv)+++def test_every_arm_failing_exits_non_zero_and_says_so(config, monkeypatch) -> None:+ def fail(*args, **kwargs):+ raise FileNotFoundError("Data file not found: missing.jsonl")++ monkeypatch.setattr(sweep_mod, "_run_single", fail)+ result = _sweep(config, ["lr=1e-5,2e-5"])+ out = _plain(result.output)+ assert result.exit_code == 1, (result.exit_code, out)+ assert "no sweep run completed" in out.lower()+ assert "2 of 2" in out+ assert "missing.jsonl" in out # the first error, so the cause is on screen+++def test_a_single_failing_arm_exits_non_zero_too(config, monkeypatch) -> None:+ monkeypatch.setattr(sweep_mod, "_run_single", lambda *a, **k: 1 / 0)+ result = _sweep(config, ["lr=1e-5"])+ assert result.exit_code == 1, _plain(result.output)+ assert "1 of 1" in _plain(result.output)+++def test_control_one_completed_arm_still_exits_zero(config, monkeypatch) -> None:+ calls = {"n": 0}++ def one_fails(cfg, combo, run_name, config_path):+ calls["n"] += 1+ if calls["n"] == 1:+ raise RuntimeError("boom")+ return {"final_loss": 0.5, "run_id": "r2", "duration": "1s"}++ monkeypatch.setattr(sweep_mod, "_run_single", one_fails)+ result = _sweep(config, ["lr=1e-5,2e-5"])+ out = _plain(result.output)+ assert result.exit_code == 0, (result.exit_code, out)+ assert "no sweep run completed" not in out.lower()+++def test_control_all_arms_completing_exits_zero(config, monkeypatch) -> None:+ monkeypatch.setattr(+ sweep_mod, "_run_single",+ lambda cfg, combo, name, path: {"final_loss": 0.4, "run_id": name, "duration": "1s"},+ )+ result = _sweep(config, ["lr=1e-5,2e-5"])+ assert result.exit_code == 0, _plain(result.output)