Repository navigation
perf(quota): collapse cold-start todo.read waterfall and planning RPCs - #9552
loopx-agent wants to merge 1 commit into
Conversation
Share effect_runtime_request_scope across quota should-run status collection and decision building so fresh canonical snapshots reuse head-checked todo.quota_planning.project batching (with fail-closed reload on StaleCanonicalQuotaSourceError). Scope single-role todo.read query projections to the requested role and lazy-compute lineageFacts, and coalesce planning_inventory summary page reads into a single request. Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
loopx-agent
left a comment
There was a problem hiding this comment.
Reviewer: model_agent · Gemini · Google · self_reported
Approval conclusion (author-owned PR; GitHub blocks formal self-approval)
English Verdict: APPROVE
独立核验结论:在无阻塞性缺陷、未变更任何规范决策语义与持久化边界的前提下,批准合入。下文所有数据与代码引用均基于
509360fb0d3e9e6e578ddf5c12db587886016b23与bd9932c72a83b939019d08220f14da7fe6a75ad1的实测对比及逐行源码审计。
动机 / Motivation
问题与触发场景: 高频调用 loopx quota should-run 进行调度准入判断的本地协调编排器与调度器,以及按单角色执行 todo.read (kind="query") 的命令行查询调用方。
改动前后对照(Before / After): 改动前(baseline 509360fb0d3e):quota should-run 先通过 collect_status 触发完整 todo.read (canonical_fields),随后脱离同一请求作用域调用 build_live_quota_should_run_decision,导致 select_quota_todo_contexts 失去同作用域原像指纹与头校验基础,只能再次发起全量 todo.read (quota_projection);同时 planning_inventory 对选定任务、可运行候选与更高优先级不可用候选分别发起多次 todo.context.page,read_projection.ts 在单角色 kind="query" 下仍全量评估双角色分组并提前计算跨角色 lineageFacts 与未消费的 standing 决策。改动后(HEAD bd9932c72a83):handle_quota_command 为 should-run 建立覆盖 collect_status 与 build_live_quota_should_run_decision 的 effect_runtime_request_scope(),仅在 status 非磁盘缓存命中时启用 reuse_fresh_canonical_snapshot=True,走轻量 todo.quota_planning.project (todo_quota_planning_batch_v0) 并由 TS 侧执行头校验与 rollout_log_stat 守卫;若并发写入导致 StaleCanonicalQuotaSourceError,立即重读非缓存 collect_status 并关闭快照复用 fail-closed 重试。单角色 todo.read 仅投影目标角色并延后 lineageFacts 计算;planning_inventory 将多次 compact_todo_summary_items 合并为单次批处理。
可观测收益与证据边界: 在独立的 File 与 SQLite 规范存储对比验证中,完整 CLI loopx quota should-run --dry-run 在保留 64 个规范输出键零语义漂移的前提下,将单次冷启动 Effect RPC 总数从 52 次降至 50 次(todo.read:quota_projection 1->0 替换为轻量 todo.quota_planning.project:todo_quota_planning_batch_v0 1 次,todo.context.page 从 7 次降至 5 次;独立 build_quota_planning_inventory_request 压实调用从 2 次降至 1 次),并在盘中并发修改 Todo 状态时自动触发 StaleCanonicalQuotaSourceError 回退至最新 todo_a_run_2。若保持现状不改,每次冷启动准入检查都会重复一次重型全量 Todo 重建与多轮分页 RPC 往返,持续放大调度检查尾延迟,而通过受请求作用域约束的轻量批处理与单次重读兜底即可在零权威退化的前提下消除该冗余开销。
边界与非目标(Non-goals): 本 PR 不修改持久化权威存储格式或 CLI 输出 schema,不缓存跨进程持久快照,也不取消 todo.quota_planning.project 对 provider_revision、cursor 与 rollout_log_stat 的强一致校验。
改动思路 / Approach
整体思路是在不新增第二权威或改变任何控制面判决语义的前提下,把“同一命令生命周期内重复跨进程重建已知规范状态”的路径收口到既有所有者内部:
- 入口作用域打通与 fail-closed 兜底(Python CLI -> Live Decision -> TS Batch Head Check):
handle_quota_command在检测到quota_command == "should-run"时开启外层effect_runtime_request_scope(),使collect_status与build_live_quota_should_run_decision共享同一次请求指纹(todo_projection_request_identity())与todo.context.page进程内去重缓存。仅当cache_metadata未命中时才通过签名探测向build_live_quota_should_run_decision传入reuse_fresh_canonical_snapshot=True,驱动select_quota_todo_contexts走todo.quota_planning.project并核验provider_revision、cursor与rollout_log_stat。一旦发生并发修改抛出StaleCanonicalQuotaSourceError,立即调用不走磁盘投影缓存的collect_status(..., include_presentation_projections=False)并移除该复用参数重试。 - 只读查询去冗余(TS
read_projection.ts): 当且仅当kind === "query"、selection == null且明确指定单一角色"user"或"agent"时,仅评估目标角色并跳过未消费的standing_decision_authority;lineage仍保留全量双角色记录且resume_lineage在存在resume_when时保留跨角色全集。 - 规划候选批处理合并(Python
planning_inventory.py): 拆出_raw_runnable_action_candidates与_raw_unavailable_higher_priority_candidates,将原本分散在selected、候选队列及不可用更高优先级列表中的compact_todo_summary_items合并为单次批处理并按引用切片回填。
flowchart LR
S["handle_quota_command(should-run): 开启 request scope"] --> C["collect_status 产出带 identity 的源摘要"]
C --> F{"cache_metadata.hit == True ?"}
F -- "是(缓存命中)" --> FULL["reuse=False: 直接走 todo.read:quota_projection"]
F -- "否(新鲜读)" --> BATCH["reuse=True: todo.quota_planning.project + TS head/rollout_log_stat 校验"]
BATCH -- "通过(零并发写入)" --> INV["planning_inventory 合并单次 compact_todo_summary_items"]
BATCH -- "并发写入抛出 StaleCanonicalQuotaSourceError" --> RETRY["重读非缓存 collect_status 并 pop(reuse) 重试"]
RETRY --> INV
示意图(基于 exact head bd9932c72a83b939019d08220f14da7fe6a75ad1 源码 quota.py、quota_should_run.py 与 read_transaction.ts 梳理,仅用于流程说明,非独立执行或测试证明)。
架构边界评估(Architecture Assessment): 三处优化均复用既有 TypeScript 与 Python 所有权边界,未引入并行状态机或缓存权威;快照复用作为可选即时边界,遇到缓存命中、并发变更或签名不兼容时均 fail-closed 退回既有全量路径。 当前 PR 边界严格限定在单次请求作用域内的瞬时快照复用、planning_inventory 批处理合并及无持久化变化的单角色只读投影裁剪,不扩展至跨命令或跨进程缓存。 失败语义上,快照复用路径属于瞬时优化而非独立持久通道:一旦校验失败,系统确定性退回全量读并重放一次完整决策;无额外写副作用或孤立残留状态。
具体改动 / Changes
- 规范引用判定(
spec_basis):no_spec(spec_source: none)——本次 PR 属于运行时冷启动 RPC 扇出优化,无独立书面 RFC 或协议修订文档(相关读写合约仍受既有单拥有者与规范新鲜度不变量约束)。 - 变更构成: 共 7 个文件(
+582 / -29),其中 5 个核心运行时与控制面文件(+121 / -29)与 2 个回归测试文件(+461 / -0),无无关 docs/目录改动或公共边界越界。
关键代码讲解
-
loopx/cli_commands/quota.py:378—handle_quota_command(execute()内分支 L409-418)
在args.quota_command == "should-run"时用with effect_runtime_request_scope():包裹_execute_quota_command,使状态采集、execute_quota_should_run、reentry重入及后续收据回写全程维持同一个_REQUEST_RUNTIME_REVISION指纹。既有设计已保证collect_status本身独立使用该作用域;将其提升至整条should-run执行期后,select_quota_todo_contexts可确认摘要同源且直接复用todo.context.page作用域内结果。 -
loopx/cli_commands/quota_should_run.py:410—execute_quota_should_run(L523-545)
通过fresh_status = not bool(cache_metadata and cache_metadata.get("hit") is True)精确区分新鲜状态与磁盘投影缓存命中,并利用inspect.signature(decision_builder)检测显式参数或VAR_KEYWORD后注入reuse_fresh_canonical_snapshot=fresh_status(兼容未声明该参数的桩函数/测试替身)。捕获StaleCanonicalQuotaSourceError后立即调用collect_status(..., include_presentation_projections=False)(经核对status.py:1317直接构造实时读模型,不经磁盘投影缓存)、更新execution.status_payload、弹出reuse_fresh_canonical_snapshot后 fail-closed 重算决策。 -
loopx/control_plane/quota/live_decision.py:306—build_live_quota_should_run_decision(L339, L441)
新增默认关闭参数reuse_fresh_canonical_snapshot: bool = False,仅将其透传至build_quota_should_run/select_quota_todo_contexts,确保未经过should-run新鲜度判定的其他调用方保持原有默认行为不变。 -
loopx/control_plane/todos/read_projection.ts:280—projectCanonicalTodoFields(L286-324)
识别singleRoleQuery = input.kind === "query" && input.selection == null && (query.role === "user" || query.role === "agent")时,将循环收敛为[String(query.role)],并在kind === "query"下跳过未在todoListPayload消费的projectStandingDecisions。同时通过canonicalTodoReadItems(original)保留全量all与lineage上下文,resolveLineageFacts()按需延迟求值;且仅当当前角色条目含resume_when时才构建完整双角色resume_lineage,对于未知/非法角色(如role="bogus")singleRoleQuery为false,仍交由selectTodoReadFields按原样拒绝。 -
loopx/control_plane/work_items/planning_inventory.py:179—build_quota_planning_inventory_request(L25-56, L179-224)
将原本在构建候选切片阶段各自调用的compact_todo_summary_items抽取为_raw_runnable_action_candidates与_raw_unavailable_higher_priority_candidates(并保留原quota_runnable_action_candidates/unavailable_higher_priority_candidates公共包装签名以兼容外部调用方),在顶层build_quota_planning_inventory_request内收集[selected, *agent_todo_source_items, *raw_runnable, *raw_unavailable]统一压实后再映射回对应位置与可选元数据,保证产物字节级等价。
对主干的风险 / Risks
本次审核未发现阻断合入的 [P1] / [P2] 缺陷。围绕边界条件与残余风险核查如下:
-
并发写入与缓存陈旧风险(已验证 fail-closed 闭合):
- 当
status命中磁盘缓存(cache_metadata.hit === True)时,fresh_status严格为False,绝不复用缓存中可能已陈旧的权威指纹。 - 当
collect_status至build_live_quota_should_run_decision之间发生并发写入或 rollout 日志追加时,TS 侧projectCanonicalQuotaBatch(read_transaction.ts#L304-314)在 File 与 SQLite 后端均校验provider_revision、cursor及rollout_log_stat,实测触发quota_canonical_source_changed-> PythonStaleCanonicalQuotaSourceError-> 无复用二次重算后切换选定最新任务todo_a_run_2。 - 单一重试边界假设:
execute_quota_should_run在except StaleCanonicalQuotaSourceError分支内弹出reuse_fresh_canonical_snapshot后重试decision_builder会退回 TSreadCanonicalQuotaProjection;若极小窗口内在重算collect_status与该次原子读取之间连续发生第二次并发写入,readCanonicalQuotaProjection会继续按quota_canonical_source_changedfail-closed 报错而非吞错继续,由外层 CLI/调度器处理,符合失败不降级原则。
- 当
-
单角色
todo.read(kind="query") 非目标角色校验语义微调(无阻断、可接受,已在observable_semantics披露):- 对比
origin/main与 HEAD 发现:在单角色查询(如loopx todo list --role user)且目标角色无resume_when时,TS 侧跳过对另一角色(如agent)调用projectTodoReadGroup/evaluateTodoResumeConditionsFromSource。因此若人工破坏另一角色文件写入不合法todo_id(不满足/^todo_[a-z\d_-]{3,64}$/)或损坏resume_when,--role user在 HEAD 会成功返回有效用户列表(rc=0),而改动前会连带拒绝;但规范写入路径均已在落盘前强校验字段,且不带--role的全量列表或指定--role agent查询仍会触发同一校验拒绝。 - 另有一处极微小的可进一步简化点(非阻塞
[P3]):read_projection.ts:309在items.length === 0时传入lineage_facts: undefined,而projectTodoReadGroup(read_projection.ts:180)遇到input.lineage_facts == null时仍会执行lineage.map(successionFacts),后续可顺手省去空列表场景下的该次遍历。
- 对比
-
本地验证汇总(所有验证均在
bd9932c72a83b939019d08220f14da7fe6a75ad1独立工作树实测完成,未等待远程 GitHub CI):- TypeScript:
npm run typecheck:control-planePASS(0 errors);node --experimental-sqlite --experimental-strip-types --test tests/control_plane_ts/todo_read.test.ts tests/control_plane_ts/quota_selection.test.tsPASS(53 passed, 0 failed, 0 skipped);关联 5 个 TS 测试文件(含todo_quota_closure、content_digest_single_owner、todo_summary_projection等)PASS(85 passed, 0 failed);额外 6 个关联 TS 文件(含todo_context_projection、quota_run_decision、quota_summary_transaction等)PASS(93 passed, 0 failed)。 - Python 单测与架构守卫:
test_quota_should_run_waterfall.py+test_status_prequota_hotpath_efficiency.py+test_quota_closeout_query_failure.py+test_effect_turn_live_quota_decision.pyPASS(69 passed);tests/control_plane/*planning*.pyPASS(259 passed);tests/architecture/+tests/canary/test_maintainability_ratchet.py+ 5 个 quota/frontier/handoff 测试 PASS(2030 passed)。 - 静态检查与门禁:
ruff checkPASS;mypy --no-incremental --follow-imports=silent对[tool.mypy]17 个严格文件 +live_decision.py+planning_inventory.py共 19 个文件 PASS(0 errors),cli_commands/quota.py与quota_should_run.py仅余 5 个基线同源既有报错(未新增错误);check_rfc_bilingual.pyPASS;loopx check --scan-path ...7 个文件 PASS(0 errors, 0 warnings);loopx canary premerge --tier standard下4/4direct checks +py_compile+10/10catalog canaries +8/8risk profile smokes 全部 PASS(manual_holds=0;整体退出状态quality_receipt_missing因临时复核工作树未生成本地 change-quality 收据,属评审环境边界)。 - 基线 vs HEAD 反事实对比: File 与 SQLite 后端真实
loopx quota should-run --dry-run输出经标准化后 64 个核心字段 0 差异,RPC 稳定由52 -> 50、todo.context.page由7 -> 5、todo.read:quota_projection1->0 替换为todo.quota_planning.project1 次;盘中通过真实 CAS 修改todo_a_run_1状态时,两端点均精准触发StaleCanonicalQuotaSourceError并在重试切换为todo_a_run_2;build_quota_planning_inventory_request独立调用由 2 次 RPC 合并为 1 次且产物完全等价。
- TypeScript:
我的整体评价 / Verdict
- 长程与用户体验评估(Outcome Impact):
- long_horizon (
improved): 消除quota should-run每轮重复重建全量 Todo 视图与分散分页压缩 RPC 的冷启动放大问题,同时借助StaleCanonicalQuotaSourceError在并发写入或 rollout 日志推进时 fail-closed 回退重算,跨轮恢复与状态机一致性完整保持,无卡死或静默陈旧选优风险。 - user_experience (
preserved/visual_review: not_applicable): 命令行入参、错误诊断码(含非法角色拒绝)与 JSON 输出结构与基线保持一致,单次命令延迟降低而无需人工干预。CLI 与控制面只读投影/RPC 批处理优化,无渲染 UI 或视觉布局变更。(unverified_scope:none)。
- long_horizon (
- 代码体量、可简化性与语义词汇归属:
- 变更集中(核心 runtime +121/-29,测试 +461),未新增持久状态字段或新协议名;所涉及的
reuse_fresh_canonical_snapshot属既有控制面内部参数,read_projection.ts与planning_inventory.py均复用了现有所有权与词汇体系(semantic_alignment:aligned/reuse_existing,无需新注册表项或 RFC 更新)。
- 变更集中(核心 runtime +121/-29,测试 +461),未新增持久状态字段或新协议名;所涉及的
- 最终结论: APPROVE(exact head
bd9932c72a83b939019d08220f14da7fe6a75ad1;无阻塞性缺陷,所有改动不变量均已由本地多后端测试与反事实对比直接验证。注意:若合入前团队按流程要求,仍需在合入前生成与该精确 head 匹配的本地change-quality收据及按目标分支策略完成门禁检查)。
loopx-agent
left a comment
There was a problem hiding this comment.
Reviewer: model_agent · gpt-6.2-sol · OpenAI · runtime_reported · xhigh
Approval conclusion (author-owned PR; GitHub blocks formal self-approval)
动机 / Motivation
受影响的是每轮启动先执行 quota should-run 的本地 Agent,特别是有跨角色等待条件或大量候选待办的 Goal。 基线构造状态后再次完整读取 Todo 投影,并分别为选中、备选和不可用工作压缩摘要。 普通守卫要求从当前 Todo 状态选到可执行工作。若 Status 刚读完就出现新的用户审批门,守卫必须丢弃旧视图并退回等待处理。 新路径避免重复完整投影和一批摘要调用,并在来源变动时重新读取同一 Goal。真实配对中可执行选择和现行门禁保持一致。 此次覆盖源码 CLI、File 和 SQLite。本机小夹具用来核对调用与可见决策,实际大工作区、冷 worker 和 PostgreSQL 性能另行测量。
改动思路 / Approach
按请求固定现有 Effect 运行时版本,让本轮 canonical 快照可以复用。通过原生 head 检查确认新鲜度;检查失败时重新读取并回到完整投影。 继续使用单一 TypeScript 选择和权威状态所有者。查询按显式角色投影,依赖仍从完整跨角色谱系核对。Python 在既有投影入口集中提交摘要。 复用同一批摘要的大小切分规则。跨角色门禁和来源证据继续从原提供者取得。
具体改动 / Changes
精确提交 bd9932c72a83b939019d08220f14da7fe6a75ad1,目标基线 509360fb0d3e9e6e578ddf5c12db587886016b23。7 个文件,+582/−29。核对实际后端配对(matched-real-backend-measurement)、新鲜度拒绝(canonical-freshness)和跨角色投影与规划(cross-role-query-and-planning)。优化验收规范
关键代码讲解
handle_quota_command。在同一次 should-run 中复用原有逻辑请求作用域。 源码execute_quota_should_run。仅对新采集状态尝试轻量复用,来源变化后回到完整投影。 源码projectCanonicalTodoFields。显式单角色查询仅渲染该角色,复用跨角色谱系与原选择逻辑。 源码build_quota_planning_inventory_request。把候选批量压缩后按原类别切分,保留每行来源和不可用原因。 源码test_quota_should_run_uses_head_checked_canonical_reuse_and_single_role_parity。真正读到 File 和 SQLite 权威数据与使用轻量路径。 源码
对主干的风险 / Risks
File、SQLite 两种真实 CLI 均从 49 减至 48 次 Effect RPC。一个完整 quota_projection 被轻量检查投影代替,摘要 RPC 从 6 降至 5。守卫决定及选中 Todo 在配对中一致。原有跨角色谱系、单角色和空角色回归通过。 在真实 Status 之后、实际 guard 之前经权威 CAS 将已完成用户门重新打开。File 与 SQLite 均尝试复用、发现版本变化、改用新状态并返回 operator_gate_notify。两者都拒绝正常交付。
语义与 CI 对齐
两种后端真实 CLI 都保留 todo_agent_primary 与 normal_run。每臂五次交替取样,复用常驻 worker。File 的中位数 338.87→347.23 ms,SQLite 330.91→325.81 ms。该样本支持 RPC 减量。
69 项定向 Python 回归、259 项规划回归、53 项 TypeScript 回归、2 项独立的并发 CAS 门禁验证、控制面 TypeScript 编译、Ruff 和 git diff --check 均通过。原严格 mypy 的 17 个输入在基线和候选均产生 3,992 条既有诊断,唯一差异是两处改动模块中的既有诊断行号平移。
五次常驻样本的双边耗时变化较小。File 样本慢约 8 ms,SQLite 快约 5 ms。它们无法验证作者大工作区的宣布幅度、进程冷启动或 PostgreSQL 性能。标准预合并为作者报告,本轮独立验证为上述定向范围。
我的整体评价 / Verdict
APPROVE。 调用减少已在两个真实后端复现,独立并发读写对照保留用户门禁。 在相同两后端的真实守卫入口插入受控 CAS,原快照可运行而当前快照新增全局用户门,断言首次复用后用新状态返回操作员门禁。
English verdict: APPROVE at bd9932c. Paired File and SQLite source-CLI runs reduce Effect RPC count from 49 to 48 and retain the same decision. An interleaved authoritative gate update prevents normal delivery on both backends. The small warm samples do not establish a broader latency gain.
Summary
Reduces cold-start Effect RPC fan-out and projection latency on
loopx quota should-runwhile preserving fail-closed canonical freshness and full cross-role semantics:loopx/cli_commands/quota.py,loopx/cli_commands/quota_should_run.py,loopx/control_plane/quota/live_decision.py):quota should-runexecution ineffect_runtime_request_scope()acrosscollect_statusandbuild_live_quota_should_run_decision, forwardingreuse_fresh_canonical_snapshot=Truewhenstatuscache was not a cache hit (via signature/**kwargsdetection).select_quota_todo_contextsto use lightweighttodo.quota_planning.project(todo_quota_planning_batch_v0) with head checks instead of falling back to a fulltodo.read(kind="quota_projection").StaleCanonicalQuotaSourceErrorinexecute_quota_should_run, reloads uncachedcollect_status, and retries fail-closed without snapshot reuse.todo.readkind="query"projection (loopx/control_plane/todos/read_projection.ts):targetRolesand skips unusedstanding(standing_decision_authority) extraction onkind="query".lineageFactslazily only when the rendered items referencesource_goal_idorsource_todo_id.loopx/control_plane/work_items/planning_inventory.py):compact_todo_summary_itemsrequest instead of repeatedtodo.context.pagecalls.Paired Benchmark (
quota should-run --dry-run, cleanorigin/mainvs PR head)Measured over 3 sequential CLI invocations against a connected local workspace state:
origin/main(509360fb0d3e)todo.readcountquota_projectionreadtodo.read:quota_projection: 352.5–564.9 mstodo.quota_planning.project: 183.1–226.0 mstodo.read:query(2 calls)todo.context.pagecountVerification
npm run typecheck:control-plane: 0 errorsnode --experimental-strip-types --test tests/control_plane_ts/todo_read.test.ts tests/control_plane_ts/quota_selection.test.ts: 53 passed, 0 failed (including File + SQLite parity and single-role cross-role lineage tests)uv run --extra test python -m pytest -n 4 -q tests/control_plane/test_quota_should_run_waterfall.py tests/control_plane/test_status_prequota_hotpath_efficiency.py tests/cli_commands/test_quota_closeout_query_failure.py tests/control_plane/test_effect_turn_live_quota_decision.py: 69 passed (covers File & SQLite head-checked canonical reuse, stale canonical mutation recovery, single-role parity, and single-RPC planning inventory)uv run --extra test python -m pytest -n 4 -q tests/control_plane/*planning*.py: 259 passeduv run --extra test ruff checkon touched Python files: passeduv run --extra test mypy --follow-imports=silent([tool.mypy]17 strict files +live_decision.py/planning_inventory.py): 0 errorsuv run --extra test loopx canary premerge --from-git-diff --git-diff-base origin/main: passed (standardtier: 4/4 direct checks, 10/10 catalog canaries, 8/8 risk smokes, 0 failures,manual_holds=0)loopx check --scan-path ...): 0 errors, 0 warnings