Repository navigation
fix(quota): support fenced completed_lease_takeover for a Turn completed under a reclaimed lease - #9561
Conversation
…se generation When a task lease expires mid-Turn, the documented settlement order (todo complete before writeback) deadlocks permanently: the re-claim creates a new lease generation with a fresh idempotency key, the exact prepared receipt no longer matches, recovery binding requires steward key shapes no CLI path produces for this case, and every recovery path (requalification, takeover, execution-loss closeout) requires the Todo to still be open. The writeback then fails forever with refresh_task_lease_unavailable. A completed Todo can never produce another lease generation (claims and lifecycle operations reject non-open Todos), so the owner's retired head lease unambiguously is the completing generation. The completion receipt already proves a lease-fenced terminal transition for the exact Turn; binding writeback to it admits no execution the completion fence did not already permit, while refusing to bind strands the exact Turn the settlement plan instructs to complete first. Admit retired-lease binding only when the readback carries an exact todo_complete receipt for this Turn, Todo, and agent, and the requested proof (when given) matches the completing generation exactly. Foreign or fabricated receipts and proofs are still rejected. Signed-off-by: Wang, Xiang-Han <wanghank00@gmail.com>
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
…ted_lease_takeover Revert the Python execution_preparation.py writeback backdoor that bypassed lease-generation fencing on direct refresh-state and broke retired-generation regression tests. Instead, extend PR loopx-project#9488's TypeScript-owned fenced lease takeover to handle a prepared Turn whose Todo was already completed under a reclaimed lease generation before rerunning quota should-run: - Direct refresh-state continues to fail closed (refresh_task_lease_unavailable) until the original Turn's guard runs. - Rerunning quota should-run acquires the canonical maintenance lock, verifies canonical done status, completion_turn_key, completing owner, monotonic retired lease generation, and matching rollout todo_complete receipt, and appends a completed_lease_takeover receipt updating prepared_lease without repeating work or altering admission/billing identity. - Cold settlement readback validates completed_lease_takeover lineage and cross-checks takeover_completion_event_id against the Turn's todo_complete receipt. - Stale original-generation proofs and unprepared Turns remain fenced. Signed-off-by: Wang, Xiang-Han <wanghank00@gmail.com>
loopx-agent
left a comment
There was a problem hiding this comment.
Reviewer: model_agent · gpt-6.2-sol · OpenAI · runtime_reported · xhigh
动机 / Motivation
任务租约在执行期间到期时,原持有人可以重新认领并完成 Todo。主干直接结算会拒绝已退役的租约,而且原轮次的准入读回无法接上完成时使用的新租约。操作者明明已通过 Todo 验证,仍无法把原轮次结算闭环。这个 PR 让原轮次从已完成的 Todo 恢复结算。验收依据是 PR 对 #9488 的扩展描述,以及主干既有的租约隔离和 Goal 实例隔离。基于 File 与 SQLite 的对照确认了正常路径改进,同时发现一处会重新造成结算停滞的隔离问题。
在任务完成前重新认领租约、需要结算原轮次的操作者。 File/SQLite 的 todo complete、原轮次 quota should-run 与 refresh-state。 候选同来源两后端都升级并结算一次;有另一 Goal 实例的历史记账时两端仍只重放。 外实例事件不属于当前轮次的 typed readback,但 Python 阻止接续。File/SQLite 两对照通过、两负例失败。 未测量实际安装、多小时生产复现、PostgreSQL 和稳定延迟。远端 CI 未查询。 当前轮次无法忽略另一 Goal 实例的历史记账事件。
按基线 811c1a1f66652d3fc3b9830d467e14b45b7423c1 上的 docs/architecture/rfcs/typescript-control-plane-migration-v0.md 核对两项。
existing-runtime-owner对应现有 runtime 的职责和来源。real-path-parity对应真实 File/SQLite 入口的行为对照。
改动思路 / Approach
直接写回继续受原租约围栏约束。重入原轮次的 quota should-run 在维护锁下读取完成收据与退役租约,由 TypeScript 决定是否追加接续收据。这个边界允许已验证的完成结果继续走原轮次,不需要重跑任务。复用现有收据链比在写回入口放宽租约规则更合适。Python 为读快照增加的前置筛选也需要使用原轮次的 Goal 实例身份。
验证完成来源、租约代次、原轮次与结算身份保持在同一 Goal 实例。 让 Python 快照前置检查复用同一 Goal 实例和结算身份的判定,或由现有 typed 结算所有者决定何时需要快照。
具体改动 / Changes
heartbeat_receipt.py的requalify_bound_heartbeat_receipt在追加前先识别已完成且尚未记账的请求,取得维护锁后读取权威租约。heartbeatCompletedLeaseTakeover核对完成事件、Todo、同一持有人、新租约代次及时间边界。validateHeartbeatTakeoverParent和settlement_readback.ts在冷读时检查原准入与完成事件。readExecutionPreparationSource仅在 takeover 读取中提供退役时间。- Python 新用例走真实 File/SQLite 命令,覆盖直接写回拒绝、准入重入、旧证明拒绝、一次结算和幂等重放。TypeScript 用例覆盖其他持有人、未准备轮次、畸形完成收据和已经开始记账的请求。
对主干的风险 / Risks
[P2] 其他 Goal 实例的历史记账事件会阻止当前轮次接续。 requalify_bound_heartbeat_receipt 的前置筛选只匹配 Goal 名称、Agent 和轮次字符串。结算冷读按精确 Goal 实例隔离,Python 却会把另一个实例的 refresh_state 当成当前轮次已经记账。File、SQLite 的隔离对照都先实际完成重领后的 Todo。在只增加一条其他实例的历史记账记录后,冷读仍正确报告当前轮次待结算,原轮次 guard 却由 upgraded 变为 replayed,漏绑完成时的租约。请在维护锁前按同一来源和结算身份筛选,或让现有结算所有者提供是否需要快照的判断。补上同文本轮次跨 Goal 实例的双后端回归。 Python 前置筛选
原正常用例两端在主干均只重放,候选在无跨实例记录时能够完成原轮次。同源拒绝及单次记账用例随 145 项 Python 检查通过。相关 TypeScript 的 211 项通过。生产安装态的多小时场景和 PostgreSQL 不在验证范围。
18 项本地预合并检查中的 17 项首跑通过。补装仓库锁定的 npm 开发依赖后,单独重跑余下一项语义词汇检查通过。
我的整体评价 / Verdict
保留已完成租约通过原 guard 接续的总体设计。将 Python 快照前置判断收敛到同一个 Goal 实例和结算身份,再复验冷读、重放与 File/SQLite 一次结算。远端 CI 未查询。
English verdict: REQUEST_CHANGES at 845d88b. Ignore accounting events from another Goal instance when qualifying the completed-lease takeover. Both File and SQLite controls recover, while both cross-instance counterfactuals strand the original settlement.
| and original_details.get("prepared_lease_key_sha256") | ||
| and not details.get("prepared_lease_key_sha256") | ||
| ): | ||
| turn_events = [ |
There was a problem hiding this comment.
[P2] 按 Goal 实例筛选记账记录。 File 和 SQLite 的真实 guard 对照中,另一实例的同文本轮次有历史记账时,冷读仍报告当前轮次待结算,前置扫描却跳过完成租约接续。请让这里使用与结算读回相同的来源和结算身份,并覆盖该负例。
…ify shared takeover validation Address P2 review finding: scope requalify_bound_heartbeat_receipt's completed_takeover_candidate pre-filter by the exact goal_ref owner (sharing _expected_goal_ref / _event_matches_goal_ref with _agent_heartbeat_receipt_events) and settlement_effect_id so historical accounting events from another Goal instance or settlement effect do not suppress takeover. Add File and SQLite cross-instance regression coverage (test_completed_lease_takeover_ignores_foreign_goal_instance_accounting), share the common takeover validation core in heartbeat_receipt_identity.ts, and revert the unnecessary released_at projection change in read_transaction.ts. Signed-off-by: Wang, Xiang-Han <wanghank00@gmail.com>
loopx-agent
left a comment
There was a problem hiding this comment.
Reviewer: model_agent · gpt-6.2-sol · OpenAI · runtime_reported · xhigh
动机 / Motivation
已准入、重领同一硬租约任务并在运行原守卫前完成 Todo 的 Agent 需要结算原轮。 上一提交遇到其他 Goal 实例的同轮历史账务,守卫重放旧回执,File 和 SQLite 都卡在接管。 本提交按 GoalRef 和 settlement effect 筛出完成与账务事件,守卫能接管。对于 legacy Goal 与另一实例同 Todo 的历史写回,后续回执仍会被去重,原轮扣额为零。 限于已准入并完成的原硬租约任务及其账务恢复。 复测使用隔离 File、SQLite 和合成历史行,复用实际 Todo 完成、quota should-run、生成的 refresh-state 和扣额命令。部署态升级与托管 CI 未验证。 既有接管契约 上一轮评审
改动思路 / Approach
原 guard 持有 rollout 锁,并在核验候选退役租约时读取 canonical authority。TypeScript 复用开放任务与已完成任务的共同校验,分别处理 active 和 released 状态。完成接管追加原 admission 和 completion 的引用,冷读校验两者配对。后续 refresh-state 继续用原写回与扣额链路。 守卫 冷读
具体改动 / Changes
评审提交 696be1e2628d6dfb0c1c8d0923cfa9b6efc2e6d1,PR 基线 811c1a1f66652d3fc3b9830d467e14b45b7423c1。五个文件 +655/-58。
关键代码讲解
requalify_bound_heartbeat_receipt在取维护锁前筛选同 GoalRef 和同 effect 的 rollout 事件。独立对照确认上一轮指出的守卫误判已消失。 事件筛选verifyTakeoverCommon核对原准入、单条 canonical lease、owner、代数、时间和来源。heartbeatCompletedLeaseTakeover另要求完成键、released 状态及原轮 completion;settlement_readback用该事件 ID 校验冷读。 共同校验 完成接管 冷读- Python 的 File/SQLite 测试覆盖新守卫、生成写回与重放。跨实例用例中的历史
refresh_state使用另一个 Todo,未覆盖历史写回与当前 Todo 相同的案例。TypeScript 测试保护接管的拒绝条件和持久化读回。 File/SQLite TypeScript
核对三项验收。guard-fence 已通过。completion-lineage 已通过。scoped-settlement-once 卡在真实写回后的扣额。 既有同轮恢复约定
对主干的风险 / Risks
[P2] legacy 写回的去重仍会吞掉当前 Goal 的回执。 无 GoalRef 的当前 legacy 写回在 append_rollout_event_once 按字段去重时省略 goal_ref。这使同 Todo 的异实例历史写回占用当前记录。结算冷读仍按实例隔离,所以找不到本轮自己的写回回执。两种 provider 在无历史和异 Todo 历史时均完成结算并只扣一次。只有异实例、同 Todo 的两项在守卫升级和幂等重放之后返回 matching accountable refresh-state receipt is missing,并且没有当前实例的写回回执,扣额为零。 让 refresh-state 的 append-once 身份显式区分没有 GoalRef 的 legacy 事件和携带 GoalRef 的事件。沿用已核验的当前作用域,增加同 Todo 的 File/SQLite 用例,核对当前回执、扣额及重放各一次。 写回去重键 去重匹配 结算错误
前置直接写回和旧 lease 证明仍被拒。已有 TS 矩阵覆盖来源不符、完成身份不符、已写回、其他 owner 与回执父链。 仓库 Python 301 通过、10 跳过,TypeScript 211 通过。本地 canary 17 项选定检查及 6 项直接检查通过。
我的整体评价 / Verdict
REQUEST_CHANGES。原守卫的实例隔离已复验。请补齐写回回执的实例隔离,并在 File 与 SQLite 复验生成命令、回执冷读和同轮重放,确认恢复完成后只扣一次。
English verdict: REQUEST_CHANGES at 696be1e. The guard recovers the original Turn, but legacy writeback deduplication can still suppress its receipt when the same Todo has history from another Goal instance. File and SQLite both leave the debit uncommitted.
Goal And Delivered Outcome
todo completebefore rerunningquota should-run. The re-claim creates a new lease generation with a fresh idempotency key; oncetodo completeretires that lease and marks the Tododone, every existing recovery path inmainrequires an open Todo (active-leaselease_takeover, requalification, execution-loss closeout), while directrefresh-statefails closed withrefresh_task_lease_unavailable. The Turn is then stranded from durable writeback and quota spend.refresh-statewithrefresh_task_lease_unavailable, and rerunning the original Turn'squota should-runcannot bind the retired completing generation, permanently stranding settlement.refresh-statecontinues to fail closed (refresh_task_lease_unavailable) and retired-generation regression tests remain intact; rerunning the original Turn'squota should-runacquires the canonical maintenance lock, verifies canonical completion ownership in TypeScript, appends an append-onlycompleted_lease_takeoverreceipt updatingprepared_leaseto the completing generation (without repeating work or altering admission/billing identity), and lets the guard-returnedrefresh-statesettle the original Turn once. Stale original-generation proofs, unprepared Turns, and tampered/foreign sources remain rejected. Proven by theunit,real_entrypoint, andregression_parityrows in the Validation table below.mainReproduction (real install)
prepared_leaseat epoch 1).quota should-run:todo complete --turn-instance-id <TURN>succeeds under epoch 2 (atomically settingtodo.status = "done",todo.completion_turn_key = identity.effect_id, and retiring the epoch-2 lease asreleased), then run writeback.refresh_task_lease_unavailable, and rerunningquota should-runpreviously could not qualifylease_takeoverbecausereplayPhase === "settlement_pending"andtodo.status === "done". Permanent settlement deadlock.Why fenced
completed_lease_takeoveris safeloopx/control_plane/quota/execution_preparation.pyis unchanged frommain. Directrefresh-statestill fails closed (refresh_task_lease_unavailable) until the original Turn's guard explicitly qualifies takeover, preservingtest_first_writeback_refuses_generation_retired_by_later_work.lease_takeovermechanism,requalify_bound_heartbeat_receipttakes the nonblocking canonical maintenance lock only when a prepared Turn has a matchingtodo_completeevent and no accounting (refresh_state,quota_spend,todo_supersede) has started. TypeScript (heartbeatCompletedLeaseTakeoverinheartbeat_receipt_identity.ts) alone decides eligibility.heartbeatPreparedWorkAdmission(original, identity)(unprepared Turns stay refused), canonicalhandoff_mode === "hard_lease"fromfile_v0/sqlite_v0withdecision_read_from_provider === trueandlegacy_fallback_used === false,todo.status === "done",todo.done === true,todo.completion_turn_key === identity.effect_id, same completingowner, singlereleasedlease with strictly advancinglease_epochandversionand distinct key digest,leaseRepositoryRejection === null, monotonic timestamps (admitted <= acquired <= updated <= observed_atandreleased <= expires), and an exact matchingtodo_completerollout receipt.validateHeartbeatTakeoverParentverifies the append-only parent chain back to the original admission, andsettlement_readback.tscross-checkstakeover_completion_event_id === completionEvent.event_idon cold readback. Replayingquota should-runis idempotent, and stale original-generation proofs remain rejected.Author Declaration
Implemented against
988a80c2b1) fencedlease_takeoversemantics while preservingexecution_preparation.ts("Recovery must not borrow a replacement lease or execution") and retired-generation writeback fencing.refresh-statecontinues to fail closed before guard takeover; retired-generation regression stays greenloopx/control_plane/quota/execution_preparation.py(unchanged frommain)tests/control_plane/test_completed_lease_takeover.py+test_first_writeback_refuses_generation_retired_by_later_work(8 passed)completed_lease_takeoverunder maintenance fence only before accounting starts and validates canonical completion + retired lease ownershipheartbeatCompletedLeaseTakeover,validateHeartbeatTakeoverParent,heartbeatWorkRequalificationinloopx/control_plane/quota/heartbeat_receipt_identity.ts;requalify_bound_heartbeat_receiptinloopx/control_plane/quota/heartbeat_receipt.py;readExecutionPreparationSourceinloopx/control_plane/todos/read_transaction.tstests/control_plane_ts/native_child_admission.test.ts+tests/control_plane/test_completed_lease_takeover.py(File & SQLite)takeover_completion_event_idagainsttodo_completeheartbeatValidationEvent,readQuotaSettlementFromRequest,requalifyHeartbeatReceiptinloopx/control_plane/quota/settlement_readback.tstests/control_plane_ts/native_child_admission.test.ts+tests/control_plane_ts/quota_settlement_readback.test.tstests/control_plane_ts/native_child_admission.test.ts+tests/control_plane/test_completed_lease_takeover.pyexecution_preparation.pywriteback bypass after catching that it broketest_first_writeback_refuses_generation_retired_by_later_work[False-complete-file|sqlite]and weakened direct-writeback fencing; verified full TypeScript control-plane suite, targeted Python control-plane suites (File & SQLite),ruff, touched-filemypy,loopx check,scripts/generate_semantic_inventory.py,loopx canary premerge --from-git-diff, and published-diff parity againstorigin/main...HEAD. Not verified: live multi-hour reproduction (reproduced on a real install prior to the patch; end-to-end File & SQLite CLI lifecycle is covered intests/control_plane/test_completed_lease_takeover.py) and full repo-wide 6-shardpytestlocally.Scope And Continuation
Validation
845d88b1ab25fd56f77c228c97046906fc9774cefinishedsynthetic,public_fixturestaticpassednpm run typecheck:control-plane(tsc --project tsconfig.control-plane.json --noEmit): 0 errors;python -m ruff check loopx/control_plane/quota/heartbeat_receipt.py loopx/control_plane/quota/execution_preparation.py tests/control_plane/test_completed_lease_takeover.py: passed;python -m mypy --follow-imports=silent loopx/control_plane/quota/heartbeat_receipt.py loopx/control_plane/quota/execution_preparation.py: 0 issues;loopx checkon all 6 changed files: clean (0 errors, 0 warnings);python scripts/generate_semantic_inventory.py --changed-from origin/main: 0 unsupported new vocabulary carriers;git diff --check: cleanunitpassednpm run test:control-plane: 6896 passed, 0 failed, 1 skipped (includes newcompleted_lease_takeover, retired-leaseupdated_atfallback, and cold-readtakeover_completion_event_idtamper tests intests/control_plane_ts/native_child_admission.test.ts; CItypescript-core (1-3/3)andtypescript-coveragegreen on845d88b1a)real_entrypointpassedpython -m pytest -vv tests/control_plane/test_completed_lease_takeover.py tests/control_plane/test_heartbeat_lease_takeover.py tests/control_plane/test_quota_execution_preparation.py tests/control_plane/test_execution_loss_closeout_cli.py: 145 passed, 0 failed (File & SQLite end-to-end CLI flow:todo completeunder reclaimed lease -> directrefresh-statefails closed ->quota should-runrecordscompleted_lease_takeover-> idempotent replay -> stale proof rejected -> guard-returnedrefresh-statesettles once; unprepared Turn stays refused)regression_paritypassedpython -m pytest -vv tests/control_plane/test_quota_authority_settlement_journey.py -k test_first_writeback_refuses_generation_retired_by_later_work: 8 passed, 0 failed (confirmed failing on commit 194642d06a`[False-complete-fileintegrationpassedloopx canary premerge --from-git-diff: 18/18 checks passed (0 failures, 0 warnings), includingcontrol-plane-maintainability-ratchet-smoke.py,semantic-vocabulary-drift-smoke.py,task-lease-runtime-smoke.py,refresh-state-write-correctness-smoke.py,todo-write-correctness-smoke.py, andquota-plan-smoke.pystaticblockedkernel-contractsfailed on pre-existingmainrepo-widemypyerrors (Found 3834 errors in 395 files, tracked in #9549), which causes CIpytestshards andmerge-gateto be skipped/blocked until #9549 lands onmainand this branch rebasespytestwas not run locally and is currently skipped in CI behind Isolate private capture platform support from quota type checking #9549's pre-existingkernel-contractsmypy failure; (2)test_quota_authority_settlement_journey.py::test_original_turn_refuses_readiness_from_a_replacement_lease[file|sqlite]fails on currentmainon this host due to pre-existing PR fix(quota): resume unfinished turns with fenced lease takeover #9488 open-Todolease_takeoverbehavior (its Todo staysopenand never callstodo complete, so it is unrelated tocompleted_lease_takeover).See validation disclosure guidance.
Frontend / Visual Evidence
nonenoneType of Change
LoopX Area
Technical Direction
Shared-authority RFC fixture impact
N/A — this PR fixes the completed-Todo fenced lease takeover settlement gap and does not claim new Shared Goal Authority RFC migration progress.
Boundary Checklist
.loopx/,.codex/goals/, and liveACTIVE_GOAL_STATE.md).python3 scripts/check_rfc_bilingual.py --base origin/main --head HEADpasses, or no paired RFC changed.none.Signed-off-bytrailer (git commit -s).Related audit gap (not fixed here)
While diagnosing the incident, the rollout event log projection (
loopx/rollout_event_log.py_safe_details) was observed flattening nested dict values such asmutation_authority.idempotency_keyinto truncated 240-character strings, which destroys lease-key audit evidence in the log. The ledger itself is unaffected. This is a separate observability defect; it is reported here for maintainer awareness rather than fixed in this PR to keep the slice reviewable.