Repository navigation
Conversation
M4n5ter
left a comment
There was a problem hiding this comment.
English
The underlying bugs are real (old Reorder clobbered negative interrupt-handoff position values and broke entry_enqueued_at), and the core fix works. However, there are several design, implementation, and test-quality issues worth addressing before merging:
1. Schema / data model: decouple position instead of patching around i64::MIN + revision
agent_queue_items is a disposable projection, and this PR already pays the cost of adding Migration 53 (with a comment-only 0053_queue_reorder_projection.sql and a Rust data migration). Continuing to overload position as a magic i64::MIN + revision pointer forces:
entry_enqueued_at()inplugins/agent/state/src/queue/sql.rsto reach across module boundaries intosession_history's privateagent_history_queue_requestsindex (whichqueue::rebuild()does not maintain) and execute two queries (EXISTS+JOIN).interrupt_handoff()to keep decodingposition - i64::MINand joining back toagent_queue_events+contentswithjson_extract(CAST(b.payload AS TEXT), ...).upgrade_compat.rsto hardcode(-9223372036854775807 - 1)in raw SQL.
Adding explicit enqueued_at INTEGER NOT NULL DEFAULT 0 and interrupted_run TEXT columns to agent_queue_items in Migration 53 (passing at: UnixMillis into project(), which both write() and rebuild() already have) would make entry_enqueued_at() a single primary-key lookup, interrupt_handoff() a direct single-table read, and PendingSteerRevision / Reorder check interrupted_run IS NOT NULL instead of relying on negative-position encoding—leaving position strictly for ordering.
2. Implementation cleanup in plugins/agent/state/src/queue/sql.rs
- Dead tuple element in
Reorder:ordinary.push((position, request))storespositiononly to discard it infor (position, (_, request)) in ordinary.iter().enumerate(). This looks like a leftover from an earlier draft that tried to reuse old slots (also reflected in the PR summary's mention of duplicate slots). - Redundant per-item queries & JSON parsing in
Reorder: Before the loop it callspending(&requests[0])andSELECT count(*), and inside the loop each request callspending()(SELECT entry_json, state+serde_json::from_str) followed by anotherSELECT positionon the same row. Sincelaneandpositionare native columns, a singleSELECT request, position FROM agent_queue_items WHERE session=? AND state='pending' AND lane=? ORDER BY position, requestgives the lane count, membership, and orderedpriority_prefixwith zero JSON deserialization—and simplifies the validation toif check && !requests.starts_with(&priority_prefix). - Migration 53 scope & cursor hygiene:
repair_reordered_projections()runsrebuild()on every session that ever recorded areorder, even sessions that never had aresume_after_interruptevent. If keeping the current schema, scoping the query to sessions with bothreorderandresume_after_interrupt(and collecting session IDs into aVec<String>before callingrebuild()) reduces unnecessary replay and failure blast radius.
3. products/maka/cli/tests/upgrade_compat.rs assertion does not catch the target bug
The added check filters WHERE q.position < 0, whereas the old Reorder bug overwrote handoffs to position >= 0 (0, 1, 2, ...). If Migration 53 failed to repair a clobbered handoff, this query would still return 0 and pass. In addition, upgrade_compat.rs doesn't exercise queue reorder or interrupt handoffs in its capsule yet. Recommend removing this check (or only adding an effective assertion once the capsule actually exercises the scenario).
4. Test quality & ratio in plugins/agent/state/src/store/stop_tests.rs
Tests account for ~84% of the added lines (427 lines in stop_tests.rs + 19 in upgrade_compat.rs vs. ~60 lines of core Rust logic), with heavy copy-paste and artificial SQL state injection:
reorder_preserves_interrupt_handoff_through_delivery_and_rebuild(115 lines) andupgrade_repairs_old_reorder_handoff_before_queue_is_used(177 lines) duplicate most of the setup, reorder, rebuild, termination, admission, and handoff checks.- Two important behavioral edge cases are still missing:
- Rejecting a reorder that swaps two pending interrupt handoffs (the
priority.windows(2)path). - Upgrading a v52 database whose persisted
agent_queue_eventsactually contains a historical invalid order such asReorder([b, interrupt, a])(the current upgrade test only writes the valid[interrupt, b, a]order and manually corruptspositionvia raw SQL, so thecheck = falsereplay recovery of a reordered handoff is not actually exercised).
- Rejecting a reorder that swaps two pending interrupt handoffs (the
reorder_keeps_enqueue_times_and_repairs_duplicate_positions(129 lines) injects an artificialUPDATE agent_queue_items SET position=0statement leftover from an earlier draft instead of testing observable behavior, while omittingentry_enqueued_atafterPromote(which also previously overwroteposition).
Suggest replacing these 3 tests with 2 concise behavioral tests sharing a small helper: (1) live reorder with multiple handoffs + ordinary entries and entry_enqueued_at across Reorder / Update / Promote, and (2) v52 -> v53 upgrade replaying a persisted historical Reorder([b, interrupt, a]) event.
5. Minor API note
QueueEntry from controls.rs::queue() still reports both interrupt handoffs and ordinary follow-ups as QueueKind::Followup, so callers of edit_queue (Reorder) cannot tell upfront which entries are pinned; rejecting a move surfaces as StoreError::InvalidTransition rather than QueueRejection::InvalidEdit (matching existing reorder validation behavior, so not a regression here, just worth noting).
简体中文
这个 PR 修的确实是真实 bug(老 Reorder 会把负数 interrupt handoff 的 position 刷成 0, 1, 2...,导致 handoff 丢失并把 entry_enqueued_at 打挂),核心路径也能跑通,但设计、实现细节和测试质量还有几个比较明显的问题建议处理一下:
1. Schema / 数据模型:既然已经发了 Migration 53,建议顺手给 position 解耦,别再继续围着 i64::MIN + revision 打补丁
agent_queue_items 本身是可重建的派生投影表,这个 PR 也已经承担了新增 Migration 53 的成本(目前 0053_queue_reorder_projection.sql 只有注释,加了一个 Rust data migration)。继续保留 position = i64::MIN + revision 的魔术编码带来了几个很别扭的连锁反应:
plugins/agent/state/src/queue/sql.rs里的entry_enqueued_at()跨模块去读session_history私有的agent_history_queue_requests索引表(queue::rebuild()并不维护它),而且做了两次查询(先EXISTS再JOIN)。interrupt_handoff()仍然要靠position - i64::MIN回表 JOINagent_queue_events+contents做json_extract(CAST(b.payload AS TEXT), ...)。upgrade_compat.rs里甚至把(-9223372036854775807 - 1)硬编码进了 SQL。
如果直接在 Migration 53 给 agent_queue_items 加上显式的 enqueued_at INTEGER NOT NULL DEFAULT 0 和 interrupted_run TEXT 两列(把 at: UnixMillis 传进 project(),write() 和 rebuild() 手头都已经有这个值):entry_enqueued_at() 直接退化成单表主键点查,interrupt_handoff() 单表直读不再回表解析 JSON,PendingSteerRevision 和 Reorder 直接判 interrupted_run IS NOT NULL,position 回归纯粹的排序职责。
2. plugins/agent/state/src/queue/sql.rs 的实现清理
Reorder里的残留死字段:ordinary.push((position, request))存了position,但下面遍历是for (position, (_, request)) in ordinary.iter().enumerate()直接丢掉了(这也对应 PR 描述里那句略显突兀的 duplicate slots,像是前一版复用旧槽位草稿改回enumerate()后的残留)。Reorder的重复查询与 JSON 反序列化:循环前调了pending(&requests[0])和SELECT count(*),循环内对每个 request 又调一遍pending()(SELECT entry_json, state+serde_json::from_str),紧接着对同一行再发一次SELECT position。lane和position都是原生列,循环外一条SELECT request, position FROM agent_queue_items WHERE session=? AND state='pending' AND lane=? ORDER BY position, request就能一次拿齐数量、归属和有序的priority_prefix,0 次 JSON 解析,后面的校验也能直接简化成if check && !requests.starts_with(&priority_prefix)。- Migration 53 扫描范围与游标写法:
repair_reordered_projections()对历史上所有出现过reorder的 session 都跑全量rebuild(),哪怕该 session 从未有过resume_after_interrupt事件。如果保持当前表结构,建议只筛选同时包含reorder和resume_after_interrupt的 session,并先把 session 列表collect::<Vec<String>>()出来再调rebuild(),缩小重放范围与失败影响面。
3. products/maka/cli/tests/upgrade_compat.rs 新增断言抓不到目标回归
新增 SQL 只过滤 WHERE q.position < 0,但老 Reorder 破坏 handoff 的表现恰恰是把 position 覆盖成 >= 0(0, 1, 2...)。就算 Migration 53 完全没修复损坏行,这条断言依然会返回 0 并通过;而且 upgrade_compat.rs 当前的 capsule 里也没有跑 queue reorder / interrupt handoff 场景。建议移除这段空转断言(等 capsule 真正覆盖该场景时再补有效校验)。
4. plugins/agent/state/src/store/stop_tests.rs 测试占比过高且信噪比偏低
本次新增代码里测试占了约 84%(stop_tests.rs +427 行、upgrade_compat.rs +19 行,核心 Rust 改动仅约 60 行),且存在大量复制粘贴和人造 SQL 改库:
reorder_preserves_interrupt_handoff_through_delivery_and_rebuild(115 行)与upgrade_repairs_old_reorder_handoff_before_queue_is_used(177 行)大部分初始化、reorder、rebuild、terminate、admit 和 handoff 断言几乎原样重复。- 两个真正关键的行为边界反而漏测了:
- 两条 pending interrupt handoff 同时存在时,互换它们的顺序应被拒绝(代码里的
priority.windows(2)分支)。 - v52 历史
agent_queue_events里真实落盘了一条把普通消息排在 handoff 前面的旧顺序(如Reorder([b, interrupt, a]))时,升级走check = false重放能把 handoff 拉回最前(当前升级测试只录了本身就合法的[interrupt, b, a],再手动 SQL 改position模拟损坏)。
- 两条 pending interrupt handoff 同时存在时,互换它们的顺序应被拒绝(代码里的
reorder_keeps_enqueue_times_and_repairs_duplicate_positions(129 行)专门写了UPDATE agent_queue_items SET position=0去测前版草稿遗留的人造重复槽位,偏测内部实现;反而漏测了Promote后的entry_enqueued_at(此前Promote同样会覆盖position)。
建议把这 3 个测试整体删掉,抽一个小 helper 重写成 2 个精炼的行为测试:(1)多条 handoff + 普通消息的实时 reorder 行为,以及 Reorder / Update / Promote 后的 entry_enqueued_at;(2)v52 -> v53 升级重放历史非法顺序 Reorder([b, interrupt, a]) 的恢复行为。
5. 一点 API 侧的小提示
controls.rs::queue() 返回的 QueueEntry 目前把 interrupt handoff 和普通 followup 都标为 QueueKind::Followup,edit_queue (Reorder) 的调用方事前看不出哪些消息已锁定不可移动;触发拒绝时走的是底层 StoreError::InvalidTransition 而非 QueueRejection::InvalidEdit(与现有 reorder 校验报错方式一致,不算本次回归,顺带提一下)。
Rebased onto main (bumped migration 0053 -> 0054 after #7207). Generated-by: Maka (ChatGPT)
Extract shared test helpers in stop_tests.rs, drop the duplicate assert_state call, and slim down the reorder and v53->v54 upgrade tests while keeping full behavioral coverage. Generated-by: Maka (Gemini)
7209923 to
7fd9183
Compare
There was a problem hiding this comment.
LGTM! Thanks for decoupling enqueued_at and interrupted_run from position and simplifying Reorder and upgrade_compat. Rebased onto main (bumping the migration to 0054_queue_reorder_projection.sql after #7207) and consolidated the stop_tests.rs cases.
Summary
Reordering ordinary messages no longer changes their original enqueue time or moves interrupt handoffs. The durable queue projection now stores enqueue time and original interrupted Run separately from the ordering position. Enqueue time comes from the canonical event; the current frontier is still derived from run admission. Reorder loads the pending lane once and performs no per-entry JSON deserialization.
Migration 53 adds the fields and rebuilds the queue projections from canonical events and their timestamps in bounded pages, before Host admission. It restores handoffs damaged by historical reorder events. This is a one-time transaction, does not change the event or RPC wire formats, and does not add a hot-path cross-module read.
Verification
cargo check -p maka-cli --test upgrade_compatpassed; the full current-version CLI capsule roundtrip passed. Full CLI VERIFY against the published v52 nightly capsule (producer600e617fa497) passed on Ubuntu: the runtime ledger moved from v52 to v53, including the enqueue timestamp check and live continuation. On macOS, the same Linux-produced capsule passed migration and the queue projection check but hitagent_workspace_unavailableduring live continuation; Ubuntu did not reproduce that workspace error.7209923d99. Large-root migration duration and peak disk use have not been measured.AI use
Maka (ChatGPT) implemented the projection repair and tests and performed independent review.