Files
OBLITERATUS/tests/test_observation_compare_cli.py
Joseph MaglyandClaude Opus 5.5 434e4a7235 feat(experiments): weight fingerprint, capture retention and attempt pruning
Weights edited in place under the same model id and revision were not
detected, expired captures still loaded, and run stores could not be
pruned because reused steps reference earlier attempts.

- Fingerprint: a deterministic fingerprint of every parameter and
  buffer (names, shapes, dtypes and a fixed strided sample of each
  tensor, with an optional full digest) joins the capture identity and
  the runner's model identity. Captures and steps from before the
  fingerprint are refused or recomputed with a recorded reason. The
  pipeline's entry-point cache identity is unchanged.
- Retention: load_capture refuses captures past expires_at unless
  inspection is requested; comparison inspects stored captures
  regardless of expiry.
- Pruning: `obliteratus experiments prune` (dry run by default) keeps
  the latest complete attempt, the newest N, active attempts and every
  attempt a kept one reuses, records a pruned event before deleting,
  and finishes interrupted removals on the next applied prune.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 16:28:26 -05:00

113 lines
5.5 KiB
Python

"""Observation result comparison and the shared CLI/Python entry point."""
from __future__ import annotations
from copy import deepcopy
import json
import pytest
import torch
from obliteratus.cli import main
from obliteratus.experiments import compare_results, load_result, run_observation
from tests.test_observation_runs import build_pack, factory, make_spec, tiny_gpt2
pytestmark = pytest.mark.cpu
@pytest.fixture
def pack_dir(tmp_path):
return build_pack(tmp_path / "pack")
@pytest.fixture
def api_result(pack_dir, tmp_path):
return run_observation(make_spec(pack_dir), tmp_path / "api", model_factory=factory())
def test_cli_and_api_runs_of_one_spec_compare_equal(pack_dir, api_result, tmp_path, capsys,
monkeypatch):
loaded = []
monkeypatch.setattr("obliteratus.experiments.inputs.default_model_factory", factory(loaded))
spec_path = tmp_path / "spec.json"
spec_path.write_text(json.dumps(make_spec(pack_dir)))
main(["experiments", "run", str(spec_path), "--store", str(tmp_path / "cli")])
summary = json.loads(capsys.readouterr().out)
assert loaded == [{"id": "local/tiny-gpt2", "dtype": "float32", "revision": None,
"device": "cpu"}]
assert summary["spec_digest"] == api_result["spec_digest"] and summary["state"] == "complete"
report = compare_results(api_result, summary["location"]["run_dir"])
assert report["equal"] is True and report["differences"] == []
exact = {entry["field"] for entry in report["exact"]}
tolerance = {entry["field"] for entry in report["tolerance"]}
assert {"spec_digest", "inputs.model", "scorecard.tasks.answers.records",
"capture.identity_sha256"} <= exact
assert {"scorecard.tasks.answers.task_success.rate", "capture.values.layer.0"} <= tolerance
assert not exact & tolerance
assert {e["field"] for e in report["not_compared"]} >= {"profile", "completed_at"}
main(["experiments", "compare", api_result["location"]["result"],
summary["location"]["run_dir"]])
assert json.loads(capsys.readouterr().out)["equal"] is True
main(["experiments", "history", str(spec_path), "--store", str(tmp_path / "cli")])
history = json.loads(capsys.readouterr().out)
assert [a["state"] for a in history["attempts"]] == ["complete"]
def test_comparison_reports_real_differences(pack_dir, api_result, tmp_path, capsys):
same = deepcopy(api_result)
same["scorecard"]["tasks"]["answers"]["invalid_output"]["rate"] += 1e-12
same["attempt"], same["completed_at"], same["tool"] = 99, "later", {"other": True}
assert compare_results(api_result, same)["equal"] is True
changed = deepcopy(api_result)
changed["scorecard"]["tasks"]["answers"]["records"][0]["completion_sha256"] = "0" * 64
changed["scorecard"]["tasks"]["answers"]["invalid_output"]["rate"] += 1e-3
report = compare_results(api_result, changed)
assert report["equal"] is False
assert set(report["differences"]) == {"scorecard.tasks.answers.records",
"scorecard.tasks.answers.invalid_output.rate"}
entry = next(e for e in report["tolerance"]
if e["field"] == "scorecard.tasks.answers.invalid_output.rate")
assert entry["max_abs_diff"] == pytest.approx(1e-3) and entry["within"] is False
loose = compare_results(api_result, changed, tolerances={"rates": {"atol": 1e-2}})
assert loose["differences"] == ["scorecard.tasks.answers.records"]
model = tiny_gpt2()
with torch.no_grad():
model.transformer.h[0].mlp.c_proj.weight.add_(0.5)
perturbed = run_observation(make_spec(pack_dir), tmp_path / "perturbed",
model_factory=factory(model=model))
report = compare_results(api_result, perturbed)
assert "capture.values.layer.0" in report["differences"]
values = next(e for e in report["tolerance"] if e["field"] == "capture.values.layer.0")
assert values["max_abs_diff"] > values["atol"]
# The weight fingerprint is part of both identities, so the in-place edit is visible there too.
assert {"inputs.model", "capture.identity_sha256"} <= set(report["differences"])
with pytest.raises(SystemExit) as exit_info:
main(["experiments", "compare", api_result["location"]["run_dir"],
perturbed["location"]["result"]])
assert exit_info.value.code == 1
assert json.loads(capsys.readouterr().out)["equal"] is False
def test_comparison_without_capture_and_input_validation(pack_dir, api_result, tmp_path,
capsys):
bare = run_observation(make_spec(pack_dir, capture=None, profile=False), tmp_path / "bare",
model_factory=factory())
report = compare_results(api_result, bare)
assert {"spec_digest", "capture.present"} <= set(report["differences"])
assert compare_results(bare, load_result(bare["location"]["result"]))["equal"] is True
for bad in ({"speed": {"atol": 1}}, {"rates": {"atol": -1}}, {"rates": {"tol": 1}}):
with pytest.raises(ValueError, match="Tolerances"):
compare_results(bare, bare, tolerances=bad)
with pytest.raises(ValueError, match="not an observation result"):
(tmp_path / "x.json").write_text("{}")
load_result(tmp_path / "x.json")
with pytest.raises(SystemExit) as exit_info:
main(["experiments", "compare", str(tmp_path / "x.json"), str(tmp_path / "x.json")])
assert exit_info.value.code == 4
assert "not an observation result" in capsys.readouterr().err