From 6c8eb35f0bdb291382efc72b81aff38aeab0ff49 Mon Sep 17 00:00:00 2001 From: huangruiteng <14976749+huangruiteng@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:34:21 +0800 Subject: [PATCH] fix(quota): resume unfinished turns with fenced lease takeover Signed-off-by: huangruiteng <14976749+huangruiteng@users.noreply.github.com> --- docs/reference/protocols/turn-envelope-v0.md | 28 +++++ .../quota/execution_loss_closeout.ts | 7 +- .../quota/execution_preparation.py | 4 +- .../control_plane/quota/heartbeat_receipt.py | 52 ++++++++- .../quota/heartbeat_receipt_identity.ts | 88 ++++++++++++++- .../quota/settlement_readback.ts | 11 +- loopx/control_plane/todos/read_transaction.ts | 10 +- .../test_execution_loss_closeout_cli.py | 103 +++++------------- .../test_heartbeat_lease_takeover.py | 91 ++++++++++++++++ .../native_child_admission.test.ts | 61 ++++++++++- 10 files changed, 363 insertions(+), 92 deletions(-) create mode 100644 tests/control_plane/test_heartbeat_lease_takeover.py diff --git a/docs/reference/protocols/turn-envelope-v0.md b/docs/reference/protocols/turn-envelope-v0.md index c63dcd48d2..0d6aed3642 100644 --- a/docs/reference/protocols/turn-envelope-v0.md +++ b/docs/reference/protocols/turn-envelope-v0.md @@ -378,6 +378,34 @@ the original admission's lease proof after a renewal in that same generation. The submitted version must be between the admitted and current versions, inclusive, and the lease must still match the original admission. Ordinary refresh without the option still requires the current proof. + +An unfinished prepared Turn can also resume after lease expiry through the +ordinary managed claim and its original `quota should-run`. For local File and +SQLite authority, a fresh eligible guard checks the same Agent's current lease +under the canonical maintenance fence and appends a `lease_takeover` receipt. +The original admission, workspace obligation, quota source and settlement effect +stay unchanged. The append records both generations and current Todo/acceptance +digests; it does not accept an old result. The current holder reads current +requirements, dependencies and artifact revisions, reuses only still-valid +evidence and runs affected validation before completion or writeback. Stale keys, +competing holders, unavailable authority and stopped work remain fenced. Existing +writeback/spend effects are recovered exactly once; takeover cannot reopen a +closeout that has started. Explicit administrative no-spend closeout remains +available when no business result can be recovered. + +中文:未交账的原轮次在租约过期后,可通过普通领取和原 `quota should-run` 接续。 +本地 File/SQLite 权威源在维护锁下核验同一 Agent 的当前有效租约,追加 +`lease_takeover` 回执,保留原准入、工作区义务、额度来源与结算身份,并记录两代 +租约及当前任务、验收摘要。接管不代表旧成果自动通过:当前持有人核对需求、依赖和 +产物版本,只复用仍有效的证据,完成受影响检查后交账。旧 key、其他持有人、权威源 +不可用和停止状态继续受到保护;已开始的交账只能恢复欠缺步骤,不能重开或重复扣账。 +没有可复用业务成果时,仍可显式执行不扣账的中断关闭。 + +This requires no saved automation prompt migration and adds no user confirmation. +It does not attach Codex App to a background lease-renewal timer: automatic +renewal remains scoped to the existing supervised live-host process. +中文:该流程不需要迁移已有自动化提示词,也不增加用户确认。它没有为 Codex App +增加后台续租计时器;自动续租仍限于现有可信宿主进程监督路径。 When `--delivery-workspace-path` names the producing worktree, the combined operation also runs the owed command there, using the originating CLI's implementation. The normal workspace and settlement guards still apply; a diff --git a/loopx/control_plane/quota/execution_loss_closeout.ts b/loopx/control_plane/quota/execution_loss_closeout.ts index 7db48ec55d..4300bb2c23 100644 --- a/loopx/control_plane/quota/execution_loss_closeout.ts +++ b/loopx/control_plane/quota/execution_loss_closeout.ts @@ -172,10 +172,13 @@ export async function observeFencedExecution(root: string, identity: ReturnType< const writerMatches = todo.claimed_by === identity.agent_id && lease.owner === identity.agent_id && todo.done !== true && leaseRepositoryRejection(todo, lease) === null && canonicalLeaseTodoFact(todo)?.excluded_agents.includes(identity.agent_id) === false; - const active = writerMatches && leaseIsActive(lease, now); + // Same-owner recovery can re-enter the original guard. That path records a + // fenced takeover before any new validation/writeback; this observation alone + // never admits work or accepts a result. Competing ownership still holds. + if (writerMatches) return null; return {original_prepared_epoch: prepared.prepared_lease_epoch, current_lease_epoch: lease.lease_epoch, current_lease_version: lease.version, current_owner: lease.owner, - current_control_writer_active: active, can_reclaim_control_writer: writerMatches && !active}; + current_control_writer_active: false, can_reclaim_control_writer: false}; } function optionalAssignedReplan(receipt: JsonObject): boolean { diff --git a/loopx/control_plane/quota/execution_preparation.py b/loopx/control_plane/quota/execution_preparation.py index d3156749ce..a9b98ea174 100644 --- a/loopx/control_plane/quota/execution_preparation.py +++ b/loopx/control_plane/quota/execution_preparation.py @@ -70,14 +70,14 @@ def project_selected_todo_execution_preparation( def _read_execution_snapshot( - runtime_root: str | Path, goal_id: str, todo_id: str, + runtime_root: str | Path, goal_id: str, todo_id: str, *, include_takeover_basis: bool = False, ) -> dict[str, Any] | None: response = effect_runtime_result( "todo.read", {"schema_version": "todo_read_request_v0", "kind": "execution_preparation_source", "source": {"runtime_root": str(Path(runtime_root).expanduser().resolve(strict=False)), "goal_id": goal_id}, - "todo_id": todo_id}, + "todo_id": todo_id, **({"include_takeover_basis": True} if include_takeover_basis else {})}, timeout=LOCAL_COORDINATION_TODO_LIST_TIMEOUT_SECONDS, ) snapshot = ( diff --git a/loopx/control_plane/quota/heartbeat_receipt.py b/loopx/control_plane/quota/heartbeat_receipt.py index 14fa1798ec..a6c97c8227 100644 --- a/loopx/control_plane/quota/heartbeat_receipt.py +++ b/loopx/control_plane/quota/heartbeat_receipt.py @@ -1,7 +1,8 @@ from __future__ import annotations import json -from collections.abc import Callable, Mapping +from collections.abc import Callable, Mapping, Sequence +from contextlib import ExitStack from functools import lru_cache from pathlib import Path @@ -85,7 +86,7 @@ def _heartbeat_receipt_events( ] -def heartbeat_receipt_request_subject(event: Mapping[str, object] | None) -> dict | None: +def heartbeat_receipt_request_subject(event: Mapping[str, object] | None) -> dict[str, object] | None: """Transport the original request's path-free identity from scalar event details.""" details = (event or {}).get("details") if not isinstance(details, Mapping) or "request_id" not in details: @@ -119,7 +120,7 @@ def _receipt_selection( def _select_receipt_facts( - events: list[Mapping[str, object]], + events: Sequence[Mapping[str, object]], ) -> tuple[int | None, tuple[SettlementBindingKind, str, str] | None]: # Keep unknown details in the reader. Only the shared identity owner's raw # fields enter this pure projection/cache; no receipt or source is cached. @@ -767,15 +768,42 @@ def requalify_bound_heartbeat_receipt( from .settlement import read_heartbeat_settlement log_path = rollout_event_log_path(runtime_root, goal_id) - with exclusive_cross_runtime_file_lock(log_path, operation="requalify_heartbeat_work"): + with ExitStack() as locks: + locks.enter_context(exclusive_cross_runtime_file_lock(log_path, operation="requalify_heartbeat_work")) original, _ = _effective_heartbeat_receipt(_heartbeat_receipt_events( load_rollout_events(log_path), goal_id=goal_id, agent_id=agent_id, turn_instance_id=turn_instance_id, goal_ref=goal_ref, )) + original_details_value = original.get("details") if original else None + original_details = original_details_value if isinstance(original_details_value, Mapping) else {} + # Snapshot only the changed-generation path. The TS receipt owner alone + # decides eligibility. A nonblocking maintenance fence avoids reversing + # the ordinary maintenance -> receipt lock order while keeping the source + # unchanged through the append below. + guard_details = dict(details) + guard_details.pop("lease_takeover_source", None) + if (todo_id and original_details.get("prepared_lease_key_sha256") + and details.get("prepared_lease_key_sha256") + and (original_details.get("prepared_lease_key_sha256") != details.get("prepared_lease_key_sha256") + or original_details.get("prepared_lease_epoch") != details.get("prepared_lease_epoch"))): + from ..coordination.shadow_management import ( + require_shadow_primary_write_allowed, shadow_maintenance_lock_target, + ) + from ..runtime.time import now_local_iso + from .execution_preparation import _read_execution_snapshot + + locks.enter_context(exclusive_cross_runtime_file_lock( + shadow_maintenance_lock_target(runtime_root, goal_id), timeout_seconds=0, + operation="requalify_heartbeat_work", + )) + require_shadow_primary_write_allowed(runtime_root, goal_id) + snapshot = _read_execution_snapshot(runtime_root, goal_id, todo_id, include_takeover_basis=True) + if snapshot is not None: + guard_details["lease_takeover_source"] = {**snapshot, "observed_at": now_local_iso(timespec="microseconds")} readback = read_heartbeat_settlement( runtime_root, goal_id=goal_id, agent_id=agent_id, todo_id=todo_id, turn_instance_id=turn_instance_id, replan_obligation_id=replan_obligation_id, - registry_path=registry_path, goal_ref=goal_ref, heartbeat_reentry_guard=details, + registry_path=registry_path, goal_ref=goal_ref, heartbeat_reentry_guard=guard_details, ) if original is None or readback is None or readback.identity.value is None: raise ValueError("work requalification requires the original admitted settlement identity") @@ -796,11 +824,12 @@ def requalify_bound_heartbeat_receipt( summary = { "review_guard_upgrade": "same-Turn review guard upgraded without rebinding", "lease_readiness": "same-Turn lease readiness recorded without readmission", + "lease_takeover": "current holder resumed the original Turn; validate saved results against current requirements", }.get(receipt_revision, "same-Turn work admission requalified without rebinding") corrected = build_rollout_event( goal_id=goal_id, goal_ref=goal_ref, event_kind="quota_should_run", agent_id=agent_id, todo_id=todo_id, run_id=turn_instance_id, - status=str(original.get("status") or status) if receipt_revision == "lease_readiness" else status, + status=str(original.get("status") or status) if receipt_revision in {"lease_readiness", "lease_takeover"} else status, summary=summary, source_event_id=event_id, caused_by=event_id, details=dict(qualified_details), ) @@ -828,6 +857,17 @@ def heartbeat_receipt_view( } if details.get("closeout_required") is True: receipt["closeout_required"] = True + if details.get("takeover_original_event_id"): + receipt["lease_takeover"] = { + "original_receipt_event_id": details["takeover_original_event_id"], + "original_lease_epoch": details.get("takeover_original_epoch"), + "current_lease_epoch": details.get("prepared_lease_epoch"), + "evidence_policy": ( + "Current ownership resumed the original Turn, not acceptance of old results. " + "Read current requirements, dependencies and artifact revisions; reuse only evidence " + "that remains valid, run affected validation, then settle this original identity once." + ), + } todo_id = str(details.get("todo_id") or "").strip() replan_obligation_id = normalize_todo_replan_obligation_id( details.get("replan_obligation_id") diff --git a/loopx/control_plane/quota/heartbeat_receipt_identity.ts b/loopx/control_plane/quota/heartbeat_receipt_identity.ts index d08e40b0de..73d2a8bdee 100644 --- a/loopx/control_plane/quota/heartbeat_receipt_identity.ts +++ b/loopx/control_plane/quota/heartbeat_receipt_identity.ts @@ -16,6 +16,11 @@ import { BARE_SHA256_PATTERN } from "../content_digest.ts"; import { jsonObject, requireJsonObject } from "../runtime_decode.ts"; import {nativeChildReportAdmission} from "../capabilities/native_child_admission.ts"; import type {ReceiptBoundReplayPhase} from "./settlement_phase.ts"; +import {createHash} from "node:crypto"; +import {isDeepStrictEqual} from "node:util"; +import {canonicalAuthoritySha256} from "../coordination/authority_store_codec.ts"; +import {leaseRepositoryRejection} from "../work_items/task_lease_repository.ts"; +import {parseTodoTimestampMicros} from "../runtime_timestamp.ts"; const TODO_ID_PATTERN = /^todo_[a-z0-9_-]{3,64}$/; const REPLAN_OBLIGATION_ID_PATTERN = /^replan-[a-f0-9]{16}$/; @@ -302,6 +307,87 @@ export function isHeartbeatLeaseReadiness(event: JsonObject): boolean { return heartbeatReceiptDetails(event).settlement_receipt_revision === "lease_readiness"; } +/** A fresh guard and fenced canonical snapshot qualify a new writer, not old + * test results. The original admission stays reachable through receipt lineage. */ +function heartbeatLeaseTakeover(original: JsonObject, current: JsonObject, + identity: SettlementIdentity, previous: HeartbeatPreparedLease, + prepared: HeartbeatPreparedLease | null): JsonObject { + const reject = (): never => {throw receiptIdentityConflict( + "work requalification must preserve this Turn's original task lease generation unless a fenced current holder qualifies takeover");}; + const source = jsonObject(current.lease_takeover_source); + const basis = jsonObject(source?.takeover_basis), todo = jsonObject(basis?.todo); + const leases = source?.leases; + const lease = Array.isArray(leases) && leases.length === 1 ? jsonObject(leases[0]) : null; + const old = heartbeatReceiptDetails(original); + if (!source || !basis || !todo || !lease || !prepared || + typeof original.event_id !== "string" || !original.event_id || + previous.prepared_lease_epoch === undefined || prepared.prepared_lease_epoch === undefined || + source.goal_id !== identity.goal_id || source.todo_id !== identity.todo_id || + source.handoff_mode !== "hard_lease" || !["file_v0", "sqlite_v0"].includes(String(source.source_authority)) || + source.decision_read_from_provider !== true || source.legacy_fallback_used !== false || + typeof source.provider_revision !== "string" || !source.provider_revision || + typeof basis.acceptance_sha256 !== "string" || !BARE_SHA256_PATTERN.test(basis.acceptance_sha256) || + todo.todo_id !== identity.todo_id || todo.role !== "agent" || todo.task_class !== "advancement_task" || + todo.status !== "open" || todo.done === true || todo.archive_state !== "active" || + todo.claimed_by !== identity.agent_id || + (Array.isArray(todo.excluded_agents) && todo.excluded_agents.includes(identity.agent_id)) || + lease.todo_id !== identity.todo_id || lease.owner !== identity.agent_id || lease.status !== "active" || + leaseRepositoryRejection(todo, lease) !== null || + typeof lease.idempotency_key !== "string" || !lease.idempotency_key || + lease.version !== prepared.prepared_lease_version || lease.lease_epoch !== prepared.prepared_lease_epoch || + prepared.prepared_lease_version <= previous.prepared_lease_version || + prepared.prepared_lease_epoch <= previous.prepared_lease_epoch || + prepared.prepared_lease_key_sha256 === previous.prepared_lease_key_sha256 || + createHash("sha256").update(lease.idempotency_key).digest("hex") !== prepared.prepared_lease_key_sha256 || + heartbeatPreparedWorkAdmission(original, identity) === null || + normalizeHeartbeatReplanObligationId(old.semantic_replan_obligation_id) !== null || + normalizeHeartbeatReplanObligationId(current.semantic_replan_obligation_id) !== null) return reject(); + const clock = (value: unknown): bigint | null => typeof value === "string" ? parseTodoTimestampMicros(value, true) : null; + const at = clock(source.observed_at), admitted = clock(original.recorded_at), + acquired = clock(lease.acquired_at), updated = clock(lease.updated_at), expires = clock(lease.expires_at); + if (at === null || admitted === null || acquired === null || updated === null || expires === null || + admitted > acquired || acquired > updated || updated > at || expires <= at) return reject(); + return {append: true, details: {...old, ...prepared, settlement_receipt_revision: "lease_takeover", + takeover_original_event_id: original.event_id, + takeover_original_key_sha256: previous.prepared_lease_key_sha256, + takeover_original_version: previous.prepared_lease_version, + takeover_original_epoch: previous.prepared_lease_epoch, + takeover_owner: identity.agent_id, takeover_observed_at: source.observed_at, + takeover_expires_at: lease.expires_at, takeover_provider_revision: source.provider_revision, + takeover_todo_sha256: canonicalAuthoritySha256(todo), takeover_acceptance_sha256: basis.acceptance_sha256}}; +} + +/** Reject broken or rewritten takeover lineage during cold settlement reads. */ +export function validateHeartbeatTakeoverParent(event: JsonObject, parent: JsonObject, + identity: SettlementIdentity): void { + const details = heartbeatReceiptDetails(event); + if (details.settlement_receipt_revision !== "lease_takeover") return; + const old = heartbeatPreparedWorkAdmission(parent, identity), current = heartbeatPreparedLease(details); + const fields = {takeover_original_event_id: details.takeover_original_event_id, + takeover_original_key_sha256: details.takeover_original_key_sha256, + takeover_original_version: details.takeover_original_version, takeover_original_epoch: details.takeover_original_epoch, + takeover_owner: details.takeover_owner, takeover_observed_at: details.takeover_observed_at, + takeover_expires_at: details.takeover_expires_at, takeover_provider_revision: details.takeover_provider_revision, + takeover_todo_sha256: details.takeover_todo_sha256, takeover_acceptance_sha256: details.takeover_acceptance_sha256}; + const time = (value: unknown): bigint | null => typeof value === "string" ? parseTodoTimestampMicros(value, true) : null; + const at = time(details.takeover_observed_at), expires = time(details.takeover_expires_at), recorded = time(event.recorded_at); + if (!old || !current || old.prepared_lease_epoch === undefined || + current.prepared_lease_epoch === undefined || current.prepared_lease_epoch <= old.prepared_lease_epoch || + current.prepared_lease_version <= old.prepared_lease_version || + current.prepared_lease_key_sha256 === old.prepared_lease_key_sha256 || + details.takeover_original_event_id !== parent.event_id || details.takeover_owner !== identity.agent_id || + details.takeover_original_key_sha256 !== old.prepared_lease_key_sha256 || + details.takeover_original_version !== old.prepared_lease_version || + details.takeover_original_epoch !== old.prepared_lease_epoch || + !isDeepStrictEqual(details, {...heartbeatReceiptDetails(parent), ...current, + settlement_receipt_revision: "lease_takeover", ...fields}) || + ![details.takeover_todo_sha256, details.takeover_acceptance_sha256].every(value => typeof value === "string" && BARE_SHA256_PATTERN.test(value)) || + typeof details.takeover_provider_revision !== "string" || !details.takeover_provider_revision || + at === null || expires === null || recorded === null || expires <= at || recorded < at) { + throw receiptIdentityConflict("lease takeover does not preserve original admission and verified current ownership"); + } +} + /** 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( @@ -338,7 +424,7 @@ export function heartbeatWorkRequalification( (previous.prepared_lease_epoch === undefined ? preparedLease.prepared_lease_version !== previous.prepared_lease_version : preparedLease.prepared_lease_epoch !== previous.prepared_lease_epoch))) { - throw receiptIdentityConflict("work requalification must preserve this Turn's original task lease generation"); + return heartbeatLeaseTakeover(original, currentDetails, identity, previous, preparedLease); } if (nativeChildReportAdmission(oldDetails, original.status, identity.effect_id, phase, false, originalReplan) .report_permission === "new_operation") { diff --git a/loopx/control_plane/quota/settlement_readback.ts b/loopx/control_plane/quota/settlement_readback.ts index 64347eb04c..0e30ead5c5 100644 --- a/loopx/control_plane/quota/settlement_readback.ts +++ b/loopx/control_plane/quota/settlement_readback.ts @@ -66,6 +66,7 @@ import { selectAdmissionHeartbeatReceipt, selectEffectiveHeartbeatReceipt, heartbeatWorkRequalification, + validateHeartbeatTakeoverParent, heartbeatPreparedLease, heartbeatPreparedWorkAdmission, isHeartbeatLeaseReadiness, @@ -704,7 +705,9 @@ function heartbeatValidationEvent( receipt: JsonObject, identity: SettlementIdentity, ): JsonObject | null { - if (!isHeartbeatLeaseReadiness(receipt)) return receipt; + const continuation = (event: JsonObject): boolean => isHeartbeatLeaseReadiness(event) + || details(event).settlement_receipt_revision === "lease_takeover"; + if (!continuation(receipt)) return receipt; // Readiness appends to the same Turn; only its original positive work // admission can serve as validation. Follow durable links toward that root. let validation = receipt; @@ -719,7 +722,8 @@ function heartbeatValidationEvent( event.goal_id !== identity.goal_id || event.agent_id !== identity.agent_id || fact.run_id !== identity.turn_instance_id || fact.todo_id !== identity.todo_id || !effectIdsMatch(fact.settlement_effect_id, identity.effect_id)) return null; - if (!isHeartbeatLeaseReadiness(event)) return event; + validateHeartbeatTakeoverParent(validation, event, identity); + if (!continuation(event)) return event; validation = event; } return null; @@ -1375,6 +1379,9 @@ function readQuotaSettlementFromRequest( ); } const receiptDetails = details(heartbeatReceipt); + if (receiptDetails.takeover_original_event_id !== undefined && heartbeatValidationEvent(events, heartbeatReceipt, identity) === null) { + throw new EffectRuntimeRequestError("lease takeover original admission is unavailable", "malformed_settlement_state"); + } const preparedLease = heartbeatPreparedLease(receiptDetails); if (Object.hasOwn(receiptDetails, "prepared_lease_required") && receiptDetails.prepared_lease_required !== true) { throw new EffectRuntimeRequestError("Turn readiness requirement is malformed", "malformed_settlement_state"); diff --git a/loopx/control_plane/todos/read_transaction.ts b/loopx/control_plane/todos/read_transaction.ts index 365a9e09ee..2983163edd 100644 --- a/loopx/control_plane/todos/read_transaction.ts +++ b/loopx/control_plane/todos/read_transaction.ts @@ -389,6 +389,8 @@ const originalRecords = (value: unknown): JsonObject[] => Array.isArray(value) ? * Reuse full collection validation; only the fields used by preparation cross * the caller boundary. This read acquires no lease and grants no readiness. */ export async function readExecutionPreparationSource(input: JsonObject, dependencies: LocalAuthorityProviderDependencies = {}): Promise { + const takeover = input.include_takeover_basis === undefined ? false + : requireBoolean(input.include_takeover_basis, "include_takeover_basis"); const source = requireJsonObject(input.source, "execution preparation source"); const goalId = requireNonEmptyString(source.goal_id, "goal_id"); const todoId = id(input.todo_id); @@ -401,14 +403,18 @@ export async function readExecutionPreparationSource(input: JsonObject, dependen const todo = originalRecords(canonical.todos).find(row => row.todo_id === todoId); if (!todo) return unavailable; const leases = originalRecords(canonical.leases).filter(row => row.todo_id === todoId) - .map(({todo_id, schema_version, status, owner, expires_at, idempotency_key, version, lease_epoch}) => - ({todo_id, schema_version, status, owner, expires_at, idempotency_key, version, lease_epoch})); + .map(({todo_id, schema_version, status, owner, acquired_at, updated_at, expires_at, + idempotency_key, version, lease_epoch, write_repository}) => + ({todo_id, schema_version, status, owner, expires_at, idempotency_key, version, lease_epoch, + ...(takeover ? {acquired_at, updated_at, write_repository} : {})})); return {schema_version: TODO_READ_RESULT, execution_preparation_source: { goal_id: goalId, todo_id: todoId, handoff_mode: canonical.handoff_mode, source_authority: canonical.source_authority, provider_revision: canonical.provider_revision, decision_read_from_provider: canonical.decision_read_from_provider, legacy_fallback_used: canonical.legacy_fallback_used, todo: {todo_id: todoId, status: todo.status, claimed_by: todo.claimed_by}, leases, + ...(takeover ? {takeover_basis: {todo, + acceptance_sha256: canonicalAuthoritySha256(canonical.goal_acceptance_contract ?? null)}} : {}), }}; } diff --git a/tests/control_plane/test_execution_loss_closeout_cli.py b/tests/control_plane/test_execution_loss_closeout_cli.py index 3b22d249a5..407242f149 100644 --- a/tests/control_plane/test_execution_loss_closeout_cli.py +++ b/tests/control_plane/test_execution_loss_closeout_cli.py @@ -227,6 +227,7 @@ def cli(*argv): code, pending = cli(*_guard_args(context)) assert code == 0 and pending["execution_preparation"]["state"] == "claim_required", pending claim = _claim(context, OWNER, "execution-loss-original-claim") + context["current_claim"] = claim original_lease = _lease(context) context["original_lease"] = original_lease if prepared: @@ -258,8 +259,10 @@ def now(cls, tz=None): # Registered transport clock seams, never edits to persisted lease bytes. monkeypatch.setattr(runtime_time, "datetime", AfterExpiryDatetime) monkeypatch.setattr(task_lease, "now_utc", lambda: after_expiry.astimezone(timezone.utc)) + monkeypatch.setattr(rollout_event_log, "_now_iso", lambda: runtime_time.now_local_iso(timespec="microseconds")) assert runtime_time.now_utc() == after_expiry.astimezone(timezone.utc) replacement = _claim(context, replacement_owner, "execution-loss-replacement-claim") + context["current_claim"] = replacement assert replacement["claim_operation_id"] != claim["claim_operation_id"] current = _lease(context) assert current["owner"] == replacement_owner @@ -497,38 +500,8 @@ def test_closeout_preserves_the_original_turn_and_releases_the_next_guard( _assert_original_prepared_generation(context, original) assert not original.writeback.receipts and not original.spend.receipts argv = _closeout_args(context) - if not source_profile: - before_replay = _unchanged_state(context) - replay_args = _guard_args(context) - selection = replay_args.index("--todo-id") - del replay_args[selection:selection + 2] - - code, same_turn = context["cli"](*replay_args) - assert code == 0, same_turn - assert same_turn["normal_delivery_allowed"] is False - assert same_turn["interaction_contract"]["cli_channel"]["spend_allowed_now"] is False - debt = same_turn["unsettled_host_turn_recovery"] - assert debt["prior_turn_instance_id"] == TURN - assert debt["repair"] == "execution_loss_closeout" - assert _unchanged_state(context) == before_replay - - # A fresh host Turn can also discover the outstanding original debt. - route = str(tmp_path / "fixture launcher" / "loopx") - code, recovery = context["cli"]( - "--cli-bin", route, "quota", "should-run", "--context-delivery", "off", "--codex-app", - "--goal-id", context["goal_id"], "--agent-id", OWNER, "--turn-instance-id", "needs-recovery", - ) - assert code == 0, recovery - debt = recovery["unsettled_host_turn_recovery"] - assert debt["repair"] == "execution_loss_closeout" - assert debt["prior_turn_instance_id"] == TURN - assert debt["execution_loss"]["original_prepared_epoch"] == context["original_lease"]["lease_epoch"] - assert debt["execution_loss"]["current_lease_epoch"] == context["current_lease"]["lease_epoch"] - assert recovery["execution_obligation"]["delivery_allowed"] is False - cli_channel = recovery["interaction_contract"]["cli_channel"] - assert cli_channel["spend_allowed_now"] is False - argv = _projected_preview_args(cli_channel, context["current_lease"])[:-1] - assert argv[:2] == ["--cli-bin", route] + # Administrative no-spend closeout stays explicit. A same-owner guard now + # resumes work through a fenced takeover instead of discarding its result. before = _unchanged_state(context) code, preview = context["cli"](*argv, "--dry-run") assert code == 0 and preview["would_close_without_spend"] is True, preview @@ -727,66 +700,50 @@ def test_recovery_guides_self_claim_only_for_the_retained_assignee( ) assert code == 0, recovery debt = recovery["unsettled_host_turn_recovery"] - assert debt["repair"] == "execution_loss_closeout" - assert debt["reason_code"] == "execution_loss_control_writer_required" - assert "execution_preparation" not in recovery - assert recovery["interaction_contract"]["agent_channel"]["must_attempt"] is False - assert recovery["execution_obligation"]["delivery_allowed"] is False - cli_channel = recovery["interaction_contract"]["cli_channel"] - assert cli_channel["spend_allowed_now"] is False - claim_commands = [command for command in cli_channel["next_cli_actions"] if "todo claim" in command] if owner == PEER: - assert not claim_commands + assert debt["repair"] == "execution_loss_closeout" + assert debt["reason_code"] == "execution_loss_control_writer_required" + assert recovery["interaction_contract"]["agent_channel"]["must_attempt"] is False + commands = recovery["interaction_contract"]["cli_channel"]["next_cli_actions"] + assert not any("todo claim" in command for command in commands) _assert_no_completion_or_debit(context) return - - [claim_command] = claim_commands + assert debt["repair"] == "resume_prior_turn" + assert recovery["interaction_contract"]["agent_channel"]["must_attempt"] is True + code, prepare = context["cli"](*_guard_args(context)) + assert code == 0 and prepare["execution_preparation"]["state"] == "claim_required", prepare + claim_command = prepare["execution_preparation"]["claim"]["command_line"] tokens = shlex.split(claim_command) code, claimed = context["cli"](*tokens[tokens.index("todo"):]) assert code == 0, claimed current = _lease(context) assert current["owner"] == OWNER and current["lease_epoch"] > lease["lease_epoch"] - argv = _projected_preview_args(cli_channel, current) - code, preview = context["cli"](*argv) - assert code == 0 and preview["would_close_without_spend"] is True, preview - code, closed = context["cli"](*argv[:-1]) - assert code == 0 and closed["settlement_progress"]["no_spend"] is True, closed - assert closed["settlement_identity"] == _readback(context).identity.value.as_dict() - code, replay = context["cli"](*argv[:-1]) - assert code == 0 and replay["idempotent_replay"] is True and replay["appended"] is False, replay + code, resumed = context["cli"](*_guard_args(context)) + assert code == 0 and resumed["normal_delivery_allowed"], json.dumps(resumed) + assert _readback(context).prepared_lease["prepared_lease_epoch"] == current["lease_epoch"] _assert_no_completion_or_debit(context) @pytest.mark.parametrize("provider", ["file", "sqlite"]) -def test_original_turn_reentry_projects_execution_loss_without_repeating_work( +def test_original_turn_reentry_qualifies_takeover_without_repeating_work( tmp_path, monkeypatch, capsys, provider, ): context = _fixture(tmp_path, monkeypatch, capsys, provider, source_profile=False) before = _receipt_lines(context) - # Re-enter through the route a failed refresh returns and through the - # implicit receipt binding. Both must preserve the same original guard. base = ["quota", "should-run", "--runtime-profile", "generic_cli", "--context-delivery", "off", "--goal-id", context["goal_id"], "--agent-id", OWNER, "--turn-instance-id", TURN] for scope in (["--todo-id", context["todo"]], []): code, recovery = context["cli"](*base, *scope) - assert code == 0, (recovery.get("error_code"), recovery.get("reason")) - assert recovery["normal_delivery_allowed"] is False - assert recovery["unsettled_host_turn_recovery"]["prior_turn_instance_id"] == TURN - channel = recovery["interaction_contract"]["cli_channel"] - assert channel["spend_allowed_now"] is False - preview = _projected_preview_args(channel, context["current_lease"]) - code, result = context["cli"](*preview) - assert code == 0 and result["would_close_without_spend"], result - code, closed = context["cli"](*preview[:-1]) - assert code == 0 and closed["settlement_progress"]["no_spend"], closed - code, replay = context["cli"](*preview[:-1]) - assert code == 0 and replay["idempotent_replay"] and not replay["appended"], replay - assert _receipt_lines(context) == before + assert code == 0 and recovery["normal_delivery_allowed"], recovery + assert recovery["interaction_contract"]["cli_channel"]["spend_allowed_now"] is False + after = _receipt_lines(context) + assert after[:len(before)] == before and len(after) == len(before) + 1 + assert json.loads(after[-1])["details"]["settlement_receipt_revision"] == "lease_takeover" _assert_no_completion_or_debit(context) @pytest.mark.parametrize("provider", ["file", "sqlite"]) -def test_original_lease_loss_claims_only_for_closeout(tmp_path, monkeypatch, capsys, provider): +def test_original_lease_loss_claims_then_revalidates_current_work(tmp_path, monkeypatch, capsys, provider): context = _fixture(tmp_path, monkeypatch, capsys, provider, source_profile=False, replace=False) original = context["original_lease"] code, released = context["cli"]("task-lease", "release", "--goal-id", context["goal_id"], @@ -795,7 +752,7 @@ def test_original_lease_loss_claims_only_for_closeout(tmp_path, monkeypatch, cap assert code == 0, released code, recovery = context["cli"](*_guard_args(context)) assert code == 0, recovery - assert recovery.get("unsettled_host_turn_recovery", {}).get("repair") == "execution_loss_closeout" + assert recovery["execution_preparation"]["state"] == "claim_required" assert recovery["normal_delivery_allowed"] is False channel = recovery["interaction_contract"]["cli_channel"] claims = [shlex.split(command) for command in channel["next_cli_actions"] if "todo claim" in command] @@ -804,10 +761,6 @@ def test_original_lease_loss_claims_only_for_closeout(tmp_path, monkeypatch, cap assert code == 0, claimed code, ready = context["cli"](*_guard_args(context)) assert code == 0, ready - assert ready["normal_delivery_allowed"] is False - preview = _projected_preview_args(ready["interaction_contract"]["cli_channel"], _lease(context)) - code, result = context["cli"](*preview) - assert code == 0 and result["would_close_without_spend"], result - code, closed = context["cli"](*preview[:-1]) - assert code == 0 and closed["settlement_progress"]["no_spend"], closed + assert ready["normal_delivery_allowed"] is True + assert _readback(context).prepared_lease["prepared_lease_epoch"] == _lease(context)["lease_epoch"] _assert_no_completion_or_debit(context) diff --git a/tests/control_plane/test_heartbeat_lease_takeover.py b/tests/control_plane/test_heartbeat_lease_takeover.py new file mode 100644 index 0000000000..a5b142da62 --- /dev/null +++ b/tests/control_plane/test_heartbeat_lease_takeover.py @@ -0,0 +1,91 @@ +"""Current ownership may resume an unfinished Turn, without accepting stale work.""" +from __future__ import annotations + +import json +import shlex +import sys + +import pytest + +from tests.control_plane.test_execution_loss_closeout_cli import ( + OWNER, TURN, _canonical, _fixture, _guard_args, _readback, _receipt_lines, _spend_run_count, +) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("complete", [False, True], ids=["progress", "completion"]) +def test_current_holder_resumes_original_turn_and_settles_once(tmp_path, monkeypatch, capsys, provider, complete): + context = _fixture(tmp_path, monkeypatch, capsys, provider, source_profile=False) + cli = context["cli"] + original_lines = _receipt_lines(context) + code, decision = cli(*_guard_args(context)) + assert code == 0 and decision["normal_delivery_allowed"] is True, decision + readback = _readback(context) + assert readback.heartbeat_receipt["details"]["settlement_receipt_revision"] == "lease_takeover" + assert readback.prepared_lease["prepared_lease_epoch"] == context["current_lease"]["lease_epoch"] + assert _receipt_lines(context)[:len(original_lines)] == original_lines + assert _spend_run_count(context["runtime"]) == 0 + + if complete: + code, completed = cli("todo", "complete", "--goal-id", context["goal_id"], + "--agent-id", OWNER, "--todo-id", context["todo"], "--turn-instance-id", TURN, + "--claim-operation-id", context["current_claim"]["claim_operation_id"], + "--evidence", "evidence:current-validation") + assert code == 0 and completed["ok"], completed + assert (context["project"] / "completion-validator-ran").read_text() == "ran" + + plan = decision["interaction_contract"]["cli_channel"]["settlement_plan"] + writeback = next(step for step in plan["ordered_steps"] if step["kind"] == "durable_writeback") + vision = tmp_path / "vision.json" + vision.write_text(json.dumps({ + "schema_version": "goal_vision_replan_contract_v0", "state": "vision_patch_proposed", + "vision_patch": {"acceptance_summary": "Revalidate saved work under current ownership."}, + "path_delta": {"outcome": "continue", "prior_assumption": "Prior work needs current verification.", + "observed_reality": "The current holder verified the saved result.", + "retained": ["Original task"], "evidence_refs": ["evidence:revalidated-result"]}, + })) + tokens = shlex.split(writeback["semantic_closeout_command_template"]) + replacements = {"": "revalidated_result", "": "implementation", + "": "outcome_progress", "": str(vision)} + args = [replacements.get(token, token) for token in tokens[tokens.index("refresh-state"):]] + args += ["--no-global-sync", "--suppress-external-sinks"] + stale = args.copy() + key_index = next(i for i, value in enumerate(stale) if value.startswith("--task-lease-idempotency-key=")) + stale[key_index] = f"--task-lease-idempotency-key={context['original_lease']['idempotency_key']}" + stale[stale.index("--task-lease-expected-version") + 1] = str(context["original_lease"]["version"]) + code, rejected = cli(*stale) + assert code == 1 and rejected["appended"] is False, rejected + assert _spend_run_count(context["runtime"]) == 0 + code, result = cli(*args) + assert code == 0 and result["settlement_progress"]["state"] == "settled", result + assert result["settlement_identity"] == plan["identity"] + assert result["settlement_identity"]["turn_instance_id"] == TURN + assert _spend_run_count(context["runtime"]) == 1 + code, replay = cli(*args) + assert code == 0 and replay["idempotent_replay"], replay + assert _spend_run_count(context["runtime"]) == 1 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_takeover_uses_the_current_validator_and_does_not_inherit_old_acceptance(tmp_path, monkeypatch, capsys, provider): + context = _fixture(tmp_path, monkeypatch, capsys, provider, source_profile=False) + cli = context["cli"] + claim = context["current_claim"]["claim_operation_id"] + validation = [sys.executable, "-c", "from pathlib import Path; assert Path('current-artifact').read_text() == 'valid'"] + code, updated = cli("todo", "update", "--goal-id", context["goal_id"], "--todo-id", context["todo"], + "--agent-id", OWNER, "--claim-operation-id", claim, "--update-operation-id", "current-validator", + "--update-expected-provider-revision", _canonical(context)["provider_revision"], + "--validation-command-json", json.dumps(validation)) + assert code == 0 and updated["ok"], json.dumps(updated) + code, resumed = cli(*_guard_args(context)) + assert code == 0 and resumed["normal_delivery_allowed"], resumed + completion = ["todo", "complete", "--goal-id", context["goal_id"], "--agent-id", OWNER, + "--todo-id", context["todo"], "--turn-instance-id", TURN, "--claim-operation-id", claim, + "--evidence", "evidence:current-validator"] + code, rejected = cli(*completion) + assert code != 0 and rejected["ok"] is False, rejected + assert _spend_run_count(context["runtime"]) == 0 + (context["project"] / "current-artifact").write_text("valid") + code, completed = cli(*completion) + assert code == 0 and completed["ok"], completed + assert not (context["project"] / "completion-validator-ran").exists() diff --git a/tests/control_plane_ts/native_child_admission.test.ts b/tests/control_plane_ts/native_child_admission.test.ts index 2614b768a7..b8c6b600ce 100644 --- a/tests/control_plane_ts/native_child_admission.test.ts +++ b/tests/control_plane_ts/native_child_admission.test.ts @@ -3,11 +3,12 @@ import {appendFile, mkdir, mkdtemp, rm, writeFile} from "node:fs/promises"; import {tmpdir} from "node:os"; import {join} from "node:path"; import test from "node:test"; +import {createHash} from "node:crypto"; import {nativeChildReportAdmission} from "../../loopx/control_plane/capabilities/native_child_admission.ts"; -import {settlementIdentity, settlementIdentityPayload} from "../../loopx/control_plane/effect_program.ts"; +import {settlementIdentity, settlementIdentityPayload, type JsonObject} from "../../loopx/control_plane/effect_program.ts"; import {QUOTA_SETTLEMENT_READBACK_REQUEST_SCHEMA, readQuotaSettlement} from "../../loopx/control_plane/quota/settlement_readback.ts"; -import {heartbeatWorkRequalification, projectHeartbeatReceiptSelection} from "../../loopx/control_plane/quota/heartbeat_receipt_identity.ts"; +import {heartbeatWorkRequalification, projectHeartbeatReceiptSelection, validateHeartbeatTakeoverParent} from "../../loopx/control_plane/quota/heartbeat_receipt_identity.ts"; const proof = { ok: true, should_run: true, must_attempt_work: true, @@ -309,6 +310,62 @@ test("one prepared Turn admits only renewal of its original lease generation", a } finally {await rm(root, {recursive: true, force: true});} }); +test("fenced takeover preserves admission and rejects competing or stale source facts", async () => { + const {root, identity, event} = await fixture(); + try { + const original = {...event, recorded_at: "2026-01-01T00:00:00Z", details: {...event.details, + closeout_required: true, prepared_lease_required: true, prepared_lease_key_sha256: "a".repeat(64), + prepared_lease_version: 1, prepared_lease_epoch: 1}}; + const source = {goal_id: goalId, todo_id: todoId, handoff_mode: "hard_lease", + source_authority: "sqlite_v0", provider_revision: "sqlite:fixture:3", + decision_read_from_provider: true, legacy_fallback_used: false, + observed_at: "2026-01-01T01:00:01Z", takeover_basis: { + acceptance_sha256: "b".repeat(64), todo: {todo_id: todoId, role: "agent", task_class: "advancement_task", + status: "open", archive_state: "active", done: false, claimed_by: agentId}}, + leases: [{todo_id: todoId, owner: agentId, status: "active", idempotency_key: "current-claim", + version: 2, lease_epoch: 2, acquired_at: "2026-01-01T01:00:00Z", + updated_at: "2026-01-01T01:00:00Z", expires_at: "2026-01-01T04:00:00Z"}]}; + const current = {...original.details, prepared_lease_key_sha256: createHash("sha256").update("current-claim").digest("hex"), + prepared_lease_version: 2, prepared_lease_epoch: 2, lease_takeover_source: source}; + const result = heartbeatWorkRequalification(original, current, identity, "open", false); + assert.equal(result.append, true); + const details = result.details as JsonObject; + assert.equal(details.settlement_receipt_revision, "lease_takeover"); + assert.equal(details.settlement_effect_id, identity.effect_id); + assert.equal(details.takeover_original_event_id, original.event_id); + assert.equal(details.takeover_original_epoch, 1); + assert.equal(details.prepared_lease_epoch, 2); + assert.equal(details.lease_takeover_source, undefined); + const resumed = {...original, event_id: "takeover-event", recorded_at: source.observed_at, details}; + validateHeartbeatTakeoverParent(resumed, original, identity); + for (const mutate of [ + (s: typeof source) => {s.leases[0]!.owner = "competing-holder";}, + (s: typeof source) => {s.leases[0]!.status = "released";}, + (s: typeof source) => {s.leases[0]!.expires_at = s.observed_at;}, + (s: typeof source) => {s.leases[0]!.acquired_at = "2025-12-31T23:59:59Z";}, + (s: typeof source) => {s.takeover_basis.todo.status = "done";}, + (s: typeof source) => {s.takeover_basis.todo.claimed_by = "other-agent";}, + (s: typeof source) => {s.decision_read_from_provider = false;}, + (s: typeof source) => {s.legacy_fallback_used = true;}, + (s: typeof source) => {s.provider_revision = "";}, + (s: typeof source) => {s.leases.push({...s.leases[0]!});}, + ]) { + const invalid = structuredClone(source); mutate(invalid); + assert.throws(() => heartbeatWorkRequalification(original, + {...current, lease_takeover_source: invalid}, identity, "open", false), /original task lease generation/); + } + for (const field of ["takeover_owner", "takeover_original_event_id", "takeover_todo_sha256", "takeover_acceptance_sha256", "takeover_expires_at"]) { + const corrupted = structuredClone(resumed); + corrupted.details[field] = "invalid"; + assert.throws(() => validateHeartbeatTakeoverParent(corrupted, original, identity), /lease takeover/); + } + assert.throws(() => validateHeartbeatTakeoverParent({...resumed, + details: {...details, quota_spend_source: "changed-source"}}, original, identity), /lease takeover/); + assert.equal(heartbeatWorkRequalification(original, current, identity, "settlement_pending", false).append, false); + assert.equal(heartbeatWorkRequalification(original, current, identity, "open", true).append, false); + } finally {await rm(root, {recursive: true, force: true});} +}); + test("work requalification fails closed on binding and semantic guard conflicts", async () => { const {root, identity, event} = await fixture(); try {