Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
245 lines
10 KiB
Python
245 lines
10 KiB
Python
"""Completion ownership, persistence and terminal-state race regressions."""
|
|
|
|
import sqlite3
|
|
|
|
import pytest
|
|
from test_agent_cycle import done, m, verdict
|
|
from test_agent_cycle import setup as cycle_setup
|
|
|
|
setup = cycle_setup
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("lease_seconds", "expired_at"), [(10, 110.0), (100, 200.0)], ids=["lease", "deadline"]
|
|
)
|
|
def test_completion_rechecks_expiry_after_source_validation(
|
|
setup, monkeypatch, lease_seconds, expired_at
|
|
):
|
|
c, plan, clock = setup
|
|
plan["limits"]["lease_seconds"] = lease_seconds
|
|
identity = c.begin(plan)
|
|
claim = c.claim(identity, "one", "annotate", "author")
|
|
monkeypatch.setattr(m, "validate_packet", lambda *args: clock.__setitem__(0, expired_at))
|
|
|
|
with pytest.raises(ValueError, match="(?i)expired|deadline|lease"):
|
|
c.complete(claim["token"], "author", dict(reason="source inspected"))
|
|
|
|
attempt = c.db.execute(
|
|
"SELECT finished,result,result_sha FROM agent_attempts WHERE token=?", (claim["token"],)
|
|
).fetchone()
|
|
assert tuple(attempt) == (None, None, None)
|
|
tasks = c.db.execute(
|
|
"SELECT stage,result FROM agent_tasks WHERE cycle=?", (identity,)
|
|
).fetchall()
|
|
assert [tuple(task) for task in tasks] == [("annotate", None)]
|
|
|
|
|
|
def test_root_decision_cannot_close_a_newly_interrupted_executor(setup, monkeypatch):
|
|
c, plan, clock = setup
|
|
identity = c.begin(plan)
|
|
claim = c.claim(identity, "one", "annotate", "author")
|
|
other = m.Cycle(c.root, clock=c.clock)
|
|
status = c.status
|
|
|
|
def status_with_competing_expiry(identity):
|
|
snapshot = status(identity)
|
|
# The old implementation releases its status transaction before decide.
|
|
# Do not attempt a second writer if the fixed implementation keeps it held.
|
|
if not c.db.in_transaction:
|
|
clock[0] = claim["expires"]
|
|
assert other.status(identity)["tasks"][0]["state"] == "interrupted"
|
|
return snapshot
|
|
|
|
monkeypatch.setattr(c, "status", status_with_competing_expiry)
|
|
rejected = dict(verdict(), verdict="rejected", next="revise", admitted_units=[])
|
|
try:
|
|
with pytest.raises(ValueError, match="(?i)root decision|executor|terminal|interrupted"):
|
|
c.decide(identity, "root", rejected)
|
|
assert other.status(identity)["state"] != "closed"
|
|
c.reconcile(claim["token"], "root", "Executor confirmed stopped")
|
|
assert other.status(identity)["tasks"][0]["state"] == "blocked"
|
|
finally:
|
|
other.close()
|
|
|
|
|
|
def test_completion_rejects_unknown_token_and_wrong_actor(setup):
|
|
c, plan, _ = setup
|
|
identity = c.begin(plan)
|
|
claim = c.claim(identity, "one", "annotate", "author")
|
|
result = dict(reason="source inspected")
|
|
for token, actor in (("unknown-token", "author"), (claim["token"], "other")):
|
|
with pytest.raises(ValueError, match="ownership"):
|
|
c.complete(token, actor, result)
|
|
task = c.status(identity)["tasks"][0]
|
|
assert task["state"] == "active" and task["result"] is None
|
|
c.complete(claim["token"], "author", result)
|
|
|
|
|
|
def test_completion_replay_after_reopen_preserves_evidence_and_review(setup):
|
|
c, plan, clock = setup
|
|
identity = c.begin(plan)
|
|
claim = c.claim(identity, "one", "annotate", "author")
|
|
result = dict(reason="source inspected", geometry=[1, 2])
|
|
sha = c.complete(claim["token"], "author", result)
|
|
original = dict(
|
|
c.db.execute("SELECT * FROM agent_attempts WHERE token=?", (claim["token"],)).fetchone()
|
|
)
|
|
c.close()
|
|
clock[0] = 201.0
|
|
reopened = m.Cycle(c.root, clock=c.clock)
|
|
try:
|
|
assert reopened.complete(claim["token"], "author", result) == sha
|
|
with pytest.raises(ValueError, match="ownership"):
|
|
reopened.complete(claim["token"], "other", result)
|
|
with pytest.raises(ValueError, match="Changed duplicate"):
|
|
reopened.complete(claim["token"], "author", dict(reason="changed"))
|
|
persisted = dict(
|
|
reopened.db.execute(
|
|
"SELECT * FROM agent_attempts WHERE token=?", (claim["token"],)
|
|
).fetchone()
|
|
)
|
|
assert persisted == original
|
|
assert reopened.db.execute(
|
|
"SELECT COUNT(*) FROM agent_tasks WHERE cycle=? AND stage='review'", (identity,)
|
|
).fetchone()[0] == 1
|
|
assert reopened.db.execute(
|
|
"SELECT COUNT(*) FROM agent_attempts WHERE cycle=?", (identity,)
|
|
).fetchone()[0] == 1
|
|
finally:
|
|
reopened.close()
|
|
|
|
|
|
def test_executor_actor_cannot_reconcile_or_decide(setup):
|
|
c, plan, _ = setup
|
|
identity = c.begin(plan)
|
|
claim = c.claim(identity, "one", "annotate", "author")
|
|
with pytest.raises(ValueError, match="Root reconciliation"):
|
|
c.reconcile(claim["token"], "author", "Executor stopped")
|
|
assert c.status(identity)["tasks"][0]["state"] == "active"
|
|
c.reconcile(claim["token"], "root", "Executor confirmed stopped", retry=True)
|
|
done(c, identity)
|
|
with pytest.raises(ValueError, match="Root decision"):
|
|
c.decide(identity, "author", verdict())
|
|
assert c.status(identity)["root_review"] is None
|
|
c.decide(identity, "root", verdict())
|
|
|
|
|
|
def test_sqlite_failure_rolls_back_completion_and_allows_same_claim_retry(setup):
|
|
c, plan, _ = setup
|
|
identity = c.begin(plan)
|
|
claim = c.claim(identity, "one", "annotate", "author")
|
|
result = dict(reason="source inspected")
|
|
c.db.executescript("""
|
|
CREATE TEMP TRIGGER fail_review_creation BEFORE INSERT ON agent_tasks
|
|
WHEN NEW.stage = 'review'
|
|
BEGIN SELECT RAISE(ABORT, 'injected review insert failure'); END;
|
|
""")
|
|
with pytest.raises(sqlite3.IntegrityError, match="injected review insert failure"):
|
|
c.complete(claim["token"], "author", result)
|
|
attempt = c.db.execute(
|
|
"SELECT finished,result,result_sha FROM agent_attempts WHERE token=?", (claim["token"],)
|
|
).fetchone()
|
|
assert tuple(attempt) == (None, None, None)
|
|
tasks = c.status(identity)["tasks"]
|
|
assert len(tasks) == 1 and tasks[0]["state"] == "active" and tasks[0]["result"] is None
|
|
|
|
c.db.execute("DROP TRIGGER fail_review_creation")
|
|
assert c.complete(claim["token"], "author", result) == m.digest(result)
|
|
tasks = c.status(identity)["tasks"]
|
|
assert [(task["stage"], task["state"]) for task in tasks] == [
|
|
("annotate", "done"),
|
|
("review", "ready"),
|
|
]
|
|
|
|
|
|
def test_ready_cancellation_rejects_foreign_actor_without_changing_state(setup):
|
|
c, plan, _ = setup
|
|
identity = c.begin(plan)
|
|
before = c.status(identity)
|
|
with pytest.raises(ValueError, match="(?i)root"):
|
|
c.cancel_ready(identity, "author", "Stop the bounded trial")
|
|
assert c.status(identity) == before
|
|
|
|
|
|
def test_ready_cancellation_preserves_evidence_and_requires_executor_reconciliation(setup):
|
|
c, plan, clock = setup
|
|
plan["limits"]["parallel"] = 3
|
|
plan["units"].extend(
|
|
dict(plan["units"][0], id=unit) for unit in ["two", "three", "four", "five"]
|
|
)
|
|
identity = c.begin(plan)
|
|
done(c, identity)
|
|
interrupted = c.claim(identity, "three", "annotate", "stopped-author")
|
|
proposed = c.claim(identity, "four", "annotate", "finished-author")
|
|
c.complete(proposed["token"], "finished-author", dict(reason="Preserve this proposal"))
|
|
clock[0] = 105.0
|
|
active = c.claim(identity, "two", "annotate", "active-author")
|
|
clock[0] = 110.0
|
|
before = c.status(identity)
|
|
frozen = tuple(
|
|
c.db.execute(
|
|
"SELECT plan,created,deadline FROM agent_cycles WHERE id=?", (identity,)
|
|
).fetchone()
|
|
)
|
|
attempts = [
|
|
dict(row)
|
|
for row in c.db.execute(
|
|
"SELECT * FROM agent_attempts WHERE cycle=? ORDER BY token", (identity,)
|
|
)
|
|
]
|
|
untouched = {
|
|
(task["unit"], task["stage"]): task for task in before["tasks"] if task["state"] != "ready"
|
|
}
|
|
reason = "Abort this trial after the dispatched authors stopped; revise before resuming"
|
|
c.cancel_ready(identity, "root", reason)
|
|
|
|
reopened = m.Cycle(c.root, clock=c.clock)
|
|
try:
|
|
after = reopened.status(identity)
|
|
tasks = {(task["unit"], task["stage"]): task for task in after["tasks"]}
|
|
for key, task in untouched.items():
|
|
assert tasks[key] == task
|
|
for key in [("four", "review"), ("five", "annotate")]:
|
|
task = tasks[key]
|
|
assert task["state"] == "blocked" and task["token"] is None
|
|
assert task["attempt"] == 0 and task["result"]["reason"] == reason
|
|
assert task["result_sha"] == m.digest(task["result"])
|
|
assert after["root_review"] is None
|
|
assert after["dispatches"] == before["dispatches"]
|
|
assert tuple(
|
|
reopened.db.execute(
|
|
"SELECT plan,created,deadline FROM agent_cycles WHERE id=?", (identity,)
|
|
).fetchone()
|
|
) == frozen
|
|
assert [
|
|
dict(row)
|
|
for row in reopened.db.execute(
|
|
"SELECT * FROM agent_attempts WHERE cycle=? ORDER BY token", (identity,)
|
|
)
|
|
] == attempts
|
|
|
|
# A retry with nothing left to cancel must not replace the recorded reason.
|
|
reopened.cancel_ready(identity, "root", "A different later explanation")
|
|
assert reopened.status(identity) == after
|
|
rejected = dict(
|
|
verdict(),
|
|
verdict="rejected",
|
|
next="revise",
|
|
admitted_units=[],
|
|
inspected_units=[unit["id"] for unit in plan["units"]],
|
|
)
|
|
with pytest.raises(ValueError, match="(?i)root decision|executor|terminal"):
|
|
reopened.decide(identity, "root", rejected)
|
|
reopened.reconcile(active["token"], "root", "Active executor confirmed stopped")
|
|
with pytest.raises(ValueError, match="executors"):
|
|
reopened.decide(identity, "root", rejected)
|
|
reopened.reconcile(interrupted["token"], "root", "Expired executor confirmed stopped")
|
|
reopened.decide(identity, "root", rejected)
|
|
closed = reopened.status(identity)
|
|
assert closed["state"] == "closed" and closed["root_review"] == rejected
|
|
with pytest.raises(ValueError, match="(?i)root|closed"):
|
|
reopened.cancel_ready(identity, "root", reason)
|
|
assert reopened.status(identity) == closed
|
|
finally:
|
|
reopened.close()
|