diff --git a/docs/reference/local-delegation.md b/docs/reference/local-delegation.md index cbb2b8ca8d..afd9bf3194 100644 --- a/docs/reference/local-delegation.md +++ b/docs/reference/local-delegation.md @@ -1410,17 +1410,19 @@ Inspect the original execution and canonical lease before recovery. These observations do not extend deadlines, grant authority, or change stop settlement. Successful and ordinary unleased Host results retain their existing shape. After the Host returns, periodic renewal stops but final execution readback -remains bounded by the latest proved lease expiry. An in-flight renewal that -finishes with fresh canonical proof advances that deadline; a committed renewal -whose proof is unavailable does not. +remains bounded by the latest proved lease expiry. The supervisor carries +elapsed monotonic time across wall-clock corrections. Re-reading the same +version can only retain or shorten its deadline. A newer proof can extend +the deadline when it arrives within the previously proved window. 受管委派错误通过 `lease:/` 保留首个类型化租约失败原因, 区分启动前证明失败、续期拒绝和已证明期限到达。仅有 Host 的 `cancelled` 结果不代表用户请求停止,也不证明租约已释放;恢复前需读回原执行与 canonical 租约。这些诊断不延长期限、不授予权限,也不改变停止结算条件;成功执行与普通 无租约 Host 的结果结构保持不变。Host 返回后不再安排周期续期,但最终执行读回 -仍受最新已证明的租约期限约束;进行中的续期取得新鲜 canonical 证明后更新该期限, -仅有续期提交而没有及时取得证明不能延长执行权限。 +仍受最新已证明的租约期限约束。监督进程跟踪单调时钟的已逝时间,系统时钟回拨 +时仍继续计时。再次读回同一版本只能保留或缩短截止时间。更高版本的证明必须在 +原截止时间之前到达,才可以延长执行期限。 | Interruption | Behavior and recovery | | --- | --- | diff --git a/loopx/control_plane/turn_driver/leased_host_process.ts b/loopx/control_plane/turn_driver/leased_host_process.ts index e0371a9c0b..15fc8540e5 100644 --- a/loopx/control_plane/turn_driver/leased_host_process.ts +++ b/loopx/control_plane/turn_driver/leased_host_process.ts @@ -59,6 +59,24 @@ export async function runLeasedHostProcess(request: HostProcessRequest, context: let renewalTimer: ReturnType | undefined; let expiryTimer: ReturnType | undefined; let pending: Promise | undefined; + let provedExpiry: number | undefined; + let lastMonotonic = performance.now(); + let effectiveWall = Date.now(); + const leaseTime = () => { + const monotonic = performance.now(); + // Carry elapsed time across wall-clock corrections. A rollback cannot + // add time to an already observed execution window. + effectiveWall = Math.max(Date.now(), effectiveWall + (monotonic - lastMonotonic)); + lastMonotonic = monotonic; + return effectiveWall; + }; + const timeBeforeExpiry = () => { + const now = leaseTime(); + if (provedExpiry !== undefined && now >= provedExpiry) { + throw new LeaseSupervisionFailure("proved_deadline_elapsed"); + } + return now; + }; // A receipt is historical. This exact claim replay proves the original // execution is still current and returns its latest version, not a new key. const currentProof = (raw: unknown): LeaseRecord => { @@ -66,10 +84,14 @@ export async function runLeasedHostProcess(request: HostProcessRequest, context: if (result.ok !== true) throw new LeaseSupervisionFailure("execution_proof_rejected"); const record = requireJsonObject(result.lease, "delegated current lease"); const observed = canonicalTaskLease(record, String(lease.goal_id), String(lease.todo_id)); - if (!leaseIsActive(observed, new Date())) throw new LeaseSupervisionFailure("lease_inactive"); + if (!leaseIsActive(observed, new Date(timeBeforeExpiry()))) throw new LeaseSupervisionFailure("lease_inactive"); + const version = leaseVersion(observed), previousVersion = leaseVersion(lease); if (observed.owner !== lease.owner || observed.idempotency_key !== lease.idempotency_key || leaseEpoch(observed) !== leaseEpoch(lease) || - leaseVersion(observed) < leaseVersion(lease)) throw new LeaseSupervisionFailure("execution_identity_changed"); + version < previousVersion) throw new LeaseSupervisionFailure("execution_identity_changed"); + // leaseIsActive already validated the expiry timestamp. + const expiry = parseIsoTimestamp(String(observed.expires_at))!.valueOf(); + provedExpiry = provedExpiry === undefined || version > previousVersion ? expiry : Math.min(provedExpiry, expiry); return observed; }; const cli = async (argv: string[]): Promise => { @@ -90,18 +112,19 @@ export async function runLeasedHostProcess(request: HostProcessRequest, context: failure ??= {reason: owner.aborted ? "owner_cancelled" : reason, boundary}; abort(); }; - const reject = (error: unknown, boundary: LeaseFailureBoundary) => - lose(error instanceof LeaseSupervisionFailure ? error.reason : "lease_observation_failed", boundary); + const reject = (error: unknown, boundary: LeaseFailureBoundary) => { + const reason = error instanceof LeaseSupervisionFailure ? error.reason : "lease_observation_failed"; + lose(reason, reason === "proved_deadline_elapsed" ? "deadline" : boundary); + }; const clearTimers = () => { clearTimeout(renewalTimer); clearTimeout(expiryTimer); }; const schedule = () => { clearTimers(); - const expires = parseIsoTimestamp(String(lease.expires_at)); - const remaining = expires === null ? 0 : expires.valueOf() - Date.now(); + const remaining = (provedExpiry ?? 0) - leaseTime(); if (remaining <= 0) { lose("proved_deadline_elapsed", "deadline"); return; } // Stop at the last proved deadline even if renewal or its transport hangs. - expiryTimer = setTimeout(() => lose("proved_deadline_elapsed", "deadline"), remaining); + expiryTimer = setTimeout(() => lose("proved_deadline_elapsed", "deadline"), Math.ceil(remaining)); // A returned Host still needs final proof under the latest proved expiry. // Only periodic renewal ends at Host return; expiry supervision does not. if (finished) return; @@ -111,8 +134,8 @@ export async function runLeasedHostProcess(request: HostProcessRequest, context: // Keep the existing revocation/proof cadence, but do not rewrite a // long-lived lease on every observation. Renew in its latter half; // this leaves the same retry/deadline supervision for short leases. - const deadline = parseIsoTimestamp(String(lease.expires_at)); - const renew = deadline === null || deadline.valueOf() - Date.now() <= context.ttl_seconds * 500; + const remaining = (provedExpiry ?? 0) - timeBeforeExpiry(); + const renew = remaining <= context.ttl_seconds * 500; if (renew) { const argv = [...context.renew_argv, "--expected-version", String(leaseVersion(lease)), "--ttl-seconds", String(context.ttl_seconds)]; @@ -136,9 +159,10 @@ export async function runLeasedHostProcess(request: HostProcessRequest, context: }; try { // No Host input or process launch precedes current execution readback. - try { lease = currentProof(await cli(context.read_argv)); } - catch (error) { reject(error, "initial_proof"); } - schedule(); + try { + lease = currentProof(await cli(context.read_argv)); + schedule(); + } catch (error) { reject(error, "initial_proof"); } // The CLI's TERM adapter unwinds the nested Host transport (bounded at // five seconds). Allow that acknowledgement before a forced group kill. // This is private supervisor behavior, not a model-controlled timeout. diff --git a/tests/control_plane_ts/host_process.test.ts b/tests/control_plane_ts/host_process.test.ts index 7f64275b7f..ac418a9bf4 100644 --- a/tests/control_plane_ts/host_process.test.ts +++ b/tests/control_plane_ts/host_process.test.ts @@ -317,3 +317,31 @@ test("the spawned Host group is reported once before input, and an unrecorded gr throw new Error("record unavailable"); }}); assert.equal(refused.outcome, "cancelled"); assert.equal(refused.output_complete, false); }); + +test("an unchanged lease proof cannot extend a running Host after wall clock rollback", async t => { + const directory = await mkdtemp(join(tmpdir(), "host-clock-rollback-")); + t.after(() => rm(directory, {recursive: true, force: true})); + const marker = join(directory, "late-completion"); + const reads = join(directory, "reads"); + const wall = Date.now(); + const lease = {schema_version: "task_lease_v0", goal_id: "goal-clock", todo_id: "todo_clock", + owner: "agent-a", status: "active", version: 1, lease_epoch: 1, idempotency_key: "original", + expires_at: new Date(wall + 2400).toISOString()}; + const context = decodeDelegatedHostLease({lease, ttl_seconds: 1, + read_argv: request(`require('fs').appendFileSync(${JSON.stringify(reads)}, 'r'); + console.log(${JSON.stringify(JSON.stringify({ok: true, lease}))});`).argv, + // The supervisor appends lease flags. Keep them out of the Node option parser. + renew_argv: [...request("setTimeout(() => console.log(JSON.stringify({ok: false})), 5000)").argv, "--"]}); + t.mock.timers.enable({apis: ["Date"], now: wall}); + const child = request(`setTimeout(() => { + require('fs').writeFileSync(${JSON.stringify(marker)}, 'finished'); + console.log('late result'); + }, 3400)`, {timeout_ms: 4500}); + const result = await runLeasedHostProcess(child, context, async () => {}, + new AbortController().signal, async () => t.mock.timers.setTime(wall - 30_000)); + + assert.ok((await readFile(reads, "utf8")).length >= 2, "the supervisor observed the unchanged proof again"); + assert.deepEqual({outcome: result.outcome, leaseFailure: result.lease_failure, lateMarker: existsSync(marker)}, { + outcome: "cancelled", leaseFailure: {reason: "proved_deadline_elapsed", boundary: "deadline"}, lateMarker: false, + }); +}); diff --git a/tests/models/host_lease/Deadline.lean b/tests/models/host_lease/Deadline.lean new file mode 100644 index 0000000000..15c90144ca --- /dev/null +++ b/tests/models/host_lease/Deadline.lean @@ -0,0 +1,62 @@ +import Init + +namespace HostLeaseDeadline + +-- Elapsed time comes from the supervisor's process-local monotonic clock. +def effectiveTime (priorWall wall elapsed : Int) : Int := + max wall (priorWall + elapsed) + +-- The authority proof has already passed the identity and activity checks. +def proofDeadline (currentVersion newVersion : Nat) (currentExpiry newExpiry : Int) : Int := + if currentVersion < newVersion then newExpiry else min currentExpiry newExpiry + +def acceptProof (observed currentExpiry : Int) (currentVersion newVersion : Nat) + (newExpiry : Int) : Option Int := + if currentExpiry ≤ observed then none + else some (proofDeadline currentVersion newVersion currentExpiry newExpiry) + +theorem rollback_preserves_monotonic_elapsed_time (priorWall wall elapsed : Int) + (rollback : wall ≤ priorWall + elapsed) : + effectiveTime priorWall wall elapsed = priorWall + elapsed := by + unfold effectiveTime + exact Int.max_eq_right rollback + +theorem effective_time_includes_elapsed (priorWall wall elapsed : Int) : + priorWall + elapsed ≤ effectiveTime priorWall wall elapsed := by + unfold effectiveTime + exact Int.le_max_right _ _ + +theorem unchanged_version_cannot_extend (version : Nat) (currentExpiry newExpiry : Int) : + proofDeadline version version currentExpiry newExpiry ≤ currentExpiry := by + simp only [proofDeadline, Nat.lt_irrefl, if_false] + exact Int.min_le_left _ _ + +theorem new_proof_cannot_revive_elapsed_deadline (priorWall wall elapsed currentExpiry newExpiry : Int) + (currentVersion newVersion : Nat) (expired : currentExpiry ≤ priorWall + elapsed) : + acceptProof (effectiveTime priorWall wall elapsed) currentExpiry currentVersion + newVersion newExpiry = none := by + have effectiveExpired := Int.le_trans expired (effective_time_includes_elapsed priorWall wall elapsed) + simp [acceptProof, effectiveExpired] + +theorem validated_new_version_before_expiry_can_extend (observed currentExpiry newExpiry : Int) + (currentVersion newVersion : Nat) (before : observed < currentExpiry) + (advanced : currentVersion < newVersion) : + acceptProof observed currentExpiry currentVersion newVersion newExpiry = some newExpiry := by + have notExpired : ¬currentExpiry ≤ observed := by omega + simp [acceptProof, notExpired, proofDeadline, advanced] + +theorem raw_wall_can_show_time_left_after_real_expiry : + let priorWall : Int := 100000 + let expiry : Int := 102400 + let wall : Int := 70000 + let elapsed : Int := 2400 + wall < expiry ∧ expiry ≤ effectiveTime priorWall wall elapsed := by decide + +#print axioms rollback_preserves_monotonic_elapsed_time +#print axioms effective_time_includes_elapsed +#print axioms unchanged_version_cannot_extend +#print axioms new_proof_cannot_revive_elapsed_deadline +#print axioms validated_new_version_before_expiry_can_extend +#print axioms raw_wall_can_show_time_left_after_real_expiry + +end HostLeaseDeadline diff --git a/tests/models/host_lease/README.md b/tests/models/host_lease/README.md new file mode 100644 index 0000000000..c11dfbdf3f --- /dev/null +++ b/tests/models/host_lease/README.md @@ -0,0 +1,15 @@ +# Delegated Host lease deadline model + +Run `lean -t 0 -DwarningAsError=true Deadline.lean` with the pinned toolchain. + +`effectiveTime` represents how the supervisor carries forward elapsed time +between wall-clock samples. `acceptProof` represents the existing deadline +check and version-based update in the [delegated Host supervisor](../../../loopx/control_plane/turn_driver/leased_host_process.ts). +The model assumes a living supervisor and nonnegative elapsed ticks. Each +candidate proof must also pass the production identity, epoch and activity +checks. The model covers observed deadlines. The effect of machine suspend +on clock readings and process-group termination latency require runtime evidence. + +The [integration test](../../control_plane_ts/host_process.test.ts) runs a real +child process and replaces only the supervisor's wall clock. It observes +whether the child writes a marker after readback of an unchanged proof. diff --git a/tests/models/host_lease/lean-toolchain b/tests/models/host_lease/lean-toolchain new file mode 100644 index 0000000000..6ac6d4c4ce --- /dev/null +++ b/tests/models/host_lease/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.22.0