Files
NODEDC_MISSION_CORE/tests/test_agent_cycle.py
T
DCCONSTRUCTIONS 25dc0a1b44 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.
2026-10-29 09:10:00 +03:00

296 lines
10 KiB
Python

"""Failure paths that must stop an autonomous annotation loop."""
import copy
import importlib.util
import sys
from pathlib import Path
import pytest
SOURCE = Path(__file__).parents[1] / "simulation/semantic-learning"
sys.path.insert(0, str(SOURCE))
checksum = __import__("dataset_store").checksum
spec = importlib.util.spec_from_file_location("tested_agent_cycle", SOURCE / "agent_cycle.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
@pytest.fixture
def setup(tmp_path, monkeypatch):
monkeypatch.setattr(m, "validate_packet", lambda *args: None)
source = tmp_path / "raw.bin"
source.write_bytes(b"bounded synthetic evidence")
clock = [100.0]
c = m.Cycle(tmp_path, clock=lambda: clock[0])
plan = dict(
schema_version=m.SCHEMA,
root_actor="root",
objective="complete ROI",
baseline_sha256="a" * 64,
recipe="v1",
acceptance="source review",
limits=dict(parallel=2, attempts=2, dispatches=8, seconds=100, lease_seconds=10),
units=[
dict(
id="one",
physical_group="area",
split="train",
sources=[
dict(path="raw.bin", sha256=checksum(source), bytes=source.stat().st_size)
],
payload={},
)
],
parent=None,
)
yield c, plan, clock
c.close()
def annotated(c, identity):
claim = c.claim(identity, "one", "annotate", "author")
result = dict(reason="source inspected", geometry=[1, 2])
sha = c.complete(claim["token"], "author", result)
return claim, result, sha
def done(c, identity):
_, _, sha = annotated(c, identity)
claim = c.claim(identity, "one", "review", "reviewer")
c.complete(
claim["token"],
"reviewer",
dict(reason="raw + proposal checked", proposal_sha256=sha, verdict="accept"),
)
def verdict():
return dict(
verdict="accepted",
next="continue",
reason="reviewed",
inspected_units=["one"],
admitted_units=["one"],
checks=dict(coverage=True),
tuning="keep limits",
)
def test_root_gate_and_restart(setup):
c, plan, _ = setup
identity = c.begin(plan)
done(c, identity)
other = m.Cycle(c.root, clock=c.clock)
try:
assert other.status(identity)["state"] == "root_pending"
next_plan = dict(plan, parent=identity, recipe="v2")
with pytest.raises(ValueError, match="close"):
other.begin(next_plan)
other.decide(identity, "root", verdict())
assert other.begin(next_plan) != identity
finally:
other.close()
def test_review_identity_and_exact_proposal(setup):
c, plan, _ = setup
identity = c.begin(plan)
_, _, sha = annotated(c, identity)
with pytest.raises(ValueError, match="own"):
c.claim(identity, "one", "review", "author")
review = c.claim(identity, "one", "review", "reviewer")
with pytest.raises(ValueError, match="exact"):
c.complete(
review["token"],
"reviewer",
dict(reason="x", verdict="accept", proposal_sha256="f" * 64),
)
assert review["proposal_sha256"] == sha
def test_expired_claim_reserves_resource_until_stopped(setup):
c, plan, clock = setup
plan["limits"]["parallel"] = 1
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
clock[0] += 11
assert c.status(identity)["state"] == "root_pending"
with pytest.raises(ValueError, match="Expired"):
c.complete(claim["token"], "author", dict(reason="late"))
with pytest.raises(ValueError, match="executors"):
c.decide(identity, "root", verdict())
c.reconcile(claim["token"], "root", "executor terminated, receipt abc", retry=True)
replacement = c.claim(identity, "one", "annotate", "author")
assert replacement["token"] != claim["token"]
with pytest.raises(ValueError, match="superseded"):
c.complete(claim["token"], "author", dict(reason="stale"))
clock[0] += 11
c.status(identity)
with pytest.raises(ValueError, match="budget"):
c.reconcile(replacement["token"], "root", "stopped", retry=True)
def test_idempotent_completion_and_source_mutation(setup):
c, plan, _ = setup
identity = c.begin(plan)
claim, result, sha = annotated(c, identity)
assert c.complete(claim["token"], "author", result) == sha
with pytest.raises(ValueError, match="Changed duplicate"):
c.complete(claim["token"], "author", dict(reason="changed"))
(c.root / "raw.bin").write_bytes(b"mutation")
with pytest.raises(ValueError, match="source changed"):
c.claim(identity, "one", "review", "reviewer")
def test_dispatch_budget_and_no_claim_twice(setup):
c, plan, _ = setup
plan["limits"]["dispatches"] = 1
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
other = m.Cycle(c.root, clock=c.clock)
try:
with pytest.raises(ValueError):
other.claim(identity, "one", "annotate", "other")
finally:
other.close()
c.complete(claim["token"], "author", dict(reason="done"))
assert c.status(identity)["state"] == "root_pending"
with pytest.raises(ValueError, match="incomplete"):
c.decide(identity, "root", verdict())
def test_rejection_cannot_be_retried_without_changed_evidence(setup):
c, plan, _ = setup
identity = c.begin(plan)
_, _, sha = annotated(c, identity)
review = c.claim(identity, "one", "review", "reviewer")
c.complete(
review["token"],
"reviewer",
dict(reason="bad boundary", verdict="reject", proposal_sha256=sha),
)
root = dict(verdict(), verdict="rejected", next="revise", admitted_units=[])
c.decide(identity, "root", root)
with pytest.raises(ValueError, match="No progress"):
c.begin(dict(plan, parent=identity))
new = dict(plan, parent=identity, recipe="review finer source crop")
c.begin(new)
def test_input_validation_and_deadline(setup):
c, plan, clock = setup
bad = copy.deepcopy(plan)
bad["units"][0]["split"] = "test"
with pytest.raises(ValueError, match="TRAIN"):
c.begin(bad)
identity = c.begin(plan)
clock[0] += 101
assert c.status(identity)["state"] == "root_pending"
with pytest.raises(ValueError):
c.claim(identity, "one", "annotate", "author")
assert c.status(identity)["dispatches"] == 0
def test_concurrency_across_connections(setup):
c, plan, _ = setup
plan["limits"]["parallel"] = 1
plan["units"].append(dict(plan["units"][0], id="two"))
identity = c.begin(plan)
c.claim(identity, "one", "annotate", "author")
other = m.Cycle(c.root, clock=c.clock)
try:
with pytest.raises(ValueError, match="concurrency"):
other.claim(identity, "two", "annotate", "other")
finally:
other.close()
def test_accepted_iteration_cannot_repeat_same_work_with_new_id(setup):
c, plan, _ = setup
identity = c.begin(plan)
done(c, identity)
c.decide(identity, "root", verdict())
new = copy.deepcopy(plan)
new["parent"] = identity
new["units"][0]["id"] = "renamed"
with pytest.raises(ValueError, match="No progress"):
c.begin(new)
def test_parallel_claims_cannot_exceed_dispatch_budget(setup):
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
c, plan, _ = setup
plan["limits"].update(parallel=2, dispatches=1)
plan["units"].append(dict(plan["units"][0], id="two"))
identity = c.begin(plan)
gate = Barrier(2)
def compete(unit):
other = m.Cycle(c.root, clock=c.clock)
try:
gate.wait(timeout=5)
try:
other.claim(identity, unit, "annotate", unit)
return True
except ValueError:
return False
finally:
other.close()
with ThreadPoolExecutor(max_workers=2) as pool:
assert sum(pool.map(compete, ["one", "two"])) == 1
assert c.status(identity)["dispatches"] == 1
def test_root_quarantines_rejected_unit_without_repeating_accepted_work(setup):
c, plan, _ = setup
plan["units"].append(dict(plan["units"][0], id="two"))
identity = c.begin(plan)
done(c, identity)
claim = c.claim(identity, "two", "annotate", "other")
sha = c.complete(claim["token"], "other", dict(reason="uncertain source"))
review = c.claim(identity, "two", "review", "reviewer")
c.complete(
review["token"],
"reviewer",
dict(reason="insufficient evidence", verdict="reject", proposal_sha256=sha),
)
root = dict(verdict(), inspected_units=["one", "two"])
with pytest.raises(ValueError, match="failed"):
c.decide(identity, "root", dict(root, admitted_units=["one", "two"]))
c.decide(identity, "root", root)
assert c.status(identity)["root_review"]["admitted_units"] == ["one"]
def test_deadline_rechecked_after_source_verification(setup, monkeypatch):
c, plan, clock = setup
identity = c.begin(plan)
monkeypatch.setattr(m, "validate_packet", lambda *args: clock.__setitem__(0, 201))
with pytest.raises(ValueError, match="deadline passed"):
c.claim(identity, "one", "annotate", "author")
assert c.status(identity)["dispatches"] == 0
def test_evidence_quota_never_silently_drops_completion(setup, monkeypatch):
c, plan, _ = setup
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
monkeypatch.setattr(m, "MAX_LEDGER_JSON", 1)
with pytest.raises(ValueError, match="quota"):
c.complete(claim["token"], "author", dict(reason="bounded output"))
state = c.status(identity)
assert state["tasks"][0]["state"] == "active"
assert state["tasks"][0]["result"] is None
def test_large_output_is_rejected_before_it_can_bloat_root_packet(setup):
c, plan, _ = setup
identity = c.begin(plan)
claim = c.claim(identity, "one", "annotate", "author")
with pytest.raises(ValueError, match="Result byte"):
c.complete(claim["token"], "author", dict(reason="x", dump="x" * m.MAX_RESULT))
assert c.status(identity)["tasks"][0]["state"] == "active"