From 0001e94d008a3249555350819b7fd583d359129a Mon Sep 17 00:00:00 2001 From: Duang777 Date: Sun, 15 Nov 2026 02:45:11 +0000 Subject: [PATCH 1/4] fix(replan): accept a same-second whole-second historical ACK historicalAckDelta still required generated > admitted at microsecond precision. Compact generated_at is the whole-second run clock, while admission guard_recorded_at is often fractional inside that second, so an exact later ACK was dropped and the original receipt-bound Turn stayed unsettleable. A whole-second stamp at or after the admission second is post-admission. A fractional stamp still has to be strictly later than the admitted instant. Earlier fractions and the previous whole second stay rejected. Signed-off-by: Duang777 --- .../work_items/replan_semantics.ts | 10 ++- .../control_plane_ts/replan_semantics.test.ts | 62 +++++++++++++------ 2 files changed, 51 insertions(+), 21 deletions(-) diff --git a/loopx/control_plane/work_items/replan_semantics.ts b/loopx/control_plane/work_items/replan_semantics.ts index 333467ebfe..0ae40cd672 100644 --- a/loopx/control_plane/work_items/replan_semantics.ts +++ b/loopx/control_plane/work_items/replan_semantics.ts @@ -111,11 +111,19 @@ function historicalAckDelta( const ackTurn = typeof ack.turn_instance_id === "string" ? ack.turn_instance_id.trim() : ""; const generated = typeof ack.generated_at === "string" ? parseTodoTimestampMicros(ack.generated_at) : null; + // Compact generated_at is the whole-second run clock. Admission + // guard_recorded_at often keeps a fractional receipt instant, so a + // whole-second stamp in the admission second is post-admission. A + // fractional stamp still has to be strictly later than that instant. + const admissionSecond = admitted / 1_000_000n * 1_000_000n; + const afterAdmission = generated !== null && (generated % 1_000_000n === 0n + ? generated >= admissionSecond + : generated > admitted); const outcomes = strings(delta.outcomes); const satisfying = strings(delta.satisfying_outcomes); return ack.schema_version === "autonomous_replan_ack_v0" && ack.recorded === true && ack.goal_id === goal && ack.agent_id === agent && ackTurn && ackTurn !== guardTurn && - generated !== null && generated > admitted && + generated !== null && afterAdmission && delta.schema_version === "replan_semantic_delta_v0" && delta.accepted === true && delta.obligation_id === selected && outcomes.length > 0 && satisfying.length > 0 && outcomes.every(outcome => KNOWN_OUTCOMES.has(outcome)) && diff --git a/tests/control_plane_ts/replan_semantics.test.ts b/tests/control_plane_ts/replan_semantics.test.ts index d1b226b408..e2fd4dbd00 100644 --- a/tests/control_plane_ts/replan_semantics.test.ts +++ b/tests/control_plane_ts/replan_semantics.test.ts @@ -649,24 +649,49 @@ test("a later durable exact ACK settles only its original receipt-bound Turn", ( const request = {guard_scoped: true, selected_obligation_id: id, transition_candidates: [candidate], goal_id: goal, agent_id: agent, guard_recorded_at: "2026-08-01T00:00:01Z", guard_turn_instance_id: guardTurn}; - assert.deepEqual(projectReplanSemantics({operation: "turn_transition", ...request}).semantic_delta, delta); - const obligation = projectReplanSemantics({operation: "receipt_bound_obligation", ...request, - current_obligation: null, replay_phase: "open"}).obligation as JsonObject; - assert.equal(obligation.obligation_id, id); - assert.equal(obligation.resolution_mode, "receipt_bound_replan_settlement"); - const packet = obligation.settlement_action_packet as JsonObject; - assert.equal(packet.decision, "historical_ack_recorded"); - assert.equal(packet.settlement_only, true); - assert.equal(packet.required_outcome, "durable_writeback_receipt"); - assert.deepEqual(packet.semantic_delta, delta); - assert.equal((packet.writeback_contract as JsonObject).preferred_input, "exact_historical_ack"); + const settled = (current: typeof request) => { + assert.deepEqual(projectReplanSemantics({operation: "turn_transition", ...current}).semantic_delta, delta); + const obligation = projectReplanSemantics({operation: "receipt_bound_obligation", ...current, + current_obligation: null, replay_phase: "open"}).obligation as JsonObject; + assert.equal(obligation.obligation_id, id); + assert.equal(obligation.resolution_mode, "receipt_bound_replan_settlement"); + const packet = obligation.settlement_action_packet as JsonObject; + assert.equal(packet.decision, "historical_ack_recorded"); + assert.equal(packet.settlement_only, true); + assert.equal(packet.required_outcome, "durable_writeback_receipt"); + assert.deepEqual(packet.semantic_delta, delta); + assert.equal((packet.writeback_contract as JsonObject).preferred_input, "exact_historical_ack"); + }; + const rejected = (current: typeof request) => { + assert.equal(projectReplanSemantics({operation: "turn_transition", ...current}).semantic_delta, null); + assert.throws(() => projectReplanSemantics({operation: "receipt_bound_obligation", ...current, + current_obligation: null, replay_phase: "open"}), /identity conflicts/); + }; + settled(request); for (const missingGuard of [{guard_scoped: false}, {goal_id: null}, {agent_id: null}, {guard_recorded_at: null}, {guard_turn_instance_id: null}]) { - const unbound = {...request, ...missingGuard}; - assert.equal(projectReplanSemantics({operation: "turn_transition", ...unbound}).semantic_delta, null); - assert.throws(() => projectReplanSemantics({operation: "receipt_bound_obligation", ...unbound, - current_obligation: null, replay_phase: "open"}), /identity conflicts/); + rejected({...request, ...missingGuard}); + } + + // Compact generated_at is the whole-second run clock. A stamp in the + // admission second is post-admission when guard_recorded_at is that same + // whole second, or a fraction inside it (.500Z / .123456Z), including the + // offset form of that instant. The later Turn keeps its own turn id. + for (const guard_recorded_at of [ + "2026-08-01T00:00:01Z", "2026-08-01T00:00:01.500Z", "2026-08-01T00:00:01.123456Z", + ]) { + for (const generated_at of ["2026-08-01T00:00:01Z", "2026-08-01T08:00:01+08:00"]) { + settled({...request, guard_recorded_at, transition_candidates: [ + {historical_ack: {...historicalAck, generated_at}}]}); + } + } + // A fractional ACK earlier in the admission second is not the truncated run + // clock, and the previous whole second is still before admission. + const fractionalAdmission = {...request, guard_recorded_at: "2026-08-01T00:00:01.500Z"}; + for (const generated_at of ["2026-08-01T00:00:01.100Z", "2026-08-01T00:00:00Z"]) { + rejected({...fractionalAdmission, transition_candidates: [ + {historical_ack: {...historicalAck, generated_at}}]}); } const invalid = [ @@ -676,7 +701,7 @@ test("a later durable exact ACK settles only its original receipt-bound Turn", ( {historical_ack: {...historicalAck, agent_id: "peer"}}, {historical_ack: {...historicalAck, turn_instance_id: guardTurn}}, {historical_ack: {...historicalAck, turn_instance_id: null}}, - {historical_ack: {...historicalAck, generated_at: "2026-08-01T00:00:01Z"}}, + {historical_ack: {...historicalAck, generated_at: "2026-08-01T00:00:00Z"}}, {historical_ack: {...historicalAck, generated_at: "invalid"}}, {historical_ack: {...historicalAck, semantic_delta: {...delta, schema_version: "wrong"}}}, {historical_ack: {...historicalAck, semantic_delta: {...delta, accepted: false}}}, @@ -686,10 +711,7 @@ test("a later durable exact ACK settles only its original receipt-bound Turn", ( {historical_ack: {...historicalAck, semantic_delta: {...delta, satisfying_outcomes: ["new_surface"]}}}, ]; for (const badCandidate of invalid) { - const changed = {...request, transition_candidates: [badCandidate]}; - assert.equal(projectReplanSemantics({operation: "turn_transition", ...changed}).semantic_delta, null); - assert.throws(() => projectReplanSemantics({operation: "receipt_bound_obligation", ...changed, - current_obligation: null, replay_phase: "open"}), /identity conflicts/); + rejected({...request, transition_candidates: [badCandidate]}); } }); From 007bf6558da10194df4f64d2cc9abec384fa6ed7 Mon Sep 17 00:00:00 2001 From: Duang777 Date: Sun, 15 Nov 2026 20:37:12 +0000 Subject: [PATCH 2/4] fix(replan): require writeback order for same-second historical ACKs A whole-second generated_at cannot separate an ACK written before admission from one written after it. Same-second recovery now requires the original refresh_state event bound to the Goal, Agent, obligation, and ACK Turn, with both its recorded time and log position after admission. A generated_at that is already strictly later keeps the precise path. Missing or conflicting order leaves the obligation pending. Signed-off-by: Duang777 --- loopx/control_plane/quota/live_decision.py | 5 +- .../work_items/autonomous_replan_ack.py | 88 ++++++++++++++++++- .../work_items/replan_semantics.ts | 23 +++-- .../work_items/semantic_replan_writeback.py | 18 +++- .../test_autonomous_replan_ack.py | 34 +++++++ .../test_quota_settlement_cli.py | 75 ++++++++++++++++ .../control_plane_ts/replan_semantics.test.ts | 32 +++++-- 7 files changed, 258 insertions(+), 17 deletions(-) diff --git a/loopx/control_plane/quota/live_decision.py b/loopx/control_plane/quota/live_decision.py index 5498b6ea28..f7cb06de9d 100644 --- a/loopx/control_plane/quota/live_decision.py +++ b/loopx/control_plane/quota/live_decision.py @@ -759,7 +759,10 @@ def build_live_quota_should_run_decision( ): from ..work_items.autonomous_replan_ack import load_receipt_replan_ack_candidates decision_status_payload["receipt_bound_replan_ack_candidates"] = load_receipt_replan_ack_candidates( - runtime_root, goal_id=goal_id, agent_id=agent_id, obligation_id=receipt_bound_replan_obligation_id) + runtime_root, goal_id=goal_id, agent_id=agent_id, + obligation_id=receipt_bound_replan_obligation_id, + guard_recorded_at=receipt_bound_guard_fields["receipt_bound_guard_recorded_at"], + guard_turn_instance_id=receipt_bound_guard_fields["receipt_bound_guard_turn_instance_id"]) fresh_operator_inbox_read = _fresh_operator_inbox_read_required( turn_start_hook_dispatch ) diff --git a/loopx/control_plane/work_items/autonomous_replan_ack.py b/loopx/control_plane/work_items/autonomous_replan_ack.py index c01f7e8738..e7974c6c14 100644 --- a/loopx/control_plane/work_items/autonomous_replan_ack.py +++ b/loopx/control_plane/work_items/autonomous_replan_ack.py @@ -267,18 +267,104 @@ def autonomous_replan_ack_candidates_for_obligation( return candidates +def _event_details(event: dict[str, Any]) -> dict[str, Any]: + details = event.get("details") + return details if isinstance(details, dict) else {} + + +def _admission_event_index( + events: list[dict[str, Any]], *, goal_id: str, agent_id: str, + turn_instance_id: str, recorded_at: str, +) -> int | None: + if not turn_instance_id or not recorded_at: + return None + found: int | None = None + for index, event in enumerate(events): + if ( + event.get("event_kind") == "quota_should_run" + and event.get("goal_id") == goal_id + and event.get("agent_id") == agent_id + and event.get("run_id") == turn_instance_id + and event.get("recorded_at") == recorded_at + ): + found = index + return found + + +def _original_writeback_event_index( + events: list[dict[str, Any]], *, goal_id: str, agent_id: str, + obligation_id: str, turn_instance_id: str, +) -> int | None: + if not turn_instance_id or not obligation_id: + return None + for index, event in enumerate(events): + details = _event_details(event) + if ( + event.get("event_kind") == "refresh_state" + and event.get("goal_id") == goal_id + and event.get("agent_id") == agent_id + and event.get("run_id") == turn_instance_id + and details.get("autonomous_replan_recorded") is True + and str(details.get("replan_obligation_id") or "").strip() == obligation_id + ): + return index + return None + + +def attach_historical_ack_writeback_order( + candidates: list[dict[str, Any]], events: list[dict[str, Any]], *, + goal_id: str, agent_id: str, obligation_id: str, + guard_recorded_at: str | None, guard_turn_instance_id: str | None, +) -> None: + """Copy the original refresh event order onto matching ACK candidates. + + The compact run clock is whole seconds. The decision owner compares this + event with admission; this reader only selects the bound original event. + """ + + admission_index = _admission_event_index( + events, goal_id=goal_id, agent_id=agent_id, + turn_instance_id=str(guard_turn_instance_id or "").strip(), + recorded_at=str(guard_recorded_at or "").strip(), + ) + for candidate in candidates: + evidence_index = _original_writeback_event_index( + events, goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id, + turn_instance_id=str(candidate.get("turn_instance_id") or "").strip(), + ) + if evidence_index is None: + continue + event = events[evidence_index] + candidate["writeback_recorded_at"] = event.get("recorded_at") + candidate["writeback_goal_id"] = event.get("goal_id") + candidate["writeback_agent_id"] = event.get("agent_id") + candidate["writeback_turn_instance_id"] = event.get("run_id") + candidate["writeback_obligation_id"] = obligation_id + candidate["writeback_follows_admission"] = ( + admission_index is not None and evidence_index > admission_index + ) + + def load_receipt_replan_ack_candidates( runtime_root: Path, *, goal_id: str, agent_id: str, obligation_id: str, + guard_recorded_at: str | None = None, guard_turn_instance_id: str | None = None, ) -> list[dict[str, Any]]: """Read exact recovery candidates without widening ordinary status history.""" from ...history import load_index + from ...rollout_event_log import load_rollout_events, rollout_event_log_path from ..runtime.time import chronology_key runs, _ = load_index(runtime_root / "goals" / goal_id / "runs" / "index.jsonl") newest_first = [run for _, run in sorted(enumerate(runs), key=lambda item: (*chronology_key(item[1].get("generated_at")), item[0]), reverse=True)] - return autonomous_replan_ack_candidates_for_obligation(newest_first, + candidates = autonomous_replan_ack_candidates_for_obligation(newest_first, goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id) + attach_historical_ack_writeback_order( + candidates, load_rollout_events(rollout_event_log_path(runtime_root, goal_id)), + goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id, + guard_recorded_at=guard_recorded_at, guard_turn_instance_id=guard_turn_instance_id, + ) + return candidates def latest_blocked_successor_frontier_identity( diff --git a/loopx/control_plane/work_items/replan_semantics.ts b/loopx/control_plane/work_items/replan_semantics.ts index 0ae40cd672..8fcdb1b41b 100644 --- a/loopx/control_plane/work_items/replan_semantics.ts +++ b/loopx/control_plane/work_items/replan_semantics.ts @@ -111,14 +111,23 @@ function historicalAckDelta( const ackTurn = typeof ack.turn_instance_id === "string" ? ack.turn_instance_id.trim() : ""; const generated = typeof ack.generated_at === "string" ? parseTodoTimestampMicros(ack.generated_at) : null; - // Compact generated_at is the whole-second run clock. Admission - // guard_recorded_at often keeps a fractional receipt instant, so a - // whole-second stamp in the admission second is post-admission. A - // fractional stamp still has to be strictly later than that instant. + // A generated_at that is already strictly later proves order on its own. + // The compact run clock is whole seconds, so a stamp inside the admission + // second can be either side of a fractional guard_recorded_at. That + // candidate needs the original refresh_state event, bound to this Goal, + // Agent, obligation, and ACK Turn, with both its recorded time and its + // log position after admission. Missing or conflicting order stays pending. const admissionSecond = admitted / 1_000_000n * 1_000_000n; - const afterAdmission = generated !== null && (generated % 1_000_000n === 0n - ? generated >= admissionSecond - : generated > admitted); + const preciseLater = generated !== null && generated > admitted; + const sameSecond = generated !== null && generated % 1_000_000n === 0n && + generated >= admissionSecond && !preciseLater; + const written = typeof ack.writeback_recorded_at === "string" + ? parseTodoTimestampMicros(ack.writeback_recorded_at) : null; + const writebackAfterAdmission = sameSecond && written !== null && written > admitted && + ack.writeback_follows_admission === true && ack.writeback_goal_id === goal && + ack.writeback_agent_id === agent && ack.writeback_turn_instance_id === ackTurn && + ack.writeback_obligation_id === selected; + const afterAdmission = preciseLater || writebackAfterAdmission; const outcomes = strings(delta.outcomes); const satisfying = strings(delta.satisfying_outcomes); return ack.schema_version === "autonomous_replan_ack_v0" && ack.recorded === true && diff --git a/loopx/control_plane/work_items/semantic_replan_writeback.py b/loopx/control_plane/work_items/semantic_replan_writeback.py index 494bb176ad..ccdaa3886c 100644 --- a/loopx/control_plane/work_items/semantic_replan_writeback.py +++ b/loopx/control_plane/work_items/semantic_replan_writeback.py @@ -24,6 +24,7 @@ ) from ..todos.succession_warning import todo_succession_gap_items from .autonomous_replan_ack import ( + attach_historical_ack_writeback_order, autonomous_replan_ack_candidates_for_obligation, latest_monitor_replan_frontier_identity, watch_lane_continuation_todo_ids, @@ -294,9 +295,24 @@ def qualify_replan_writeback( ] } } - status_payload["receipt_bound_replan_ack_candidates"] = autonomous_replan_ack_candidates_for_obligation( + historical_ack_candidates = autonomous_replan_ack_candidates_for_obligation( newest_first_runs, goal_id=goal_id, agent_id=safe_agent_id, obligation_id=guard_semantic_replan_obligation_id if guard_scoped else None) + runtime_root_text = str((replan_source_route or {}).get("runtime_root") or "").strip() + if runtime_root_text and guard_scoped and guard_semantic_replan_obligation_id: + from pathlib import Path + + from ...rollout_event_log import load_rollout_events, rollout_event_log_path + + attach_historical_ack_writeback_order( + historical_ack_candidates, + load_rollout_events(rollout_event_log_path(Path(runtime_root_text), goal_id)), + goal_id=goal_id, agent_id=safe_agent_id, + obligation_id=guard_semantic_replan_obligation_id, + guard_recorded_at=receipt_bound_guard_recorded_at, + guard_turn_instance_id=receipt_bound_guard_turn_instance_id, + ) + status_payload["receipt_bound_replan_ack_candidates"] = historical_ack_candidates if capability_evidence is not None: status_payload["bounded_research_frontier"] = capability_evidence.frontier context = build_goal_frontier_projection_context_from_status( diff --git a/tests/control_plane/test_autonomous_replan_ack.py b/tests/control_plane/test_autonomous_replan_ack.py index e3a0c2bebd..0c5b73e542 100644 --- a/tests/control_plane/test_autonomous_replan_ack.py +++ b/tests/control_plane/test_autonomous_replan_ack.py @@ -8,6 +8,7 @@ from loopx.control_plane.work_items.autonomous_replan_ack import ( AUTONOMOUS_REPLAN_ACK_MATERIAL_RUN_WINDOW, AUTONOMOUS_REPLAN_ACK_RECOVERY_CANDIDATE_LIMIT, + attach_historical_ack_writeback_order, autonomous_replan_ack_candidates_for_obligation, compact_autonomous_replan_ack, latest_autonomous_replan_ack_for_projection, @@ -325,3 +326,36 @@ def test_long_chain_trigger_checkpoint_survives_ack_compaction() -> None: assert compact["semantic_delta"]["trigger_checkpoints"] == [ {"kind": "long_todo_chain", "frontier_revision": frontier_revision} ] + + +def test_same_second_candidate_keeps_only_the_bound_original_writeback_order() -> None: + turn = "guided-start:later" + admission = {"event_kind": "quota_should_run", "goal_id": GOAL_ID, "agent_id": AGENT_ID, + "run_id": "guided-start:original", "recorded_at": "2026-08-01T00:00:01.500000Z"} + early = {"event_kind": "refresh_state", "goal_id": GOAL_ID, "agent_id": AGENT_ID, + "run_id": turn, "recorded_at": "2026-08-01T00:00:01.100000Z", "details": { + "autonomous_replan_recorded": True, "replan_obligation_id": LONG_CHAIN_OBLIGATION_ID}} + other_goal = {"event_kind": "refresh_state", "goal_id": "other-goal", "agent_id": AGENT_ID, + "run_id": turn, "recorded_at": "2026-08-01T00:00:01.900000Z", "details": { + "autonomous_replan_recorded": True, "replan_obligation_id": LONG_CHAIN_OBLIGATION_ID}} + before = {"turn_instance_id": turn, "generated_at": "2026-08-01T00:00:01Z"} + attach_historical_ack_writeback_order( + [before], [early, other_goal, admission], goal_id=GOAL_ID, agent_id=AGENT_ID, + obligation_id=LONG_CHAIN_OBLIGATION_ID, + guard_recorded_at="2026-08-01T00:00:01.500000Z", + guard_turn_instance_id="guided-start:original", + ) + assert before["writeback_recorded_at"] == "2026-08-01T00:00:01.100000Z" + assert before["writeback_follows_admission"] is False + assert before["writeback_goal_id"] == GOAL_ID + assert before["writeback_turn_instance_id"] == turn + assert before["writeback_obligation_id"] == LONG_CHAIN_OBLIGATION_ID + after = {"turn_instance_id": turn} + attach_historical_ack_writeback_order( + [after], [admission, early], goal_id=GOAL_ID, agent_id=AGENT_ID, + obligation_id=LONG_CHAIN_OBLIGATION_ID, + guard_recorded_at="2026-08-01T00:00:01.500000Z", + guard_turn_instance_id="guided-start:original", + ) + assert after["writeback_recorded_at"] == "2026-08-01T00:00:01.100000Z" + assert after["writeback_follows_admission"] is True diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py index e747385d8c..520b62a97f 100644 --- a/tests/control_plane/test_quota_settlement_cli.py +++ b/tests/control_plane/test_quota_settlement_cli.py @@ -8975,3 +8975,78 @@ def test_exact_later_ack_executes_original_todo_settlement_commands( rc, todo = _run_cli(registry, runtime, "todo", "list", "--goal-id", GOAL_ID, "--todo-id", SELECTED_REPLAN_TODO_ID) assert rc == 0 and todo["todo"]["status"] == "open", todo + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("order", ["after", "before", "time_after_log_before", "time_before_log_after"]) +def test_same_second_historical_ack_requires_writeback_after_admission( + tmp_path: Path, provider: str, order: str, +) -> None: + project, runtime, registry = _write_fixture(tmp_path) + _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off") + _initialize_git_checkout(project) + _initialize_fixture_authority(project, runtime, provider=provider) + original_turn = "turn-historical-same-second" + admitted = _bind_selected_replan_guard(registry, runtime, project, original_turn) + obligation = admitted["replan_action_packet"]["obligation_id"] + recorded_at = admitted["heartbeat_receipt"]["recorded_at"] + recorded = datetime.fromisoformat(recorded_at.replace("Z", "+00:00")) + later_turn = "later-accepted-same-second" + time_after = order in {"after", "time_after_log_before"} + written = recorded + timedelta(microseconds=1 if time_after else -1) + written_at = written.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + event = build_rollout_event( + goal_id=GOAL_ID, event_kind="refresh_state", agent_id=AGENT_ID, run_id=later_turn, + status="appended", summary="accepted same-second historical review", + recorded_at=written_at, details={ + "command": "refresh-state", "autonomous_replan_recorded": True, + "replan_obligation_id": obligation, + }, + ) + log_path = runtime / "goals" / GOAL_ID / "rollout-event-log.jsonl" + events = [json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines() if line.strip()] + admission_index = next(index for index, item in enumerate(events) + if item.get("event_kind") == "quota_should_run" and item.get("run_id") == original_turn + and item.get("recorded_at") == recorded_at) + log_after = order in {"after", "time_before_log_after"} + events.insert(len(events) if log_after else admission_index, event) + log_path.write_text("".join(json.dumps(item) + "\n" for item in events), encoding="utf-8") + runs_dir = runtime / "goals" / GOAL_ID / "runs" + runs_dir.mkdir(parents=True, exist_ok=True) + run = {"goal_id": GOAL_ID, "agent_id": AGENT_ID, "turn_instance_id": later_turn, + "generated_at": recorded.replace(microsecond=0).astimezone(timezone.utc).isoformat().replace("+00:00", "Z"), + "classification": "bounded_replan_progress", + "autonomous_replan_ack": {"schema_version": "autonomous_replan_ack_v0", "recorded": True, + "source": "refresh_state", "semantic_delta": {"schema_version": "replan_semantic_delta_v0", + "accepted": True, "obligation_id": obligation, + "outcomes": ["fresh_vision_path_outcome"], "satisfying_outcomes": ["fresh_vision_path_outcome"]}}} + source = runs_dir / "later-accepted-same-second.json" + source.write_text(json.dumps(run), encoding="utf-8") + markdown = source.with_suffix(".md") + markdown.write_text("# Accepted same-second historical review\n", encoding="utf-8") + with (runs_dir / "index.jsonl").open("a", encoding="utf-8") as stream: + stream.write(json.dumps({**run, "json_path": str(source), "markdown_path": str(markdown)}) + "\n") + guard_args = ("quota", "should-run", "--codex-app", "--goal-id", GOAL_ID, + "--agent-id", AGENT_ID, "--turn-instance-id", original_turn, + "--todo-id", SELECTED_REPLAN_TODO_ID) + rc, recovery = _run_cli(registry, runtime, *guard_args) + decision = (recovery.get("replan_action_packet") or {}).get("decision") + if order != "after": + assert decision != "historical_ack_recorded", { + "rc": rc, "decision": decision, "error": recovery.get("error"), + "error_code": recovery.get("error_code"), + } + assert _spend_run_count(runtime) == 0 + return + assert rc == 0, recovery + assert decision == "historical_ack_recorded", recovery.get("replan_action_packet") + actions = recovery["interaction_contract"]["cli_channel"]["next_cli_actions"] + writeback = next(command for command in actions if "refresh-state" in command) + spend = next(command for command in actions if "spend-slot" in command) + before = _spend_run_count(runtime) + rc, written_payload = _run_generated_cli(writeback, registry_path=registry) + assert rc == 0 and written_payload["ok"] is True and written_payload["appended"] is True, written_payload + assert _spend_run_count(runtime) == before + rc, spent = _run_generated_cli(spend, registry_path=registry) + assert rc == 0 and spent["ok"] is True, spent + assert _spend_run_count(runtime) == before + 1 diff --git a/tests/control_plane_ts/replan_semantics.test.ts b/tests/control_plane_ts/replan_semantics.test.ts index e2fd4dbd00..cd45042277 100644 --- a/tests/control_plane_ts/replan_semantics.test.ts +++ b/tests/control_plane_ts/replan_semantics.test.ts @@ -674,24 +674,42 @@ test("a later durable exact ACK settles only its original receipt-bound Turn", ( rejected({...request, ...missingGuard}); } - // Compact generated_at is the whole-second run clock. A stamp in the - // admission second is post-admission when guard_recorded_at is that same - // whole second, or a fraction inside it (.500Z / .123456Z), including the - // offset form of that instant. The later Turn keeps its own turn id. + // The whole-second run clock cannot order two writes inside the admission + // second. A bound refresh_state event whose recorded time and log position + // are both after admission can. The later Turn keeps its own turn id. + const boundWriteback = (generated_at: string, writeback_recorded_at: string, follows = true) => ({ + historical_ack: {...historicalAck, generated_at, writeback_recorded_at, + writeback_follows_admission: follows, writeback_goal_id: goal, writeback_agent_id: agent, + writeback_turn_instance_id: laterTurn, writeback_obligation_id: id}, + }); for (const guard_recorded_at of [ "2026-08-01T00:00:01Z", "2026-08-01T00:00:01.500Z", "2026-08-01T00:00:01.123456Z", ]) { for (const generated_at of ["2026-08-01T00:00:01Z", "2026-08-01T08:00:01+08:00"]) { settled({...request, guard_recorded_at, transition_candidates: [ + boundWriteback(generated_at, "2026-08-01T00:00:01.900000Z")]}); + rejected({...request, guard_recorded_at, transition_candidates: [ {historical_ack: {...historicalAck, generated_at}}]}); } } - // A fractional ACK earlier in the admission second is not the truncated run - // clock, and the previous whole second is still before admission. const fractionalAdmission = {...request, guard_recorded_at: "2026-08-01T00:00:01.500Z"}; + const sameSecondAck = boundWriteback("2026-08-01T00:00:01Z", "2026-08-01T00:00:01.900000Z"); + rejected({...fractionalAdmission, transition_candidates: [ + boundWriteback("2026-08-01T00:00:01Z", "2026-08-01T00:00:01.100Z")]}); + rejected({...fractionalAdmission, transition_candidates: [ + boundWriteback("2026-08-01T00:00:01Z", "2026-08-01T00:00:01.900000Z", false)]}); + for (const broken of [ + {writeback_goal_id: "goal-b"}, {writeback_agent_id: "peer"}, + {writeback_turn_instance_id: guardTurn}, {writeback_obligation_id: "replan-2222222222222222"}, + ]) { + rejected({...fractionalAdmission, transition_candidates: [ + {historical_ack: {...sameSecondAck.historical_ack, ...broken}}]}); + } + // A fractional ACK earlier in the admission second, and a previous whole + // second, stay pending even when a later event is attached. for (const generated_at of ["2026-08-01T00:00:01.100Z", "2026-08-01T00:00:00Z"]) { rejected({...fractionalAdmission, transition_candidates: [ - {historical_ack: {...historicalAck, generated_at}}]}); + boundWriteback(generated_at, "2026-08-01T00:00:01.900000Z")]}); } const invalid = [ From c0902e53161a09e00d35e28c9856362f0fbb6098 Mon Sep 17 00:00:00 2001 From: Duang777 Date: Sun, 15 Nov 2026 21:32:56 +0000 Subject: [PATCH 3/4] fix(replan): bind same-second ACKs through the Todo receipt A Todo-bound refresh records the obligation on the accepted semantic delta and leaves replan_obligation_id empty on the rollout event. Match that event by the Todo settlement receipt, and keep the time and log-order checks. Historical events that omit the field still bind when the receipt agrees. The writeback qualifier calls the shared reader instead of loading events itself. Signed-off-by: Duang777 --- .../work_items/autonomous_replan_ack.py | 95 ++++++++++++++++--- .../work_items/semantic_replan_writeback.py | 26 ++--- .../test_autonomous_replan_ack.py | 49 ++++++---- .../test_quota_settlement_cli.py | 71 +++++++++----- 4 files changed, 163 insertions(+), 78 deletions(-) diff --git a/loopx/control_plane/work_items/autonomous_replan_ack.py b/loopx/control_plane/work_items/autonomous_replan_ack.py index e7974c6c14..fcf4280735 100644 --- a/loopx/control_plane/work_items/autonomous_replan_ack.py +++ b/loopx/control_plane/work_items/autonomous_replan_ack.py @@ -291,21 +291,63 @@ def _admission_event_index( return found +def _binding_text(value: Any) -> str: + return str(value or "").strip() + + +def _source_run( + runs: list[dict[str, Any]] | None, *, turn_instance_id: str, obligation_id: str, +) -> dict[str, Any]: + for run in runs or []: + if _binding_text(run.get("turn_instance_id")) != turn_instance_id: + continue + ack = run.get("autonomous_replan_ack") + delta = ack.get("semantic_delta") if isinstance(ack, dict) else None + if isinstance(delta, dict) and _binding_text(delta.get("obligation_id")) == obligation_id: + return run + return {} + + +def _todo_receipt_matches(event: dict[str, Any], run: dict[str, Any]) -> bool: + """A Todo-bound refresh stores the obligation on the semantic delta. + + The rollout event leaves replan_obligation_id empty and carries the Todo + settlement receipt. Historical events may omit that receipt too. A present + identity on both sides must still be the same receipt. + """ + + details = _event_details(event) + identity = run.get("settlement_identity") + identity = identity if isinstance(identity, dict) else {} + event_effect = _binding_text(details.get("settlement_effect_id")) + run_effect = _binding_text(identity.get("effect_id")) + if event_effect and run_effect and event_effect != run_effect: + return False + event_todo = _binding_text(event.get("todo_id")) + run_todo = _binding_text(run.get("todo_id") or identity.get("todo_id")) + if event_todo and run_todo and event_todo != run_todo: + return False + return True + + def _original_writeback_event_index( - events: list[dict[str, Any]], *, goal_id: str, agent_id: str, - obligation_id: str, turn_instance_id: str, + events: list[dict[str, Any]], runs: list[dict[str, Any]] | None, *, + goal_id: str, agent_id: str, obligation_id: str, turn_instance_id: str, ) -> int | None: if not turn_instance_id or not obligation_id: return None + run = _source_run(runs, turn_instance_id=turn_instance_id, obligation_id=obligation_id) for index, event in enumerate(events): details = _event_details(event) + event_obligation = _binding_text(details.get("replan_obligation_id")) if ( event.get("event_kind") == "refresh_state" and event.get("goal_id") == goal_id and event.get("agent_id") == agent_id - and event.get("run_id") == turn_instance_id + and _binding_text(event.get("run_id")) == turn_instance_id and details.get("autonomous_replan_recorded") is True - and str(details.get("replan_obligation_id") or "").strip() == obligation_id + and (not event_obligation or event_obligation == obligation_id) + and _todo_receipt_matches(event, run) ): return index return None @@ -315,6 +357,7 @@ def attach_historical_ack_writeback_order( candidates: list[dict[str, Any]], events: list[dict[str, Any]], *, goal_id: str, agent_id: str, obligation_id: str, guard_recorded_at: str | None, guard_turn_instance_id: str | None, + runs: list[dict[str, Any]] | None = None, ) -> None: """Copy the original refresh event order onto matching ACK candidates. @@ -328,9 +371,10 @@ def attach_historical_ack_writeback_order( recorded_at=str(guard_recorded_at or "").strip(), ) for candidate in candidates: + turn_instance_id = _binding_text(candidate.get("turn_instance_id")) evidence_index = _original_writeback_event_index( - events, goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id, - turn_instance_id=str(candidate.get("turn_instance_id") or "").strip(), + events, runs, goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id, + turn_instance_id=turn_instance_id, ) if evidence_index is None: continue @@ -345,26 +389,49 @@ def attach_historical_ack_writeback_order( ) +def historical_ack_candidates_with_writeback_order( + newest_first_runs: list[dict[str, Any]] | None, *, + goal_id: str, agent_id: str, obligation_id: str | None, + guard_scoped: bool = True, runtime_root: Path | str | None = None, + source_route: Any = None, + guard_recorded_at: str | None = None, guard_turn_instance_id: str | None = None, +) -> list[dict[str, Any]]: + """Project obligation candidates and attach their original writeback order.""" + from ...rollout_event_log import load_rollout_events, rollout_event_log_path + + selected = _binding_text(obligation_id) if guard_scoped else "" + candidates = autonomous_replan_ack_candidates_for_obligation( + newest_first_runs, goal_id=goal_id, agent_id=agent_id, obligation_id=selected or None) + route = source_route if isinstance(source_route, dict) else {} + root_text = runtime_root or route.get("runtime_root") + root = Path(str(root_text)) if root_text else None + if root is None or not selected: + return candidates + attach_historical_ack_writeback_order( + candidates, load_rollout_events(rollout_event_log_path(root, goal_id)), + goal_id=goal_id, agent_id=agent_id, obligation_id=selected, + guard_recorded_at=guard_recorded_at, guard_turn_instance_id=guard_turn_instance_id, + runs=newest_first_runs, + ) + return candidates + + def load_receipt_replan_ack_candidates( runtime_root: Path, *, goal_id: str, agent_id: str, obligation_id: str, guard_recorded_at: str | None = None, guard_turn_instance_id: str | None = None, ) -> list[dict[str, Any]]: """Read exact recovery candidates without widening ordinary status history.""" from ...history import load_index - from ...rollout_event_log import load_rollout_events, rollout_event_log_path from ..runtime.time import chronology_key runs, _ = load_index(runtime_root / "goals" / goal_id / "runs" / "index.jsonl") newest_first = [run for _, run in sorted(enumerate(runs), key=lambda item: (*chronology_key(item[1].get("generated_at")), item[0]), reverse=True)] - candidates = autonomous_replan_ack_candidates_for_obligation(newest_first, - goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id) - attach_historical_ack_writeback_order( - candidates, load_rollout_events(rollout_event_log_path(runtime_root, goal_id)), - goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id, - guard_recorded_at=guard_recorded_at, guard_turn_instance_id=guard_turn_instance_id, + return historical_ack_candidates_with_writeback_order( + newest_first, goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id, + runtime_root=runtime_root, guard_recorded_at=guard_recorded_at, + guard_turn_instance_id=guard_turn_instance_id, ) - return candidates def latest_blocked_successor_frontier_identity( diff --git a/loopx/control_plane/work_items/semantic_replan_writeback.py b/loopx/control_plane/work_items/semantic_replan_writeback.py index ccdaa3886c..22eee62fda 100644 --- a/loopx/control_plane/work_items/semantic_replan_writeback.py +++ b/loopx/control_plane/work_items/semantic_replan_writeback.py @@ -24,8 +24,7 @@ ) from ..todos.succession_warning import todo_succession_gap_items from .autonomous_replan_ack import ( - attach_historical_ack_writeback_order, - autonomous_replan_ack_candidates_for_obligation, + historical_ack_candidates_with_writeback_order, latest_monitor_replan_frontier_identity, watch_lane_continuation_todo_ids, ) @@ -295,24 +294,13 @@ def qualify_replan_writeback( ] } } - historical_ack_candidates = autonomous_replan_ack_candidates_for_obligation( + status_payload["receipt_bound_replan_ack_candidates"] = historical_ack_candidates_with_writeback_order( newest_first_runs, goal_id=goal_id, agent_id=safe_agent_id, - obligation_id=guard_semantic_replan_obligation_id if guard_scoped else None) - runtime_root_text = str((replan_source_route or {}).get("runtime_root") or "").strip() - if runtime_root_text and guard_scoped and guard_semantic_replan_obligation_id: - from pathlib import Path - - from ...rollout_event_log import load_rollout_events, rollout_event_log_path - - attach_historical_ack_writeback_order( - historical_ack_candidates, - load_rollout_events(rollout_event_log_path(Path(runtime_root_text), goal_id)), - goal_id=goal_id, agent_id=safe_agent_id, - obligation_id=guard_semantic_replan_obligation_id, - guard_recorded_at=receipt_bound_guard_recorded_at, - guard_turn_instance_id=receipt_bound_guard_turn_instance_id, - ) - status_payload["receipt_bound_replan_ack_candidates"] = historical_ack_candidates + obligation_id=guard_semantic_replan_obligation_id, guard_scoped=guard_scoped, + source_route=replan_source_route, + guard_recorded_at=receipt_bound_guard_recorded_at, + guard_turn_instance_id=receipt_bound_guard_turn_instance_id, + ) if capability_evidence is not None: status_payload["bounded_research_frontier"] = capability_evidence.frontier context = build_goal_frontier_projection_context_from_status( diff --git a/tests/control_plane/test_autonomous_replan_ack.py b/tests/control_plane/test_autonomous_replan_ack.py index 0c5b73e542..0ee197e279 100644 --- a/tests/control_plane/test_autonomous_replan_ack.py +++ b/tests/control_plane/test_autonomous_replan_ack.py @@ -328,34 +328,41 @@ def test_long_chain_trigger_checkpoint_survives_ack_compaction() -> None: ] -def test_same_second_candidate_keeps_only_the_bound_original_writeback_order() -> None: +def test_same_second_candidate_keeps_the_todo_bound_writeback_order() -> None: turn = "guided-start:later" + run = { + "goal_id": GOAL_ID, "agent_id": AGENT_ID, "turn_instance_id": turn, + "todo_id": "todo-original", + "settlement_identity": {"todo_id": "todo-original", "effect_id": "effect-later"}, + "autonomous_replan_ack": {"semantic_delta": {"obligation_id": LONG_CHAIN_OBLIGATION_ID}}, + } admission = {"event_kind": "quota_should_run", "goal_id": GOAL_ID, "agent_id": AGENT_ID, "run_id": "guided-start:original", "recorded_at": "2026-08-01T00:00:01.500000Z"} - early = {"event_kind": "refresh_state", "goal_id": GOAL_ID, "agent_id": AGENT_ID, + # A Todo-bound refresh leaves the obligation field empty. The semantic + # delta and the Todo receipt identify the writeback. + todo_event = {"event_kind": "refresh_state", "goal_id": GOAL_ID, "agent_id": AGENT_ID, + "run_id": turn, "todo_id": "todo-original", "recorded_at": "2026-08-01T00:00:01.900000Z", + "details": {"autonomous_replan_recorded": True, "replan_obligation_id": None, + "settlement_effect_id": "effect-later"}} + other_obligation = {"event_kind": "refresh_state", "goal_id": GOAL_ID, "agent_id": AGENT_ID, "run_id": turn, "recorded_at": "2026-08-01T00:00:01.100000Z", "details": { - "autonomous_replan_recorded": True, "replan_obligation_id": LONG_CHAIN_OBLIGATION_ID}} - other_goal = {"event_kind": "refresh_state", "goal_id": "other-goal", "agent_id": AGENT_ID, - "run_id": turn, "recorded_at": "2026-08-01T00:00:01.900000Z", "details": { - "autonomous_replan_recorded": True, "replan_obligation_id": LONG_CHAIN_OBLIGATION_ID}} - before = {"turn_instance_id": turn, "generated_at": "2026-08-01T00:00:01Z"} + "autonomous_replan_recorded": True, "replan_obligation_id": "replan-ffffffffffffffff"}} + candidate = {"turn_instance_id": turn, "generated_at": "2026-08-01T00:00:01Z"} attach_historical_ack_writeback_order( - [before], [early, other_goal, admission], goal_id=GOAL_ID, agent_id=AGENT_ID, + [candidate], [other_obligation, admission, todo_event], goal_id=GOAL_ID, agent_id=AGENT_ID, obligation_id=LONG_CHAIN_OBLIGATION_ID, - guard_recorded_at="2026-08-01T00:00:01.500000Z", - guard_turn_instance_id="guided-start:original", + guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original", + runs=[run], ) - assert before["writeback_recorded_at"] == "2026-08-01T00:00:01.100000Z" - assert before["writeback_follows_admission"] is False - assert before["writeback_goal_id"] == GOAL_ID - assert before["writeback_turn_instance_id"] == turn - assert before["writeback_obligation_id"] == LONG_CHAIN_OBLIGATION_ID - after = {"turn_instance_id": turn} + assert candidate["writeback_recorded_at"] == "2026-08-01T00:00:01.900000Z" + assert candidate["writeback_follows_admission"] is True + assert candidate["writeback_obligation_id"] == LONG_CHAIN_OBLIGATION_ID + mismatched = {"turn_instance_id": turn} + mismatched_event = {**todo_event, "details": {**todo_event["details"], "settlement_effect_id": "effect-other"}} attach_historical_ack_writeback_order( - [after], [admission, early], goal_id=GOAL_ID, agent_id=AGENT_ID, + [mismatched], [admission, mismatched_event], goal_id=GOAL_ID, agent_id=AGENT_ID, obligation_id=LONG_CHAIN_OBLIGATION_ID, - guard_recorded_at="2026-08-01T00:00:01.500000Z", - guard_turn_instance_id="guided-start:original", + guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original", + runs=[run], ) - assert after["writeback_recorded_at"] == "2026-08-01T00:00:01.100000Z" - assert after["writeback_follows_admission"] is True + assert "writeback_recorded_at" not in mismatched diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py index 67e2b65c9f..1cebb5c3bd 100644 --- a/tests/control_plane/test_quota_settlement_cli.py +++ b/tests/control_plane/test_quota_settlement_cli.py @@ -9074,40 +9074,63 @@ def test_same_second_historical_ack_requires_writeback_after_admission( recorded_at = admitted["heartbeat_receipt"]["recorded_at"] recorded = datetime.fromisoformat(recorded_at.replace("Z", "+00:00")) later_turn = "later-accepted-same-second" - time_after = order in {"after", "time_after_log_before"} - written = recorded + timedelta(microseconds=1 if time_after else -1) - written_at = written.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") - event = build_rollout_event( - goal_id=GOAL_ID, event_kind="refresh_state", agent_id=AGENT_ID, run_id=later_turn, - status="appended", summary="accepted same-second historical review", - recorded_at=written_at, details={ - "command": "refresh-state", "autonomous_replan_recorded": True, - "replan_obligation_id": obligation, + later_admitted = _bind_selected_replan_guard(registry, runtime, project, later_turn) + assert later_admitted["replan_action_packet"]["obligation_id"] == obligation + vision = project / "vision.json" + vision.write_text(json.dumps({ + "schema_version": "goal_vision_replan_contract_v0", + "state": "vision_patch_proposed", + "vision_patch": {"acceptance_summary": "Verified fixture artifact; original work remains open."}, + "todo_delta": [f"retain:{SELECTED_REPLAN_TODO_ID}"], + "path_delta": { + "outcome": "replan", + "prior_assumption": "Fixture work needs a verified next route.", + "observed_reality": "A fixture check supports continuing the existing work.", + "retained": ["Original requirements and the existing Todo."], + "evidence_refs": ["evidence:fixture-check"], }, + }), encoding="utf-8") + rc, refreshed = _run_cli( + registry, runtime, "refresh-state", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, + "--todo-id", SELECTED_REPLAN_TODO_ID, "--turn-instance-id", later_turn, + "--classification", "bounded_replan_progress", "--delivery-batch-scale", "single_surface", + "--delivery-outcome", "outcome_progress", "--delivery-workspace-path", str(project), + "--delivery-boundary", "semantic_closeout", "--agent-vision-json", str(vision), + "--autonomous-replan-recorded", "--repair-delta-kind", "goal_vision_patch", + "--no-global-sync", "--suppress-external-sinks", ) + assert rc == 0 and refreshed["appended"] is True, refreshed + assert refreshed["autonomous_replan_ack"]["semantic_delta"]["obligation_id"] == obligation + same_second = recorded.replace(microsecond=0).astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + index_path = runtime / "goals" / GOAL_ID / "runs" / "index.jsonl" + rows = [json.loads(line) for line in index_path.read_text(encoding="utf-8").splitlines() if line.strip()] + matched_runs = [row for row in rows if row.get("turn_instance_id") == later_turn] + assert matched_runs + for row in matched_runs: + row["generated_at"] = same_second + source = Path(row["json_path"]) + payload = json.loads(source.read_text(encoding="utf-8")) + payload["generated_at"] = same_second + source.write_text(json.dumps(payload), encoding="utf-8") + index_path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8") + time_after = order in {"after", "time_after_log_before"} + written_at = (recorded + timedelta(microseconds=1 if time_after else -1)).astimezone( + timezone.utc).isoformat().replace("+00:00", "Z") log_path = runtime / "goals" / GOAL_ID / "rollout-event-log.jsonl" events = [json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines() if line.strip()] + event = next(item for item in events + if item.get("event_kind") == "refresh_state" and item.get("run_id") == later_turn) + assert not str((event.get("details") or {}).get("replan_obligation_id") or "").strip() + assert event["details"]["autonomous_replan_recorded"] is True + assert event.get("todo_id") == SELECTED_REPLAN_TODO_ID + events.remove(event) + event["recorded_at"] = written_at admission_index = next(index for index, item in enumerate(events) if item.get("event_kind") == "quota_should_run" and item.get("run_id") == original_turn and item.get("recorded_at") == recorded_at) log_after = order in {"after", "time_before_log_after"} events.insert(len(events) if log_after else admission_index, event) log_path.write_text("".join(json.dumps(item) + "\n" for item in events), encoding="utf-8") - runs_dir = runtime / "goals" / GOAL_ID / "runs" - runs_dir.mkdir(parents=True, exist_ok=True) - run = {"goal_id": GOAL_ID, "agent_id": AGENT_ID, "turn_instance_id": later_turn, - "generated_at": recorded.replace(microsecond=0).astimezone(timezone.utc).isoformat().replace("+00:00", "Z"), - "classification": "bounded_replan_progress", - "autonomous_replan_ack": {"schema_version": "autonomous_replan_ack_v0", "recorded": True, - "source": "refresh_state", "semantic_delta": {"schema_version": "replan_semantic_delta_v0", - "accepted": True, "obligation_id": obligation, - "outcomes": ["fresh_vision_path_outcome"], "satisfying_outcomes": ["fresh_vision_path_outcome"]}}} - source = runs_dir / "later-accepted-same-second.json" - source.write_text(json.dumps(run), encoding="utf-8") - markdown = source.with_suffix(".md") - markdown.write_text("# Accepted same-second historical review\n", encoding="utf-8") - with (runs_dir / "index.jsonl").open("a", encoding="utf-8") as stream: - stream.write(json.dumps({**run, "json_path": str(source), "markdown_path": str(markdown)}) + "\n") guard_args = ("quota", "should-run", "--codex-app", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--turn-instance-id", original_turn, "--todo-id", SELECTED_REPLAN_TODO_ID) From d2b7ece8f9415f2046028a615e6894aaa27d0be8 Mon Sep 17 00:00:00 2001 From: Duang777 Date: Sun, 15 Nov 2026 21:58:03 +0000 Subject: [PATCH 4/4] fix(replan): require a positive writeback identity for same-second ACKs A historical index can omit the Todo and effect. An empty comparison then accepted a same-second refresh for a different Todo. Bind only when the event obligation equals the accepted semantic delta, or its Todo and effect equal the ACK receipt. Fill a missing index identity from that turn's heartbeat receipt. An event with no identity stays pending. Signed-off-by: Duang777 --- .../work_items/autonomous_replan_ack.py | 82 +++++++++++++------ .../test_autonomous_replan_ack.py | 35 ++++++++ .../test_quota_settlement_cli.py | 27 +++++- 3 files changed, 117 insertions(+), 27 deletions(-) diff --git a/loopx/control_plane/work_items/autonomous_replan_ack.py b/loopx/control_plane/work_items/autonomous_replan_ack.py index fcf4280735..a9a8ecb81f 100644 --- a/loopx/control_plane/work_items/autonomous_replan_ack.py +++ b/loopx/control_plane/work_items/autonomous_replan_ack.py @@ -308,26 +308,69 @@ def _source_run( return {} -def _todo_receipt_matches(event: dict[str, Any], run: dict[str, Any]) -> bool: - """A Todo-bound refresh stores the obligation on the semantic delta. - - The rollout event leaves replan_obligation_id empty and carries the Todo - settlement receipt. Historical events may omit that receipt too. A present - identity on both sides must still be the same receipt. +def _expected_todo_receipt( + run: dict[str, Any], events: list[dict[str, Any]], *, + goal_id: str, agent_id: str, turn_instance_id: str, +) -> tuple[str, str]: + """Todo settlement identity for this ACK, filled from its heartbeat receipt. + + A historical index can omit the Todo and effect. The turn's existing + quota receipt still has that exact identity. An empty side is not a match. """ - details = _event_details(event) identity = run.get("settlement_identity") identity = identity if isinstance(identity, dict) else {} - event_effect = _binding_text(details.get("settlement_effect_id")) - run_effect = _binding_text(identity.get("effect_id")) - if event_effect and run_effect and event_effect != run_effect: + todo = _binding_text(run.get("todo_id") or identity.get("todo_id")) + effect = _binding_text(identity.get("effect_id")) + if todo and effect: + return todo, effect + for event in events: + if ( + event.get("event_kind") != "quota_should_run" + or event.get("goal_id") != goal_id + or event.get("agent_id") != agent_id + or _binding_text(event.get("run_id")) != turn_instance_id + ): + continue + details = _event_details(event) + todo = todo or _binding_text(event.get("todo_id") or details.get("todo_id")) + effect = effect or _binding_text(details.get("settlement_effect_id")) + return todo, effect + + +def _writeback_event_is_bound( + event: dict[str, Any], run: dict[str, Any], events: list[dict[str, Any]], *, + goal_id: str, agent_id: str, obligation_id: str, turn_instance_id: str, +) -> bool: + """Require one positive identity shared with the accepted ACK. + + The event obligation must equal the semantic delta, or its Todo and effect + must equal the ACK receipt. Missing fields do not count as agreement. + """ + + if ( + event.get("event_kind") != "refresh_state" + or event.get("goal_id") != goal_id + or event.get("agent_id") != agent_id + or _binding_text(event.get("run_id")) != turn_instance_id + ): return False + details = _event_details(event) + if details.get("autonomous_replan_recorded") is not True: + return False + event_obligation = _binding_text(details.get("replan_obligation_id")) + if event_obligation: + return event_obligation == obligation_id event_todo = _binding_text(event.get("todo_id")) - run_todo = _binding_text(run.get("todo_id") or identity.get("todo_id")) - if event_todo and run_todo and event_todo != run_todo: + event_effect = _binding_text(details.get("settlement_effect_id")) + if not event_todo or not event_effect: return False - return True + expected_todo, expected_effect = _expected_todo_receipt( + run, events, goal_id=goal_id, agent_id=agent_id, turn_instance_id=turn_instance_id) + return bool( + expected_todo and expected_effect + and event_todo == expected_todo and event_effect == expected_effect + ) def _original_writeback_event_index( @@ -338,16 +381,9 @@ def _original_writeback_event_index( return None run = _source_run(runs, turn_instance_id=turn_instance_id, obligation_id=obligation_id) for index, event in enumerate(events): - details = _event_details(event) - event_obligation = _binding_text(details.get("replan_obligation_id")) - if ( - event.get("event_kind") == "refresh_state" - and event.get("goal_id") == goal_id - and event.get("agent_id") == agent_id - and _binding_text(event.get("run_id")) == turn_instance_id - and details.get("autonomous_replan_recorded") is True - and (not event_obligation or event_obligation == obligation_id) - and _todo_receipt_matches(event, run) + if _writeback_event_is_bound( + event, run, events, goal_id=goal_id, agent_id=agent_id, + obligation_id=obligation_id, turn_instance_id=turn_instance_id, ): return index return None diff --git a/tests/control_plane/test_autonomous_replan_ack.py b/tests/control_plane/test_autonomous_replan_ack.py index 0ee197e279..70b0594896 100644 --- a/tests/control_plane/test_autonomous_replan_ack.py +++ b/tests/control_plane/test_autonomous_replan_ack.py @@ -366,3 +366,38 @@ def test_same_second_candidate_keeps_the_todo_bound_writeback_order() -> None: runs=[run], ) assert "writeback_recorded_at" not in mismatched + sparse_run = { + "goal_id": GOAL_ID, "agent_id": AGENT_ID, "turn_instance_id": turn, + "autonomous_replan_ack": {"semantic_delta": {"obligation_id": LONG_CHAIN_OBLIGATION_ID}}, + } + later_receipt = {"event_kind": "quota_should_run", "goal_id": GOAL_ID, "agent_id": AGENT_ID, + "run_id": turn, "todo_id": "todo-original", "recorded_at": "2026-08-01T00:00:01.200000Z", + "details": {"settlement_effect_id": "effect-later", "todo_id": "todo-original"}} + filled = {"turn_instance_id": turn} + attach_historical_ack_writeback_order( + [filled], [admission, later_receipt, todo_event], goal_id=GOAL_ID, agent_id=AGENT_ID, + obligation_id=LONG_CHAIN_OBLIGATION_ID, + guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original", + runs=[sparse_run], + ) + assert filled["writeback_recorded_at"] == todo_event["recorded_at"] + foreign = {"turn_instance_id": turn} + foreign_event = {**todo_event, "todo_id": "todo-other", + "details": {**todo_event["details"], "settlement_effect_id": "effect-other"}} + attach_historical_ack_writeback_order( + [foreign], [admission, later_receipt, foreign_event], goal_id=GOAL_ID, agent_id=AGENT_ID, + obligation_id=LONG_CHAIN_OBLIGATION_ID, + guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original", + runs=[sparse_run], + ) + assert "writeback_recorded_at" not in foreign + blank = {"turn_instance_id": turn} + blank_event = {**todo_event, "todo_id": "", "details": { + "autonomous_replan_recorded": True, "replan_obligation_id": None, "settlement_effect_id": None}} + attach_historical_ack_writeback_order( + [blank], [admission, later_receipt, blank_event], goal_id=GOAL_ID, agent_id=AGENT_ID, + obligation_id=LONG_CHAIN_OBLIGATION_ID, + guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original", + runs=[sparse_run], + ) + assert "writeback_recorded_at" not in blank diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py index 1cebb5c3bd..6bb924e7c4 100644 --- a/tests/control_plane/test_quota_settlement_cli.py +++ b/tests/control_plane/test_quota_settlement_cli.py @@ -9060,7 +9060,10 @@ def test_exact_later_ack_executes_original_todo_settlement_commands( @pytest.mark.parametrize("provider", ["file", "sqlite"]) -@pytest.mark.parametrize("order", ["after", "before", "time_after_log_before", "time_before_log_after"]) +@pytest.mark.parametrize("order", [ + "after", "before", "time_after_log_before", "time_before_log_after", + "receipt_fill", "foreign_todo", "blank_identity", +]) def test_same_second_historical_ack_requires_writeback_after_admission( tmp_path: Path, provider: str, order: str, ) -> None: @@ -9106,14 +9109,21 @@ def test_same_second_historical_ack_requires_writeback_after_admission( rows = [json.loads(line) for line in index_path.read_text(encoding="utf-8").splitlines() if line.strip()] matched_runs = [row for row in rows if row.get("turn_instance_id") == later_turn] assert matched_runs + sparse_index = order in {"receipt_fill", "foreign_todo", "blank_identity"} for row in matched_runs: row["generated_at"] = same_second source = Path(row["json_path"]) payload = json.loads(source.read_text(encoding="utf-8")) payload["generated_at"] = same_second + if sparse_index: + for record in (row, payload): + record.pop("todo_id", None) + record.pop("settlement_identity", None) source.write_text(json.dumps(payload), encoding="utf-8") index_path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8") - time_after = order in {"after", "time_after_log_before"} + time_after = order in { + "after", "time_after_log_before", "receipt_fill", "foreign_todo", "blank_identity", + } written_at = (recorded + timedelta(microseconds=1 if time_after else -1)).astimezone( timezone.utc).isoformat().replace("+00:00", "Z") log_path = runtime / "goals" / GOAL_ID / "rollout-event-log.jsonl" @@ -9125,10 +9135,19 @@ def test_same_second_historical_ack_requires_writeback_after_admission( assert event.get("todo_id") == SELECTED_REPLAN_TODO_ID events.remove(event) event["recorded_at"] = written_at + if order == "foreign_todo": + event["todo_id"] = "todo_other_binding" + event["details"]["settlement_effect_id"] = "effect-other" + if order == "blank_identity": + event.pop("todo_id", None) + event["details"]["settlement_effect_id"] = None + event["details"]["replan_obligation_id"] = None admission_index = next(index for index, item in enumerate(events) if item.get("event_kind") == "quota_should_run" and item.get("run_id") == original_turn and item.get("recorded_at") == recorded_at) - log_after = order in {"after", "time_before_log_after"} + log_after = order in { + "after", "time_before_log_after", "receipt_fill", "foreign_todo", "blank_identity", + } events.insert(len(events) if log_after else admission_index, event) log_path.write_text("".join(json.dumps(item) + "\n" for item in events), encoding="utf-8") guard_args = ("quota", "should-run", "--codex-app", "--goal-id", GOAL_ID, @@ -9136,7 +9155,7 @@ def test_same_second_historical_ack_requires_writeback_after_admission( "--todo-id", SELECTED_REPLAN_TODO_ID) rc, recovery = _run_cli(registry, runtime, *guard_args) decision = (recovery.get("replan_action_packet") or {}).get("decision") - if order != "after": + if order not in {"after", "receipt_fill"}: assert decision != "historical_ack_recorded", { "rc": rc, "decision": decision, "error": recovery.get("error"), "error_code": recovery.get("error_code"),