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(data)[#1274]: fail loud on provider errors in augment and distill-prompt (#1463)
Aaron Probha81ee37be8ec7
diff --git a/changelog.d/0.75.1/1463.fixed.md b/changelog.d/0.75.1/1463.fixed.mdnew file mode 100644index 00000000..17a62870--- /dev/null+++ b/changelog.d/0.75.1/1463.fixed.md@@ -0,0 +1 @@+- **`soup data augment` wrote rows with an empty rewritten field, and `soup distill-prompt` silently dropped every failed row, both still reporting success (#1274 by @AaronProbha18 in #1463).** Both commands built their LLM provider without `raise_on_error`, so a connection error, HTTP 404/429/500 or malformed response came back as empty text instead of raising — `augment` rewrote a field to `""` and kept the row, `distill-prompt` dropped the row and wrote an empty output file with `Rows: 0`, and both exited 0. Same defect class as #1221 (fixed for `soup data forge` in #1261): the provider is now built with `raise_on_error=True` for both commands, failures (a raised error or an empty/whitespace-only reply) are counted via the shared `ForgeJudgeStats`, and a row is never written with an empty or unrewritten field. A run where every call failed exits 1 without writing an output file; a partial outage keeps only the successful rows under a yellow "with provider failures" panel reporting `N of M provider calls failed` with the endpoint and first error.diff --git a/docs/commands.md b/docs/commands.mdindex 7032c482..83f97100 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -339,7 +339,7 @@ soup lock write --base-sha <h> --dataset-sha <h> --env-lock soup-env.lock Auto-soup lock show [PATH] Print tracked lock filesoup lock check [PATH] --base-sha <h> --dataset-sha <h> --env-hash <h> --base-model <m> Refuse with exit 2 on drift, 3 on usage/missing locksoup compile <program.py> --eval <suite> [--optimizer mipro|gepa|textgrad|copro|bootstrap_fewshot] [--plan-only] DSPy / GEPA / TextGrad prompt-program compiler — live (v0.71.13; pip install "soup-cli[compile]")-soup distill-prompt --traces <jsonl> --teacher <m> --student <m> --strategy sft|preference|kl [--provider ollama|anthropic|vllm] [--base-url <url>] [--temperature F] [--max-rows N] Distill prompt-heavy traces via a live teacher (v0.71.13)+soup distill-prompt --traces <jsonl> --teacher <m> --student <m> --strategy sft|preference|kl [--provider ollama|anthropic|vllm] [--base-url <url>] [--temperature F] [--max-rows N] Distill prompt-heavy traces via a live teacher (v0.71.13); a teacher/student call that fails or returns nothing drops that trace, and the command exits 1 without writing the file when nothing is leftsoup compile-tools <spec.json|yaml> --eval <jsonl> [--optimizer textgrad|gepa] [--plan-only] TextGrad / GEPA tool-schema optimiser — live (v0.71.13; pip install "soup-cli[compile]")soup apple-adapter <source-dir> --direction hf-to-mlx|mlx-to-hf|hf-to-apple|mlx-to-apple --output <dir> [--sign] [--plan-only] PEFT LoRA <-> mlx-lm adapter conversion — live (v0.71.21; *-to-apple upstream-gated exit 3)soup local-rl init --db <path> Create personal-LLM flywheel SQLite schema (v0.68.0)diff --git a/docs/data.md b/docs/data.mdindex 1c063bdb..446a2537 100644--- a/docs/data.md+++ b/docs/data.md@@ -526,6 +526,8 @@ soup data augment ./data/train.jsonl --strategy rephrase --count 2 \Works with any provider supported by `soup data generate` (OpenAI, Ollama, vLLM, local server). `--model` and `--base-url` select a specific local model/endpoint; the Ollama/vLLM paths are loopback-only (SSRF-hardened). `--count` is capped at 10; `--lang` and `--styles` each capped at 10 entries × 32 chars.+A provider call that fails (transport error, non-200 status, malformed response) or returns an empty reply never becomes a row: that variant is dropped. The summary reports `N of M provider calls failed` with the first error, and the command exits 1 without writing the output file when no call produced a usable row.+## Trace-to-Preferencediff --git a/src/soup_cli/commands/data.py b/src/soup_cli/commands/data.pyindex 65d692fc..12dd929c 100644--- a/src/soup_cli/commands/data.py+++ b/src/soup_cli/commands/data.py@@ -1725,6 +1725,10 @@ def augment_data(console.print(f"[red]{exc}[/]")raise typer.Exit(2) from exc+ from soup_cli.utils.data_forge import ForgeJudgeStats++ stats = ForgeJudgeStats()+max_entries = 10max_entry_len = 32@@ -1748,19 +1752,40 @@ def augment_data(target_langs = _bounded_list(lang, "lang")augmented = augment_fn(data, provider=provider_instance,- languages=target_langs or None,+ languages=target_langs or None, stats=stats,)elif strategy == "style":target_styles = _bounded_list(styles, "styles")augmented = augment_fn(data, provider=provider_instance, styles=target_styles or None,+ stats=stats,)else:- augmented = augment_fn(data, provider=provider_instance, count=count)+ augmented = augment_fn(+ data, provider=provider_instance, count=count, stats=stats,+ )except ValueError as exc:console.print(f"[red]{exc}[/]")raise typer.Exit(1)+ failure_summary = ""+ if stats.failures:+ from soup_cli.utils.recipe_run import _provider_endpoint_label++ endpoint = _provider_endpoint_label(provider, base_url or None)+ failure_summary = (+ f"{stats.failures} of {stats.calls} provider calls failed for "+ f"--provider {provider} ({endpoint}); first error: {stats.first_error}"+ )++ if not augmented and stats.failures:+ from rich.markup import escape++ console.print(+ f"[red]No usable rows produced:[/] {escape(failure_summary)}"+ )+ raise typer.Exit(1)+# Optional dedupif dedup:seen = set()@@ -1783,11 +1808,21 @@ def augment_data()written = atomic_write_text(payload, output_path, field="--output")- console.print(- f"[green]Augmentation complete:[/] {len(data)} → {len(final_rows)} "- f"({strategy} via {provider})\n"- f" Output: {written}"- )+ if stats.failures:+ from rich.markup import escape++ console.print(+ f"[yellow]Augmentation complete with provider failures:[/] "+ f"{len(data)} → {len(final_rows)} ({strategy} via {provider})\n"+ f" Output: {written}"+ )+ console.print(f"[yellow]Warning:[/] {escape(failure_summary)}")+ else:+ console.print(+ f"[green]Augmentation complete:[/] {len(data)} → {len(final_rows)} "+ f"({strategy} via {provider})\n"+ f" Output: {written}"+ )class _AugmentProvider:@@ -1841,6 +1876,7 @@ def _load_augment_provider(canonical,model=model or _AUGMENT_DEFAULT_MODELS[canonical],base_url=base_url or None,+ raise_on_error=True,)return _AugmentProvider(fn)diff --git a/src/soup_cli/commands/distill_prompt.py b/src/soup_cli/commands/distill_prompt.pyindex deca69ec..516e8c90 100644--- a/src/soup_cli/commands/distill_prompt.py+++ b/src/soup_cli/commands/distill_prompt.py@@ -78,6 +78,9 @@ def distill_prompt_cmd(if plan_only:return+ from soup_cli.utils.data_forge import ForgeJudgeStats, ProviderCallError++ stats = ForgeJudgeStats()try:n = prepare_distill_dataset(plan,@@ -85,7 +88,13 @@ def distill_prompt_cmd(base_url=base_url,temperature=temperature,max_rows=max_rows,+ stats=stats,)+ except ProviderCallError as exc:+ # #1274: every teacher/student call failed — fail loudly instead of+ # writing an empty dataset and reporting "done" (mirrors #1221).+ console.print(f"[red]No usable rows produced:[/] {escape(str(exc))}")+ raise typer.Exit(1) from excexcept (TypeError, ValueError) as exc:console.print(f"[red]{escape(str(exc))}[/]")raise typer.Exit(2) from exc@@ -98,10 +107,19 @@ def distill_prompt_cmd()raise typer.Exit(2) from exc+ call_line = ""+ title = "soup distill-prompt — done"+ if stats.failures:+ call_line = (+ f"Provider calls: [bold yellow]{stats.failures} of "+ f"{stats.calls} failed[/]\n"+ )+ title = "soup distill-prompt — done with provider failures"console.print(Panel(+ f"{call_line}"f"Rows: [bold]{n}[/]\n"f"Output: [bold]{escape(plan.output_path)}[/]",- title="soup distill-prompt — done",+ title=title,))diff --git a/src/soup_cli/data/augment.py b/src/soup_cli/data/augment.pyindex ab0cf07e..111265ba 100644--- a/src/soup_cli/data/augment.py+++ b/src/soup_cli/data/augment.py@@ -11,7 +11,9 @@ method and returns a list of augmented dict rows in the same format as input.from __future__ import annotations-from typing import Callable, Protocol+from typing import Callable, Optional, Protocol++from soup_cli.utils.data_forge import ForgeJudgeStats, _describe_judge_errorMAX_AUGMENT_COUNT = 10DEFAULT_LANGUAGES = ("ru", "zh", "es")@@ -45,16 +47,35 @@ def _apply_rewrite(return new_row+def _call_provider(provider: Provider, prompt: str, stats: ForgeJudgeStats) -> str:+ """Call ``provider.generate`` and count it in ``stats``.++ An empty/whitespace-only reply is a failure too (#1274, mirrors forge's+ #1221 "an empty answer is no answer" rule) — never rewrite a field to "".+ """+ stats.calls += 1+ result = provider.generate(prompt)+ if not isinstance(result, str) or not result.strip():+ raise ValueError("provider returned an empty reply")+ return result++def augment_rephrase(examples: list[dict],provider: Provider,count: int = 2,+ *,+ stats: Optional[ForgeJudgeStats] = None,) -> list[dict]:"""Rephrase each example ``count`` times preserving meaning.- Returns ``len(examples) * count`` rows.+ Returns up to ``len(examples) * count`` rows — a variant whose provider+ call fails is dropped (never written with an unrewritten/empty field);+ pass ``stats`` to see the call/failure counts (#1274)."""_validate_count(count)+ if stats is None:+ stats = ForgeJudgeStats()augmented: list[dict] = []for row in examples:for i in range(count):@@ -63,8 +84,11 @@ def augment_rephrase(f"Rewrite the following text preserving its meaning but using "f"different wording (variant {_i + 1}):\n\n{text}")- return provider.generate(prompt)- augmented.append(_apply_rewrite(row, _rewrite))+ return _call_provider(provider, prompt, stats)+ try:+ augmented.append(_apply_rewrite(row, _rewrite))+ except Exception as exc: # noqa: BLE001 — provider backends vary+ stats.record_failure(_describe_judge_error(exc))return augmented@@ -72,8 +96,14 @@ def augment_translate(examples: list[dict],provider: Provider,languages: list[str] | None = None,+ *,+ stats: Optional[ForgeJudgeStats] = None,) -> list[dict]:- """Translate each example into every target language."""+ """Translate each example into every target language.++ A language variant whose provider call fails is dropped; pass ``stats``+ to see the call/failure counts (#1274).+ """if languages is None:langs = list(DEFAULT_LANGUAGES)else:@@ -84,6 +114,8 @@ def augment_translate(raise ValueError(f"too many languages: {len(langs)} > {MAX_AUGMENT_COUNT}")+ if stats is None:+ stats = ForgeJudgeStats()augmented: list[dict] = []for row in examples:for lang in langs:@@ -92,8 +124,11 @@ def augment_translate(f"Translate the following text into {_lang}, preserving the "f"meaning exactly. Do not add commentary:\n\n{text}")- return provider.generate(prompt)- augmented.append(_apply_rewrite(row, _rewrite))+ return _call_provider(provider, prompt, stats)+ try:+ augmented.append(_apply_rewrite(row, _rewrite))+ except Exception as exc: # noqa: BLE001 — provider backends vary+ stats.record_failure(_describe_judge_error(exc))return augmented@@ -101,8 +136,14 @@ def augment_style(examples: list[dict],provider: Provider,styles: list[str] | None = None,+ *,+ stats: Optional[ForgeJudgeStats] = None,) -> list[dict]:- """Rewrite each example in multiple tonal styles."""+ """Rewrite each example in multiple tonal styles.++ A style variant whose provider call fails is dropped; pass ``stats`` to+ see the call/failure counts (#1274).+ """if styles is None:target_styles = list(DEFAULT_STYLES)else:@@ -113,6 +154,8 @@ def augment_style(raise ValueError(f"too many styles: {len(target_styles)} > {MAX_AUGMENT_COUNT}")+ if stats is None:+ stats = ForgeJudgeStats()augmented: list[dict] = []for row in examples:for style in target_styles:@@ -121,8 +164,11 @@ def augment_style(f"Rewrite the following in a {_style} tone, preserving "f"meaning:\n\n{text}")- return provider.generate(prompt)- augmented.append(_apply_rewrite(row, _rewrite))+ return _call_provider(provider, prompt, stats)+ try:+ augmented.append(_apply_rewrite(row, _rewrite))+ except Exception as exc: # noqa: BLE001 — provider backends vary+ stats.record_failure(_describe_judge_error(exc))return augmenteddiff --git a/src/soup_cli/utils/prompt_distill.py b/src/soup_cli/utils/prompt_distill.pyindex 828cc081..ece11d63 100644--- a/src/soup_cli/utils/prompt_distill.py+++ b/src/soup_cli/utils/prompt_distill.py@@ -23,13 +23,16 @@ import jsonimport loggingimport osfrom dataclasses import dataclass-from typing import Any, Callable, List, Mapping, Optional+from typing import TYPE_CHECKING, Any, Callable, List, Mapping, Optionalfrom soup_cli.utils.paths import (atomic_write_text,enforce_under_cwd_and_no_symlink,)+if TYPE_CHECKING:+ from soup_cli.utils.data_forge import ForgeJudgeStats+_LOG = logging.getLogger("soup.distill_prompt")SUPPORTED_DISTILL_STRATEGIES: frozenset[str] = frozenset({"sft", "preference", "kl"})@@ -211,6 +214,7 @@ def _build_provider_fn(model=model,base_url=base_url,temperature=temperature,+ raise_on_error=True,)@@ -223,6 +227,7 @@ def prepare_distill_dataset(max_rows: Optional[int] = None,teacher_fn: "Optional[Callable[[str], Mapping[str, Any]]]" = None,student_fn: "Optional[Callable[[str], Mapping[str, Any]]]" = None,+ stats: "Optional[ForgeJudgeStats]" = None,) -> int:"""Prepare a distillation dataset from prompt-heavy traces (v0.71.13 #226).@@ -245,12 +250,20 @@ def prepare_distill_dataset(number of teacher calls — a prompt whose teacher reply is empty stillconsumes a call without producing a row)."""+ from soup_cli.utils.data_forge import (+ ForgeJudgeStats,+ ProviderCallError,+ _describe_judge_error,+ )+if not isinstance(plan, DistillPromptPlan):raise TypeError("plan must be DistillPromptPlan")if max_rows is not None and (isinstance(max_rows, bool) or not isinstance(max_rows, int) or max_rows < 1):raise ValueError("max_rows must be a positive int or None")+ if stats is None:+ stats = ForgeJudgeStats()teacher = teacher_fnif teacher is None:@@ -271,13 +284,16 @@ def prepare_distill_dataset(prompt = extract_prompt(row)if prompt is None:continue+ stats.calls += 1try:t_reply = teacher(prompt)except Exception as exc: # noqa: BLE001 — provider error variety_LOG.debug("teacher call failed: %s", exc)+ stats.record_failure(_describe_judge_error(exc))continuet_text = t_reply.get("text") if isinstance(t_reply, Mapping) else Noneif not isinstance(t_text, str) or not t_text.strip():+ stats.record_failure("teacher returned an empty reply")continueif plan.strategy in ("sft", "kl"):@@ -293,13 +309,16 @@ def prepare_distill_dataset())else: # preference+ stats.calls += 1try:s_reply = student(prompt) if student is not None else Noneexcept Exception as exc: # noqa: BLE001_LOG.debug("student call failed: %s", exc)+ stats.record_failure(_describe_judge_error(exc))continues_text = s_reply.get("text") if isinstance(s_reply, Mapping) else Noneif not isinstance(s_text, str) or not s_text.strip():+ stats.record_failure("student returned an empty reply")continueout_lines.append(json.dumps(@@ -308,6 +327,17 @@ def prepare_distill_dataset())+ if not out_lines and stats.failures:+ # #1274: a teacher/student that produced nothing usable must fail+ # loudly rather than write an empty dataset (mirrors #1221 forge).+ from soup_cli.utils.recipe_run import _provider_endpoint_label++ endpoint = _provider_endpoint_label(provider, base_url)+ raise ProviderCallError(+ f"{stats.failures} of {stats.calls} provider calls failed for "+ f"--provider {provider} ({endpoint}); first error: {stats.first_error}"+ )+text = "\n".join(out_lines) + ("\n" if out_lines else "")atomic_write_text(text, plan.output_path, field="output_path")return len(out_lines)diff --git a/tests/test_data_augment.py b/tests/test_data_augment.pyindex ad604158..07677df6 100644--- a/tests/test_data_augment.py+++ b/tests/test_data_augment.py@@ -106,18 +106,23 @@ class TestAugmentStrategies:with pytest.raises(ValueError):augment_style([{"x": "y"}], provider=FakeProvider(), styles=[])- def test_provider_exception_propagates(self):- """When provider raises, augment propagates the error (fail-loud)."""+ def test_provider_exception_drops_row_and_counts_failure(self):+ """A failing provider call drops the row instead of writing an+ unrewritten/empty field, and is counted in ``stats`` (#1274)."""from soup_cli.data.augment import augment_rephrase+ from soup_cli.utils.data_forge import ForgeJudgeStatsclass FailingProvider:def generate(self, prompt: str, max_tokens: int = 512) -> str:raise RuntimeError("provider down")- with pytest.raises(RuntimeError, match="provider down"):- augment_rephrase(- [{"instruction": "x"}], provider=FailingProvider(), count=1,- )+ stats = ForgeJudgeStats()+ augmented = augment_rephrase(+ [{"instruction": "x"}], provider=FailingProvider(), count=1, stats=stats,+ )+ assert augmented == []+ assert (stats.calls, stats.failures) == (1, 1)+ assert stats.first_error == "provider down"# ---------------------------------------------------------------------------diff --git a/tests/test_issue1274_augment_distill_provider_failures.py b/tests/test_issue1274_augment_distill_provider_failures.pynew file mode 100644index 00000000..f75968d9--- /dev/null+++ b/tests/test_issue1274_augment_distill_provider_failures.py@@ -0,0 +1,408 @@+"""#1274 — ``soup data augment`` / ``soup distill-prompt`` must not turn failed+provider calls into rows.++Same defect class as #1221 (fixed for ``soup data forge`` in #1261): both+commands built their LLM provider without ``raise_on_error=True``, so every+transport/HTTP/malformed-response failure came back as ``{"text": ""}``.+``augment`` wrote a row with the field rewritten to an empty string, and+``distill-prompt`` silently dropped every failed row — both reported success+(exit 0) even when every call failed.+"""++from __future__ import annotations++import json+import re+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from typing import Iterator, List++import pytest+from typer.testing import CliRunner++from tests.conftest import strip_ansi++_HEALTHY_ANSWER = "Rewritten text."++runner = CliRunner()+++def _terminal_text(result) -> str:+ return re.sub(r"\s+", " ", strip_ansi(result.output))+++class _StubJudge:+ def __init__(self) -> None:+ self.mode = "healthy"+ self.calls = 0+ self._lock = threading.Lock()++ def respond(self) -> tuple[int, bytes]:+ with self._lock:+ self.calls += 1+ n = self.calls+ mode = self.mode+ if mode == "alternate":+ mode = "healthy" if n % 2 else "500"+ if mode in {"404", "429", "500"}:+ return int(mode), b'{"error": "stub"}'+ if mode == "malformed":+ return 200, b"this is not json"+ content = "" if mode == "empty" else _HEALTHY_ANSWER+ body = {"choices": [{"message": {"role": "assistant", "content": content}}]}+ return 200, json.dumps(body).encode("utf-8")+++def stub_judge() -> Iterator[tuple[_StubJudge, str]]:+ stub = _StubJudge()++ class Handler(BaseHTTPRequestHandler):+ def do_POST(self) -> None: # noqa: N802 — http.server API+ length = int(self.headers.get("Content-Length") or 0)+ self.rfile.read(length)+ status, payload = stub.respond()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++ def log_message(self, *_args) -> None:+ return++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield stub, f"http://127.0.0.1:{server.server_address[1]}"+ finally:+ server.shutdown()+ server.server_close()+++# --------------------------------------------------------------------------- augment+++def _write_augment_data(tmp_path: Path) -> None:+ # One string field per row so each row costs exactly one provider call+ # (parity-sensitive tests below rely on that 1:1 mapping).+ rows = [{"text": f"q{i}"} for i in range(2)]+ (tmp_path / "data.jsonl").write_text(+ "\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8"+ )+++def _run_augment(tmp_path: Path, monkeypatch, *extra: str):+ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ _write_augment_data(tmp_path)+ return runner.invoke(+ app,+ [+ "data", "augment",+ "--input", "data.jsonl",+ "--output", "augmented.jsonl",+ "--strategy", "rephrase",+ "--count", "1",+ *extra,+ ],+ )+++def _augment_rows(tmp_path: Path) -> List[dict]:+ path = tmp_path / "augmented.jsonl"+ if not path.exists():+ return []+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()]+++def test_augment_unreachable_provider_exits_nonzero_no_file(tmp_path, monkeypatch) -> None:+ result = _run_augment(+ tmp_path, monkeypatch,+ "--provider", "ollama", "--base-url", "http://127.0.0.1:9",+ )+ output = _terminal_text(result)++ assert result.exit_code == 1, (output, repr(result.exception))+ assert not (tmp_path / "augmented.jsonl").exists()+ assert "of" in output and "provider calls failed" in output+ assert "--provider ollama (http://127.0.0.1:9)" in output+++ ("mode", "first_error"),+ [+ ("500", "provider returned HTTP 500"),+ ("empty", "provider returned an empty reply"),+ ("malformed", "provider returned a malformed response"),+ ],+)+def test_augment_failing_provider_exits_nonzero(+ tmp_path, monkeypatch, stub_judge, mode: str, first_error: str+) -> None:+ stub, url = stub_judge+ stub.mode = mode+ result = _run_augment(+ tmp_path, monkeypatch,+ "--provider", "ollama", "--base-url", url,+ )+ output = _terminal_text(result)++ assert result.exit_code == 1, (output, repr(result.exception))+ assert not (tmp_path / "augmented.jsonl").exists()+ assert first_error in output+++def test_augment_partial_outage_keeps_only_successful_rows(+ tmp_path, monkeypatch, stub_judge+) -> None:+ stub, url = stub_judge+ stub.mode = "alternate"+ result = _run_augment(+ tmp_path, monkeypatch,+ "--provider", "ollama", "--base-url", url,+ )+ output = _terminal_text(result)++ assert result.exit_code == 0, output+ rows = _augment_rows(tmp_path)+ # 2 source rows + only the augmented row whose rewrite succeeded+ # (call 1 healthy, call 2 fails under "alternate").+ assert len(rows) == 3+ assert rows[2]["text"] == _HEALTHY_ANSWER+ assert "1 of 2 provider calls failed" in output+ assert "Augmentation complete with provider failures" in output+++def test_augment_healthy_provider_control(tmp_path, monkeypatch, stub_judge) -> None:+ stub, url = stub_judge+ result = _run_augment(+ tmp_path, monkeypatch,+ "--provider", "ollama", "--base-url", url,+ )+ output = _terminal_text(result)++ assert result.exit_code == 0, output+ rows = _augment_rows(tmp_path)+ assert len(rows) == 4+ assert "provider calls failed" not in output+ assert "Augmentation complete:" in output+++ ("strategy", "strategy_args"),+ [("translate", ["--lang", "es"]), ("style", ["--styles", "formal"])],+)+def test_augment_translate_and_style_fail_loudly_too(+ tmp_path, monkeypatch, stub_judge, strategy: str, strategy_args: list+) -> None:+ stub, url = stub_judge+ stub.mode = "500"+ result = _run_augment(+ tmp_path, monkeypatch,+ "--strategy", strategy, *strategy_args,+ "--provider", "ollama", "--base-url", url,+ )+ output = _terminal_text(result)++ assert result.exit_code == 1, (output, repr(result.exception))+ assert not (tmp_path / "augmented.jsonl").exists()+ assert "provider returned HTTP 500" in output+++ ("strategy", "strategy_args"),+ [("translate", ["--lang", "es"]), ("style", ["--styles", "formal"])],+)+def test_augment_translate_and_style_partial_outage_keeps_only_good_rows(+ tmp_path, monkeypatch, stub_judge, strategy: str, strategy_args: list+) -> None:+ stub, url = stub_judge+ stub.mode = "alternate"+ result = _run_augment(+ tmp_path, monkeypatch,+ "--strategy", strategy, *strategy_args,+ "--provider", "ollama", "--base-url", url,+ )+ output = _terminal_text(result)++ assert result.exit_code == 0, (output, repr(result.exception))+ rows = _augment_rows(tmp_path)+ assert len(rows) == 3 # 2 source rows + the one variant whose call succeeded+ assert all(row["text"] for row in rows)+ assert "1 of 2 provider calls failed" in output+++def test_augment_failure_summary_is_not_parsed_as_rich_markup(tmp_path, monkeypatch) -> None:+ import soup_cli.commands.data as data_mod+ from soup_cli.utils.data_forge import ProviderCallError++ class Boom:+ def generate(self, prompt: str, max_tokens: int = 512) -> str:+ raise ProviderCallError("upstream said [/oops]")++ monkeypatch.setattr(data_mod, "_load_augment_provider", lambda *a, **k: Boom())+ result = _run_augment(+ tmp_path, monkeypatch, "--provider", "ollama", "--base-url", "http://127.0.0.1:9"+ )++ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert result.exception is None or isinstance(result.exception, SystemExit)+ assert "[/oops]" in _terminal_text(result)+++def test_augment_partial_failure_warning_is_not_parsed_as_rich_markup(+ tmp_path, monkeypatch+) -> None:+ # The partial-failure path writes the file FIRST and only then prints the warning, so an+ # unescaped "[/oops]" in the provider's error crashes the command after a successful write.+ import soup_cli.commands.data as data_mod+ from soup_cli.utils.data_forge import ProviderCallError++ class FailsOnce:+ def __init__(self) -> None:+ self.calls = 0++ def generate(self, prompt: str, max_tokens: int = 512) -> str:+ self.calls += 1+ if self.calls == 1:+ raise ProviderCallError("upstream said [/oops]")+ return "Rewritten text."++ monkeypatch.setattr(data_mod, "_load_augment_provider", lambda *a, **k: FailsOnce())+ result = _run_augment(+ tmp_path, monkeypatch, "--provider", "ollama", "--base-url", "http://127.0.0.1:9"+ )++ assert result.exit_code == 0, (result.output, repr(result.exception))+ assert len(_augment_rows(tmp_path)) == 3 # 2 source rows + the one variant that succeeded+ assert "[/oops]" in _terminal_text(result)+++# --------------------------------------------------------------------------- distill-prompt+++def _write_traces(tmp_path: Path, prompts: List[str]) -> None:+ with open(tmp_path / "traces.jsonl", "w", encoding="utf-8") as fh:+ for p in prompts:+ fh.write(json.dumps({"prompt": p}) + "\n")+++def _run_distill(tmp_path: Path, monkeypatch, *extra: str):+ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ _write_traces(tmp_path, ["q1", "q2"])+ return runner.invoke(+ app,+ [+ "distill-prompt",+ "--traces", "traces.jsonl",+ "--teacher", "qwen2.5:0.5b",+ "--student", "smol",+ "--strategy", "sft",+ "--output", "distilled.jsonl",+ *extra,+ ],+ )+++def test_distill_unreachable_provider_exits_nonzero_no_file(tmp_path, monkeypatch) -> None:+ result = _run_distill(+ tmp_path, monkeypatch,+ "--provider", "ollama", "--base-url", "http://127.0.0.1:9",+ )+ output = _terminal_text(result)++ assert result.exit_code == 1, (output, repr(result.exception))+ assert not (tmp_path / "distilled.jsonl").exists()+ assert "No usable rows produced" in output+ assert "2 of 2 provider calls failed" in output+++def test_distill_failing_provider_exits_nonzero(tmp_path, monkeypatch, stub_judge) -> None:+ stub, url = stub_judge+ stub.mode = "500"+ result = _run_distill(+ tmp_path, monkeypatch,+ "--provider", "ollama", "--base-url", url,+ )+ output = _terminal_text(result)++ assert result.exit_code == 1, (output, repr(result.exception))+ assert not (tmp_path / "distilled.jsonl").exists()+ assert "provider returned HTTP 500" in output+++def test_distill_partial_outage_keeps_only_successful_rows(+ tmp_path, monkeypatch, stub_judge+) -> None:+ stub, url = stub_judge+ stub.mode = "alternate"+ result = _run_distill(+ tmp_path, monkeypatch,+ "--provider", "ollama", "--base-url", url,+ )+ output = _terminal_text(result)++ assert result.exit_code == 0, output+ with open(tmp_path / "distilled.jsonl", encoding="utf-8") as fh:+ rows = [json.loads(line) for line in fh if line.strip()]+ assert len(rows) == 1+ assert "1 of 2 failed" in output+ assert "done with provider failures" in output+++def test_distill_healthy_provider_control(tmp_path, monkeypatch, stub_judge) -> None:+ stub, url = stub_judge+ result = _run_distill(+ tmp_path, monkeypatch,+ "--provider", "ollama", "--base-url", url,+ )+ output = _terminal_text(result)++ assert result.exit_code == 0, output+ with open(tmp_path / "distilled.jsonl", encoding="utf-8") as fh:+ rows = [json.loads(line) for line in fh if line.strip()]+ assert len(rows) == 2+ assert "provider failures" not in output+++def test_distill_preference_strategy_exercises_teacher_and_student(+ tmp_path, monkeypatch, stub_judge+) -> None:+ stub, url = stub_judge+ stub.mode = "alternate"+ result = _run_distill(+ tmp_path, monkeypatch,+ "--provider", "ollama", "--base-url", url,+ "--strategy", "preference",+ )+ output = _terminal_text(result)++ # alternate: call 1 ok (teacher q1), call 2 fails (student q1),+ # call 3 ok (teacher q2), call 4 fails (student q2) -> both rows drop+ # for lack of a student reply, even though only the student calls failed.+ assert result.exit_code == 1, (output, repr(result.exception))+ assert not (tmp_path / "distilled.jsonl").exists()+ assert "2 of 4 provider calls failed" in output+++def test_distill_failure_summary_is_not_parsed_as_rich_markup(tmp_path, monkeypatch) -> None:+ import soup_cli.utils.prompt_distill as distill_mod+ from soup_cli.utils.data_forge import ProviderCallError++ def boom(prompt: str):+ raise ProviderCallError("upstream said [/oops]")++ monkeypatch.setattr(distill_mod, "_build_provider_fn", lambda *a, **k: boom)+ result = _run_distill(+ tmp_path, monkeypatch, "--provider", "ollama", "--base-url", "http://127.0.0.1:9"+ )++ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert result.exception is None or isinstance(result.exception, SystemExit)+ assert "[/oops]" in _terminal_text(result)diff --git a/tests/test_v07113.py b/tests/test_v07113.pyindex 6d67b9a8..a498b943 100644--- a/tests/test_v07113.py+++ b/tests/test_v07113.py@@ -613,13 +613,32 @@ class TestPrepareDistillDataset:rows = [json.loads(line) for line in fh if line.strip()]assert rows[0] == {"prompt": "q1", "chosen": "teach", "rejected": "stud"}- def test_empty_teacher_reply_skipped(self, tmp_path, monkeypatch):+ def test_empty_teacher_reply_all_fail_raises(self, tmp_path, monkeypatch):+ """#1274: every row failing must raise, not silently write an empty+ file and report success — mirrors #1221's forge fix."""monkeypatch.chdir(tmp_path)+ from soup_cli.utils.data_forge import ProviderCallErrorfrom soup_cli.utils.prompt_distill import prepare_distill_datasetplan = self._plan(tmp_path, "sft")- n = prepare_distill_dataset(plan, teacher_fn=lambda p: {"text": ""})- assert n == 0+ with pytest.raises(ProviderCallError, match="2 of 2 provider calls failed"):+ prepare_distill_dataset(plan, teacher_fn=lambda p: {"text": ""})+ assert not os.path.exists(tmp_path / "out.jsonl")++ def test_partial_teacher_failure_keeps_successful_rows(self, tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ from soup_cli.utils.data_forge import ForgeJudgeStats+ from soup_cli.utils.prompt_distill import prepare_distill_dataset++ plan = self._plan(tmp_path, "sft")++ def teacher(p):+ return {"text": "T"} if p == "q1" else {"text": ""}++ stats = ForgeJudgeStats()+ n = prepare_distill_dataset(plan, teacher_fn=teacher, stats=stats)+ assert n == 1+ assert (stats.calls, stats.failures) == (2, 1)def test_max_rows_cap(self, tmp_path, monkeypatch):monkeypatch.chdir(tmp_path)@@ -647,8 +666,9 @@ class TestPrepareDistillDataset:with pytest.raises(TypeError):prepare_distill_dataset({"traces_path": "x"})- def test_teacher_exception_skipped(self, tmp_path, monkeypatch):+ def test_teacher_exception_all_fail_raises(self, tmp_path, monkeypatch):monkeypatch.chdir(tmp_path)+ from soup_cli.utils.data_forge import ProviderCallErrorfrom soup_cli.utils.prompt_distill import prepare_distill_datasetplan = self._plan(tmp_path, "sft")@@ -656,8 +676,8 @@ class TestPrepareDistillDataset:def boom(p):raise RuntimeError("provider down")- n = prepare_distill_dataset(plan, teacher_fn=boom)- assert n == 0+ with pytest.raises(ProviderCallError, match="provider down"):+ prepare_distill_dataset(plan, teacher_fn=boom)class TestDistillPromptCli:@@ -1328,8 +1348,9 @@ class TestCoverageGaps:out = extract_prompt({"prompt": "x" * (_MAX_PROMPT_CHARS + 50)})assert len(out) == _MAX_PROMPT_CHARS- def test_preference_empty_student_skipped(self, tmp_path, monkeypatch):+ def test_preference_empty_student_all_fail_raises(self, tmp_path, monkeypatch):monkeypatch.chdir(tmp_path)+ from soup_cli.utils.data_forge import ProviderCallErrorfrom soup_cli.utils.prompt_distill import (build_distill_prompt_plan,prepare_distill_dataset,@@ -1343,15 +1364,17 @@ class TestCoverageGaps:strategy="preference",output_path="o.jsonl",)- n = prepare_distill_dataset(- plan,- teacher_fn=lambda p: {"text": "T"},- student_fn=lambda p: {"text": ""},- )- assert n == 0+ with pytest.raises(ProviderCallError, match="1 of 2 provider calls failed"):+ prepare_distill_dataset(+ plan,+ teacher_fn=lambda p: {"text": "T"},+ student_fn=lambda p: {"text": ""},+ )+ assert not os.path.exists(tmp_path / "o.jsonl")- def test_preference_student_exception_skipped(self, tmp_path, monkeypatch):+ def test_preference_student_exception_all_fail_raises(self, tmp_path, monkeypatch):monkeypatch.chdir(tmp_path)+ from soup_cli.utils.data_forge import ProviderCallErrorfrom soup_cli.utils.prompt_distill import (build_distill_prompt_plan,prepare_distill_dataset,@@ -1369,10 +1392,10 @@ class TestCoverageGaps:def boom(p):raise RuntimeError("down")- n = prepare_distill_dataset(- plan, teacher_fn=lambda p: {"text": "T"}, student_fn=boom- )- assert n == 0+ with pytest.raises(ProviderCallError, match="down"):+ prepare_distill_dataset(+ plan, teacher_fn=lambda p: {"text": "T"}, student_fn=boom+ )# --- #227 compile-tools ----------------------------------------------def test_spec_path_extension_rejected(self, tmp_path, monkeypatch):@@ -1438,9 +1461,10 @@ class TestReachableInternals:seen = {}- def fake_make(provider, *, model, base_url, temperature):+ def fake_make(provider, *, model, base_url, temperature, raise_on_error=False):seen.update(- provider=provider, model=model, base_url=base_url, temperature=temperature+ provider=provider, model=model, base_url=base_url,+ temperature=temperature, raise_on_error=raise_on_error,)return lambda prompt: {"text": f"R:{prompt}"}@@ -1454,6 +1478,7 @@ class TestReachableInternals:"model": "qwen2.5:0.5b","base_url": "http://localhost:11434","temperature": 0.2,+ "raise_on_error": True,}def test_prepare_distill_default_teacher_wires_provider(self, tmp_path, monkeypatch):