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(loop): harvest recorded thumbs through explicit database paths (#1832)
Srinivasan R92b85e8f0ede
diff --git a/changelog.d/0.76.0/1832.fixed.md b/changelog.d/0.76.0/1832.fixed.mdnew file mode 100644index 00000000..5a94a862--- /dev/null+++ b/changelog.d/0.76.0/1832.fixed.md@@ -0,0 +1 @@+- `soup loop watch` with the pre-wired stages now learns from `soup serve --record-thumbs`: the harvest reads the thumbs database named by `SOUP_LOOP_THUMBS_DB` or `soup loop init --thumbs-db PATH` and unions its preference pairs (tagged `source: "soup-serve-thumbs"`) with the trace pairs. Before, it read only `--trace-log` directories, which carry no thumbs signal, so a loop next to a serve that recorded thumbs harvested nothing. A configured database outside cwd, a symlink, a missing file, or a file that is not a thumbs database stops `soup loop watch` with exit 2, naming the field (#1440 by @Srinivasan8888 in #1832).diff --git a/docs/adapters-and-governance.md b/docs/adapters-and-governance.mdindex 302d1bdb..9a760217 100644--- a/docs/adapters-and-governance.md+++ b/docs/adapters-and-governance.md@@ -116,6 +116,17 @@ soup loop watch --poll-interval 300soup loop init registry://abc12 --eval evals/lock.json --baseline registry://prod --pre-wiredsoup loop watch --pre-wired --pack-cans --poll-interval 300+# Learn from Soup's own serving (#1440): the pre-wired harvest also reads the+# thumbs `soup serve --record-thumbs` captures through POST /v1/thumbs, pairing+# the latest π and π answer per prompt. The database must stay under cwd and+# exist as a thumbs database: start the serve first, or `soup loop watch` refuses,+# naming the field.+soup serve --model ./base --record-thumbs ./rl.db+soup loop init registry://abc12 --eval evals/lock.json --baseline registry://prod \+ --pre-wired --thumbs-db ./rl.db+# or per run, overriding loop.yaml:+SOUP_LOOP_THUMBS_DB=./rl.db soup loop watch --pre-wired+# Unpack a recorded iteration's Soup Can for what-if analysis (v0.71.4)soup loop replay iter-20260515T120000-abcdef01 --extract ./iter-dumpdiff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex da6330c4..0b03fd2c 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -2691,6 +2691,7 @@ Usage: `soup loop init [OPTIONS] SERVED_MODEL`| `--monthly-budget` | text | | | Monthly USD cap (e.g. 50usd, 100). || `--max-runs-per-day` | integer | | | Cap on iteration starts per UTC day. || `--pre-wired` | flag | off | | Use the pre-wired harvest/train/gate/deploy stages (utils/loop_stages.py) on watch instead of no-op stubs (v0.71.4). |+| `--thumbs-db` | text | | | Local-RL SQLite written by `soup serve --record-thumbs`; the pre-wired harvest turns its thumbs into preference pairs. Must stay under cwd. SOUP_LOOP_THUMBS_DB overrides it. || `--force` | flag | off | | Overwrite existing loop.yaml. |### `soup loop pause`diff --git a/docs/commands.md b/docs/commands.mdindex 1d7459c6..eab9a4fd 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -173,7 +173,7 @@ soup adapters audit <adapter> --config soup.yaml [--json] Compare a finished rsoup adapters branches List snapshotted branchessoup adapters checkout <name> Restore a snapshotted branch's configsoup adapters diff <a> <b> Per-layer ΞW Frobenius diff + effective-rank drift-soup loop init <model> --eval <s> --baseline <b> [--pre-wired] Create .soup/loop.yaml (data flywheel; --pre-wired = real stages)+soup loop init <model> --eval <s> --baseline <b> [--pre-wired] [--thumbs-db <db>] Create .soup/loop.yaml (data flywheel; --pre-wired = real stages; --thumbs-db = harvest `serve --record-thumbs` thumbs)soup loop status Counters + status + pre_wired flagsoup loop watch [--detach] [--max-iterations N] [--pre-wired] [--pack-cans] Harvest β train β gate β deploy daemon (pre-wired stages + Soup Can packing)soup loop pause Atomic status flip: pause watch daemon at next iteration boundarydiff --git a/src/soup_cli/commands/loop.py b/src/soup_cli/commands/loop.pyindex 9f11612f..c5dc42ff 100644--- a/src/soup_cli/commands/loop.py+++ b/src/soup_cli/commands/loop.py@@ -41,6 +41,7 @@ from soup_cli.utils.loop_state import (read_state,write_state,)+from soup_cli.utils.terminal import for_terminalapp = typer.Typer(name="loop",@@ -82,6 +83,14 @@ def init_cmd("(utils/loop_stages.py) on watch instead of no-op stubs (v0.71.4)."),),+ thumbs_db: Optional[str] = typer.Option(+ None, "--thumbs-db",+ help=(+ "Local-RL SQLite written by `soup serve --record-thumbs`; the "+ "pre-wired harvest turns its thumbs into preference pairs. Must "+ "stay under cwd. SOUP_LOOP_THUMBS_DB overrides it."+ ),+ ),force: bool = typer.Option(False, "--force", help="Overwrite existing loop.yaml."),) -> None:"""Create the .soup/loop.yaml control file (one-time setup)."""@@ -97,6 +106,14 @@ def init_cmd():console.print("[red]--max-runs-per-day must be a positive int[/]")raise typer.Exit(code=2)+ if thumbs_db is not None:+ from soup_cli.utils.local_rl import validate_db_path++ try:+ validate_db_path(thumbs_db)+ except (TypeError, ValueError) as exc:+ console.print(f"[red]invalid --thumbs-db:[/] {for_terminal(exc)}")+ raise typer.Exit(code=2)try:state, path = init_state(served_model=served_model,@@ -105,6 +122,7 @@ def init_cmd(monthly_budget_usd=budget_usd,max_runs_per_day=max_runs_per_day,pre_wired=pre_wired,+ thumbs_db=thumbs_db,force=force,)except (FileExistsError, FileNotFoundError, TypeError, ValueError) as exc:@@ -215,6 +233,21 @@ def watch_cmd(console.print("[red]--detach and --foreground are mutually exclusive[/]")raise typer.Exit(code=2)state = _safe_read() # ensure state exists before forking+ if pre_wired or state.pre_wired:+ # #1440: a configured thumbs database the harvest would refuse stops the+ # watch here, before it starts or detaches, instead of mid-iteration.+ from soup_cli.utils.loop_stages import checked_thumbs_db++ try:+ checked_thumbs_db(state)+ except ValueError as exc:+ console.print(f"[red]invalid thumbs database:[/] {for_terminal(exc)}")+ raise typer.Exit(code=2)+ elif os.environ.get("SOUP_LOOP_THUMBS_DB") or state.thumbs_db:+ console.print(+ "[yellow]warning:[/] a thumbs database is configured but the stub stages "+ "never read it; run `soup loop watch --pre-wired` to harvest it"+ )if detach:argv = [sys.executable,diff --git a/src/soup_cli/utils/loop_stages.py b/src/soup_cli/utils/loop_stages.pyindex 126d85a7..7975638e 100644--- a/src/soup_cli/utils/loop_stages.py+++ b/src/soup_cli/utils/loop_stages.py@@ -22,21 +22,24 @@ and offline smokes inject behaviour without a GPU or a network:from __future__ import annotations+import contextlibimport jsonimport loggingimport osimport re+import sqlite3import sysimport uuidfrom pathlib import Path-from typing import TYPE_CHECKING, Callable, Mapping, Optional+from typing import TYPE_CHECKING, Callable, Mapping, Optional, Tuplefrom soup_cli.utils.loop_state import LoopStatefrom soup_cli.utils.net_guard import LOOPBACK_HOSTS as _LOOPBACK_HOSTSfrom soup_cli.utils.net_guard import parse_ip_literal-from soup_cli.utils.paths import atomic_write_text+from soup_cli.utils.paths import atomic_write_text, quote_pathif TYPE_CHECKING:+ from soup_cli.data.traces.pair_builder import PreferencePairfrom soup_cli.utils.loop_daemon import WatchConfig_LOG = logging.getLogger(__name__)@@ -44,6 +47,8 @@ _LOG = logging.getLogger(__name__)_PAIRS_DIR = ".soup-loops/pairs"_ADAPTERS_DIR = ".soup-loops/adapters"_DEFAULT_TRACE_DIR = ".soup-loops/traces"+# #1440 β `source` tag on pairs harvested from the `--record-thumbs` database.+_THUMBS_SOURCE = "soup-serve-thumbs"# Test / smoke escape hatches (default None β real behaviour)._TRACE_DIR_RESOLVER: Optional[Callable[[LoopState], Optional[str]]] = None@@ -85,27 +90,120 @@ def _resolve_trace_dir(state: LoopState) -> Optional[str]:return None-def harvest_from_traces(state: LoopState) -> Mapping[str, object]:- """Scan serve traces for thumbs/regeneration signals β preference pairs.+def _resolve_thumbs_db(state: LoopState) -> Optional[Tuple[str, str]]:+ """Return ``(path, field)`` for the thumbs database, or ``None``.++ Same precedence as the trace directory: ``SOUP_LOOP_THUMBS_DB`` env, then+ ``thumbs_db`` from ``loop.yaml`` (``soup loop init --thumbs-db``). The+ field name travels with the path so a refusal names where it came from.+ """+ env = os.environ.get("SOUP_LOOP_THUMBS_DB")+ if env:+ return env, "SOUP_LOOP_THUMBS_DB"+ if state.thumbs_db:+ return state.thumbs_db, "thumbs_db"+ return None+++def checked_thumbs_db(state: LoopState) -> Optional[str]:+ """Return the configured thumbs database, checked, or ``None`` (#1440).++ The harvest reads a database only when told to, like ``soup serve+ --record-thumbs`` itself. A configured path that leaves cwd or is a+ symlink (the rule ``--record-thumbs`` applies on the serve side), or that+ is not an existing, readable thumbs database, raises ``ValueError`` naming+ its field instead of harvesting a silent 0. A database that is merely+ locked (a running serve) passes. ``soup loop watch`` runs this before it+ starts.+ """+ resolved = _resolve_thumbs_db(state)+ if resolved is None:+ return None+ path, field = resolved+ from soup_cli.utils.local_rl import validate_db_path++ try:+ validate_db_path(path)+ except (TypeError, ValueError) as exc:+ msg = str(exc)+ if "under cwd" in msg or "symlink" in msg:+ msg += "; move the database under the project directory"+ raise ValueError(f"{field}: {msg}") from exc+ if not os.path.isfile(path):+ raise ValueError(+ f"{field}: no database file at {quote_path(path)}; "+ f"soup serve --record-thumbs {quote_path(path)} creates it"+ )+ try:+ # Short timeout: a lock is not a verdict, so do not wait out sqlite's 5 s.+ with contextlib.closing(sqlite3.connect(os.path.abspath(path), timeout=0.1)) as conn:+ conn.execute("SELECT 1 FROM thumbs LIMIT 1")+ except sqlite3.Error as exc:+ if "locked" in str(exc).lower():+ return path+ raise ValueError(+ f"{field}: {quote_path(path)} is not a readable thumbs database "+ f"({type(exc).__name__}); soup serve --record-thumbs creates one"+ ) from exc+ return path+++def _thumbs_pairs(state: LoopState) -> "list[PreferencePair]":+ """Pairs from the ``soup serve --record-thumbs`` database (#1440)."""+ path = checked_thumbs_db(state)+ if path is None:+ return []+ from soup_cli.data.traces.pair_builder import PreferencePair+ from soup_cli.utils.local_rl import harvest_dpo_pairs++ try:+ found = harvest_dpo_pairs(path)+ except sqlite3.Error as exc:+ # Passed the check, then failed while reading (lock, corruption).+ raise ValueError(+ f"{_resolve_thumbs_db(state)[1]}: {quote_path(path)} could not be read "+ f"({type(exc).__name__}: {exc})"+ ) from exc+ return [+ PreferencePair(+ prompt=p.prompt, chosen=p.chosen, rejected=p.rejected, source=_THUMBS_SOURCE+ )+ for p in found+ ]+- Writes the harvested pairs to ``.soup-loops/pairs/<uuid>.jsonl`` (cwd-- contained) and returns ``{pairs_harvested, pairs_path, traces_collected}``.- Yields zero pairs (no path) when no trace directory is configured.+def harvest_from_traces(state: LoopState) -> Mapping[str, object]:+ """Serve traces and recorded thumbs β preference pairs.++ Reads ``soup serve --trace-log`` directories (thumbs/regeneration signals)+ and, when one is configured, the ``soup serve --record-thumbs`` database+ (#1440); the two are unioned without exact duplicates. Writes the pairs to+ ``.soup-loops/pairs/<uuid>.jsonl`` (cwd-contained) and returns+ ``{pairs_harvested, pairs_path, traces_collected, thumbs_pairs}``+ (``thumbs_pairs`` counts the pairs READ from the database, before the union+ drops any that a trace already supplied). Yields+ zero pairs (no path) when neither source has any; a configured database+ that is refused or missing raises (see ``checked_thumbs_db``)."""from soup_cli.data.traces.pair_builder import build_pairsfrom soup_cli.data.traces.parsers import parse_soup_servetrace_dir = _resolve_trace_dir(state)- if not trace_dir:- return {"pairs_harvested": 0, "pairs_path": None, "traces_collected": 0}-- traces = list(parse_soup_serve(trace_dir))- pairs = list(build_pairs(traces, signal="thumbs_up"))+ traces = list(parse_soup_serve(trace_dir)) if trace_dir else []+ pairs = list(build_pairs(traces, signal="thumbs_up")) if traces else []+ thumbs = _thumbs_pairs(state)+ seen = {(p.prompt, p.chosen, p.rejected) for p in pairs}+ for p in thumbs:+ key = (p.prompt, p.chosen, p.rejected)+ if key not in seen: # harvest_dpo_pairs yields one pair per prompt: no self-dupes+ pairs.append(p)+ extra = {"thumbs_pairs": len(thumbs)}if not pairs:return {"pairs_harvested": 0,"pairs_path": None,"traces_collected": len(traces),+ **extra,}pairs_dir = Path(_PAIRS_DIR)@@ -119,6 +217,7 @@ def harvest_from_traces(state: LoopState) -> Mapping[str, object]:"pairs_harvested": len(pairs),"pairs_path": pairs_path,"traces_collected": len(traces),+ **extra,}diff --git a/src/soup_cli/utils/loop_state.py b/src/soup_cli/utils/loop_state.pyindex ab4e6f56..bc53099c 100644--- a/src/soup_cli/utils/loop_state.py+++ b/src/soup_cli/utils/loop_state.py@@ -71,6 +71,10 @@ class LoopState:iteration_count: int = 0created_at: str = ""updated_at: str = ""+ # #1440 β local-RL SQLite that `soup serve --record-thumbs` writes; the+ # pre-wired harvest reads its thumbs as preference pairs. None = not used.+ # Last, so adding it shifted no existing positional field.+ thumbs_db: Optional[str] = Nonedef __post_init__(self) -> None: # noqa: D401 β validator hook# Closed-allowlist enforcement + bool-as-int rejection mirror the@@ -118,6 +122,8 @@ class LoopState:raise ValueError("pre_wired must be bool")if self.canary_active is not None:_require_str("canary_active", self.canary_active, allow_empty=False)+ if self.thumbs_db is not None:+ _require_str("thumbs_db", self.thumbs_db, allow_empty=False)if self.canary_rollout_id is not None:_require_str("canary_rollout_id", self.canary_rollout_id, allow_empty=False)if self.last_iteration_id is not None:@@ -282,6 +288,7 @@ def init_state(monthly_budget_usd: Optional[float] = None,max_runs_per_day: Optional[int] = None,pre_wired: bool = False,+ thumbs_db: Optional[str] = None,path: Optional[str] = None,force: bool = False,) -> Tuple[LoopState, str]:@@ -310,6 +317,7 @@ def init_state(baseline=baseline,status="stopped",pre_wired=pre_wired,+ thumbs_db=thumbs_db,monthly_budget_usd=monthly_budget_usd,max_runs_per_day=max_runs_per_day,created_at=now,diff --git a/tests/test_loop_thumbs_harvest.py b/tests/test_loop_thumbs_harvest.pynew file mode 100644index 00000000..b2df46e7--- /dev/null+++ b/tests/test_loop_thumbs_harvest.py@@ -0,0 +1,619 @@+"""#1440 (producer half) β the loop must learn from `soup serve --record-thumbs`.++`soup serve --record-thumbs PATH` stores every `POST /v1/thumbs` as a+`(prompt, response, thumb)` row in a local-RL SQLite, and+`local_rl.harvest_dpo_pairs` already turns those rows into DPO pairs. The+pre-wired loop harvest read only `soup serve --trace-log` directories, whose+records carry no thumbs signal, so a loop next to a serve that recorded thumbs+harvested nothing.++The harvest now also reads a thumbs database named by `SOUP_LOOP_THUMBS_DB` or+by `soup loop init --thumbs-db PATH` (persisted in `.soup/loop.yaml`).+"""++from __future__ import annotations++import json+import os+import sqlite3++import pytest+from typer.testing import CliRunner++from tests.conftest import strip_ansi+++def _record(db: str, *rows) -> None:+ from soup_cli.utils import local_rl++ if not os.path.exists(db):+ local_rl.init_local_rl_db(db)+ for prompt, response, thumb in rows:+ local_rl.record_thumb(db_path=db, prompt=prompt, response=response, thumb=thumb)+++def _write_jsonl(path, rows) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8")+++def _read_jsonl(path) -> list:+ with open(path, encoding="utf-8") as fh:+ return [json.loads(line) for line in fh if line.strip()]+++def _state(**kwargs):+ from soup_cli.utils.loop_state import LoopState++ # A registry ref, so the served model is never mistaken for a trace dir.+ return LoopState(served_model="registry://dummy", eval_suite="e", baseline="b", **kwargs)+++def cwd(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ monkeypatch.delenv("SOUP_LOOP_TRACE_DIR", raising=False)+ monkeypatch.delenv("SOUP_LOOP_THUMBS_DB", raising=False)+ return tmp_path+++def test_the_issue_reproduction_harvests_the_recorded_pair(cwd, monkeypatch):+ """One up and one down thumb for the same prompt, no trace directory at all."""+ from soup_cli.utils.loop_stages import harvest_from_traces++ _record("thumbs.db", ("Q", "Good", "up"), ("Q", "Bad", "down"))+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "thumbs.db")++ result = harvest_from_traces(_state())++ assert result["pairs_harvested"] == 1, result+ assert result["thumbs_pairs"] == 1, result+ pairs = _read_jsonl(result["pairs_path"])+ assert pairs == [+ {"prompt": "Q", "chosen": "Good", "rejected": "Bad", "source": "soup-serve-thumbs"}+ ]+++def test_the_database_named_in_loop_state_is_read(cwd):+ from soup_cli.utils.loop_stages import harvest_from_traces++ _record("thumbs.db", ("Q", "Good", "up"), ("Q", "Bad", "down"))++ result = harvest_from_traces(_state(thumbs_db="thumbs.db"))++ assert result["pairs_harvested"] == 1, result+++def test_the_environment_overrides_loop_state(cwd, monkeypatch):+ """Same precedence as the trace directory: env first, then loop.yaml."""+ from soup_cli.utils.loop_stages import harvest_from_traces++ _record("a.db", ("Q", "Good", "up"), ("Q", "Bad", "down"))+ _record("b.db", ("Q2", "Yes", "up"), ("Q2", "No", "down"))+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "b.db")++ pairs = _read_jsonl(harvest_from_traces(_state(thumbs_db="a.db"))["pairs_path"])++ assert [(p["prompt"], p["chosen"]) for p in pairs] == [("Q2", "Yes")]+++def test_trace_and_thumbs_pairs_are_unioned_without_duplicates(cwd, monkeypatch):+ from soup_cli.utils.loop_stages import harvest_from_traces++ def _trace(i, prompt, good, bad):+ return [+ {"id": f"{i}a", "prompt": prompt, "output": good, "signal": "thumbs_up"},+ {"id": f"{i}b", "prompt": prompt, "output": bad, "signal": "thumbs_down"},+ ]++ _write_jsonl(+ cwd / "traces" / "t.jsonl",+ _trace(1, "Q", "Good", "Bad") + _trace(2, "R", "G2", "B2") + _trace(3, "Q2", "Yes", "No"),+ )+ _record(+ "thumbs.db",+ ("Q", "Good", "up"), ("Q", "Bad2", "down"), # same prompt+chosen, other rejected: kept+ ("R", "G3", "up"), ("R", "B2", "down"), # same prompt+rejected, other chosen: kept+ ("Q2", "Yes", "up"), ("Q2", "No", "down"), # exact duplicate of a trace pair: dropped+ ("Q3", "A", "up"), ("Q3", "B", "down"), # new prompt: kept+ )+ monkeypatch.setenv("SOUP_LOOP_TRACE_DIR", str(cwd / "traces"))+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "thumbs.db")++ result = harvest_from_traces(_state())++ assert result["traces_collected"] == 6, result+ assert result["thumbs_pairs"] == 4, result # pairs READ from the database, duplicates included+ assert result["pairs_harvested"] == 6, result+ rows = _read_jsonl(result["pairs_path"])+ # Trace pairs first, then the thumbs pairs the union kept (order decides the val_split tail).+ assert [p["source"] for p in rows] == ["thumbs_up"] * 3 + ["soup-serve-thumbs"] * 3, rows+ got = sorted((p["prompt"], p["chosen"], p["rejected"], p["source"]) for p in rows)+ assert got == [+ ("Q", "Good", "Bad", "thumbs_up"),+ ("Q", "Good", "Bad2", "soup-serve-thumbs"),+ ("Q2", "Yes", "No", "thumbs_up"), # the duplicate keeps the trace row's source+ ("Q3", "A", "B", "soup-serve-thumbs"),+ ("R", "G2", "B2", "thumbs_up"),+ ("R", "G3", "B2", "soup-serve-thumbs"),+ ]+++def test_thumbs_pairs_is_reported_when_nothing_was_harvested(cwd, monkeypatch):+ """Zero-pair path: a database with only up-thumbs reads 0 pairs, and says so."""+ from soup_cli.utils.loop_stages import harvest_from_traces++ _record("thumbs.db", ("Q", "Good", "up"))+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "thumbs.db")++ result = harvest_from_traces(_state())++ assert result["pairs_harvested"] == 0, result+ assert result["pairs_path"] is None, result+ assert result["thumbs_pairs"] == 0, result++[email protected]("via", ["env", "loop.yaml"])+def test_a_configured_database_that_does_not_exist_fails_the_stage_by_name(+ cwd, monkeypatch, via+):+ """Maintainer ruling: missing fails the stage naming the field, never a silent 0."""+ from soup_cli.utils.loop_stages import harvest_from_traces++ if via == "env":+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "not-yet.db")+ state, field = _state(), "SOUP_LOOP_THUMBS_DB"+ else:+ state, field = _state(thumbs_db="not-yet.db"), "thumbs_db"++ with pytest.raises(ValueError, match=f"^{field}: no database file at 'not-yet.db'"):+ harvest_from_traces(state)+ assert not os.path.exists(os.path.join(".soup-loops", "pairs"))+++def test_a_directory_at_the_database_path_is_refused_too(cwd, monkeypatch):+ from soup_cli.utils.loop_stages import harvest_from_traces++ os.mkdir("thumbs.db")+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "thumbs.db")++ with pytest.raises(ValueError, match="SOUP_LOOP_THUMBS_DB: no database file"):+ harvest_from_traces(_state())+++def test_a_database_outside_the_project_is_refused_by_name(cwd, monkeypatch, tmp_path_factory):+ """The file EXISTS, so only the containment rule can be what refuses it."""+ from soup_cli.utils.loop_stages import harvest_from_traces++ outside = tmp_path_factory.mktemp("elsewhere") / "thumbs.db"+ sqlite3.connect(str(outside)).close()+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", str(outside))++ with pytest.raises(+ ValueError,+ match=r"^SOUP_LOOP_THUMBS_DB: db_path 'thumbs.db' must stay under cwd; "+ r"move the database under the project directory$",+ ):+ harvest_from_traces(_state())++[email protected]_symlink+def test_a_symlinked_database_is_refused_by_name(cwd):+ from soup_cli.utils.loop_stages import harvest_from_traces++ _record("real.db", ("Q", "Good", "up"), ("Q", "Bad", "down"))+ os.symlink("real.db", "link.db")++ with pytest.raises(+ ValueError,+ match=r"^thumbs_db: db_path must not be a symlink.*; "+ r"move the database under the project directory$",+ ):+ harvest_from_traces(_state(thumbs_db="link.db"))+++def test_a_refusal_that_is_not_about_location_gets_no_move_advice(cwd, monkeypatch):+ from soup_cli.utils.loop_stages import checked_thumbs_db++ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "a\nb.db")++ with pytest.raises(+ ValueError,+ match=r"^SOUP_LOOP_THUMBS_DB: db_path must not contain newline / carriage return$",+ ):+ checked_thumbs_db(_state())+++def test_without_a_thumbs_database_the_harvest_is_unchanged(cwd):+ """Control: no env, no loop.yaml field, no trace dir -> the old zero result."""+ from soup_cli.utils.loop_stages import harvest_from_traces++ result = harvest_from_traces(_state())++ assert result["pairs_harvested"] == 0, result+ assert result["pairs_path"] is None, result+ assert result["traces_collected"] == 0, result+++def test_loop_init_persists_thumbs_db_and_an_old_state_file_still_loads(cwd):+ from soup_cli.cli import app+ from soup_cli.utils.loop_state import default_state_path, read_state++ runner = CliRunner()+ result = runner.invoke(app, [+ "loop", "init", "registry://m", "--eval", "suite.yaml", "--baseline", "b",+ "--thumbs-db", "thumbs.db",+ ])+ assert result.exit_code == 0, strip_ansi(result.output)+ assert read_state().thumbs_db == "thumbs.db"++ # A loop.yaml written before the field existed loads with thumbs_db unset.+ path = default_state_path()+ data = json.loads(open(path, encoding="utf-8").read())+ del data["thumbs_db"]+ with open(path, "w", encoding="utf-8") as fh:+ json.dump(data, fh)+ assert read_state().thumbs_db is None+++def test_loop_init_refuses_a_thumbs_db_outside_the_project(cwd, tmp_path_factory):+ from soup_cli.cli import app++ outside = tmp_path_factory.mktemp("elsewhere") / "thumbs.db"+ result = CliRunner().invoke(app, [+ "loop", "init", "registry://m", "--eval", "suite.yaml", "--baseline", "b",+ "--thumbs-db", str(outside),+ ])+ text = " ".join(strip_ansi(result.output).split())+ assert result.exit_code == 2, text+ # The option exists and the refusal is the containment rule, not a usage error.+ assert "No such option" not in text, text+ assert "--thumbs-db" in text and "under cwd" in text, text+ assert not os.path.exists(os.path.join(".soup", "loop.yaml"))+++def test_thumbs_db_is_the_last_field_so_positional_fields_keep_their_meaning():+ """Adding the field must not shift `traces_collected` and the rest for positional callers."""+ import dataclasses++ from soup_cli.utils.loop_state import LoopState++ names = [f.name for f in dataclasses.fields(LoopState)]+ assert names[-1] == "thumbs_db", names+ state = LoopState("m", "e", "b", "stopped", False, 7)+ assert state.traces_collected == 7+ assert state.thumbs_db is None+++def _make_bad_db(kind: str, path: str = "thumbs.db") -> None:+ if kind == "text":+ with open(path, "w", encoding="utf-8") as fh:+ fh.write("this is not a database\n" * 20)+ else: # a valid SQLite file with no thumbs table (empty, or another Soup .db)+ sqlite3.connect(path).close()++[email protected]("kind", ["text", "empty-sqlite"])[email protected]("via", ["env", "loop.yaml"])+def test_a_file_that_is_not_a_thumbs_database_fails_the_stage_by_name(+ cwd, monkeypatch, via, kind+):+ from soup_cli.utils.loop_stages import harvest_from_traces++ _make_bad_db(kind)+ if via == "env":+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "thumbs.db")+ state, field = _state(), "SOUP_LOOP_THUMBS_DB"+ else:+ state, field = _state(thumbs_db="thumbs.db"), "thumbs_db"++ with pytest.raises(+ ValueError,+ match=rf"^{field}: 'thumbs.db' is not a readable thumbs database "+ r"\(\w*Error\); soup serve --record-thumbs creates one$",+ ):+ harvest_from_traces(state)+ assert not os.path.exists(os.path.join(".soup-loops", "pairs"))+++def test_a_locked_database_is_not_refused_by_the_check(cwd, monkeypatch):+ """A running serve can hold the lock briefly; that is not a bad database."""+ import time++ from soup_cli.utils.loop_stages import checked_thumbs_db++ _record("thumbs.db", ("Q", "Good", "up"))+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "thumbs.db")+ holder = sqlite3.connect("thumbs.db", isolation_level=None)+ try:+ holder.execute("BEGIN EXCLUSIVE")+ started = time.monotonic()+ assert checked_thumbs_db(_state()) == "thumbs.db"+ assert time.monotonic() - started < 3, "the check must not wait out sqlite's 5 s default"+ finally:+ holder.close()++[email protected]("via", ["env", "loop.yaml"])+def test_a_sqlite_failure_mid_harvest_names_the_field(cwd, monkeypatch, via):+ """The file passed the check, then sqlite failed while reading (lock, corruption)."""+ import soup_cli.utils.local_rl as local_rl+ from soup_cli.utils.loop_stages import harvest_from_traces++ _record("thumbs.db", ("Q", "Good", "up"), ("Q", "Bad", "down"))+ if via == "env":+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "thumbs.db")+ state, field = _state(), "SOUP_LOOP_THUMBS_DB"+ else:+ state, field = _state(thumbs_db="thumbs.db"), "thumbs_db"++ def _boom(_path):+ raise sqlite3.OperationalError("database is locked")++ monkeypatch.setattr(local_rl, "harvest_dpo_pairs", _boom)++ with pytest.raises(+ ValueError,+ match=rf"^{field}: 'thumbs.db' could not be read \(OperationalError: database is locked\)$",+ ):+ harvest_from_traces(state)+++def test_control_characters_in_a_configured_path_never_reach_the_message(cwd, monkeypatch):+ from soup_cli.utils.loop_stages import checked_thumbs_db++ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "a\x1b[2Jb.db")++ with pytest.raises(ValueError) as info:+ checked_thumbs_db(_state())++ assert "\x1b[2J" not in str(info.value)+ assert "no database file at" in str(info.value)+++def _stored_state_with(**fields):+ from soup_cli.utils.loop_state import default_state_path, read_state++ _init_loop(True)+ path = default_state_path()+ data = json.loads(open(path, encoding="utf-8").read())+ data.update(fields)+ with open(path, "w", encoding="utf-8") as fh:+ json.dump(data, fh)+ return read_state++[email protected]("bad", ["", 123, "x" * 513])+def test_read_state_refuses_a_bad_thumbs_db(cwd, bad):+ read_state = _stored_state_with(thumbs_db=bad)++ with pytest.raises(ValueError, match="thumbs_db"):+ read_state()+++def test_an_empty_environment_variable_is_treated_as_unset(cwd, monkeypatch):+ """Like SOUP_LOOP_TRACE_DIR: empty falls through to loop.yaml, or to nothing."""+ from soup_cli.utils.loop_stages import harvest_from_traces++ _record("a.db", ("Q", "Good", "up"), ("Q", "Bad", "down"))+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "")++ assert harvest_from_traces(_state(thumbs_db="a.db"))["pairs_harvested"] == 1+ assert harvest_from_traces(_state())["pairs_harvested"] == 0+++# --- `soup loop watch` refuses a bad thumbs database before it starts --------+++def _init_loop(pre_wired: bool, *extra: str) -> None:+ from soup_cli.cli import app++ args = ["loop", "init", "registry://m", "--eval", "suite.yaml", "--baseline", "b"]+ if pre_wired:+ args.append("--pre-wired")+ result = CliRunner().invoke(app, args + list(extra))+ assert result.exit_code == 0, strip_ansi(result.output)+++def _watch(*extra: str):+ from soup_cli.cli import app++ result = CliRunner().invoke(+ app, ["loop", "watch", "--max-iterations", "1", "--poll-interval", "1", *extra]+ )+ return result, " ".join(strip_ansi(result.output).split())++[email protected]("how", ["init --pre-wired", "watch --pre-wired"])+def test_watch_refuses_a_missing_database_before_any_iteration(cwd, monkeypatch, how):+ from soup_cli.utils.loop_state import read_state++ _init_loop(pre_wired=how.startswith("init"))+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "not-yet.db")++ result, text = _watch(*(["--pre-wired"] if how.startswith("watch") else []))++ assert result.exit_code == 2, text+ assert "invalid thumbs database" in text, text+ assert "SOUP_LOOP_THUMBS_DB: no database file at 'not-yet.db'" in text, text+ assert "Traceback" not in text, text+ assert not os.path.exists(".soup-loops"), "no iteration may run"+ assert read_state().status == "stopped"+++def test_watch_refuses_the_loop_yaml_field_and_an_outside_path_by_name(+ cwd, monkeypatch, tmp_path_factory+):+ _init_loop(True, "--thumbs-db", "gone.db")+ result, text = _watch()+ assert result.exit_code == 2, text+ assert "thumbs_db: no database file at 'gone.db'" in text, text++ outside = tmp_path_factory.mktemp("elsewhere") / "thumbs.db"+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", str(outside))+ result, text = _watch()+ assert result.exit_code == 2, text+ assert "SOUP_LOOP_THUMBS_DB:" in text and "under cwd" in text, text+++def test_watch_detach_refuses_before_spawning(cwd, monkeypatch):+ import soup_cli.commands.loop as loop_cmd++ spawned = []+ monkeypatch.setattr(loop_cmd.subprocess, "Popen", lambda *a, **k: spawned.append(a))+ _init_loop(True)+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "not-yet.db")++ result, text = _watch("--detach")++ assert result.exit_code == 2, text+ assert spawned == []+++def test_watch_with_a_recorded_database_harvests_through_the_cli(cwd, monkeypatch):+ """Control: an existing database passes the check and the iteration records the pair."""+ import soup_cli.utils.loop_stages as ls+ from soup_cli.utils.loop_iteration import list_iterations, read_iteration++ class _Failed:+ returncode = 1 # the train subprocess is not under test here++ monkeypatch.setattr(ls, "_TRAIN_RUNNER", lambda *a, **k: _Failed())+ _record("thumbs.db", ("Q", "Good", "up"), ("Q", "Bad", "down"))+ _init_loop(True, "--thumbs-db", "thumbs.db")++ result, text = _watch()++ assert result.exit_code == 0, text+ assert "stub stages never read it" not in text, text+ ids = list_iterations()+ assert len(ids) == 1, ids+ assert read_iteration(ids[0]).pairs_harvested == 1+++def test_watch_without_pre_wired_stages_does_not_check_the_database(cwd, monkeypatch):+ """Control: the stub harvest never reads it, so it is not refused there."""+ _init_loop(False)+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "not-yet.db")++ result, text = _watch()++ assert result.exit_code == 0, text+ assert "invalid thumbs database" not in text, text++[email protected]("kind", ["text", "empty-sqlite"])+def test_watch_refuses_a_file_that_is_not_a_thumbs_database(cwd, monkeypatch, kind):+ from soup_cli.utils.loop_state import read_state++ _make_bad_db(kind)+ _init_loop(True)+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "thumbs.db")++ result, text = _watch()++ assert result.exit_code == 2, text+ assert "invalid thumbs database" in text, text+ assert "SOUP_LOOP_THUMBS_DB: 'thumbs.db' is not a readable thumbs database" in text, text+ assert "Traceback" not in text, text+ assert not os.path.exists(".soup-loops"), "no iteration may run"+ assert read_state().status == "stopped"++[email protected]("kind", ["text", "empty-sqlite"])+def test_watch_detach_refuses_a_file_that_is_not_a_thumbs_database(cwd, monkeypatch, kind):+ import soup_cli.commands.loop as loop_cmd++ spawned = []+ monkeypatch.setattr(loop_cmd.subprocess, "Popen", lambda *a, **k: spawned.append(a))+ _make_bad_db(kind)+ _init_loop(True)+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "thumbs.db")++ result, text = _watch("--detach")++ assert result.exit_code == 2, text+ assert "not a readable thumbs database" in text, text+ assert spawned == []+++def test_watch_does_not_let_a_control_sequence_in_the_path_reach_the_terminal(cwd, monkeypatch):+ _init_loop(True)+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "a\x1b[2Jb.db")++ result, _text = _watch()++ assert result.exit_code == 2, result.output+ assert "\x1b[2J" not in result.output # the sequence itself, not "any ESC" (Rich adds its own)+ assert "no database file at" in " ".join(strip_ansi(result.output).split())+++def test_init_does_not_let_a_control_sequence_in_the_path_reach_the_terminal(cwd):+ from soup_cli.cli import app++ result = CliRunner().invoke(app, [+ "loop", "init", "registry://m", "--eval", "suite.yaml", "--baseline", "b",+ "--thumbs-db", "../a\x1b[2Jb.db",+ ])++ assert result.exit_code == 2, result.output+ assert "\x1b[2J" not in result.output++[email protected]("via", ["env", "loop.yaml"])+def test_watch_warns_when_the_stub_stages_will_not_read_the_database(cwd, monkeypatch, via):+ if via == "env":+ _init_loop(False)+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "not-yet.db")+ else:+ _init_loop(False, "--thumbs-db", "not-yet.db")++ result, text = _watch()++ assert result.exit_code == 0, text+ assert "stub stages never read it" in text and "--pre-wired" in text, text+ # An existing loop cannot be re-initialised without --force, which resets it.+ assert "loop init" not in text, text++[email protected]("env", [None, ""])+def test_watch_does_not_warn_without_a_thumbs_database(cwd, monkeypatch, env):+ _init_loop(False)+ if env is not None:+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", env)++ result, text = _watch()++ assert result.exit_code == 0, text+ assert "--pre-wired" not in text, text+++# --- a Rich tag in a refused path stays literal (#1440) ----------------------+++def test_init_refusal_keeps_rich_tags_in_the_path_literal(cwd):+ from soup_cli.cli import app++ result = CliRunner().invoke(app, [+ "loop", "init", "registry://m", "--eval", "suite.yaml", "--baseline", "b",+ "--thumbs-db", "../db[bold]x.db",+ ])+ plain = " ".join(strip_ansi(result.output).split())++ assert result.exit_code == 2, plain+ assert "invalid --thumbs-db:" in plain, plain+ assert "db[bold]x.db" in plain, plain # the brackets survive; nothing is parsed as markup+ assert "'dbx.db'" not in plain, plain+++def test_watch_refusal_keeps_rich_tags_in_the_path_literal(cwd, monkeypatch):+ (cwd / "db[bold]x.db").write_text("not a database", encoding="utf-8")+ _init_loop(True)+ monkeypatch.setenv("SOUP_LOOP_THUMBS_DB", "db[bold]x.db")++ result, text = _watch()++ assert result.exit_code == 2, text+ assert "invalid thumbs database:" in text, text+ assert "db[bold]x.db" in text, text # the brackets survive; nothing is parsed as markup+ assert "'dbx.db'" not in text, text