Skip to content

fix(agent): preserve interrupt handoffs when reordering queued messages - #7205

Open
me2seeks wants to merge 2 commits into
mainfrom
fix/queue-reorder-handoff
Open

me2seeks wants to merge 2 commits into
mainfrom
fix/queue-reorder-handoff

Conversation

@me2seeks

@me2seeks me2seeks commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Passed 10 focused stop/handoff tests, 6 session history tests, migration initialization/upgrade/reopen tests, and the migration lock check.
  • The state-layer upgrade test opens a v52 database containing a persisted old-style reorder and verifies routing to the original interrupted Run after v53 migration and replay.
  • Confirmed the pending handoff query uses the indexed position range. Confirmed the published v52 capsule contains an ordinary delivered enqueue and the new assertion detects missing timestamp backfill. cargo check -p maka-cli --test upgrade_compat passed; the full current-version CLI capsule roundtrip passed. Full CLI VERIFY against the published v52 nightly capsule (producer 600e617fa497) 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 hit agent_workspace_unavailable during live continuation; Ubuntu did not reproduce that workspace error.
  • Independent review approved commit 7209923d99. Large-root migration duration and peak disk use have not been measured.

AI use

  • Generative tooling made a substantive contribution

Maka (ChatGPT) implemented the projection repair and tests and performed independent review.

@github-actions github-actions Bot added the effort/L Under 1000 readable lines label Nov 23, 2026

@M4n5ter M4n5ter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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() in plugins/agent/state/src/queue/sql.rs to reach across module boundaries into session_history's private agent_history_queue_requests index (which queue::rebuild() does not maintain) and execute two queries (EXISTS + JOIN).
  • interrupt_handoff() to keep decoding position - i64::MIN and joining back to agent_queue_events + contents with json_extract(CAST(b.payload AS TEXT), ...).
  • upgrade_compat.rs to 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)) stores position only to discard it in for (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 calls pending(&requests[0]) and SELECT count(*), and inside the loop each request calls pending() (SELECT entry_json, state + serde_json::from_str) followed by another SELECT position on the same row. Since lane and position are native columns, a single SELECT request, position FROM agent_queue_items WHERE session=? AND state='pending' AND lane=? ORDER BY position, request gives the lane count, membership, and ordered priority_prefix with zero JSON deserialization—and simplifies the validation to if check && !requests.starts_with(&priority_prefix).
  • Migration 53 scope & cursor hygiene: repair_reordered_projections() runs rebuild() on every session that ever recorded a reorder, even sessions that never had a resume_after_interrupt event. If keeping the current schema, scoping the query to sessions with both reorder and resume_after_interrupt (and collecting session IDs into a Vec<String> before calling rebuild()) 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) and upgrade_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:
    1. Rejecting a reorder that swaps two pending interrupt handoffs (the priority.windows(2) path).
    2. Upgrading a v52 database whose persisted agent_queue_events actually contains a historical invalid order such as Reorder([b, interrupt, a]) (the current upgrade test only writes the valid [interrupt, b, a] order and manually corrupts position via raw SQL, so the check = false replay recovery of a reordered handoff is not actually exercised).
  • reorder_keeps_enqueue_times_and_repairs_duplicate_positions (129 lines) injects an artificial UPDATE agent_queue_items SET position=0 statement leftover from an earlier draft instead of testing observable behavior, while omitting entry_enqueued_at after Promote (which also previously overwrote position).

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 回表 JOIN agent_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 断言几乎原样重复。
  • 两个真正关键的行为边界反而漏测了:
    1. 两条 pending interrupt handoff 同时存在时,互换它们的顺序应被拒绝(代码里的 priority.windows(2) 分支)。
    2. v52 历史 agent_queue_events 里真实落盘了一条把普通消息排在 handoff 前面的旧顺序(如 Reorder([b, interrupt, a]))时,升级走 check = false 重放能把 handoff 拉回最前(当前升级测试只录了本身就合法的 [interrupt, b, a],再手动 SQL 改 position 模拟损坏)。
  • 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 校验报错方式一致,不算本次回归,顺带提一下)。

me2seeks and others added 2 commits November 23, 2026 21:20
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)
@M4n5ter
M4n5ter force-pushed the fix/queue-reorder-handoff branch from 7209923 to 7fd9183 Compare November 23, 2026 13:28

@M4n5ter M4n5ter left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/L Under 1000 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants