fix(issue-5): address phase 2a cross-review findings (F-A, F-B, R1, R2, R3)

Two reviewers raised five defects. Every one was reproduced here before being
accepted; none were rebutted.

F-A (claude, blocking) -- the CAS table had no row for two transitions the
wrapper legitimately makes, so `submit --type loop|discuss` silently stopped
working by default: the per-iteration re-dispatch was refused and its metadata
discarded, the exhausted-budget finalisation was refused, and the CLI returned 0
both times. Reproduced against the real modules. Fixed by naming those
transitions rather than carving an exception: `redispatch` and `finalize` are
requests gated on operator authority, so the wrapper can move a finished record
while an agent still cannot touch its own terminal. A re-dispatch must advance
the iteration, so a replay cannot resurrect a job. The operator CLI now exits
non-zero with a reason when a write is refused -- the silence is what let this
hide.

F-B (claude) -- moving the audit mirror out of the lock made status.json
last-writer-wins, so a slow flush could leave it behind the registry. It now
carries transition_seq and skips a write that would go backwards, restoring the
sequential consistency the lock used to provide for free.

R1 (codex, blocking) -- the policy called attribution with only the dispatch
record, so it proved the record was well-formed and never confronted the
identifiers the evidence carried. A finalized scenario with a different session,
a different attempt and a manifest from another attempt was still approved.
Observed identifiers are now collected from the timeline and every one must
agree; a manifest belonging to another attempt holds. Collecting every
occurrence rather than the first matters, because taking the first would drop
exactly the contradicting value this is meant to catch.

R2 (codex, blocking) -- a supplied expected_attempt was ignored when the record
had no attempt field, so a compare-and-swap with nothing to compare committed.
It now fails closed, which matters because 2b plans to gate inferred completion
on precisely that precondition.

R3 (codex) -- a status could ride in as an ordinary field, so `progress` could
commit a terminal from inside the boundary that exists to prevent it. Status is
now settable only by the request that owns it, unknown requests are refused, and
pending has an owning request instead of being an untyped merge.

Each of the eleven new regressions was checked against the pre-fix code first.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
This commit is contained in:
GodopuandClaude Opus 5 committed 2026-09-06 19:33:24 +09:00
1 parent 17a2dcd988
commit 56d08efa95
6 files changed
+378 -23

No files matched your search

+68 -9
View File
@@ -48,13 +48,26 @@ REQUEST_TO_STATUS = {
"cancelled": "cancelled",
"deadline_timeout": "error",
"merge": None,
# Operator-authority requests. The wrapper drives multi-iteration delegation
# (`submit --type loop|discuss`) by re-dispatching a finished job to the next
# session, and by finalising it as an error when the iteration budget is
# exhausted. Both legitimately move a terminal record, which is why they are
# separate requests gated on authority rather than an exception in the table.
"redispatch": "pending",
"finalize": "error",
}
# Only these sources may move a record out of a terminal state. An agent can
# never walk back its own terminal; that is the whole point of the CAS table.
OPERATOR_SOURCES = ("registry_cli", "operator")
OPERATOR_REQUESTS = ("redispatch", "finalize")
# A caller that merges `status=<value>` is making the request that owns that
# value; mapping it here is what stops a raw field write from sidestepping the
# CAS table. `pending` has no owning request (nothing transitions *to* pending),
# so it stays an ordinary metadata merge, exactly as before.
# CAS table. Every status has an owning request, `pending` included: the wrapper
# resets a finished job to pending to hand it to the next iteration.
STATUS_TO_REQUEST = {
"pending": "redispatch",
"running": "started",
"completed": "completed",
"error": "error",
@@ -93,17 +106,37 @@ class _Decision(object):
self.conflict = conflict
def _decide(record: Dict[str, Any], request: str, expected_status, expected_attempt) -> _Decision:
def _decide(record: Dict[str, Any], request: str, expected_status, expected_attempt,
source="unknown", fields=None) -> _Decision:
"""Pure CAS decision. No I/O, so it is safe to call under the lock.
Implements the target table in docs/contracts/issue-5/state-transitions.md §3.
"""
current = record.get("status")
fields = fields or {}
# Stale attempt or generation loses before anything else is considered.
# An unrecognised request must never fall through to the permissive branch.
if request not in REQUEST_TO_STATUS:
return _Decision(False, current, "unknown request: {!r}".format(request))
# A status may only be set by the request that owns it. Letting one ride in
# as an ordinary field would let `progress` commit a terminal, which is the
# decision table being bypassed from inside its own boundary.
if "status" in fields:
return _Decision(False, current,
"status must be requested, not merged as a field "
"(got status={!r} on request {!r})".format(fields["status"], request))
# A supplied precondition must be *proved*, not merely un-contradicted. If a
# caller names an expected attempt and the record cannot show one, the
# compare-and-swap has nothing to compare and must fail closed.
if expected_attempt is not None:
actual = record.get("attempt_id", record.get("iteration"))
if actual is not None and actual != expected_attempt:
if actual is None:
return _Decision(False, current,
"expected attempt {!r} but the record carries none".format(
expected_attempt))
if actual != expected_attempt:
return _Decision(False, current,
"stale attempt: expected {!r}, record has {!r}".format(
expected_attempt, actual))
@@ -115,10 +148,34 @@ def _decide(record: Dict[str, Any], request: str, expected_status, expected_atte
requested = REQUEST_TO_STATUS.get(request, None)
# Authority first, so a refusal says *why* rather than blaming the state.
if request in OPERATOR_REQUESTS and source not in OPERATOR_SOURCES:
return _Decision(False, current,
"{} requires operator authority (source={!r})".format(request, source))
if current in TERMINAL_STATUSES:
# Idempotent re-receipt of the same terminal is a no-op ack.
if requested == current:
return _Decision(False, current, "idempotent: already {}".format(current))
operator = source in OPERATOR_SOURCES
if operator and request == "redispatch":
# Re-dispatching a finished job to the next iteration. The attempt
# must move forward, so a replayed redispatch cannot resurrect it.
new_iteration = fields.get("iteration")
old_iteration = record.get("iteration")
if new_iteration is None:
return _Decision(False, current,
"redispatch requires an iteration", conflict=True)
if old_iteration is not None and int(new_iteration) <= int(old_iteration):
return _Decision(False, current,
"redispatch iteration {!r} does not advance past {!r}".format(
new_iteration, old_iteration), conflict=True)
return _Decision(True, "pending", "{} -> pending (redispatch)".format(current))
if operator and request in ("finalize", "error"):
return _Decision(True, "error", "{} -> error (finalize)".format(current))
if requested is None:
return _Decision(False, current,
"late {} after terminal {}; refusing".format(request, current),
@@ -128,8 +185,8 @@ def _decide(record: Dict[str, Any], request: str, expected_status, expected_atte
conflict=True)
if requested is None:
# progress / permission_required / metadata-only merge: the engine does
# not set a status, so any status in `fields` is applied as-is.
# progress / permission_required / metadata-only merge. No status is set
# here: a status-bearing field was already refused above.
return _Decision(True, None, "metadata updated ({})".format(request))
return _Decision(True, requested, "{} -> {}".format(current, requested))
@@ -155,7 +212,8 @@ def transition(job_id, request="merge", *, registry_dir=None, expected_status=No
with mqtt_common.registry_lock(registry_dir):
record = mqtt_common.load_job(job_id, registry_dir)
from_status = record.get("status")
decision = _decide(record, request, expected_status, expected_attempt)
decision = _decide(record, request, expected_status, expected_attempt,
source=source, fields=fields)
notifications: List[Dict[str, Any]] = []
if decision.commit:
@@ -206,7 +264,8 @@ def _flush(notifications, registry_dir) -> None:
try:
if kind == "status_changed":
mqtt_common.update_logged_status(
job_id, note["to"], updated_at=note.get("timestamp"))
job_id, note["to"], updated_at=note.get("timestamp"),
transition_seq=note.get("transition_seq"))
mqtt_common.append_event(job_id, {
"event": "status_changed",
"from": note.get("from"),