feat(semantics): add portable annotation, learning and review contracts

Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:00 +03:00
parent 69dc566665
commit 25dc0a1b44
128 changed files with 23742 additions and 0 deletions
+540
View File
@@ -0,0 +1,540 @@
"""Resume, lost acknowledgement and provenance failures must never duplicate fit."""
import copy
import importlib.util
import json
import subprocess
import sys
from pathlib import Path
import pytest
SOURCE = Path(__file__).parents[1] / "simulation/semantic-learning"
sys.path.insert(0, str(SOURCE))
spec = importlib.util.spec_from_file_location(
"tested_learning_execution", SOURCE / "learning_execution.py"
)
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
@pytest.fixture
def setup(tmp_path):
(tmp_path / "runner.py").write_text("# synthetic pinned runner\n")
(tmp_path / "release.json").write_text('{"accepted":true}\n')
calls = []
def invoke(root, argv, timeout):
calls.append(argv[1])
phase = argv[1].removeprefix("verify-")
name = phase + ".json"
if argv[1].startswith("verify-"):
return json.dumps(
dict(
valid=True,
outputs={name: m.pin(root, name)},
artifacts={name: m.pin(root, name)},
)
)
(root / name).write_text(json.dumps(dict(phase=phase)))
return ""
plan = dict(
schema=m.SCHEMA,
objective="synthetic resumable fit/replay",
inputs={name: m.pin(tmp_path, name) for name in ["runner.py", "release.json"]},
phases=[
dict(
name=n,
run=["runner.py", n],
verify=["runner.py", "verify-" + n],
outputs=[n + ".json"],
run_timeout_seconds=5,
verify_timeout_seconds=5,
)
for n in ["fit", "replay"]
],
)
ledger = m.Execution(tmp_path, runner=invoke)
yield ledger, plan, calls, invoke
ledger.close()
def test_restart_reuses_completed_fit_and_checks_order(setup):
ledger, plan, calls, runner = setup
identity = ledger.register(plan)
with pytest.raises(ValueError, match="Previous"):
ledger.execute(identity, "replay")
first = ledger.execute(identity, "fit")
assert first["artifact_validation"] and first["model_acceptance"] is False
reopened = m.Execution(ledger.root, runner=runner)
try:
assert reopened.register(plan) == identity
assert reopened.execute(identity, "fit") == first
reopened.execute(identity, "replay")
assert calls == ["fit", "verify-fit", "replay", "verify-replay"]
finally:
reopened.close()
def test_lost_acknowledgement_no_retry_and_root_recovers_outputs(setup):
ledger, plan, calls, runner = setup
identity = ledger.register(plan)
def lost_ack(root, argv, timeout):
result = runner(root, argv, timeout)
if argv[1] == "fit":
raise ConnectionError("acknowledgement lost after artifacts were written")
return result
ledger.runner = lost_ack
with pytest.raises(ConnectionError):
ledger.execute(identity, "fit")
state = ledger.status(identity)["phases"][0]
assert state["state"] == "unknown"
ledger.clock = lambda: 10**15
with pytest.raises(ValueError, match="reconciliation"):
ledger.execute(identity, "fit")
with pytest.raises(ValueError, match="matching"):
ledger.reconcile(identity, "fit", "wrong-token", "process stopped")
recovered = ledger.reconcile(
identity, "fit", state["token"], "trusted root verified PID stopped"
)
assert ledger.execute(identity, "fit") == recovered
assert calls.count("fit") == 1
def test_failure_with_partial_outputs_does_not_become_success(setup):
ledger, plan, _, _ = setup
identity = ledger.register(plan)
def crash(root, argv, timeout):
(root / "partial-model.pt").write_bytes(b"synthetic partial checkpoint")
raise TimeoutError("training stopped before receipt")
ledger.runner = crash
with pytest.raises(TimeoutError):
ledger.execute(identity, "fit")
state = ledger.status(identity)["phases"][0]
with pytest.raises(ValueError, match="Missing"):
ledger.reconcile(identity, "fit", state["token"], "process stopped")
assert ledger.status(identity)["phases"][0]["state"] == "unknown"
(ledger.root / "failure-archive.txt").write_text("synthetic archived diagnostics")
archive = {"failure-archive.txt": m.pin(ledger.root, "failure-archive.txt")}
result = ledger.close_failed(identity, "fit", state["token"], "verified stopped", archive)
assert result["retry_authorized"] is False
assert (ledger.root / "partial-model.pt").exists()
with pytest.raises(ValueError, match="reconciliation"):
ledger.execute(identity, "fit")
def test_two_controllers_cannot_start_same_phase(setup):
ledger, plan, calls, runner = setup
identity = ledger.register(plan)
competitor = m.Execution(ledger.root, runner=runner)
def during(root, argv, timeout):
if argv[1] == "fit":
with pytest.raises(ValueError, match="reconciliation"):
competitor.execute(identity, "fit")
return runner(root, argv, timeout)
ledger.runner = during
try:
ledger.execute(identity, "fit")
assert calls.count("fit") == 1
finally:
competitor.close()
@pytest.mark.parametrize("changed", ["release.json", "runner.py", "fit.json"])
def test_changed_provenance_blocks_completed_resume_and_next_phase(setup, changed):
ledger, plan, calls, _ = setup
identity = ledger.register(plan)
ledger.execute(identity, "fit")
(ledger.root / changed).write_text("changed")
for phase in ["fit", "replay"]:
with pytest.raises(ValueError, match="changed"):
ledger.execute(identity, phase)
assert calls.count("fit") == 1 and "replay" not in calls
@pytest.mark.parametrize("mode", ["false", "missing-output", "mutated-after-pin", "extra-field"])
def test_invalid_verifier_cannot_complete_phase(setup, mode):
ledger, plan, _, runner = setup
identity = ledger.register(plan)
def bad(root, argv, timeout):
raw = runner(root, argv, timeout)
if not argv[1].startswith("verify-"):
return raw
value = json.loads(raw)
if mode == "false":
value["valid"] = False
if mode == "missing-output":
value["outputs"] = {}
if mode == "extra-field":
value["promote"] = True
if mode == "mutated-after-pin":
(root / "fit.json").write_text("tampered")
return json.dumps(value)
ledger.runner = bad
with pytest.raises(ValueError):
ledger.execute(identity, "fit")
assert ledger.status(identity)["phases"][0]["state"] == "unknown"
@pytest.mark.parametrize("member", ["../escape", "/absolute", "a\\b", "a:stream"])
def test_unsafe_outputs_are_rejected(setup, member):
ledger, plan, _, _ = setup
plan["phases"][0]["outputs"] = [member]
with pytest.raises(ValueError, match="Unsafe"):
ledger.register(plan)
def test_existing_outputs_require_explicit_ownership(setup):
ledger, plan, calls, _ = setup
(ledger.root / "fit.json").write_text("existing result")
with pytest.raises(ValueError, match="Unowned"):
ledger.register(plan)
assert not calls
def test_unfinished_owner_blocks_different_plan(setup):
ledger, plan, _, _ = setup
identity = ledger.register(plan)
ledger.runner = lambda *args: (_ for _ in ()).throw(ConnectionError("lost"))
with pytest.raises(ConnectionError):
ledger.execute(identity, "fit")
changed = copy.deepcopy(plan)
changed["objective"] = "another run"
with pytest.raises(ValueError, match="owns resources"):
ledger.register(changed)
def test_real_bounded_subprocess_verifier(tmp_path):
code = """import sys,json,hashlib
from pathlib import Path
p=Path('result.json')
if sys.argv[1]=='fit': p.write_text('{"value":42}')
else:
h=hashlib.sha256(p.read_bytes()).hexdigest()
outputs={'result.json':dict(bytes=p.stat().st_size,sha256=h)}
print(json.dumps(dict(valid=True,outputs=outputs,artifacts=outputs)))
"""
(tmp_path / "runner.py").write_text(code)
plan = dict(
schema=m.SCHEMA,
objective="real synthetic subprocess",
inputs={"runner.py": m.pin(tmp_path, "runner.py")},
phases=[
dict(
name="fit",
run=["runner.py", "fit"],
verify=["runner.py", "verify"],
outputs=["result.json"],
run_timeout_seconds=5,
verify_timeout_seconds=5,
)
],
)
ledger = m.Execution(tmp_path)
try:
identity = ledger.register(plan)
receipt = ledger.execute(identity, "fit")
assert receipt["outputs"]["result.json"]["bytes"] == 12
assert ledger.execute(identity, "fit") == receipt
finally:
ledger.close()
def test_small_output_cap_and_deadline(tmp_path, monkeypatch):
monkeypatch.setattr(m, "MAX_LOG", 16)
(tmp_path / "runner.py").write_text("print('x'*32)\n")
with pytest.raises(ValueError, match="output exceeded"):
m.invoke(tmp_path, ["runner.py"], 2)
(tmp_path / "runner.py").write_text("import time; time.sleep(2)\n")
with pytest.raises(subprocess.TimeoutExpired):
m.invoke(tmp_path, ["runner.py"], 0.02)
def test_manifest_payload_tamper_blocks_resume_and_next_phase(setup):
ledger, plan, calls, runner = setup
identity = ledger.register(plan)
def with_payload(root, argv, timeout):
raw = runner(root, argv, timeout)
if argv[1] == "fit":
(root / "model.pt").write_bytes(b"synthetic model")
if argv[1] == "verify-fit":
value = json.loads(raw)
value["artifacts"]["model.pt"] = m.pin(root, "model.pt")
return json.dumps(value)
return raw
ledger.runner = with_payload
receipt = ledger.execute(identity, "fit")
assert set(receipt["artifacts"]) == {"fit.json", "model.pt"}
(ledger.root / "model.pt").write_bytes(b"corrupted model")
for phase in ["fit", "replay"]:
with pytest.raises(ValueError, match="changed: model.pt"):
ledger.execute(identity, phase)
assert calls.count("fit") == 1 and "replay" not in calls
def test_verifier_cannot_omit_output_from_closure(setup):
ledger, plan, _, runner = setup
identity = ledger.register(plan)
def missing(root, argv, timeout):
raw = runner(root, argv, timeout)
if argv[1].startswith("verify-"):
value = json.loads(raw)
value["artifacts"] = {}
return json.dumps(value)
return raw
ledger.runner = missing
with pytest.raises(ValueError, match="closure"):
ledger.execute(identity, "fit")
def test_separate_process_budgets_and_compact_status(setup):
ledger, plan, _, runner = setup
plan["phases"][0].update(run_timeout_seconds=7, verify_timeout_seconds=3)
calls = []
def budget(root, argv, timeout):
calls.append(timeout)
return runner(root, argv, timeout)
ledger.runner = budget
identity = ledger.register(plan)
ledger.execute(identity, "fit")
assert calls == [7, 3]
phase = ledger.status(identity)["phases"][0]
assert "receipt" not in phase and phase["artifact_count"] == 1
assert len(phase["receipt_sha256"]) == 64
def test_readonly_input_root_with_separate_state_checks_real_external_files(tmp_path):
store = tmp_path / "store"
store.mkdir()
state = tmp_path / "state"
(store / "release.json").write_text('{"target":42}')
(store / "runner.py").write_text("# trusted synthetic runner")
def invoke(root, argv, timeout):
if argv[1] == "fit":
(root / "output.json").write_text('{"result":42}')
return ""
values = {"output.json": m.pin(root, "output.json")}
return json.dumps(dict(valid=True, outputs=values, artifacts=values))
plan = dict(
schema=m.SCHEMA,
objective="separate ledger and explicit source pins",
inputs={n: m.pin(store, n) for n in ["release.json", "runner.py"]},
phases=[
dict(
name="fit",
run=["runner.py", "fit"],
verify=["runner.py", "verify"],
outputs=["output.json"],
run_timeout_seconds=5,
verify_timeout_seconds=5,
)
],
)
ledger = m.Execution(store, state_root=state, runner=invoke)
try:
identity = ledger.register(plan)
ledger.execute(identity, "fit")
assert (state / "learning-execution.sqlite3").exists()
assert not (store / "learning-execution.sqlite3").exists()
(store / "release.json").write_text("changed external target")
with pytest.raises(ValueError, match="changed: release.json"):
ledger.execute(identity, "fit")
finally:
ledger.close()
def test_input_closure_above_128_files_is_bounded_and_checked(tmp_path):
(tmp_path / "runner.py").write_text("# synthetic")
inputs = {"runner.py": m.pin(tmp_path, "runner.py")}
for i in range(130):
name = f"input-{i}.json"
(tmp_path / name).write_text(str(i))
inputs[name] = m.pin(tmp_path, name)
plan = dict(
schema=m.SCHEMA,
objective="explicit real closure",
inputs=inputs,
phases=[
dict(
name="fit",
run=["runner.py"],
verify=["runner.py"],
outputs=["out.json"],
run_timeout_seconds=1,
verify_timeout_seconds=1,
)
],
)
ledger = m.Execution(tmp_path)
try:
identity = ledger.register(plan)
(tmp_path / "input-129.json").write_text("changed")
with pytest.raises(ValueError, match="input-129.json"):
ledger.execute(identity, "fit")
finally:
ledger.close()
@pytest.fixture
def cumulative_artifacts(tmp_path):
"""Three real completed receipts retain the same model and earlier outputs."""
(tmp_path / "runner.py").write_text("# synthetic cumulative pipeline\n")
(tmp_path / "release.json").write_text('{"accepted":true}\n')
phases = ["fit", "score", "replay", "judge"]
calls, receipts = [], []
def invoke(root, argv, timeout):
calls.append(argv[1])
phase = argv[1].removeprefix("verify-")
index = phases.index(phase)
if not argv[1].startswith("verify-"):
(root / (phase + ".json")).write_text(json.dumps(dict(phase=phase)))
if phase == "fit":
for name in ("model.pt", "copy.pt"):
(root / name).write_bytes(b"same bytes, distinct physical paths")
if phase == "score":
(root / "held.npz").write_bytes(b"synthetic prediction payload")
return ""
names = [n + ".json" for n in phases[: index + 1]] + ["model.pt", "copy.pt"]
if index >= 1:
names.append("held.npz")
return json.dumps(
dict(
valid=True,
outputs={phase + ".json": m.pin(root, phase + ".json")},
artifacts={name: m.pin(root, name) for name in names},
)
)
plan = dict(
schema=m.SCHEMA,
objective="cumulative synthetic artifact closure",
inputs={name: m.pin(tmp_path, name) for name in ["runner.py", "release.json"]},
phases=[
dict(
name=name,
run=["runner.py", name],
verify=["runner.py", "verify-" + name],
outputs=[name + ".json"],
run_timeout_seconds=5,
verify_timeout_seconds=5,
)
for name in phases
],
)
ledger = m.Execution(tmp_path, runner=invoke)
try:
identity = ledger.register(plan)
for phase in phases[:3]:
receipts.append(ledger.execute(identity, phase))
yield ledger, identity, plan, receipts, calls, invoke
finally:
ledger.close()
def test_cumulative_boundary_hashes_unique_paths_and_rechecks_next_boundary(
cumulative_artifacts, monkeypatch
):
ledger, identity, plan, receipts, _, _ = cumulative_artifacts
old_entries = [item for receipt in receipts for item in receipt["artifacts"].items()]
unique = dict(old_entries)
assert len(old_entries) == 14 and len(unique) == 6
assert unique["model.pt"] == unique["copy.pt"] # Equal hashes must not merge physical paths.
original = m.checksum
reads = []
def counted(path):
reads.append((path.relative_to(ledger.root).as_posix(), path.stat().st_size))
return original(path)
monkeypatch.setattr(m, "checksum", counted)
for _ in range(2):
reads.clear()
ledger._context(identity, "judge")
assert len(reads) == len(plan["inputs"]) + len(unique) == 8
assert {name for name, _ in reads} == set(plan["inputs"]) | set(unique)
assert sum(size for _, size in reads) == sum(
pin["bytes"] for pin in [*plan["inputs"].values(), *unique.values()]
)
assert sum(size for _, size in reads) < sum(
pin["bytes"] for pin in [*plan["inputs"].values(), *(pin for _, pin in old_entries)]
)
# The previous loop made16 calls/boundary (2 inputs +14 prior artifact entries).
# This is a structural count, not a latency or disk-throughput benchmark.
@pytest.mark.parametrize("mode", ["missing", "tampered"])
def test_cumulative_payload_change_blocks_next_and_completed_resume(cumulative_artifacts, mode):
ledger, identity, _, _, calls, _ = cumulative_artifacts
path = ledger.root / "copy.pt"
if mode == "missing":
path.unlink()
else:
path.write_bytes(b"corrupted despite model.pt remaining valid")
before = list(calls)
for phase in ("judge", "replay"):
with pytest.raises(
ValueError, match="(?:Missing regular artifact|Artifact changed): copy.pt"
):
ledger.execute(identity, phase)
assert calls == before
assert ledger.status(identity)["phases"][-1]["state"] == "pending"
@pytest.mark.parametrize("field,value", [("sha256", "0" * 64), ("bytes", 999)])
def test_conflicting_previous_pins_fail_before_any_payload_hash(
cumulative_artifacts, monkeypatch, field, value
):
ledger, identity, _, receipts, calls, _ = cumulative_artifacts
conflict = copy.deepcopy(receipts[-1])
conflict["artifacts"]["model.pt"][field] = value
with ledger.db:
ledger.db.execute(
"UPDATE learning_phases SET receipt=? WHERE run=? AND name='replay'",
(json.dumps(conflict), identity),
)
reads = []
original = m.checksum
def counted(path):
reads.append(path)
return original(path)
monkeypatch.setattr(m, "checksum", counted)
before = list(calls)
with pytest.raises(ValueError, match="Conflicting previous artifact pins: model.pt"):
ledger.execute(identity, "judge")
assert not reads and calls == before
def test_previous_payload_modified_during_phase_still_fails_post_verification(cumulative_artifacts):
ledger, identity, _, _, calls, runner = cumulative_artifacts
def corrupt_during_run(root, argv, timeout):
if argv[1] == "judge":
(root / "model.pt").write_bytes(b"mutated after precheck")
# The current verifier honestly reports new bytes; prior receipts still bind old bytes.
return runner(root, argv, timeout)
ledger.runner = corrupt_during_run
with pytest.raises(ValueError, match="Artifact changed: model.pt"):
ledger.execute(identity, "judge")
assert calls.count("judge") == 1
assert ledger.status(identity)["phases"][-1]["state"] == "unknown"