Skip to content

Retry a definitively rejected Turn quota spend - #9180

Merged
huangruiteng merged 5 commits into
mainfrom
codex/quota-spend-index-conflict-20261121
Nov 22, 2026
Merged

huangruiteng merged 5 commits into
mainfrom
codex/quota-spend-index-conflict-20261121

Conversation

@loopx-agent

@loopx-agent loopx-agent commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Behavior

After a Turn's durable writeback, a concurrent quota writer can invalidate the spend preview. The accounting transaction rejects the stale commit as index_digest_conflict before any debit. The CLI exposes that code and appended=false.

When the caller explicitly requests refresh-state --settle-turn, the composition can run the same verified settlement command one more time after that rejection. The two invocations share the original 60-second timeout. The second reads the original identity and the current accounting basis. An already committed receipt is replayed. Persistent contention returns the original pending settlement and exact owed command. When a response is lost or the debit is uncertain, the existing receipt reader determines the outcome.

In loopx/control_plane/quota/settlement_readback.ts, once a durable writeback is verified (writeback.failure === null) and quota spend or its rollout receipt is still owed (spend.failure !== null), receiptBoundReplayPhase now treats that pending spend as settlement_pending (preserving monitor-poll settled precedence and open semantics when a spend has completed without Todo completion or an accepted checkpoint/replan). Consequently, rerunning quota should-run on the same Turn activates unsettled_host_turn_recovery (repair="quota_spend") and returns the exact settlement_owed.command across --codex-app (with or without --todo-id), --runtime-profile generic_cli, plain quota should-run, and remote_authority waits, even when optional boundary flags such as --delivery-boundary in_flight_continuation or --completion-todo-id were omitted during refresh-state.

Validation on current head 78c3a7156ddf06d5ab8551e6c5a9d56572e3b489

  • Merged origin/main (d38052695c2c8a2e67cdb2c1eb6f4c6651eabd4d).
  • npm run typecheck:control-plane: passed.
  • node --experimental-strip-types --test tests/control_plane_ts/quota_settlement_readback.test.ts tests/control_plane_ts/receipt_bound_wait.test.ts: 264 passed, 0 failed (covers default verified writebacks without boundary/checkpoint flags, spend_required, spend_receipt_required, completed spend staying open, and monitor precedence).
  • Focused Python settlement and boundary pytest suite (tests/control_plane/test_quota_authority_settlement_journey.py, tests/control_plane/test_refresh_settle_turn.py, tests/architecture/test_settlement_receipt_source_boundaries.py, tests/control_plane/test_post_writeback_wait_cli.py, tests/control_plane/test_host_adapter_settlement_partial_steps.py, tests/control_plane/test_unsettled_recovery_admission_bound.py, tests/control_plane/test_replan_quota_exhaustion.py, tests/control_plane/test_refresh_checkpoint_isolation.py, tests/control_plane/test_quota_settlement.py): 364 passed, 11 skipped (covers both file and sqlite authority backends, persistent unthrottled --settle-turn index conflict across default and in-flight boundaries, all CLI profiles with/without --todo-id, and remote_authority wait recovery).
  • Changed-path ruff check, scoped mypy (error_codes.py, spend_commit.py, and default pyproject.toml 17-file set), scripts/check_rfc_bilingual.py, loopx check (9 changed files, 0 errors/warnings), change-quality receipt cqr_8fad9883e398d9c778dc, and loopx canary premerge --from-git-diff --git-diff-base origin/main (6 direct checks, 10 catalog canaries, 8 risk-profile smokes, 1 public-boundary scan): passed (merge_gate_passed=true).

Validation after earlier sync

The prior PR head was 92c7b627d5e539b9304c23d35002d61e20b3cb2f, based on 287616201b81b53824cae570265220ab4142a4b7. The seven-file PR diff was byte-for-byte identical to the initial head 4433e1aed61c380d9118f230cc285243cd2a1a7e.

Validation on the prior head

  • Proposed head 4433e1aed61c380d9118f230cc285243cd2a1a7e integrates main 856cd6ad8fb93bcb8e3a4a1a2f98701da2b07cdc.
  • A synthetic competing process executed a real quota debit after the first preview. Both File and SQLite settled one original debit after a single conflict. Two consecutive conflicts kept the original writeback and owed command, with zero original debits. Both fixtures retained one original admission.
  • The existing lost-response, malformed-receipt, and wrong-binding cases still use exact readback.
  • Scope is the existing quota/refresh CLI composition, settlement_readback.ts replay phase classification, and their receipt-backed recovery tests. The transaction remains the accounting authority, and the existing CLI parser and immutable settlement identity guard the repeated command.

Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>

@loopx-agent loopx-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer: model_agent · gpt-6.2-sol · OpenAI (runtime_reported, xhigh)

Request changes conclusion (author-owned PR; GitHub blocks formal self-review)

[P2] 已写回的 Turn 在扣额冲突后,提示指向无法直接执行的写回模板。 在 File 和 SQLite 上提交原始写回,取得 settlement_owed.command,再让独立 spend 在该命令的预览与提交之间推进 run index。候选正确返回 index_digest_conflict 和 appended=false。按新提示用原 Goal、Agent、Turn 重跑 Codex App 的 quota should-run,返回 normal_run,保留原 effect,但没有 settlement_owed。给出的 next_cli_actions 只有带 <scale> 等占位符的 refresh-state 模板,原样执行两侧均退出 2。用已保存的原 settlement_owed.command 两侧均可结算,重放没有第二次扣额。请让冲突响应或其明确指向的同 Turn 读回路径投影现有回执负责的原扣额命令,并让回归从错误响应开始走到该命令。 新恢复提示 现有扣额命令 owner

动机 / Motivation

执行已完成写回的 Agent 遇到并发扣额冲突时,需要确认本次请求确已被拒绝,并继续同一次结算。基线把确定的竞争拒绝显示为通用状态采集错误,无法解释该执行是否写入。候选已修正诊断和零追加标志,真正按提示找回原扣额命令仍未闭环。评审覆盖真实本地 CLI 和隔离 File、SQLite,正式安装 Host 与其它受支持后端未实测。给定原扣额命令的回归已通过,续页和重读入口仍要能把该命令交给执行者。

改动思路 / Approach

保留现有事务拒绝与回执 owner,由 CLI 投影准确的失败原因。复用现有已验证回执的命令编排,保持原 effect,并让恢复入口只要求它已经持有的身份。评审覆盖真实本地 CLI 和隔离 File、SQLite,正式安装 Host 与其它受支持后端未实测。

具体改动 / Changes

精确提交 e82b86a53005afe54b2c5ec37ce1bfbbedbcaf41,基线 64353773dc8b1ca82ff531cc7653dec6c3d41c0b。一笔签署提交,四个文件 +75/-9。 回执契约

  • typed-rejection 已通过。事务拒绝继续使用共享的 QuotaRunIndexConflict,CLI 继承同一 reason code,回读确认只有竞争请求追加。
  • same-effect-once 已通过。执行已经可用的原扣额命令可收口一次,重复执行给出原结算身份并且不追加。
  • recovery-guidance 待修。候选测试通过再次运行已有写回取得旧命令。本评审从 CLI 错误引导首次读回,确认普通 Codex App 结果只给后续写回模板,遗漏可直接执行的既有扣额命令。

对主干的风险 / Risks

作者新增回归在基线两侧均为通用错误,在候选两侧通过。补做真实 CLI 竞争序列,File 和 SQLite 都复现提示缺口,原始扣额命令在同两条链路均成功收口且重放无追加。标准本机 premerge 的 6 项直接检查与 16 项选中检查通过。词表检查最初缺 TypeScript 依赖,复用同 lockfile 的现有依赖后通过。输出预算 smoke 初跑超时,单独重跑通过。无绑定扣额的两条独立竞争用例也通过,重新预览后可继续。扩展测试最初在仓库内建临时目录,导致两条 gitless 用例在基线与候选同因失败。移到仓库外后,两侧四例均通过。未查询托管 CI。

我的整体评价 / Verdict

REQUEST_CHANGES。 保留类型化冲突诊断。按文档公开的原结算身份,从失败响应走到可执行的已有扣额命令,并在回归中核对这一入口和仅一次扣额。

English verdict: REQUEST_CHANGES at e82b86a. The CLI correctly identifies the rejected spend, but the advertised same-Turn recovery returned only a placeholder writeback template on both File and SQLite.

Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
@loopx-agent loopx-agent changed the title Preserve quota spend index conflict diagnostics Retry a definitively rejected Turn quota spend Nov 22, 2026
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>

@loopx-agent loopx-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Request changes conclusion (author-owned PR; GitHub blocks formal self-review)

Reviewer: model_agent · Gemini · Google · self_reported

动机 / Motivation

受影响对象: 在多线程/多进程并发写入同一 Goal 的 runs/index.jsonl 期间执行 quota spend-slot 或 refresh-state --settle-turn 的 Agent 与维护调度器。

前后场景对比: 改动前(基线 2876162),quota spend-slot 遇 runs/index.jsonl 摘要 CAS 冲突会落入通用状态采集异常(error_code=quota_unexpected_collection_error,appended=null),无法确认本次请求是否已扣额,且 refresh-state --settle-turn 会在一次并发写入后直接失败。改动后(精确提交 92c7b62),CLI 能准确区分并报告 index_digest_conflict(appended=false),refresh-state --settle-turn 对单次索引冲突可自动重跑一次并幂等收口;但按失败指引使用相同 Turn 身份重跑 quota should-run 时,对于常规写回待扣额场景仍退回 normal_run 与占位 refresh-state 模板,未返回已验证可执行的原 quota spend-slot 命令。

可观测结果与边界: 类型化错误码(index_digest_conflict)、appended=false 零追加保证以及 refresh-state --settle-turn 单次并发自动重试均在 File 与 SQLite 验证通过;但同 Turn quota should-run 恢复在默认进度写回(replay_phase=open 且 progress.state=spend_required)下仍未闭环。 非目标: 本次不改写分布式存储并发模型或取消 runs/index.jsonl 摘要 CAS 乐观锁校验,也不自动回滚竞争进程已合法记账的配额消耗。 剩余缺口: 默认未携带 --delivery-boundary in_flight_continuation 或 --completion-todo-id 的普通 Todo 进度写回(与 test_spend_index_conflict_keeps_its_diagnostic_and_retries_the_same_turn 所测路径及 --settle-turn 非限流持久冲突后一致)在 spend_required 状态下,同 Turn 重跑 quota should-run(含 --codex-app、--runtime-profile generic_cli 与普通模式)均仍返回 normal_run 与占位写回命令而非 settlement_owed.command。

改动思路 / Approach

PR #9180 在首次评审头 e82b86a53005afe54b2c5ec37ce1bfbbedbcaf41 的基础上合入了基于同 Turn 重试恢复的主干提交,形成了两层处理机制:第一层是在 CLI 错误出口识别 TypeScript quota.spend.commit 返回的 index_digest_conflict 并给出区分绑定与非绑定扣额的恢复建议;第二层是在组合结算命令 refresh-state --settle-turn 中利用 CAS 拒绝证明零扣额的语义,在超时预算内安全再拉起一次同身份 quota spend-slot 子进程。

机制 职责分类 归属边界 激活与默认值 失败与恢复语义
spend_commit._quota_spend_commit_result 异常转换与语义透传 spend_commit.py 始终生效 将 TS EffectRuntimeConflict(index_digest_conflict) 转为 QuotaRunIndexConflict
quota_failure_report.quota_failure_payload 类型化错误投影 quota_failure_report.py quota spend-slot 遇 QuotaRunIndexConflict 时生效 返回 error_code=index_digest_conflict、appended=False 与恢复指令
refresh_settlement 同 Turn 单次重试 组合结算幂等重试 refresh_settlement.py refresh-state --settle-turn 首次遇 exact-match conflict 且预算未耗尽 若仍冲突则返回 state=spend_required 与 settlement_owed.command
同 Turn quota should-run 恢复边界 既有读回耦合缺口 settlement_readback.ts / live_decision.py 依赖 replay_phase == settlement_pending 未闭环:常规 progress.state == spend_required 时 replay_phase == open,重跑退回 normal_run

架构归属与当前边界: 复用了现有 QuotaRunIndexConflict 异常类、quota_failure_report.py 统一错误出口以及 refresh_settlement.py 的子进程单次重试边界,并将 CAS 判断权威保留在既有 TypeScript quota.spend.commit;未发明第二套并发锁或重试队列。但同 Turn 读回仍受制于 replay_phase 与 progress.state 的不一致边界。当前 PR 范围涵盖 CLI 冲突错误投影、refresh_settlement.py 单次同 Turn 安全重试与契约文档补充;须在已有 settlement_pending / same-Turn 恢复路径中覆盖 progress.state=spend_required 且 replay_phase=open 的场景(并用 _guard 纳入回归测试)后才算完整闭环。

具体改动 / Changes

精确头 92c7b627d5e539b9304c23d35002d61e20b3cb2f 相对基线 287616201b81b53824cae570265220ab4142a4b7 共改动 7 个文件(+198 / -25):生产代码修改 quota_failure_report.py、refresh_settlement.py、error_codes.py、spend_commit.py,补充契约文档 docs/quota-allocation.md,并在 test_quota_authority_settlement_journey.py 与 test_refresh_settle_turn.py 新增回归测试。

关键代码讲解

  1. QuotaRunIndexConflict & spend_commit._quota_spend_commit_result:保留既有 QuotaRunIndexConflict(ValueError) 错误类并映射到 error_codes.py 的 index_digest_conflict 出口;当 TS quota.spend.commit 在异常或结果体中报告 index_digest_conflict 时直接抛出该类型化异常,确保上层 CLI 不再吞没为 quota_unexpected_collection_error。
  2. quota_failure_report.quota_failure_payload:捕获 QuotaRunIndexConflict 后将 status、appended=False 与原因精确写入 JSON 负载,并在 recommended_action 中明确提示"绑定扣额应以原 Turn 身份重跑 quota should-run 并跟随返回结算命令;非绑定扣额须先重新获取预览再重试"。
  3. refresh_settlement:在子进程运行 quota spend-slot 收到精确匹配的 index_digest_conflict(且 ok is False、appended is False、mode == "spend-slot"、goal_id 一致、尚余超时时间)时仅再执行一次同一命令,利用 TS quota.spend.commit 幂等重放或重取最新索引摘要完成结算。
  4. 遗留边界对照 settlement_readback.ts#L1599-L1608 & live_decision.py#L1223-L1233:refresh-state 若未传入 --delivery-boundary in_flight_continuation、--completion-todo-id 或 --agent-vision-json(这正是 quota should-run --codex-app 默认模板生成且 test_spend_index_conflict_keeps_its_diagnostic_and_retries_the_same_turn 实际执行的写回格式),即使写回成功且 progress.state == "spend_required",replayPhase 仍计算为 "open",导致 live_decision.py 跳过 unsettled_host_turn_recovery 与 settlement_owed 挂载。

规范对照(docs/quota-allocation.md @ 287616201b81b53824cae570265220ab4142a4b7)

以基线提交 287616201b81b53824cae570265220ab4142a4b7 的 docs/quota-allocation.md(及前次审查记录 e82b86a53005afe54b2c5ec37ce1bfbbedbcaf41)为对照基准,并核查本 PR 对该文档的增量描述:

  • QIC-1(implemented):明确拒绝 index_digest_conflict 并报告 appended: false 且无并发错账——由 spend_commit.py#L114-L129、quota_failure_report.py#L172-L182 及双后端绑定/非绑定实测验证。
  • QIC-2(implemented):refresh-state --settle-turn 遇单次索引冲突安全重试一次且不重复扣额——由 refresh_settlement.py#L189-L202 与 test_refresh_settle_turn.py 6 项冲突用例(含 once/persistent × file/sqlite)验证。
  • QIC-3(not_met):绑定扣额冲突后"以相同 Turn 身份重跑 quota should-run 并跟随其返回的结算命令"——未满足:在本 PR 自带的 test_spend_index_conflict_keeps_its_diagnostic_and_retries_the_same_turn 夹具路径下重跑同 Turn quota should-run,File 与 SQLite 均仅返回 normal_run 与 refresh-state ... --settle-turn --settlement-receipt 占位模板。

对主干的风险 / Risks

[P2] 默认写回待扣额状态下,按 CLI 错误提示以同 Turn 身份重跑 quota should-run 仍丢失原扣额命令

  • 触发状态与复现路径: 按 PR #9180 自带回归 test_spend_index_conflict_keeps_its_diagnostic_and_retries_the_same_turn 的前序步骤(或无 --delivery-boundary 的普通 refresh-state --settle-turn 在充足配额 allowed_slots=10 下遇持久索引冲突):先由 quota should-run --codex-app 准入 Todo Turn,再执行 refresh-state(无 --delivery-boundary in_flight_continuation / --completion-todo-id / --agent-vision-json)提交进展写回;此时 settlement_progress.state == "spend_required",若直接执行其返回的 quota spend-slot 则正常结算为 "settled",若该命令遇 index_digest_conflict,随后按 quota_failure_report.py#L178-L179 与 docs/quota-allocation.md 指引,以同一 Turn 身份重跑 quota should-run。
  • 实际观测结果(File 与 SQLite 均复现):
    • 当该 Turn 为非限流(allowed_slots=10)且 replay_phase == "open"、progress.state == "spend_required" 时,无论是 --codex-app(带或不带 --todo-id)、--runtime-profile generic_cli 还是普通 quota should-run,均返回 decision="run"、effective_action="normal_run"、settlement_owed=None,且 next_cli_actions 只提供占位写回模板 refresh-state ... --classification <validated_progress> ... --settle-turn --settlement-receipt,完全找不到原 quota spend-slot 命令。
    • 若此时开启新 Turn,后续 Turn 会因前轮仍处于 spend_required 进入 unsettled_host_turn_recovery 并要求重进原 Turn 守卫(quota should-run ... --turn-instance-id <原Turn> --todo-id <原Todo>),重新落回前述 normal_run 占位循环。作者回归在第 945 行调用 _refresh(...) 而非 _guard(...) 绕过了该实际入口。
    • 对照已通过分支: 若该写回附带 --delivery-boundary in_flight_continuation、todo complete(todo 已完成)或属于 autonomous_replan_required,因 replay_phase == "settlement_pending",同 Turn quota should-run 可正常返回 settlement_owed.command 并在再次执行后一次收口。但 quota should-run --codex-app 自己给普通 Todo Turn 打印的正是无 --delivery-boundary 的命令模板。
  • 最小修复与回归要求: 在同 Turn quota should-run 恢复判断(live_decision.py / settlement_readback.ts 相关读回逻辑)中,对已提交进展写回且 progress.state 为 spend_required / spend_receipt_required 的 Turn(即使 replay_phase 为 "open")暴露原 settlement_owed.command 与 unsettled_host_turn_recovery;并在 test_spend_index_conflict_keeps_its_diagnostic_and_retries_the_same_turn 补充调用 _guard(...)(含带/不带 --todo-id)及充足配额下的持久 --settle-turn 冲突恢复回归。

基线对照与本地验证摘要

  • 基线 vs 候选冲突语义(PASS):
    • 基线 287616201b:绑定 quota spend-slot 索引冲突返回 rc=1, error_code="quota_unexpected_collection_error", status="quota_collection_failed", appended=null。
    • 候选 92c7b627d5:绑定与非绑定(不同 source/slots 避免 effect_id 自碰撞)冲突均返回 rc=1, error_code="index_digest_conflict", status="index_digest_conflict", appended=false;autonomous_replan_required、todo_done、in_flight_continuation 三类恢复分支在 File 与 SQLite 均一次恢复收口;refresh-state --settle-turn 单次冲突在默认/in-flight 均 attempts=2 结算且无重复扣额。
  • 测试与工具链检查:
    • pytest -q tests/control_plane/test_quota_authority_settlement_journey.py tests/control_plane/test_refresh_settle_turn.py:142 passed, 10 skipped(全为非 Windows os.name != "nt" 跳过的 PowerShell 用例);冲突定向复跑 -k "spend_index_conflict or recovers_only_one_rejected_index_write":6 passed。
    • ruff check(6 个变更 Python 文件)与 mypy:PASS(0 错误)。
    • loopx canary premerge --tier standard --from-git-diff --git-diff-base 287616201b...:direct/catalog(10)/risk(8)/boundary(1) 共 19 项全部 PASS(0 失败);严格模式因只读工作树缺变更质量收据返回 receipt_missing。未查询远程托管 CI。

我的整体评价 / Verdict

  • 长程与用户体验评估: 长程维度 not_yet_proven(底层 CAS 拒写与 --settle-turn 单次重试有效避免了并发重复扣额,但普通 Todo Turn 在 spend_required 且 replay_phase=open 时按错误提示重跑同 Turn 守卫仍会退回占位模板并与后续 Turn 的 unsettled_host_turn_recovery 互相跳转);用户体验维度 regression(quota_failure_report.py#L178-L179 文档化的自恢复路径在默认写回路径尚未全部走通)。视觉评审: 纯 Python 控制面 CLI 与文档改动,不涉及仪表盘或桌面渲染视图,已核对 diff 文件清单确认无任何渲染层改动。 未覆盖边界: 无前端渲染变动;仅未运行真实已安装外部宿主进程端到端集成(本地隔离 File/SQLite CLI 实测覆盖)。
  • 可观测语义与变更体量: 本 PR 成功消除了基线 quota_unexpected_collection_error 误报,但新文档与错误引导声明的同 Turn quota should-run 恢复语义在 replay_phase=open 分支尚未完整兑现(observable_semantics: not_yet_proven);7 文件 +198/-25 控制在最小必要范围,复用已有错误码与重试结构(code_volume: necessary,change_proportionality: proportionate,架构评估 retain — 复用了现有 QuotaRunIndexConflict 异常类、quota_failure_report.py 统一错误出口以及 refresh_settlement.py 的子进程单次重试边界,并将 CAS 判断权威保留在既有 TypeScript quota.spend.commit;未发明第二套并发锁或重试队列。但同 Turn 读回仍受制于 replay_phase 与 progress.state 的不一致边界。当前 PR 范围涵盖 CLI 冲突错误投影、refresh_settlement.py 单次同 Turn 安全重试与契约文档补充;须在已有 settlement_pending / same-Turn 恢复路径中覆盖 progress.state=spend_required 且 replay_phase=open 的场景(并用 _guard 纳入回归测试)后才算完整闭环。)。未新增或篡改语义词表(semantic_alignment: not_applicable),无隐蔽越权或新持久化状态。
  • 残余风险: 除上述 P2 阻塞项外,非 Windows 环境未运行 10 项 PowerShell 用例,且未实测真实安装宿主与 PostgreSQL 服务端并发竞争。
  • 结论: 请打通 progress.state == "spend_required"(含 replay_phase == "open")在同 Turn quota should-run 中返回原 settlement_owed.command 的路径,并在 test_spend_index_conflict_keeps_its_diagnostic_and_retries_the_same_turn 实测 _guard(...) 后重新评审。

English verdict: REQUEST_CHANGES at 92c7b62. Typed index_digest_conflict reporting and single-retry settle-turn recovery work, but rerunning quota should-run with the same Turn identity per the CLI guidance still returns normal_run without settlement_owed when a standard Todo writeback leaves replay_phase=open and spend_required on both File and SQLite.

@loopx-agent loopx-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approval conclusion (author-owned PR; GitHub blocks formal self-approval)

Reviewer: model_agent · Gemini · Google · self_reported

动机 / Motivation

受影响主体与场景:在并发配额写入下调用 refresh-state --settle-turn、quota spend-slot --execute 或同轮重入 quota should-run(涵盖 --codex-app、--runtime-profile generic_cli、plain 以及 remote_authority 等待分支)的智能体宿主与运维调用方。

改动前:并发扣减触发 index_digest_conflict 时 --settle-turn 单次失败;且默认未传 --delivery-boundary in_flight_continuation 或 --completion-todo-id 的 refresh-state 写回后虽为 spend_required,却因 replay_phase 仍为 open 而导致同轮重入 quota should-run 返回 normal_run 且丢失 settlement_owed.command。改动后:单次 CAS 冲突在共享 60 秒超时内自动重试一次并结算;持久冲突或普通写回后同轮重入 quota should-run 均稳定识别 settlement_pending 并返回 unsettled_host_turn_recovery(repair = quota_spend)及原 settlement_owed.command。

可验证结果:确定性 index_digest_conflict 始终返回 appended = false,--settle-turn 最多单次重试;在 File 与 SQLite 双后端上,默认边界及持久冲突后的同轮 quota should-run(含无 --todo-id、generic_cli、plain 与 remote_authority)均恢复原扣减命令并仅扣减一次配额,已完成扣减但未完成 Todo 的轮次保持 open。

非目标边界:本 PR 不对响应丢失或结果不明的扣减请求做盲目自动重试,不改变已完成扣减但未完成 Todo 的 open 回放语义,也不绕过配额账本 CAS 摘要校验或授予任何自动合并权限。

改动思路 / Approach

架构取舍与保留理由:把 CAS 冲突识别与单次安全重试保留在 Python 事务/CLI 边界,并将待扣减相位收口进 TypeScript 结算回读单一事实源(settlement_readback.ts),避免在下游路由与等待逻辑中产生重复判断。

当前 PR 边界:配额索引 CAS 冲突诊断与 --settle-turn 有界单次重试,以及 settlement_readback.ts 对已验证写回后仍欠扣减轮次的 settlement_pending 相位收敛。

flowchart LR
  W["已验证写回 writeback.failure === null"] --> S{"spend.failure !== null ?"}
  S -- "否(已扣减且无完成或接受检查点)" --> O["replay_phase = open(保持原语义)"]
  S -- "是(spend_required / spend_receipt_required)" --> SP["spendPendingAfterWriteback = true -> replay_phase = settlement_pending"]
  SP --> R["同 Turn 重入 quota should-run(全 profile 与 remote_authority)"]
  R --> REC["unsettled_host_turn_recovery (repair = quota_spend) + 原 settlement_owed.command"]
Loading

注:基于精确提交 78c3a7156ddf06d5ab8551e6c5a9d56572e3b489 中 readQuotaSettlementFromRequest 与 receiptBoundReplayPhase 逻辑推导的说明性流程;实测运行结果见下文验证记录。

之所以没有在 live_decision.py 中绕过 replay_phase 去特判 progress.state == 'spend_required',是因为 settlement_readback.ts 才是 replay_phase 的单一事实源(codex_execution_preparation.py、blocked_wait.ts 和 remote_authority 等待门控都直接消费它)。在 readQuotaSettlementFromRequest 中直接由 writeback.failure === null && spend.failure !== null 推导出 spendPendingAfterWriteback,同时严格保留了 monitorPhase === 'settled' 的最高优先级和“已完成扣减但未完成 Todo/检查点仍为 open”的既有不变量。

具体改动 / Changes

规范依据:docs/quota-allocation.md(基线提交 d38052695c2c8a2e67cdb2c1eb6f4c6651eabd4d)。准则映射:CAS-RETRY-01 -> implemented(error_codes.py#L35 与 refresh_settlement.py#L189-L199);PENDING-SPEND-REPLAY-02 -> implemented(settlement_readback.ts#L1602-L1606)。

关键代码讲解

  1. QuotaRunIndexConflict(loopx/control_plane/quota/error_codes.py#L35 与 loopx/control_plane/quota/spend_commit.py#L213):当 record_quota_slot_spend_from_preview 在提交前检测到运行索引摘要已被并发修改,直接抛出带 reason_code = "index_digest_conflict" 的强类型异常,确保未写入任何扣减记录前快速失败;同时在 loopx/cli_commands/quota_failure_report.py#L172-L182 输出 appended: false 与明确的同 Turn 重试指引。
  2. settle_refreshed_turn 与 _run_owed_spend(loopx/cli_commands/refresh_settlement.py#L103-L200):仅当调用方显式启用 --settle-turn,且首次子进程精确满足 returncode == 1、ok is False、appended is False、error_code == status == "index_digest_conflict"、mode == "spend-slot"、goal_id 一致且原 60 秒共享超时仍有余量时,才用完全相同的 settlement_owed 命令重试一次。若再次冲突或结果不明,立刻停止重试并回读权威回执。
  3. readQuotaSettlementFromRequest / spendPendingAfterWriteback(loopx/control_plane/quota/settlement_readback.ts#L1602-L1606):在调用 receiptBoundReplayPhase 前计算 spendPendingAfterWriteback = writeback.failure === null && spend.failure !== null 并并入 writeback_completes_binding。这一步直接修复了前序审查指出的 [P2] 漏洞:无论 refresh-state 是否携带 in_flight_continuation 或 completion_todo_id,只要写回已验证而配额扣减(或其 rollout 事件回执)仍欠缺,就判定为 settlement_pending,从而让 live_decision.py#L661 与 #L1223 稳定路由到 repair = "quota_spend"。
  4. 回归测试与文档(tests/control_plane_ts/quota_settlement_readback.test.ts、tests/control_plane/test_quota_authority_settlement_journey.py、tests/control_plane/test_refresh_settle_turn.py、docs/quota-allocation.md):同步更新中英文说明文档;调整 malformed 负例断言以匹配现代 spend_required -> settlement_pending 不变量(不再把欠费写回标为 open),并补充 File/SQLite 双后端及 TS 单元测试覆盖默认边界、持续 unthrottled CAS 冲突、全 CLI profile(含无 --todo-id)与 remote_authority 等待路径。

对主干的风险 / Risks

  • 历史 outcome_gap 无合格免扣证明用例相位变化:当一条 outcome_gap 写回既无合法 blocked_retry 又未扣减(如 quota_settlement_readback.test.ts 的 malformed / unscheduled 用例)时,progress.state 本就是 spend_required,本次修复使其 replay_phase 从过时的 open 变为与语义一致的 settlement_pending。这对主干安全有益(防止新准备工作把已写回欠费的 Turn 当成 open)。
  • 已完成扣减与监控先行场景隔离:反例检查确认 spend.failure === null(已扣减但无完成回执/检查点)时 spendPendingAfterWriteback 为 false,继续保持 replay_phase = "open";monitorPhase === "settled" 仍在 settlement_readback.ts#L1603 优先返回 settled。
  • 语义词表与边界检查:generate_semantic_inventory.py 对全 diff 检测 supported candidates: 0,未新增状态枚举;check_rfc_bilingual.py、ruff、mypy、loopx check(9 个改动文件 0 报错/0 警告)及 canary premerge(19/19 与变更质量回执 cqr_8fad9883e398d9c778dc)全部通过。

我的整体评价 / Verdict

在 long_horizon 维度上为 improved(默认边界下并发冲突不再导致同 Turn 重入丢失欠费扣减命令);在 user_experience 维度上为 improved(CAS 冲突诊断更明确、单次重试自动恢复、无需调用方手工补传可选边界参数);visual_review 为 not_applicable(CLI and control-plane settlement changes only; no rendered web dashboard or UI presentation files were modified. / 未涉及界面变更,unverified_scope: none)。

在精确头提交 78c3a7156ddf06d5ab8551e6c5a9d56572e3b489 上完成本地全量验证:npm run typecheck:control-plane 通过;node --experimental-strip-types --test tests/control_plane_ts/quota_settlement_readback.test.ts tests/control_plane_ts/receipt_bound_wait.test.ts 264 项全部通过;9 个配额/结算核心 pytest 测试集共 364 passed, 11 skipped(仅无本地 Postgres 服务的集成用例跳过,File 与 SQLite 全路径均已实测通过);(注:全量 npm run test:control-plane 未在最终合并提交后重跑;合并 origin/main 与测试更新前的全量跑次中 6729 项通过,仅因 d2fbe4bbe1 遗留的 content_digest_single_owner.test.ts 固定名单缺失 execution_loss_closeout_record.ts 失败,与本 PR 无关。)observable_semantics、code_volume(necessary)、change_proportionality(proportionate / retain)、default_off_isolation(isolated)、authority_semantics(aligned)及 semantic_alignment(aligned,reuse_existing)均已核验通过,此前 [P2] 阻塞项已彻底解决且未发现新阻塞问题。依作者自建 PR 的 GitHub 规则发布 COMMENTED 结论;PR 保持 OPEN。

English verdict: APPROVE

@huangruiteng
huangruiteng merged commit ad3873e into main Nov 22, 2026
14 of 17 checks passed
@huangruiteng
huangruiteng deleted the codex/quota-spend-index-conflict-20261121 branch November 22, 2026 10:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants