Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

feat(ship): bind evidence inputs and effective verdict policy (#2025)

Nurkhan Esenbek6e928e1fba99
diff --git a/changelog.d/0.76.0/2025.added.md b/changelog.d/0.76.0/2025.added.md
new file mode 100644
index 00000000..d9ae9e25
--- /dev/null
+++ b/changelog.d/0.76.0/2025.added.md
@@ -0,0 +1 @@
+- Bind emitted ship evidence to adapter/task/source bytes, suite versions and effective policy; add opt-in `--require-provenance` drift checks and an explicitly caller-asserted `--data-sha256` identity while preserving legacy replay. (#1765 by @kok-o in #2025)
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index ca224454..47ea3677 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -3470,6 +3470,8 @@ Usage: `soup ship [OPTIONS] [<command>] [ARGS]...`
| `--output`, `-o` | text | | | Write the verdict JSON to this path. |
| `--emit-evidence` | text | | | Write the scores in the --evidence INPUT schema so this run can be replayed offline (output-is-input). With --config it also STAMPS the config's provenance onto the emitted evidence. |
| `--config` | text | | | soup.yaml whose eval.ship block supplies defaults (CLI flags win). With --evidence alone it GATES (refuses evidence whose config_sha drifted from this config, or whose numerics family does not match); with --emit-evidence it STAMPS this config's provenance. |
+| `--require-provenance` | flag | off | | Strict offline drift check: requires --evidence, --config, --adapter and task eval. Compare artifact/task/source bytes, suite version and effective verdict policy. |
+| `--data-sha256` | text | | | Caller-asserted training-data SHA-256 for emitted/strict evidence; not proof of which bytes trained the model. |
| `--push` | text | | | Post the verdict as a GitHub PR comment (owner/repo#N). Auth via GITHUB_TOKEN / GH_TOKEN; needs the `gh` CLI. |
| `--device` | text | | | Device for the live run (cuda / cpu). |
| `--chat-template-kwargs` | text | | | Live chat-template variables as a JSON object, e.g. {"enable_thinking":false}. |
diff --git a/docs/evaluation.md b/docs/evaluation.md
index eab1987b..f94c272c 100644
--- a/docs/evaluation.md
+++ b/docs/evaluation.md
@@ -663,6 +663,55 @@ soup ship --evidence ship_evidence.json --config soup.yaml --push owner/repo#42
`soup ci init --config soup.yaml` binds the generated workflow's ship step to the committed
config, so the whole loop runs in CI (see [commands.md](commands.md)).
+### Strict evidence provenance
+
+`--emit-evidence` now adds a versioned `provenance.binding` block separately from
+`config_sha`. It records the local adapter manifest Merkle root (the existing
+adapter-signing manifest), exact task-eval file SHA-256, actual suite names plus
+Soup/scorer versions, and the effective verdict policy with a canonical SHA-256.
+The policy includes threshold, task mode, suites, judge endpoint identity and
+noise-floor repeat count. Judge URLs are hashed so endpoint paths, query values
+and credentials are not written into this descriptor.
+
+For an offline gate, opt in with the comparison inputs available locally:
+
+```bash
+soup ship --evidence ship_evidence.json --config soup.yaml --adapter ./adapter \
+ --require-provenance
+```
+
+`--task-eval` and suite/judge settings come from `eval.ship` or explicit CLI flags,
+with the usual CLI precedence. The strict gate (exit 3 on missing/mismatched
+identity) compares adapter and task bytes, current local training-source bytes,
+suite version, policy and the evidence's actual task mode/benchmark set. Unknown
+adapter/task identities are refused. Store emitted evidence outside the adapter
+directory: the manifest covers its files. A changed input during a live emitted
+run is refused on the before/after comparison; this is not a filesystem snapshot.
+
+The optional `--data-sha256 <64-lowercase-hex>` records an explicitly
+**caller-asserted training-data identity**, never proof of transformed examples
+consumed. Supply the same assertion when gating it. A simple local raw training
+source can also be compared at verdict time; remote, mixed, replay, tokenized,
+streaming and directory sources stay unknown. When that source is unknown,
+strict verification requires the caller assertion. Neither this descriptor nor
+legacy `data_sha` relabels a verdict-time hash as training-time evidence. The
+startup producer tracked in #1764 is separate.
+
+The strict mode requires offline `--evidence`, `--config`, a local nonempty
+`--adapter` manifest and a readable task-eval file; it does not claim identity for
+an arbitrary remote `--tuned` model. Judge modes also need the declared judge
+endpoint. The descriptor identifies external lm-eval suites by name and Soup
+version; it does not fingerprint external harness packages or datasets. Baseline
+scores and measured noise floors remain trusted evidence inputs, not independent
+reruns during an offline gate.
+
+Legacy/default replay remains recipe-only. `--require-provenance` keeps all
+checks even when `--emit-evidence` is also present. Ordinary external-score
+stamping remains available: it binds caller-trusted supplied scores to declared
+inputs, and records their actual task mode/suite axes. It is not a model run,
+attestation, signature or forgery protection. The unkeyed hashes detect drift;
+use the existing signing/attestation tools for a trust boundary.
+
**Baseline provenance (#404).** Produce a stamped baseline with
`soup eval gate --suite <suite.yaml> --model <id> --write-baseline baseline.json`
(`--model` is required — baselines are never written from the stub generator).
diff --git a/src/soup_cli/commands/ship.py b/src/soup_cli/commands/ship.py
index 50a03c61..9695a0fd 100644
--- a/src/soup_cli/commands/ship.py
+++ b/src/soup_cli/commands/ship.py
@@ -413,6 +413,38 @@ def _check_evidence_staleness(payload: dict, expected_sha: str) -> None:
)
+def _compute_ship_binding(
+ cfg: Optional["SoupConfig"], *, adapter: Optional[str], task_eval: Optional[str],
+ suite_names: List[str], task_mode: str, judge_model: Optional[str],
+ threshold: float, noise_floor_runs: Optional[int], data_sha256: Optional[str],
+) -> Dict[str, object]:
+ """Capture source bytes and the effective verdict policy separately from config_sha."""
+ from soup_cli.utils.ship_provenance import judge_identity, make_binding
+
+ source_sha = None
+ if cfg is not None:
+ data = cfg.data
+ if (cfg.modality == "text" and isinstance(data.train, str)
+ and data.format != "pre_tokenized" and not data.tokenized_path
+ and not data.replay and not data.forget_set and not data.retain_set
+ and data.interleave is None and not data.streaming):
+ source_sha = _safe_hash_file(data.train, _MAX_DATA_SHA_BYTES)
+ policy = {
+ "task_mode": task_mode,
+ "forgetting_threshold": threshold,
+ "general_suite": suite_names,
+ "judge_model_sha256": judge_identity(judge_model)
+ if task_mode in {"judge_score", "pairwise"} else None,
+ "noise_floor_runs": noise_floor_runs,
+ }
+ return make_binding(
+ adapter=adapter,
+ task_eval_sha256=_safe_hash_file(task_eval, _MAX_EVIDENCE_BYTES) if task_eval else None,
+ source_data_sha256=source_sha, data_sha256=data_sha256,
+ suites=suite_names, policy=policy,
+ )
+
+
def _flag_is_default(ctx: typer.Context, name: str) -> bool:
"""True when ``name`` was left at its default (so --config may fill it).
@@ -1293,6 +1325,16 @@ def ship(
"from this config, or whose numerics family does not match); with "
"--emit-evidence it STAMPS this config's provenance.",
),
+ require_provenance: bool = typer.Option(
+ False, "--require-provenance",
+ help="Strict offline drift check: requires --evidence, --config, --adapter and task eval. "
+ "Compare artifact/task/source bytes, suite version and effective verdict policy.",
+ ),
+ data_sha256: Optional[str] = typer.Option(
+ None, "--data-sha256",
+ help="Caller-asserted training-data SHA-256 for emitted/strict evidence; "
+ "not proof of which bytes trained the model.",
+ ),
push: Optional[str] = typer.Option(
None,
"--push",
@@ -1309,6 +1351,16 @@ def ship(
) -> None:
"""Decide SHIP / DON'T SHIP for a fine-tune (exit 0 = SHIP, 2 = DON'T)."""
soup_config = None
+ from soup_cli.utils.ship_provenance import check_binding, validate_data_identity
+
+ try:
+ validate_data_identity(data_sha256)
+ except ValueError as exc:
+ _fail(str(exc), _EXIT_USAGE)
+ if require_provenance and (not evidence or config is None or not adapter or tuned):
+ _fail("--require-provenance needs --evidence, --config and a local --adapter", _EXIT_USAGE)
+ if data_sha256 is not None and not (emit_evidence or require_provenance):
+ _fail("--data-sha256 needs --emit-evidence or --require-provenance", _EXIT_USAGE)
template_kwargs = _parse_chat_template_kwargs(chat_template_kwargs)
if evidence and chat_template_kwargs is not None:
_fail("--chat-template-kwargs applies only to a live run, not --evidence", _EXIT_USAGE)
@@ -1356,6 +1408,16 @@ def ship(
# (incl. data_sha over the training file) is built lazily, only when we
# actually --emit-evidence.
config_sha = _config_sha_of(soup_config) if soup_config is not None else None
+ binding: Optional[Dict[str, object]] = None
+
+ def capture_binding(
+ mode: str, names: List[str], floor_runs: Optional[int],
+ ) -> Dict[str, object]:
+ return _compute_ship_binding(
+ soup_config, adapter=adapter, task_eval=task_eval, suite_names=names,
+ task_mode=mode, judge_model=judge_model, threshold=threshold,
+ noise_floor_runs=floor_runs, data_sha256=data_sha256,
+ )
if evidence:
# An offline verdict loads no model, so there is nothing to repeat. A
@@ -1379,14 +1441,32 @@ def ship(
# * PRODUCER (--emit-evidence): STAMP the config's provenance onto these
# scores (raw scores from an external eval tool -> bound evidence), so
# the input is NOT required to already carry a matching provenance.
- if config_sha is not None and not emit_evidence:
+ if config_sha is not None and (not emit_evidence or require_provenance):
_check_evidence_staleness(payload, config_sha)
assert soup_config is not None # config_sha is computed from it
_check_evidence_numerics(
payload, _expected_numerics_family(soup_config)
)
+ # Decode/validate the complete evidence before its floor enters the
+ # canonical policy encoder. Raw JSON may contain non-finite numbers.
verdict = _verdict_from_evidence(payload, forgetting_threshold=threshold)
+ recorded_runs = verdict.noise_floor.runs if verdict.noise_floor is not None else None
+ if require_provenance:
+ binding = capture_binding(task_mode, _parse_suite(general_suite), recorded_runs)
+ try:
+ check_binding(payload, binding)
+ except ValueError as exc:
+ _fail(str(exc), _EXIT_USAGE)
+ if emit_evidence and binding is None:
+ # External scores are explicitly caller-trusted, not a claim that this
+ # command evaluated a model. Bind the actual supplied axes/mode.
+ binding = capture_binding(
+ verdict.task_win.mode, [item.name for item in verdict.benchmark_deltas],
+ recorded_runs,
+ )
elif base or tuned or adapter or task_eval:
+ if emit_evidence:
+ binding = capture_binding(task_mode, _parse_suite(general_suite), noise_floor)
verdict = _verdict_live(
base=base,
tuned=tuned,
@@ -1402,6 +1482,13 @@ def ship(
quantization=_live_eval_quantization_from_config(soup_config),
**({"chat_template_kwargs": template_kwargs} if template_kwargs is not None else {}),
)
+ if emit_evidence and binding != capture_binding(
+ task_mode, _parse_suite(general_suite), noise_floor,
+ ):
+ _fail(
+ "provenance input changed during live evaluation; re-run before emitting",
+ _EXIT_USAGE,
+ )
else:
_fail(
"provide --evidence <json> for an offline verdict, or "
@@ -1418,6 +1505,7 @@ def ship(
provenance = dict(current_baseline_stamp())
if soup_config is not None:
provenance.update(_compute_provenance(soup_config))
+ provenance["binding"] = binding
_emit_and_exit(
verdict, output, emit_evidence=emit_evidence, push=push, provenance=provenance
)
diff --git a/src/soup_cli/utils/ship_provenance.py b/src/soup_cli/utils/ship_provenance.py
new file mode 100644
index 00000000..0f6ed891
--- /dev/null
+++ b/src/soup_cli/utils/ship_provenance.py
@@ -0,0 +1,97 @@
+"""Versioned, opt-in drift binding for trusted ship evidence (not attestation)."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from typing import Any
+
+_SHA256 = re.compile(r"[0-9a-f]{64}")
+
+
+def validate_data_identity(value: str | None) -> None:
+ """Caller-supplied identity is an assertion, never inferred training evidence."""
+ if value is not None and (not isinstance(value, str) or not _SHA256.fullmatch(value)):
+ raise ValueError("--data-sha256 must be a lowercase 64-hex SHA-256")
+
+
+def policy_hash(policy: dict[str, Any]) -> str:
+ payload = json.dumps(policy, sort_keys=True, separators=(",", ":"), allow_nan=False)
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
+
+
+def make_binding(
+ *, adapter: str | None, task_eval_sha256: str | None,
+ source_data_sha256: str | None, data_sha256: str | None,
+ suites: list[str], policy: dict[str, Any],
+) -> dict[str, Any]:
+ """Bind known inputs; unknown inputs stay explicit for ordinary emit flows."""
+ from soup_cli.eval.gate import current_baseline_stamp
+ from soup_cli.utils.adapter_sign import compute_adapter_manifest
+
+ validate_data_identity(data_sha256)
+ root = None
+ if adapter is not None:
+ try:
+ manifest = compute_adapter_manifest(adapter)
+ if manifest.files:
+ root = manifest.merkle_root
+ except (OSError, ValueError, TypeError):
+ # Existing emit flows may refer to unavailable/non-local artifacts.
+ # Opt-in verification refuses unknowns; default emission stays compatible.
+ pass
+ stamp = current_baseline_stamp()
+ return {
+ "schema_version": 1,
+ "adapter_merkle_root": root,
+ "task_eval_sha256": task_eval_sha256,
+ "source_data_at_verdict_sha256": source_data_sha256,
+ "training_data": {"sha256": data_sha256, "source": "caller"}
+ if data_sha256 is not None else None,
+ "suites": {"names": suites, **stamp},
+ "policy": policy,
+ "policy_sha256": policy_hash(policy),
+ }
+
+
+def check_binding(payload: dict[str, Any], expected: dict[str, Any]) -> None:
+ """Refuse unknown/drifted identities without echoing untrusted field values."""
+ provenance = payload.get("provenance")
+ got = provenance.get("binding") if isinstance(provenance, dict) else None
+ if not isinstance(got, dict) or type(got.get("schema_version")) is not int:
+ raise ValueError("provenance binding is missing or malformed; re-emit trusted scores")
+ try:
+ recorded_policy = got.get("policy")
+ valid_policy = (isinstance(recorded_policy, dict)
+ and policy_hash(recorded_policy) == got.get("policy_sha256"))
+ except (ValueError, TypeError, RecursionError):
+ valid_policy = False
+ if not valid_policy:
+ raise ValueError("provenance policy hash is missing or inconsistent")
+ for field in ("adapter_merkle_root", "task_eval_sha256"):
+ value = expected.get(field)
+ if not isinstance(value, str) or not _SHA256.fullmatch(value):
+ raise ValueError(f"provenance comparison needs a known {field}")
+ if expected["source_data_at_verdict_sha256"] is None and expected["training_data"] is None:
+ raise ValueError("provenance needs a known local training source or explicit --data-sha256")
+ if (expected["policy"]["task_mode"] in {"judge_score", "pairwise"}
+ and expected["policy"]["judge_model_sha256"] is None):
+ raise ValueError("provenance for judge modes needs a declared --judge-model")
+ if got != expected:
+ raise ValueError(
+ "stale provenance: artifact, task, training source, suites or policy differs"
+ )
+ # The stored descriptor must describe the scores being replayed, not merely
+ # compare equal to an independent block the caller attached to other scores.
+ task = payload.get("task")
+ benchmarks = payload.get("benchmarks")
+ if (not isinstance(task, dict) or task.get("mode") != expected["policy"]["task_mode"]
+ or not isinstance(benchmarks, dict)
+ or set(benchmarks) != set(expected["suites"]["names"])):
+ raise ValueError("provenance does not describe the evidence task mode or benchmark set")
+
+
+def judge_identity(judge: str | None) -> str | None:
+ """Record endpoint identity without leaking URL paths, credentials or query values."""
+ return hashlib.sha256(judge.encode("utf-8")).hexdigest() if judge is not None else None
diff --git a/tests/test_ship_provenance.py b/tests/test_ship_provenance.py
new file mode 100644
index 00000000..24c14590
--- /dev/null
+++ b/tests/test_ship_provenance.py
@@ -0,0 +1,331 @@
+"""Opt-in drift detection binds evidence to inputs and effective verdict policy."""
+
+from __future__ import annotations
+
+import hashlib
+import importlib
+import json
+from pathlib import Path
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from tests.conftest import strip_ansi
+
+ship = importlib.import_module("soup_cli.commands.ship")
+runner = CliRunner()
+
+
+def work(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "adapter").mkdir()
+ (tmp_path / "adapter" / "adapter_model.safetensors").write_bytes(b"local fixture weights")
+ (tmp_path / "train.jsonl").write_text('{"text":"train"}\n', encoding="utf-8")
+ (tmp_path / "task.jsonl").write_text(
+ '{"prompt":"task","expected":"answer"}\n', encoding="utf-8",
+ )
+ (tmp_path / "soup.yaml").write_text(
+ "base: owner/base\ndata: {train: train.jsonl}\n"
+ "training: {quantization: none}\neval:\n ship:\n"
+ " task_eval: task.jsonl\n general_suite: mini_mmlu\n"
+ " forgetting_threshold: 0.05\n",
+ encoding="utf-8",
+ )
+ (tmp_path / "raw.json").write_text(json.dumps({
+ "task": {"mode": "metric", "base": 0.5, "tuned": 0.7},
+ "benchmarks": {"mini_mmlu": {"base": 0.6, "tuned": 0.6}},
+ "numerics": "float32",
+ }), encoding="utf-8")
+ return tmp_path
+
+
+def _produce(*extra):
+ result = runner.invoke(app, [
+ "ship", "--evidence", "raw.json", "--config", "soup.yaml", "--adapter", "adapter",
+ "--emit-evidence", "bound.json", *extra,
+ ])
+ assert result.exit_code == 0, (result.output, result.exception)
+ return json.loads(Path("bound.json").read_text(encoding="utf-8"))
+
+
+def _gate(*extra):
+ return runner.invoke(app, [
+ "ship", "--evidence", "bound.json", "--config", "soup.yaml",
+ "--adapter", "adapter", "--require-provenance", *extra,
+ ])
+
+
[email protected]("runs", [float("nan"), float("inf"), float("-inf")])
[email protected]("restamp", [False, True], ids=["read", "restamp"])
[email protected]("color", [False, True], ids=["plain", "ansi"])
+def test_strict_nonfinite_floor_runs_keep_usage_diagnostic(work, runs, restamp, color):
+ payload = _produce()
+ payload["noise_floor"] = {"runs": runs, "floors": {"mini_mmlu": 0.0}}
+ (work / "bound.json").write_text(json.dumps(payload), encoding="utf-8")
+ arguments = [
+ "ship", "--evidence", "bound.json", "--config", "soup.yaml",
+ "--adapter", "adapter", "--require-provenance", "--output", "verdict.json",
+ ]
+ if restamp:
+ arguments.extend(["--emit-evidence", "restamped.json"])
+ result = runner.invoke(app, arguments, color=color)
+ assert result.exit_code == 3, (result.output, result.exception)
+ diagnostic = " ".join(strip_ansi(result.output).split())
+ assert "evidence.noise_floor.runs must be an integer" in diagnostic
+ assert not (work / "verdict.json").exists()
+ assert not (work / "restamped.json").exists()
+
+
[email protected]("runs", [None, 2, 10], ids=["no-floor", "min-floor", "max-floor"])
[email protected]("restamp", [False, True], ids=["read", "restamp"])
+def test_strict_valid_floor_and_no_floor_controls(work, runs, restamp):
+ if runs is not None:
+ raw_path = work / "raw.json"
+ raw = json.loads(raw_path.read_text(encoding="utf-8"))
+ raw["noise_floor"] = {"runs": runs, "floors": {"mini_mmlu": 0.0}}
+ raw_path.write_text(json.dumps(raw), encoding="utf-8")
+ payload = _produce()
+ extra = ["--emit-evidence", "restamped.json"] if restamp else []
+ result = _gate("--output", "verdict.json", *extra)
+ assert result.exit_code == 0, (result.output, result.exception)
+ assert (work / "verdict.json").is_file()
+ if restamp:
+ restored = json.loads((work / "restamped.json").read_text(encoding="utf-8"))
+ assert restored.get("noise_floor") == payload.get("noise_floor")
+ assert restored["provenance"]["binding"] == payload["provenance"]["binding"]
+
+
+def test_emit_binds_actual_bytes_and_effective_policy(work):
+ from soup_cli.utils.adapter_sign import compute_adapter_manifest
+
+ payload = _produce("--forgetting-threshold", "0.2")
+ binding = payload["provenance"]["binding"]
+ assert binding["schema_version"] == 1
+ assert binding["adapter_merkle_root"] == compute_adapter_manifest("adapter").merkle_root
+ expected_task = hashlib.sha256((work / "task.jsonl").read_bytes()).hexdigest()
+ assert binding["task_eval_sha256"] == expected_task
+ assert binding["source_data_at_verdict_sha256"] == hashlib.sha256(
+ (work / "train.jsonl").read_bytes(),
+ ).hexdigest()
+ assert binding["policy"]["forgetting_threshold"] == 0.2
+ assert binding["suites"]["names"] == ["mini_mmlu"]
+ assert isinstance(binding["suites"]["soup_version"], str)
+ assert len(binding["policy_sha256"]) == 64
+ canonical = json.dumps(binding["policy"], sort_keys=True, separators=(",", ":"))
+ assert binding["policy_sha256"] == hashlib.sha256(canonical.encode()).hexdigest()
+ assert _gate("--forgetting-threshold", "0.2").exit_code == 0
+
+
[email protected]("changed", ["adapter", "task", "training", "threshold", "suite", "judge"])
+def test_strict_gate_refuses_input_and_policy_drift(work, changed):
+ _produce()
+ extra = []
+ if changed == "adapter":
+ (work / "adapter" / "adapter_model.safetensors").write_bytes(b"other weights")
+ elif changed == "task":
+ (work / "task.jsonl").write_text('{"prompt":"other"}\n', encoding="utf-8")
+ elif changed == "training":
+ (work / "train.jsonl").write_text('{"text":"reimported"}\n', encoding="utf-8")
+ else:
+ extra = {
+ "threshold": ["--forgetting-threshold", "0.2"],
+ "suite": ["--general-suite", "mini_arithmetic"],
+ "judge": ["--task-mode", "judge_score", "--judge-model", "http://localhost:8000"],
+ }[changed]
+ result = _gate(*extra)
+ assert result.exit_code == 3, (result.output, result.exception)
+ assert "provenance" in strip_ansi(result.output).lower()
+
+
+def test_default_gate_preserves_recipe_only_semantics(work):
+ _produce()
+ (work / "train.jsonl").write_text("changed source", encoding="utf-8")
+ result = runner.invoke(app, [
+ "ship", "--evidence", "bound.json", "--config", "soup.yaml",
+ "--forgetting-threshold", "0.2",
+ ])
+ assert result.exit_code == 0, (result.output, result.exception)
+
+
+def test_strict_restamp_does_not_bypass_verification(work):
+ _produce()
+ (work / "adapter" / "adapter_model.safetensors").write_bytes(b"other weights")
+ result = _gate("--emit-evidence", "laundered.json")
+ assert result.exit_code == 3
+ assert not (work / "laundered.json").exists()
+
+
+def test_strict_restamp_keeps_config_staleness_gate(work):
+ _produce()
+ cfg = work / "soup.yaml"
+ cfg.write_text(cfg.read_text(encoding="utf-8") + "output: different-output\n", encoding="utf-8")
+ result = _gate("--emit-evidence", "laundered.json")
+ assert result.exit_code == 3
+ assert "config_sha" in strip_ansi(result.output)
+ assert not (work / "laundered.json").exists()
+
+
+ "field", ["binding", "adapter_merkle_root", "task_eval_sha256", "policy_sha256"],
+)
+def test_missing_or_malformed_bindings_fail_closed(work, field):
+ payload = _produce()
+ if field == "binding":
+ del payload["provenance"][field]
+ else:
+ payload["provenance"]["binding"][field] = "\x1b[31mPRIVATE"
+ (work / "bound.json").write_text(json.dumps(payload), encoding="utf-8")
+ result = _gate()
+ assert result.exit_code == 3
+ assert "PRIVATE" not in result.output
+
+
+def test_caller_training_identity_is_explicit_and_checked(work):
+ digest = "a" * 64
+ payload = _produce("--data-sha256", digest)
+ assert payload["provenance"]["binding"]["training_data"] == {
+ "sha256": digest, "source": "caller",
+ }
+ assert _gate("--data-sha256", digest).exit_code == 0
+ assert _gate("--data-sha256", "b" * 64).exit_code == 3
+ assert _gate().exit_code == 3
+
+
+def test_unknown_composite_source_is_not_a_partial_identity(work):
+ cfg = work / "soup.yaml"
+ cfg.write_text(cfg.read_text(encoding="utf-8").replace(
+ "data: {train: train.jsonl}",
+ "data: {train: [train.jsonl, missing.jsonl], interleave: concat}",
+ ), encoding="utf-8")
+ payload = _produce()
+ assert payload["provenance"]["binding"]["source_data_at_verdict_sha256"] is None
+ assert _gate().exit_code == 3
+ digest = "a" * 64
+ _produce("--data-sha256", digest)
+ result = _gate("--data-sha256", digest)
+ assert result.exit_code == 0, (result.output, result.exception)
+
+
[email protected]("value", ["partial", "A" * 64, "a" * 64 + "\n"])
+def test_invalid_caller_digest_refused_before_outputs(work, value):
+ result = runner.invoke(app, [
+ "ship", "--evidence", "raw.json", "--emit-evidence", "bad.json", "--data-sha256", value,
+ ])
+ assert result.exit_code == 3
+ assert not (work / "bad.json").exists()
+
+
+def test_strict_requires_comparison_inputs(work):
+ _produce()
+ for args in (
+ ["ship", "--evidence", "bound.json", "--require-provenance"],
+ ["ship", "--evidence", "bound.json", "--config", "soup.yaml", "--require-provenance"],
+ ):
+ result = runner.invoke(app, args)
+ assert result.exit_code == 3
+
+
+def test_strict_rejects_scores_for_a_different_suite_or_task_mode(work):
+ payload = _produce()
+ payload["benchmarks"] = {"mini_arithmetic": {"base": 0.6, "tuned": 0.6}}
+ (work / "bound.json").write_text(json.dumps(payload), encoding="utf-8")
+ assert _gate().exit_code == 3
+
+
+def test_judge_endpoint_is_hashed_without_credentials(work):
+ raw = json.loads((work / "raw.json").read_text(encoding="utf-8"))
+ raw["task"]["mode"] = "judge_score"
+ (work / "raw.json").write_text(json.dumps(raw), encoding="utf-8")
+ payload = _produce(
+ "--task-mode", "judge_score", "--judge-model", "http://user:secret@localhost:8000/private",
+ )
+ text = json.dumps(payload["provenance"]["binding"])
+ assert "secret" not in text and "/private" not in text
+ assert payload["provenance"]["binding"]["policy"]["judge_model_sha256"] == hashlib.sha256(
+ b"http://user:secret@localhost:8000/private",
+ ).hexdigest()
+
+
[email protected]("floor_runs", [None, 3])
+def test_real_scorers_emit_replayable_binding(work, monkeypatch, floor_runs):
+ """Only generation is a stand-in; CLI, task/suite scorers and verdict are real."""
+ calls = []
+
+ def generators(*args, **kwargs):
+ def base(prompt):
+ calls.append(("base", prompt))
+ return "wrong" if prompt == "task" else "B"
+
+ def tuned(prompt):
+ calls.append(("tuned", prompt))
+ return "answer" if prompt == "task" else "B"
+
+ return base, tuned
+
+ monkeypatch.setattr(ship, "_resolve_generators", generators)
+ extra = ["--noise-floor", str(floor_runs)] if floor_runs else []
+ result = runner.invoke(app, [
+ "ship", "--base", "owner/base", "--adapter", "adapter", "--config", "soup.yaml",
+ "--device", "cpu", "--emit-evidence", "bound.json", *extra,
+ ])
+ assert result.exit_code == 0, (result.output, result.exception)
+ payload = json.loads((work / "bound.json").read_text(encoding="utf-8"))
+ assert payload["task"] == {"mode": "metric", "base": 0.0, "tuned": 1.0}
+ assert payload["benchmarks"]["mini_mmlu"]["base"] == payload["benchmarks"]["mini_mmlu"]["tuned"]
+ assert payload["provenance"]["binding"]["policy"]["noise_floor_runs"] == floor_runs
+ assert {side for side, _ in calls} == {"base", "tuned"}
+ replay = _gate()
+ assert replay.exit_code == 0, (replay.output, replay.exception)
+
+
[email protected]("changed", ["task.jsonl", "adapter/adapter_model.safetensors"])
+def test_live_input_changes_refuse_emission(work, monkeypatch, changed):
+ def generators(*args, **kwargs):
+ (work / changed).write_bytes(b'{"prompt":"changed","expected":"answer"}\n')
+ return lambda _: "wrong", lambda _: "answer"
+
+ monkeypatch.setattr(ship, "_resolve_generators", generators)
+ result = runner.invoke(app, [
+ "ship", "--base", "owner/base", "--adapter", "adapter", "--config", "soup.yaml",
+ "--device", "cpu", "--emit-evidence", "bound.json",
+ ])
+ assert result.exit_code == 3, (result.output, result.exception)
+ assert "changed during live evaluation" in strip_ansi(result.output)
+ assert not (work / "bound.json").exists()
+
+
[email protected]("mode", ["judge_score", "pairwise"])
+def test_external_judge_modes_bind_declared_endpoint(work, mode):
+ raw = json.loads((work / "raw.json").read_text(encoding="utf-8"))
+ raw["task"]["mode"] = mode
+ (work / "raw.json").write_text(json.dumps(raw), encoding="utf-8")
+ options = ["--task-mode", mode, "--judge-model", "http://localhost:8000"]
+ _produce(*options)
+ result = _gate(*options)
+ assert result.exit_code == 0, (result.output, result.exception)
+ assert _gate(*options[:-1], "http://localhost:9000").exit_code == 3
+
+
[email protected]("missing", ["adapter/adapter_model.safetensors", "task.jsonl"])
+def test_empty_adapter_and_unknown_task_are_not_verifiable(work, missing):
+ _produce()
+ (work / missing).unlink()
+ assert _gate().exit_code == 3
+
+
[email protected]("tamper", ["schema", "version", "policy", "mode"])
+def test_tampered_descriptor_and_score_mode_are_refused(work, tamper):
+ payload = _produce()
+ binding = payload["provenance"]["binding"]
+ if tamper == "schema":
+ binding["schema_version"] = True
+ elif tamper == "version":
+ binding["suites"]["soup_version"] = "older-version"
+ elif tamper == "policy":
+ binding["policy"]["forgetting_threshold"] = 0.3
+ else:
+ payload["task"]["mode"] = "pairwise"
+ (work / "bound.json").write_text(json.dumps(payload), encoding="utf-8")
+ assert _gate().exit_code == 3