From e5c920289aa883edcb22c33414e2c161ec2db085 Mon Sep 17 00:00:00 2001 From: huangruiteng <14976749+huangruiteng@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:42:42 +0800 Subject: [PATCH] Fix lost-lease recovery and default task leases to three hours Signed-off-by: huangruiteng <14976749+huangruiteng@users.noreply.github.com> --- docs/reference/canonical-lease-renew.md | 18 ++++++++++++ loopx/cli_commands/task_lease.py | 2 +- loopx/cli_commands/todo.py | 2 +- loopx/cli_commands/todo_registration.py | 2 +- .../coordination/todo_lifecycle_decision.ts | 3 +- .../quota/execution_loss_closeout.ts | 15 ++++++++-- .../quota/unsettled_host_turn_recovery.ts | 2 +- loopx/control_plane/work_items/task_lease.py | 2 +- .../work_items/task_lease_acquire.ts | 5 ++-- .../work_items/task_lease_record.ts | 1 + loopx/pi_goal_mode/README.md | 2 +- .../test_execution_loss_closeout_cli.py | 28 +++++++++++++++++++ tests/control_plane/test_task_lease.py | 5 ++++ .../test_todo_claim_argument_recovery.py | 6 ++-- .../canonical_task_lease_renew.test.ts | 26 +++++++++++++++++ .../task_lease_acquire.test.ts | 8 ++++++ 16 files changed, 112 insertions(+), 15 deletions(-) diff --git a/docs/reference/canonical-lease-renew.md b/docs/reference/canonical-lease-renew.md index d705e21fc6..78ad0802ba 100644 --- a/docs/reference/canonical-lease-renew.md +++ b/docs/reference/canonical-lease-renew.md @@ -21,6 +21,17 @@ execution authority. For a new execution on an open, eligible Todo with no prior lease: +Omitting `--ttl-seconds` now uses **3 hours (10800 seconds)** instead of +45 minutes for managed `todo claim` and task-lease acquire/renew/transfer. +Explicit values remain bounded to 1..86400 seconds. Upgrading does not extend +existing leases or rewrite receipts. When replaying an older standalone lease +operation, pass its recorded TTL explicitly so the changed default does not +alter the original intent. Renew before expiry or release promptly when work ends: a longer default +also delays recovery from an abandoned holder. + +未指定 `--ttl-seconds` 时,默认租约由 45 分钟改为 **3 小时**;显式时长仍为 +1..86400 秒。升级不修改已有租约或原操作回执。长任务仍须到期前续租,完成后及时释放。 + ```bash loopx --registry registry.json task-lease acquire \ --goal-id example-goal --todo-id todo_work --owner agent-a \ @@ -35,6 +46,13 @@ ignores ineligible holders. Standalone acquisition records explicitly requested scopes. New managed claims keep the Todo's declared paths in the Todo detail and acquire without a per-path list. +If the original Turn already admitted execution, expiry or release enters +execution-loss recovery. A new claim supplies only the control-writer proof +needed to close that original Turn without spending quota; it cannot resume +the old execution. Re-enter the original guard, follow its closeout preview, +and require a fresh admitted Turn before more delivery. A first claim on a +Turn that has not admitted execution still uses ordinary preparation. + ## Repository-relative scope identity New canonical acquisitions freeze the Todo's normalized `task_repository` as diff --git a/loopx/cli_commands/task_lease.py b/loopx/cli_commands/task_lease.py index 1ab69c0865..fd18968350 100644 --- a/loopx/cli_commands/task_lease.py +++ b/loopx/cli_commands/task_lease.py @@ -136,7 +136,7 @@ def register_task_lease_command( parser.add_argument( "--ttl-seconds", type=int, - help="Lease TTL in seconds. Defaults to 45 minutes and is capped at 24 hours.", + help="Lease TTL in seconds. Defaults to 3 hours and is capped at 24 hours.", ) parser.add_argument( "--write-scope", diff --git a/loopx/cli_commands/todo.py b/loopx/cli_commands/todo.py index dc739cea97..25e10616ca 100644 --- a/loopx/cli_commands/todo.py +++ b/loopx/cli_commands/todo.py @@ -537,7 +537,7 @@ def handle_todo_command( payload["instruction"] = ( "Continue the task. Use this original claim reference for progress " "or completion; pass --ttl-seconds on claim (1..86400) for long " - "(>45m) execution wakes or renew via `loopx task-lease renew` " + "(>3h) execution wakes or renew via `loopx task-lease renew` " "before lease_expires_at, and retain normal Turn settlement " "(omitting --next-action on completed-Todo semantic_closeout " "refresh-state)." diff --git a/loopx/cli_commands/todo_registration.py b/loopx/cli_commands/todo_registration.py index acd81ab26a..9f33d2539a 100644 --- a/loopx/cli_commands/todo_registration.py +++ b/loopx/cli_commands/todo_registration.py @@ -335,7 +335,7 @@ def register_todo_command( type=int, help=( "For todo claim, optional lease TTL in seconds (1..86400; default " - "2700 = 45m). Pass a higher TTL on claim for long (>45m) execution " + "10800 = 3h). Pass a higher TTL on claim for long (>3h) execution " "wakes, or renew via `task-lease renew` before expiry." ), ) diff --git a/loopx/control_plane/coordination/todo_lifecycle_decision.ts b/loopx/control_plane/coordination/todo_lifecycle_decision.ts index dbaff1eda3..f35e1cb981 100644 --- a/loopx/control_plane/coordination/todo_lifecycle_decision.ts +++ b/loopx/control_plane/coordination/todo_lifecycle_decision.ts @@ -11,6 +11,7 @@ import { import { normalizeRegisteredTodoAgents, normalizeTodoAgent } from "./todo_agents.ts"; import {normalizeTodoRepository} from "../todos/work_requirements.ts"; import {leaseWriteRepository, leaseRepositoryRejection} from "../work_items/task_lease_repository.ts"; +import {DEFAULT_TASK_LEASE_TTL_SECONDS} from "../work_items/task_lease_record.ts"; export const COORDINATION_TODO_TERMINAL_DECISION_REQUEST_SCHEMA = "loopx_coordination_todo_terminal_decision_request_v0"; @@ -533,7 +534,7 @@ function terminalFence( version, lease_epoch: epoch, write_scopes: [], - acquire_ttl_seconds: 2700, + acquire_ttl_seconds: DEFAULT_TASK_LEASE_TTL_SECONDS, }, }); } diff --git a/loopx/control_plane/quota/execution_loss_closeout.ts b/loopx/control_plane/quota/execution_loss_closeout.ts index a56e889821..7db48ec55d 100644 --- a/loopx/control_plane/quota/execution_loss_closeout.ts +++ b/loopx/control_plane/quota/execution_loss_closeout.ts @@ -157,11 +157,22 @@ export async function observeFencedExecution(root: string, identity: ReturnType< if (!todo || todo.status !== "open" || todo.role !== "agent" || todo.task_class !== "advancement_task" || todo.archive_state !== "active" || !rawLease) return null; const lease = canonicalTaskLease(rawLease, identity.goal_id, identity.todo_id); - if (!fencesPreparedGeneration(prepared, lease)) return null; + // Expiry/release already ends the original execution. A fresh managed claim + // may establish the administrative writer, but must never be advertised as + // preparation to resume that execution. The commit still requires a newer + // generation and independently verifies it under the writer fence. + const now = new Date(); + const originalLost = lease.lease_epoch === prepared.prepared_lease_epoch + && typeof lease.version === "number" && Number.isSafeInteger(lease.version) + && lease.version >= prepared.prepared_lease_version + && typeof lease.idempotency_key === "string" + && createHash("sha256").update(lease.idempotency_key).digest("hex") === prepared.prepared_lease_key_sha256 + && !leaseIsActive(lease, now); + if (!originalLost && !fencesPreparedGeneration(prepared, lease)) return null; 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, new Date()); + const active = writerMatches && leaseIsActive(lease, now); 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}; diff --git a/loopx/control_plane/quota/unsettled_host_turn_recovery.ts b/loopx/control_plane/quota/unsettled_host_turn_recovery.ts index 4c721035fc..ea5de6638b 100644 --- a/loopx/control_plane/quota/unsettled_host_turn_recovery.ts +++ b/loopx/control_plane/quota/unsettled_host_turn_recovery.ts @@ -671,7 +671,7 @@ export function reduceUnsettledHostTurnRecovery(value: unknown): JsonObject { if (writerRequired) obligation.reason = "the original execution lease is fenced and the current control-writer proof is unavailable"; obligation.recommended_action = executionLoss.current_control_writer_active === true ? "Use the original Turn and current control-writer proof for execution-loss closeout without debit. Verify the closeout before fresh work." - : "The original execution lease generation was replaced. Obtain authorized control-writer proof for the same Todo before execution-loss closeout. The replacement cannot resume the original business execution."; + : "The original execution lease is no longer available. Obtain authorized control-writer proof for the same Todo before execution-loss closeout. The replacement cannot resume the original business execution."; } return { schema_version: UNSETTLED_HOST_TURN_RECOVERY_RESULT_SCHEMA, diff --git a/loopx/control_plane/work_items/task_lease.py b/loopx/control_plane/work_items/task_lease.py index e468774f10..24ee364819 100644 --- a/loopx/control_plane/work_items/task_lease.py +++ b/loopx/control_plane/work_items/task_lease.py @@ -23,7 +23,7 @@ read_lease as read_lease, ) -DEFAULT_TASK_LEASE_TTL_SECONDS = 45 * 60 +DEFAULT_TASK_LEASE_TTL_SECONDS = 3 * 60 * 60 MAX_TASK_LEASE_TTL_SECONDS = 24 * 60 * 60 IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9_.:@/-]{1,160}$") diff --git a/loopx/control_plane/work_items/task_lease_acquire.ts b/loopx/control_plane/work_items/task_lease_acquire.ts index 8784dc8646..8873756581 100644 --- a/loopx/control_plane/work_items/task_lease_acquire.ts +++ b/loopx/control_plane/work_items/task_lease_acquire.ts @@ -28,13 +28,12 @@ import { } from "../coordination/local_authority_shadow_outbox.ts"; import { TASK_LEASE_ACQUIRE_REQUEST_SCHEMA, TASK_LEASE_CANONICAL_ACQUIRE_REQUEST_SCHEMA } from "../coordination/coordination_state_contract.generated.ts"; import { BARE_SHA256_PATTERN } from "../content_digest.ts"; -import {TASK_LEASE_SCHEMA_VERSION, TaskLeaseAcquireError, type LeaseRecord} from "./task_lease_record.ts"; +import {TASK_LEASE_SCHEMA_VERSION, DEFAULT_TASK_LEASE_TTL_SECONDS, TaskLeaseAcquireError, type LeaseRecord} from "./task_lease_record.ts"; export {TASK_LEASE_SCHEMA_VERSION, TaskLeaseAcquireError, leaseInteger, leaseVersion, leaseEpoch, leaseIsActive, type LeaseRecord} from "./task_lease_record.ts"; export const TASK_LEASE_ACQUIRE_REQUEST_SCHEMA_VERSION = TASK_LEASE_ACQUIRE_REQUEST_SCHEMA; -const DEFAULT_TTL_SECONDS = 45 * 60; const MAX_TTL_SECONDS = 24 * 60 * 60; type FileState = "file" | "missing"; export type TodoFactField = @@ -192,7 +191,7 @@ export function requireWriteScopes(value: unknown): string[] { export function normalizeTtl(value: unknown): number { const ttl = value === null || value === undefined - ? DEFAULT_TTL_SECONDS + ? DEFAULT_TASK_LEASE_TTL_SECONDS : optionalInteger(value, "ttl_seconds"); if (ttl === null || ttl <= 0 || ttl > MAX_TTL_SECONDS) { throw new TaskLeaseAcquireError( diff --git a/loopx/control_plane/work_items/task_lease_record.ts b/loopx/control_plane/work_items/task_lease_record.ts index e6a218b9a8..fdd790d996 100644 --- a/loopx/control_plane/work_items/task_lease_record.ts +++ b/loopx/control_plane/work_items/task_lease_record.ts @@ -2,6 +2,7 @@ import type {JsonObject} from "../effect_program.ts"; import {parseIsoTimestamp} from "../runtime_timestamp.ts"; export const TASK_LEASE_SCHEMA_VERSION = "task_lease_v0"; +export const DEFAULT_TASK_LEASE_TTL_SECONDS = 3 * 60 * 60; export interface LeaseRecord extends JsonObject { schema_version?: unknown; diff --git a/loopx/pi_goal_mode/README.md b/loopx/pi_goal_mode/README.md index 0c203a7089..91f6376558 100644 --- a/loopx/pi_goal_mode/README.md +++ b/loopx/pi_goal_mode/README.md @@ -144,7 +144,7 @@ loopx_task_lease({ todoId: "todo_ab12cd34ef56", idempotencyKey: "pi-turn-42", writeScopes: ["loopx/**"], - ttlSeconds: 2700 + ttlSeconds: 10800 }) ``` diff --git a/tests/control_plane/test_execution_loss_closeout_cli.py b/tests/control_plane/test_execution_loss_closeout_cli.py index f895ad91af..3b22d249a5 100644 --- a/tests/control_plane/test_execution_loss_closeout_cli.py +++ b/tests/control_plane/test_execution_loss_closeout_cli.py @@ -783,3 +783,31 @@ def test_original_turn_reentry_projects_execution_loss_without_repeating_work( assert code == 0 and replay["idempotent_replay"] and not replay["appended"], replay assert _receipt_lines(context) == before _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): + 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"], + "--todo-id", context["todo"], "--owner", OWNER, "--idempotency-key", original["idempotency_key"], + "--expected-version", str(original["version"])) + 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["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] + assert len(claims) == 1 + code, claimed = context["cli"](*claims[0][claims[0].index("todo"):]) + 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_no_completion_or_debit(context) diff --git a/tests/control_plane/test_task_lease.py b/tests/control_plane/test_task_lease.py index 302f995bf0..599e6691b6 100644 --- a/tests/control_plane/test_task_lease.py +++ b/tests/control_plane/test_task_lease.py @@ -74,6 +74,11 @@ def test_normalize_ttl_seconds_rejects_out_of_range(ttl: int) -> None: assert error.value.code == "invalid_ttl" +def test_task_lease_default_is_three_hours_with_explicit_override() -> None: + assert normalize_ttl_seconds(None) == 10800 + assert normalize_ttl_seconds(2700) == 2700 + + @pytest.mark.parametrize("key", ["", "contains space", "bad$key"]) def test_normalize_idempotency_key_rejects_non_token(key: str) -> None: with pytest.raises(TaskLeaseError) as error: diff --git a/tests/control_plane/test_todo_claim_argument_recovery.py b/tests/control_plane/test_todo_claim_argument_recovery.py index 36a9aa6018..ff8b1fd3a5 100644 --- a/tests/control_plane/test_todo_claim_argument_recovery.py +++ b/tests/control_plane/test_todo_claim_argument_recovery.py @@ -874,16 +874,16 @@ def test_claim_ttl_seconds_bounds_visibility_and_replay_parity(claim_cli, thin): assert "lease_ttl_seconds: `7200`" in md.stdout -def test_claim_omitted_ttl_preserves_2700_default_and_explicit_lease_ttl(claim_cli): +def test_claim_omitted_ttl_uses_three_hours_and_preserves_explicit_lease_ttl(claim_cli): _, run, _, prefix, claim, _, _, _ = claim_cli default_claim = run([ *prefix, *claim, "--claimed-by", "peer-a", "--claim-operation-id", "claim-default-ttl", ]) assert default_claim["ok"] is True and default_claim["execution_managed"] is True - assert default_claim["lease_ttl_seconds"] == 2700 + assert default_claim["lease_ttl_seconds"] == 10800 assert isinstance(default_claim["lease_expires_at"], str) and default_claim["lease_expires_at"] inspected = run([*prefix, "task-lease", "inspect", "--goal-id", GOAL, "--todo-id", TODO]) - assert inspected["lease"]["acquire_ttl_seconds"] == 2700 + assert inspected["lease"]["acquire_ttl_seconds"] == 10800 # Release and verify explicit --task-lease-idempotency-key honors --ttl-seconds too. released = run([ diff --git a/tests/control_plane_ts/canonical_task_lease_renew.test.ts b/tests/control_plane_ts/canonical_task_lease_renew.test.ts index a62b025ea1..0b43ed96a4 100644 --- a/tests/control_plane_ts/canonical_task_lease_renew.test.ts +++ b/tests/control_plane_ts/canonical_task_lease_renew.test.ts @@ -24,6 +24,8 @@ import {TASK_LEASE_CANONICAL_ACQUIRE_REQUEST_SCHEMA, TASK_LEASE_ACQUIRE_REQUEST_ TASK_LEASE_CANONICAL_CLAIM_TRANSFER_REQUEST_SCHEMA} from "../../loopx/control_plane/coordination/coordination_state_contract.generated.ts"; import {shadowManagementStatePath} from "../../loopx/control_plane/coordination/shadow_management.ts"; import {atomicWriteJson} from "../../loopx/control_plane/effect_runtime_io.ts"; +import {observeFencedExecution} from "../../loopx/control_plane/quota/execution_loss_closeout.ts"; +import {settlementIdentity} from "../../loopx/control_plane/effect_program.ts"; const NOW = new Date("2026-09-13T10:05:00Z"); const CHILD = fileURLToPath(new URL("./canonical_task_lease_renew_process.ts", import.meta.url)); @@ -108,6 +110,30 @@ for (const provider of ["file", "sqlite"] as const) { expected_version: 1, ttl_seconds: 600, write_scopes: ["src/**"], authority: request.authority}; } const acquireNow = new Date("2026-09-13T10:11:00Z"); + providerTest(`${provider} original expiry projects administrative recovery, never delivery`, async t => { + const {runtime, goal, lease} = await fixture(t, provider); + const identity = settlementIdentity({goal_id: goal, agent_id: "agent-a", todo_id: "todo_renew", + turn_instance_id: "original-turn"}); + const details = {todo_id: "todo_renew", settlement_effect_id: identity.effect_id, + closeout_required: true, prepared_lease_required: true, ok: true, should_run: true, + must_attempt_work: true, delivery_allowed: true, quiet_noop_allowed: false, + prepared_lease_key_sha256: createHash("sha256").update(lease.idempotency_key).digest("hex"), + prepared_lease_version: lease.version, prepared_lease_epoch: lease.lease_epoch}; + const receipt = {schema_version: "loopx_rollout_event_v0", event_kind: "quota_should_run", + event_id: "original-admission", goal_id: goal, agent_id: "agent-a", run_id: "original-turn", + recorded_at: "2026-09-13T10:01:00Z", status: "normal_run", details}; + t.mock.timers.enable({apis: ["Date"], now: NOW}); + assert.equal(await observeFencedExecution(runtime, identity, receipt), null); + t.mock.timers.setTime(new Date(lease.expires_at).valueOf()); + const lost = await observeFencedExecution(runtime, identity, receipt); + assert.equal(lost?.can_reclaim_control_writer, true); + assert.equal(lost?.current_control_writer_active, false); + assert.equal(lost?.original_prepared_epoch, lost?.current_lease_epoch); + for (const patch of [{prepared_lease_key_sha256: "a".repeat(64)}, + {prepared_lease_version: lease.version + 1}, {delivery_allowed: false}]) { + assert.equal(await observeFencedExecution(runtime, identity, {...receipt, details: {...details, ...patch}}), null); + } + }); providerTest(`${provider} malformed receipt scopes cannot become a root wildcard`, async t => { const {store, request, lease, goal} = await fixture(t, provider); const command = {...acquireRequest(request), write_scopes: ["**"]}; diff --git a/tests/control_plane_ts/task_lease_acquire.test.ts b/tests/control_plane_ts/task_lease_acquire.test.ts index 932f4cf258..c24c3c09cf 100644 --- a/tests/control_plane_ts/task_lease_acquire.test.ts +++ b/tests/control_plane_ts/task_lease_acquire.test.ts @@ -6,10 +6,18 @@ import test from "node:test"; import { executeTaskLeaseAcquire, + normalizeTtl, TASK_LEASE_ACQUIRE_REQUEST_SCHEMA_VERSION, } from "../../loopx/control_plane/work_items/task_lease_acquire.ts"; import {TASK_LEASE_CANONICAL_ACQUIRE_REQUEST_SCHEMA} from "../../loopx/control_plane/coordination/coordination_state_contract.generated.ts"; +test("omitted task lease TTL is three hours while explicit bounds remain unchanged", () => { + assert.equal(normalizeTtl(undefined), 10800); + assert.equal(normalizeTtl(null), 10800); + for (const seconds of [1, 600, 2700, 86400]) assert.equal(normalizeTtl(seconds), seconds); + for (const seconds of [0, -1, 86401]) assert.throws(() => normalizeTtl(seconds)); +}); + function request(runtimeRoot: string, schemaVersion: string) { return { schema_version: schemaVersion,