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): write canaries in the dataset's own format (#1216) (#1317)
Abdulwaarith Zakariyya93178cf5d117
diff --git a/changelog.d/0.75.1/1317.fixed.md b/changelog.d/0.75.1/1317.fixed.mdnew file mode 100644index 00000000..21422083--- /dev/null+++ b/changelog.d/0.75.1/1317.fixed.md@@ -0,0 +1,2 @@+- **`soup data canary insert` wrote chatml canaries into every dataset, so on any other format the loader dropped all of them and `check` could only report OK (#1216 by @abdulwaarith0 in #1317).** `insert` now writes the canaries in the dataset's own format (`--format`, default `auto`): alpaca, sharegpt and chatml, with the carrier as the prompt and the secret as the trained response. Every other format is refused before anything is written, naming the format, as is an explicit `--format` that is not the file's own. The manifest records the format; a manifest without one reads as chatml, and `check` refuses a format it does not know rather than scoring it as chat. `-o canaried.json` now writes a JSON array that loads back, and suffixes the loader would misread are refused.+ (#1216 by @abdulwaarith0 in #1317)diff --git a/docs/data.md b/docs/data.mdindex bae61c68..5699909e 100644--- a/docs/data.md+++ b/docs/data.md@@ -155,6 +155,15 @@ soup data canary insert train.jsonl -o canaried.jsonl --count 16 --manifest secrsoup data canary check --manifest secrets.json --base ./my-model --adapter ./lora```+`insert` writes the canaries in the dataset's own format, so the loader keeps them:+`--format auto` (the default) detects it from the first row, as `data.format: auto`+does. Alpaca, sharegpt and chatml are supported, each with the carrier as the prompt+and the secret as the trained response. Every other format is refused: dpo, kto and+embedding have no single supervised response, plaintext trains on raw text rather+than the chat turn `check` scores, tool-calling puts a tool-schema system turn+before the prompt, which `check` does not render, and the multimodal formats need a+real image or audio file per row. `-o` takes `.jsonl`, or `.json` for a JSON array.+`check` measures the model's loss on each inserted secret and ranks it againstnever-inserted **controls** drawn from the same secret space and sharing the samecarrier prompt — so a low loss means the *secret* is unusually likely, not thediff --git a/src/soup_cli/commands/data_canary.py b/src/soup_cli/commands/data_canary.pyindex d2f41e44..b36e794c 100644--- a/src/soup_cli/commands/data_canary.py+++ b/src/soup_cli/commands/data_canary.py@@ -13,15 +13,17 @@ from __future__ import annotationsimport jsonimport mathfrom pathlib import Path-from typing import TYPE_CHECKING, Optional+from typing import TYPE_CHECKING, NoReturn, Optionalimport typerfrom rich.console import Consolefrom rich.markup import escapefrom rich.table import Table+from soup_cli.data.formats import detect_formatfrom soup_cli.data.loader import load_raw_datafrom soup_cli.utils.canary import (+ CANARY_FORMATS,_harden_permissions,build_canary_report,canary_report_to_dict,@@ -67,16 +69,95 @@ def _guard_under_cwd(target: str, label: str) -> None:raise typer.Exit(1)+# What ``-o`` may be: the loader reads a ``.json`` file as ONE array and+# ``.jsonl`` line by line; any other suffix would not load back as written.+_OUTPUT_SUFFIXES = (".jsonl", ".json")+++def _refuse(message: str) -> NoReturn:+ console.print(f"[red]{escape(message)}[/]")+ raise typer.Exit(1)+++def _json_type(value: object) -> str:+ """The JSON name for a parsed value, for error messages."""+ if isinstance(value, bool):+ return "boolean"+ if isinstance(value, (int, float)):+ return "number"+ if isinstance(value, str):+ return "string"+ if isinstance(value, list):+ return "array"+ return "null" if value is None else type(value).__name__+++def _resolve_format(rows: list, requested: str, path: str) -> str:+ """The format the canaries are rendered in, or refuse (#1216).++ A canary row the loader cannot convert is dropped before training, and+ ``check`` then reports OK on secrets the model never saw. So the rows+ are written in the format the file loads as, and a format ``check``+ cannot score is refused rather than written.+ """+ supported = ", ".join(CANARY_FORMATS)+ if requested != "auto" and requested not in CANARY_FORMATS:+ _refuse(+ f"canary insert cannot write '{requested}' rows. "+ f"Supported: {supported}"+ )+ if not rows:+ if requested == "auto":+ _refuse(+ f"{path} is empty, so its format cannot be detected; "+ f"pass --format ({supported})"+ )+ return requested+ if not isinstance(rows[0], dict):+ # detect_format reads the first row's keys; anything else would+ # surface as a bare AttributeError.+ _refuse(+ f"{path}: the first row is a JSON {_json_type(rows[0])}, not an "+ "object; canary insert reads each row as a JSON object"+ )+ try:+ detected = detect_format(rows)+ except ValueError as exc:+ _refuse(f"{exc}. canary insert supports: {supported}")+ if requested != "auto" and requested != detected:+ # `data.format: auto` would read the file as `detected` and drop+ # every canary rendered as `requested`.+ _refuse(+ f"--format {requested} was given, but {path} is '{detected}'; "+ "canaries written in one format are dropped when the file loads "+ "as the other"+ )+ if detected not in CANARY_FORMATS:+ _refuse(+ f"{path} is '{detected}', which canary insert cannot write. "+ f"Supported: {supported}"+ )+ return detected++@app.command()def insert(path: str = typer.Argument(..., help="Path to dataset file"),- output: str = typer.Option(..., "--output", "-o", help="Output JSONL"),+ output: str = typer.Option(+ ..., "--output", "-o",+ help="Output file: .jsonl, or .json for a JSON array",+ ),manifest: str = typer.Option(..., "--manifest",help="Where to write the canary manifest (CONTAINS THE SECRETS)",),count: int = typer.Option(16, "--count", "-k", help="Number of canaries"),seed: int = typer.Option(0, "--seed", help="Canary generation seed"),+ data_format: str = typer.Option(+ "auto", "--format",+ help="Dataset format to write the canaries in: auto (detect), "+ + ", ".join(CANARY_FORMATS),+ ),):"""Insert K unique canaries into a dataset and record them."""file_path = Path(path)@@ -85,29 +166,38 @@ def insert(raise typer.Exit(1)_guard_under_cwd(output, "Output")_guard_under_cwd(manifest, "Manifest")+ suffix = Path(output).suffix.lower()+ if suffix not in _OUTPUT_SUFFIXES:+ _refuse(+ f"--output must end in {' or '.join(_OUTPUT_SUFFIXES)}, "+ f"got {output!r}"+ )rows = load_raw_data(file_path)+ fmt = _resolve_format(rows, data_format, path)try:canaries = generate_canaries(count=count, seed=seed)except (ValueError, TypeError) as exc:console.print(f"[red]{escape(str(exc))}[/]")raise typer.Exit(1)- mixed = list(rows) + canary_rows(canaries)+ mixed = list(rows) + canary_rows(canaries, fmt)# Manifest FIRST. If the dataset were written first and the manifest# then failed (disk full, permissions), a canary-poisoned dataset would# survive on disk with nothing left to identify the secrets in it — a# user who missed the error and trained on it could never audit what# was inserted. Failing before the data is written leaves no artifact.try:- write_manifest(canaries, manifest)+ write_manifest(canaries, manifest, fmt)except (ValueError, OSError) as exc:console.print(f"[red]{escape(str(exc))}[/]")raise typer.Exit(1)try:- atomic_write_text(- "\n".join(json.dumps(row) for row in mixed) + "\n", output- )+ if suffix == ".json":+ text = json.dumps(mixed, indent=2) + "\n"+ else:+ text = "\n".join(json.dumps(row) for row in mixed) + "\n"+ atomic_write_text(text, output)except (ValueError, OSError) as exc:# The manifest now describes canaries that are in no dataset. Say so# rather than leaving a manifest that looks authoritative.@@ -121,7 +211,7 @@ def insert(raise typer.Exit(1)console.print(- f"[green]Inserted {len(canaries)} canaries:[/] "+ f"[green]Inserted {len(canaries)} {fmt} canaries:[/] "f"{len(rows)} -> {len(mixed)} rows\n"f"Output: [bold]{escape(output)}[/]\n"f"Manifest: [bold]{escape(manifest)}[/]"diff --git a/src/soup_cli/utils/canary.py b/src/soup_cli/utils/canary.pyindex 98b20750..b6385faa 100644--- a/src/soup_cli/utils/canary.py+++ b/src/soup_cli/utils/canary.py@@ -35,6 +35,20 @@ _SECRET_GROUPS = 3_SECRET_GROUP_LEN = 4_SLUG = "zorbex"+# Formats ``insert`` renders canaries in (#1216). Each puts the carrier in+# one user turn and the secret in the assistant turn after it, which is+# exactly how ``check`` scores a canary (``_tokenize_pair`` in+# utils/live_eval.py renders the carrier through the chat template). Any+# other format is refused: dpo/kto/embedding have no single supervised+# target, plaintext trains on raw text with no template, tool-calling's+# converter puts a tool-schema system turn before the prompt (which+# ``check`` does not render), and the multimodal formats need a real image+# or audio file per row.+CANARY_FORMATS = ("alpaca", "sharegpt", "chatml")+# Every manifest written before #1216 has no format field and describes+# chatml rows, since that is all ``insert`` ever wrote.+_LEGACY_MANIFEST_FORMAT = "chatml"+_MAX_CANARIES = 10_000_MAX_MANIFEST_BYTES = 4 * 1024 * 1024@@ -117,20 +131,47 @@ def generate_controls(return _generate(_require_count(count, "count"), seed, exclude)-def canary_rows(canaries: Sequence[Canary]) -> list[dict]:- """Render canaries as ``{"messages": [...]}`` training rows."""- return [- {- "messages": [- {"role": "user", "content": canary.carrier},- {"role": "assistant", "content": canary.secret.strip()},+def _require_canary_format(fmt: object) -> str:+ if not isinstance(fmt, str) or fmt not in CANARY_FORMATS:+ raise ValueError(+ f"unsupported canary format {fmt!r}; "+ f"supported: {', '.join(CANARY_FORMATS)}"+ )+ return fmt+++def _canary_row(canary: Canary, fmt: str) -> dict:+ secret = canary.secret.strip()+ if fmt == "alpaca":+ return {"instruction": canary.carrier, "output": secret}+ if fmt == "sharegpt":+ return {+ "conversations": [+ {"from": "human", "value": canary.carrier},+ {"from": "gpt", "value": secret},]}- for canary in canaries- ]+ return {+ "messages": [+ {"role": "user", "content": canary.carrier},+ {"role": "assistant", "content": secret},+ ]+ }+++def canary_rows(canaries: Sequence[Canary], fmt: str = "chatml") -> list[dict]:+ """Render canaries as training rows in dataset format ``fmt``.++ The carrier is the prompt and the secret the supervised target, in+ every format, so the secret sits where the trainer computes loss.+ """+ _require_canary_format(fmt)+ return [_canary_row(canary, fmt) for canary in canaries]-def write_manifest(canaries: Sequence[Canary], path: str) -> str:+def write_manifest(+ canaries: Sequence[Canary], path: str, fmt: str = "chatml"+) -> str:"""Persist the secrets. THIS FILE IS THE SENSITIVE ARTIFACT.Anyone holding it can reproduce the canaries, so it must not be@@ -139,11 +180,13 @@ def write_manifest(canaries: Sequence[Canary], path: str) -> str:any local user on a shared box read every canary without ever running``check``. Mirrors registry/store.py, adapter_sign.py, audit_log.py."""+ _require_canary_format(fmt)safe = enforce_under_cwd_and_no_symlink(str(path), "manifest")payload = {"version": 1,"carrier_template": CARRIER_TEMPLATE,"slug": _SLUG,+ "format": fmt,"canaries": [{"carrier": canary.carrier, "secret": canary.secret}for canary in canaries@@ -181,6 +224,12 @@ def load_manifest(path: str) -> tuple[Canary, ...]:raise ValueError(f"manifest is not valid JSON: {exc}") from excif not isinstance(payload, dict):raise ValueError("manifest must be a JSON object")+ # Every supported format is scored the same way (carrier as one user+ # turn), so the value only has to be one ``check`` knows. An unknown one+ # is refused rather than scored as chat: a plaintext canary scored after+ # a chat-templated prompt the model never trained on would read as+ # "not memorized" whatever the model learned.+ _require_canary_format(payload.get("format", _LEGACY_MANIFEST_FORMAT))entries = payload.get("canaries")if not isinstance(entries, list):raise ValueError("manifest 'canaries' must be a list")diff --git a/tests/test_issue1216_canary_formats.py b/tests/test_issue1216_canary_formats.pynew file mode 100644index 00000000..7c5fdeb5--- /dev/null+++ b/tests/test_issue1216_canary_formats.py@@ -0,0 +1,333 @@+"""#1216: `soup data canary insert` writes canaries the training loader keeps.++`insert` used to append `{"messages": [...]}` rows whatever the dataset's+format, so on every non-chatml dataset the loader dropped every canary and+`check` could only ever report OK. It now writes the canaries in the file's+own format (alpaca, sharegpt, chatml) and refuses every other format.+"""++from __future__ import annotations++import json+import re+from pathlib import Path++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.config.schema import DataConfig+from soup_cli.data.formats import FORMAT_SIGNATURES, detect_format, format_to_messages+from soup_cli.data.loader import load_dataset, load_raw_data+from soup_cli.utils.canary import (+ CANARY_FORMATS,+ canary_rows,+ generate_canaries,+ load_manifest,+ write_manifest,+)+from tests.conftest import strip_ansi++_CHAT = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "a"}]+_SHAREGPT = [{"from": "human", "value": "q"}, {"from": "gpt", "value": "a"}]++# One valid row per format `detect_format` can return.+_ROWS = {+ "alpaca": {"instruction": "q", "output": "a"},+ "sharegpt": {"conversations": _SHAREGPT},+ "chatml": {"messages": _CHAT},+ "dpo": {"prompt": "q", "chosen": "a", "rejected": "b"},+ "kto": {"prompt": "q", "completion": "a", "label": True},+ "llava": {"image": "img.png", "conversations": _SHAREGPT},+ "sharegpt4v": {"image": "img.png", "conversations": _SHAREGPT},+ "embedding": {"anchor": "q", "positive": "a"},+ "tool-calling": {"messages": _CHAT, "tools": [], "tool_calls": []},+ "audio": {"audio": "clip.wav", "messages": _CHAT},+ "asr": {"audio": "clip.wav", "text": "a"},+ "plaintext": {"text": "q a"},+}+_REFUSED = sorted(set(FORMAT_SIGNATURES) - set(CANARY_FORMATS))+++def _plain(text: str) -> str:+ return re.sub(r"\s+", " ", strip_ansi(text)).strip()+++def _write_dataset(path: Path, fmt: str, count: int = 3) -> None:+ path.write_text(+ "".join(json.dumps(_ROWS[fmt]) + "\n" for _ in range(count)),+ encoding="utf-8",+ )+++def _insert(*extra: str):+ return CliRunner().invoke(+ app,+ ["data", "canary", "insert", "train.jsonl", "--manifest", "m.json",+ "--count", "4", *extra],+ )+++def _secrets() -> list[str]:+ return [canary.secret.strip() for canary in load_manifest("m.json")]+++def _loaded_rows(path: str, data_format: str) -> list[dict]:+ """The rows `soup train` would train on."""+ config = DataConfig(train=path, format=data_format, val_split=0.0)+ return list(load_dataset(config)["train"])+++def test_every_detectable_format_has_a_fixture():+ """A new detect_format result (e.g. cross_encoder) must join the sweep."""+ assert set(_ROWS) == set(FORMAT_SIGNATURES)++[email protected]("fmt", sorted(set(_ROWS) - {"sharegpt4v"}))+def test_fixture_rows_detect_as_their_format(fmt):+ # sharegpt4v has llava's signature and llava is checked first, so+ # detection never returns it; the explicit --format sweep still covers it.+ assert detect_format([_ROWS[fmt]]) == fmt+++def test_alpaca_canaries_reach_the_training_rows(tmp_path, monkeypatch):+ """The issue's repro: 0 of 4 canaries on main."""+ monkeypatch.chdir(tmp_path)+ _write_dataset(Path("train.jsonl"), "alpaca")+ result = _insert("-o", "canaried.jsonl")+ assert result.exit_code == 0, (result.output, repr(result.exception))++ rows = _loaded_rows("canaried.jsonl", "auto")+ assert len(rows) == 7+ blob = json.dumps(rows)+ assert all(secret in blob for secret in _secrets())++[email protected]("load_as", ["auto", "explicit"])[email protected]("insert_as", ["auto", "explicit"])[email protected]("fmt", CANARY_FORMATS)+def test_rendered_formats_load_every_canary(+ fmt, insert_as, load_as, tmp_path, monkeypatch+):+ monkeypatch.chdir(tmp_path)+ _write_dataset(Path("train.jsonl"), fmt)+ extra = ["--format", fmt] if insert_as == "explicit" else []+ result = _insert("-o", "canaried.jsonl", *extra)+ assert result.exit_code == 0, (result.output, repr(result.exception))++ rows = _loaded_rows("canaried.jsonl", fmt if load_as == "explicit" else "auto")+ assert len(rows) == 3 + 4+ blob = json.dumps(rows)+ missing = [secret for secret in _secrets() if secret not in blob]+ assert not missing, f"{fmt}: canaries dropped by the loader: {missing}"+ assert json.loads(Path("m.json").read_text())["format"] == fmt++[email protected]("insert_as", ["auto", "explicit"])[email protected]("fmt", _REFUSED)+def test_other_formats_are_refused_and_nothing_is_written(+ fmt, insert_as, tmp_path, monkeypatch+):+ monkeypatch.chdir(tmp_path)+ _write_dataset(Path("train.jsonl"), fmt)+ extra = ["--format", fmt] if insert_as == "explicit" else []+ result = _insert("-o", "canaried.jsonl", *extra)++ assert result.exit_code == 1, (fmt, result.output)+ named = fmt if insert_as == "explicit" else detect_format([_ROWS[fmt]])+ output = _plain(result.output)+ assert f"'{named}'" in output+ assert "Supported: alpaca, sharegpt, chatml" in output+ assert not Path("canaried.jsonl").exists()+ assert not Path("m.json").exists()+++def test_explicit_format_that_is_not_the_files_format_is_refused(+ tmp_path, monkeypatch+):+ """Under `data.format: auto` the file loads as chatml and drops them."""+ monkeypatch.chdir(tmp_path)+ _write_dataset(Path("train.jsonl"), "chatml")+ result = _insert("-o", "canaried.jsonl", "--format", "alpaca")++ assert result.exit_code == 1+ output = _plain(result.output)+ assert "--format alpaca" in output and "'chatml'" in output+ assert not Path("canaried.jsonl").exists()+ assert not Path("m.json").exists()+++def test_empty_dataset_needs_an_explicit_format(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ Path("train.jsonl").write_text("", encoding="utf-8")++ refused = _insert("-o", "canaried.jsonl")+ assert refused.exit_code == 1+ assert "--format" in _plain(refused.output)+ assert not Path("m.json").exists()++ result = _insert("-o", "canaried.jsonl", "--format", "sharegpt")+ assert result.exit_code == 0, (result.output, repr(result.exception))+ rows = _loaded_rows("canaried.jsonl", "auto")+ assert len(rows) == 4+ assert all(secret in json.dumps(rows) for secret in _secrets())+++def test_a_file_whose_format_cannot_be_detected_is_refused(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ Path("train.jsonl").write_text(+ json.dumps({"input": "q", "output": "a"}) + "\n", encoding="utf-8"+ )++ result = _insert("-o", "canaried.jsonl")++ assert result.exit_code == 1, result.output+ output = _plain(result.output)+ assert "Cannot detect format" in output+ assert "canary insert supports: alpaca, sharegpt, chatml" in output+ assert not Path("canaried.jsonl").exists()+ assert not Path("m.json").exists()+++ ("name", "content", "json_type"),+ [+ ("train.jsonl", "42\n", "number"),+ ("train.json", json.dumps(["q", "a"]), "string"),+ ("train.jsonl", "null\n", "null"),+ ],+)+def test_a_first_row_that_is_not_an_object_is_refused_by_name(+ tmp_path, monkeypatch, name, content, json_type+):+ monkeypatch.chdir(tmp_path)+ Path(name).write_text(content, encoding="utf-8")++ result = CliRunner().invoke(+ app,+ ["data", "canary", "insert", name, "--manifest", "m.json",+ "--count", "4", "-o", "canaried.jsonl"],+ )++ assert result.exit_code == 1, result.output+ assert result.exception is None or isinstance(result.exception, SystemExit)+ output = _plain(result.output)+ assert f"the first row is a JSON {json_type}, not an object" in output+ assert "AttributeError" not in output+ assert not Path("canaried.jsonl").exists()+ assert not Path("m.json").exists()+++def test_json_output_is_an_array_that_loads_back(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ _write_dataset(Path("train.jsonl"), "alpaca")+ result = _insert("-o", "canaried.json")+ assert result.exit_code == 0, (result.output, repr(result.exception))++ assert len(load_raw_data(Path("canaried.json"))) == 7+ rows = _loaded_rows("canaried.json", "auto")+ assert all(secret in json.dumps(rows) for secret in _secrets())++[email protected]("name", ["canaried.txt", "canaried.csv", "canaried"])+def test_output_suffix_the_loader_would_misread_is_refused(+ name, tmp_path, monkeypatch+):+ monkeypatch.chdir(tmp_path)+ _write_dataset(Path("train.jsonl"), "alpaca")+ result = _insert("-o", name)++ assert result.exit_code == 1+ assert ".jsonl or .json" in _plain(result.output)+ assert not Path(name).exists()+ assert not Path("m.json").exists()++[email protected]("fmt", CANARY_FORMATS)+def test_rendered_row_trains_on_the_pair_check_scores(fmt):+ """`check` scores (carrier as one user turn, secret as the target)."""+ canary = generate_canaries(count=1, seed=0)[0]+ (row,) = canary_rows([canary], fmt)+ assert format_to_messages(row, fmt)["messages"] == [+ {"role": "user", "content": canary.carrier},+ {"role": "assistant", "content": canary.secret.strip()},+ ]++[email protected]("fmt", ["plaintext", "dpo", "bogus", None])+def test_canary_rows_refuses_formats_check_cannot_score(fmt):+ with pytest.raises(ValueError, match="unsupported canary format"):+ canary_rows(generate_canaries(count=1, seed=0), fmt)+++class TestManifestFormat:+ def test_written_format_round_trips(self, tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ canaries = generate_canaries(count=2, seed=0)+ write_manifest(canaries, "m.json", "sharegpt")+ assert json.loads(Path("m.json").read_text())["format"] == "sharegpt"+ assert load_manifest("m.json") == canaries++ def test_manifest_without_format_loads_as_chatml(self, tmp_path, monkeypatch):+ """Every manifest written before #1216 has no format field."""+ monkeypatch.chdir(tmp_path)+ canaries = generate_canaries(count=2, seed=0)+ write_manifest(canaries, "m.json")+ payload = json.loads(Path("m.json").read_text())+ del payload["format"]+ Path("m.json").write_text(json.dumps(payload), encoding="utf-8")+ assert load_manifest("m.json") == canaries++ @pytest.mark.parametrize("value", ["plaintext", "dpo", "bogus", 7, None])+ def test_unknown_format_is_refused_not_scored_as_chat(+ self, value, tmp_path, monkeypatch+ ):+ monkeypatch.chdir(tmp_path)+ write_manifest(generate_canaries(count=2, seed=0), "m.json")+ payload = json.loads(Path("m.json").read_text())+ payload["format"] = value+ Path("m.json").write_text(json.dumps(payload), encoding="utf-8")+ with pytest.raises(ValueError, match="unsupported canary format"):+ load_manifest("m.json")+++class TestCheckReadsTheFormat:+ def _check(self, monkeypatch):+ from soup_cli.commands import data_canary as cmd++ monkeypatch.setattr(+ cmd, "_load_pair", lambda *a, **k: (object(), object(), "cpu")+ )+ # Canaries mid-distribution -> OK.+ monkeypatch.setattr(+ cmd, "compute_pair_losses",+ lambda model, tok, pairs, **kw: (+ [5.0] * 2 + [float(i) for i in range(len(pairs) - 2)]+ ),+ )+ return CliRunner().invoke(+ app, ["data", "canary", "check", "--manifest", "m.json",+ "--base", "fake/model", "--controls", "16"],+ )++ def _manifest(self, **overrides):+ write_manifest(generate_canaries(count=2, seed=0), "m.json")+ payload = json.loads(Path("m.json").read_text())+ payload.update(overrides)+ for key in [k for k, v in overrides.items() if v is ...]:+ del payload[key]+ Path("m.json").write_text(json.dumps(payload), encoding="utf-8")++ def test_old_manifest_without_format_still_checks(self, tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ self._manifest(format=...)+ result = self._check(monkeypatch)+ assert result.exit_code == 0, (result.output, repr(result.exception))+ assert "Verdict: OK" in _plain(result.output)++ def test_unknown_manifest_format_exits_1(self, tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ self._manifest(format="plaintext")+ result = self._check(monkeypatch)+ assert result.exit_code == 1+ assert "unsupported canary format 'plaintext'" in _plain(result.output)