Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions loopx/control_plane/quota/heartbeat_receipt_identity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,34 @@ export function selectEffectiveHeartbeatReceipt<Value>(
: entries.at(-1)!.value;
}

/**
* The first bound receipt for one Turn, used only as the admission clock.
*
* `selectEffectiveHeartbeatReceipt` still returns the latest bound receipt so
* review and work content stay current. A later same-Turn upgrade must not
* move the historical-ACK admission time or log position. Callers pass the
* GoalRef-filtered receipt list; this reduction does not widen that scope.
* Conflicting bindings fail closed, the same way the effective reduction does.
*/
export function selectAdmissionHeartbeatReceipt<Value>(
goalId: string,
agentId: string,
entries: readonly { fact: HeartbeatReceiptFact; value: Value }[],
): Value | null {
const identities = new Map<string, Value>();
for (const entry of entries) {
const binding = heartbeatReceiptBinding(goalId, agentId, entry.fact);
if (!binding || identities.has(binding.identity_key)) continue;
identities.set(binding.identity_key, entry.value);
}
if (identities.size > 1) {
throw receiptIdentityConflict(
"heartbeat receipt has conflicting settlement identities for the same goal, agent, and turn",
);
}
return identities.size === 1 ? [...identities.values()][0]! : null;
}

/** Reentry can qualify work on the original binding, never replace its authority.
* The caller commits this append-only projection under the receipt-log lock. */
export function heartbeatWorkRequalification(
Expand Down
10 changes: 8 additions & 2 deletions loopx/control_plane/quota/live_decision.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,16 @@ def _receipt_bound_guard_fields(
obligation_id and isinstance(guard, Mapping) and guard.get("scope") == "turn_guard"
and guard.get("selected_obligation_id") == obligation_id
)
# The effective receipt stays the latest content. The admission clock is the
# first bound receipt already selected by the GoalRef-filtered readback.
admission_recorded_at = getattr(readback, "admission_recorded_at", None)
return {
"receipt_bound_replan_guard_scoped": guard_scoped,
"receipt_bound_replan_execution_pending": bool(
guard_scoped and readback and readback.replan_execution_pending
),
"receipt_bound_guard_recorded_at": receipt.get("recorded_at"),
"receipt_bound_guard_recorded_at": admission_recorded_at or receipt.get("recorded_at"),
"receipt_bound_admission_event_id": getattr(readback, "admission_event_id", None),
"receipt_bound_guard_turn_instance_id": identity.turn_instance_id if identity is not None else None,
"receipt_bound_replan_review": guard.get("selected_review_source") if isinstance(guard, Mapping) else None,
"receipt_bound_successor_replan": bool(getattr(readback, "successor_replan_pending", False)),
Expand Down Expand Up @@ -786,6 +790,7 @@ def build_live_quota_should_run_decision(
receipt_bound_guard_fields = _receipt_bound_guard_fields(
settlement_readback, receipt_bound_replan_obligation_id,
)
admission_event_id = receipt_bound_guard_fields.pop("receipt_bound_admission_event_id")
if (
receipt_bound_guard_fields["receipt_bound_replan_guard_scoped"]
and receipt_bound_replay_phase is ReceiptBoundReplayPhase.OPEN
Expand All @@ -797,7 +802,8 @@ def build_live_quota_should_run_decision(
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"])
guard_turn_instance_id=receipt_bound_guard_fields["receipt_bound_guard_turn_instance_id"],
admission_event_id=admission_event_id)
fresh_operator_inbox_read = _fresh_operator_inbox_read_required(
turn_start_hook_dispatch
)
Expand Down
12 changes: 12 additions & 0 deletions loopx/control_plane/quota/settlement.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ class QuotaSettlementReadback:
heartbeat_reentry_qualification: dict[str, Any] | None = None
successor_replan_pending: bool = False
replan_execution_pending: bool = False
admission_recorded_at: str | None = None
admission_event_id: str | None = None


def render_owed_host_command(argv: list[str]) -> str:
Expand Down Expand Up @@ -315,6 +317,14 @@ def _optional_readback_record(value: Any) -> dict[str, Any] | None:
return dict(value)


def _optional_readback_text(value: Any) -> str | None:
if value is None:
return None
if not isinstance(value, str) or not value.strip():
raise RuntimeError("TypeScript quota settlement readback result shape mismatch")
return value


def _semantic_replan_guard(value: Any) -> dict[str, Any] | None:
guard = _optional_readback_record(value)
if guard is None:
Expand Down Expand Up @@ -564,4 +574,6 @@ def read_heartbeat_settlement(
if replay_phase is not None
else None
),
admission_recorded_at=_optional_readback_text(payload.get("admission_recorded_at")),
admission_event_id=_optional_readback_text(payload.get("admission_event_id")),
)
24 changes: 24 additions & 0 deletions loopx/control_plane/quota/settlement_readback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ import {
normalizeHeartbeatReplanObligationId as normalizeReplanObligationId,
normalizeHeartbeatTodoId as normalizeTodoId,
optionalHeartbeatString as optionalString,
selectAdmissionHeartbeatReceipt,
selectEffectiveHeartbeatReceipt,
heartbeatWorkRequalification,
type HeartbeatReceiptFact,
Expand Down Expand Up @@ -744,6 +745,24 @@ function effectiveHeartbeatReceipt(
: selectEffectiveHeartbeatReceipt(identity.goal_id, identity.agent_id, entries);
}

/** First bound receipt in the same already filtered Turn list. */
function admissionHeartbeatReceipt(
events: readonly JsonObject[],
identity: Pick<SettlementIdentity, "goal_id" | "agent_id" | "turn_instance_id">,
): JsonObject | null {
const entries: { fact: HeartbeatReceiptFact; value: JsonObject }[] = [];
for (const event of events) {
if (event.event_kind !== "quota_should_run") continue;
if (optionalString(event.goal_id) !== identity.goal_id) continue;
if (optionalString(event.agent_id) !== identity.agent_id) continue;
if (optionalString(event.run_id) !== identity.turn_instance_id) continue;
entries.push({ fact: heartbeatReceiptFactFromEvent(event), value: event });
}
return entries.length === 0
? null
: selectAdmissionHeartbeatReceipt(identity.goal_id, identity.agent_id, entries);
}

function writebackResult(
identity: SettlementIdentity,
run: JsonObject | null,
Expand Down Expand Up @@ -1376,6 +1395,7 @@ function readQuotaSettlementFromRequest(
quotaOwnerOwnsProjection(request.owner, run.goal_ref)
);
const heartbeatReceipt = effectiveHeartbeatReceipt(events, identity);
const admissionReceipt = admissionHeartbeatReceipt(events, identity);
if (heartbeatReceipt === null) {
return failedReadback(
failedIdentity(
Expand Down Expand Up @@ -1533,6 +1553,10 @@ function readQuotaSettlementFromRequest(
),
spend_run: includeRecords ? spendRun : null,
heartbeat_receipt: includeRecords ? heartbeatReceipt : null,
admission_recorded_at: typeof admissionReceipt?.recorded_at === "string"
&& admissionReceipt.recorded_at.trim() ? admissionReceipt.recorded_at : null,
admission_event_id: typeof admissionReceipt?.event_id === "string"
&& admissionReceipt.event_id.trim() ? admissionReceipt.event_id : null,
writeback_event: includeRecords ? writebackEvent : null,
spend_event: includeRecords ? spendEvent : null,
completion_event: includeRecords ? completionEvent : null,
Expand Down
36 changes: 30 additions & 6 deletions loopx/control_plane/work_items/autonomous_replan_ack.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,11 +274,30 @@ def _event_details(event: dict[str, Any]) -> dict[str, Any]:

def _admission_event_index(
events: list[dict[str, Any]], *, goal_id: str, agent_id: str,
turn_instance_id: str, recorded_at: str,
turn_instance_id: str, recorded_at: str, event_id: str | None = None,
) -> int | None:
if not turn_instance_id or not recorded_at:
"""Log position of the Turn's original bound admission.

The settlement readback names that event after GoalRef filtering. Matching
the id keeps a retired Goal instance that reused this Turn id out of the
order. Callers without an id use the first row with the admission time.
"""

if not turn_instance_id:
return None
if event_id:
for index, event in enumerate(events):
if (
event.get("event_id") == event_id
and 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
):
return index
return None
if not recorded_at:
return None
found: int | None = None
for index, event in enumerate(events):
if (
event.get("event_kind") == "quota_should_run"
Expand All @@ -287,8 +306,8 @@ def _admission_event_index(
and event.get("run_id") == turn_instance_id
and event.get("recorded_at") == recorded_at
):
found = index
return found
return index
return None


def _binding_text(value: Any) -> str:
Expand Down Expand Up @@ -406,6 +425,7 @@ def attach_historical_ack_writeback_order(
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,
admission_event_id: str | None = None,
) -> None:
"""Copy the original refresh event order onto matching ACK candidates.

Expand All @@ -417,6 +437,7 @@ def attach_historical_ack_writeback_order(
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(),
event_id=str(admission_event_id or "").strip() or None,
)
for candidate in candidates:
turn_instance_id = _binding_text(candidate.get("turn_instance_id"))
Expand All @@ -443,6 +464,7 @@ def historical_ack_candidates_with_writeback_order(
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,
admission_event_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
Expand All @@ -459,14 +481,15 @@ def historical_ack_candidates_with_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,
runs=newest_first_runs, admission_event_id=admission_event_id,
)
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,
admission_event_id: str | None = None,
) -> list[dict[str, Any]]:
"""Read exact recovery candidates without widening ordinary status history."""
from ...history import load_index
Expand All @@ -479,6 +502,7 @@ def load_receipt_replan_ack_candidates(
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,
admission_event_id=admission_event_id,
)


Expand Down
6 changes: 6 additions & 0 deletions loopx/control_plane/work_items/semantic_replan_writeback.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ def qualify_replan_writeback(
receipt_bound_guard_recorded_at: str | None = None,
receipt_bound_guard_turn_instance_id: str | None = None,
receipt_bound_replan_review: Mapping[str, Any] | None = None,
admission_event_id: str | None = None,
replan_source_route: Mapping[str, Any] | None = None,
replan_explore_reader: Callable[[str, str | None], Mapping[str, Any] | None] | None = None,
) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
Expand Down Expand Up @@ -300,6 +301,7 @@ def qualify_replan_writeback(
source_route=replan_source_route,
guard_recorded_at=receipt_bound_guard_recorded_at,
guard_turn_instance_id=receipt_bound_guard_turn_instance_id,
admission_event_id=admission_event_id,
)
if capability_evidence is not None:
status_payload["bounded_research_frontier"] = capability_evidence.frontier
Expand Down Expand Up @@ -456,6 +458,7 @@ def enforce_open_replan_writeback(
receipt_bound_guard_recorded_at: str | None = None,
receipt_bound_guard_turn_instance_id: str | None = None,
receipt_bound_replan_review: Mapping[str, Any] | None = None,
admission_event_id: str | None = None,
todo_fields: dict[str, Any] | None = None,
external_progress_review: Mapping[str, Any] | None = None,
capability_evidence: CapabilityReplanEvidence | None = None,
Expand Down Expand Up @@ -493,6 +496,7 @@ def enforce_open_replan_writeback(
receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at,
receipt_bound_guard_turn_instance_id=receipt_bound_guard_turn_instance_id,
receipt_bound_replan_review=receipt_bound_replan_review,
admission_event_id=admission_event_id,
replan_source_route=replan_source_route, replan_explore_reader=replan_explore_reader,
)
if not obligation:
Expand Down Expand Up @@ -542,6 +546,7 @@ def qualify_refresh_replan_writeback(
receipt_bound_guard_recorded_at: str | None = None,
receipt_bound_guard_turn_instance_id: str | None = None,
receipt_bound_replan_review: Mapping[str, Any] | None = None,
admission_event_id: str | None = None,
newest_first_runs: list[dict[str, Any]],
state_text: str,
goal_id: str,
Expand Down Expand Up @@ -629,6 +634,7 @@ def qualify_refresh_replan_writeback(
receipt_bound_guard_recorded_at=receipt_bound_guard_recorded_at,
receipt_bound_guard_turn_instance_id=receipt_bound_guard_turn_instance_id,
receipt_bound_replan_review=receipt_bound_replan_review,
admission_event_id=admission_event_id,
replan_source_route=replan_source_route, replan_explore_reader=replan_explore_reader,
)
if semantic_delta:
Expand Down
10 changes: 9 additions & 1 deletion loopx/state_refresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -1155,7 +1155,15 @@ def read_explore_context(read_goal_id: str, read_agent_id: str | None):
settlement_guard_scoped=(
settlement_replan_guard.get("scope") == "turn_guard"
),
receipt_bound_guard_recorded_at=(settlement_readback.heartbeat_receipt or {}).get("recorded_at") if settlement_readback else None,
receipt_bound_guard_recorded_at=(
settlement_readback.admission_recorded_at
if settlement_readback is not None and settlement_readback.admission_recorded_at
else (settlement_readback.heartbeat_receipt or {}).get("recorded_at")
if settlement_readback else None
),
admission_event_id=(
settlement_readback.admission_event_id if settlement_readback is not None else None
),
receipt_bound_guard_turn_instance_id=(settlement_identity.turn_instance_id if settlement_identity else None),
receipt_bound_replan_review=settlement_replan_guard.get("selected_review_source"),
settlement_guard_semantic_replan_obligation_id=(
Expand Down
60 changes: 60 additions & 0 deletions tests/control_plane/test_autonomous_replan_ack.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,3 +401,63 @@ def test_same_second_candidate_keeps_the_todo_bound_writeback_order() -> None:
runs=[sparse_run],
)
assert "writeback_recorded_at" not in blank


def test_same_turn_receipt_upgrade_keeps_writeback_after_original_admission() -> None:
"""A later same-Turn upgrade must not become the admission log index.

The compact ACK stamp is the admission second. Its refresh writeback is
after the original quota_should_run and before the upgrade. Passing the
upgrade's recorded_at, which is what the latest receipt exposes, still
has to order that writeback after the first bound receipt.
"""

turn = "guided-start:later"
guard_turn = "guided-start:original"
binding = {
"replan_obligation_id": LONG_CHAIN_OBLIGATION_ID,
"settlement_effect_id": "effect-original",
}
retired = {
"event_kind": "quota_should_run", "event_id": "evt-retired",
"goal_id": GOAL_ID, "agent_id": AGENT_ID, "run_id": guard_turn,
"recorded_at": "2026-07-01T00:00:00.000000Z",
"goal_ref": {
"goal_id": GOAL_ID,
"goal_instance_id": "ginst_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
},
"details": {
"replan_obligation_id": "replan-ffffffffffffffff",
"settlement_effect_id": "effect-retired",
},
}
admission = {
"event_kind": "quota_should_run", "event_id": "evt-admission",
"goal_id": GOAL_ID, "agent_id": AGENT_ID, "run_id": guard_turn,
"recorded_at": "2026-08-01T00:00:01.500000Z", "details": binding,
}
upgrade = {
"event_kind": "quota_should_run", "event_id": "evt-upgrade",
"goal_id": GOAL_ID, "agent_id": AGENT_ID, "run_id": guard_turn,
"recorded_at": "2026-08-01T00:00:05.000000Z",
"causality": {"source_event_id": "evt-admission", "caused_by": "evt-admission"},
"details": {**binding, "settlement_receipt_revision": "work_admission"},
}
todo_event = {
"event_kind": "refresh_state", "goal_id": GOAL_ID, "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,
},
}
candidate = {"turn_instance_id": turn, "generated_at": "2026-08-01T00:00:01Z"}
attach_historical_ack_writeback_order(
[candidate], [retired, admission, todo_event, upgrade],
goal_id=GOAL_ID, agent_id=AGENT_ID, obligation_id=LONG_CHAIN_OBLIGATION_ID,
guard_recorded_at=upgrade["recorded_at"], guard_turn_instance_id=guard_turn,
admission_event_id=admission["event_id"],
)
assert candidate["writeback_recorded_at"] == todo_event["recorded_at"]
assert candidate["writeback_follows_admission"] is True
assert candidate["writeback_obligation_id"] == LONG_CHAIN_OBLIGATION_ID
12 changes: 12 additions & 0 deletions tests/control_plane/test_effect_turn_live_quota_decision.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ def test_receipt_guard_fields_use_the_typed_identity_and_guard(
assert fields["receipt_bound_replan_execution_pending"] is expected_pending
assert fields["receipt_bound_guard_turn_instance_id"] == "original-turn"
assert fields["receipt_bound_guard_recorded_at"] == "2026-08-01T00:00:00Z"
assert fields["receipt_bound_admission_event_id"] is None
upgraded = _receipt_bound_guard_fields(SimpleNamespace(
semantic_replan_guard={"scope": "turn_guard", "selected_obligation_id": selected},
identity=SimpleNamespace(value=SimpleNamespace(turn_instance_id="original-turn")),
heartbeat_receipt={"recorded_at": "2026-08-01T02:00:00Z"},
admission_recorded_at="2026-08-01T00:00:00Z",
admission_event_id="evt-admission",
successor_replan_pending=False,
replan_execution_pending=execution_pending,
), obligation)
assert upgraded["receipt_bound_guard_recorded_at"] == "2026-08-01T00:00:00Z"
assert upgraded["receipt_bound_admission_event_id"] == "evt-admission"


@pytest.mark.parametrize("binding", ["todo", "autonomous_replan", "unbound"])
Expand Down
Loading
Loading