Skip to content

Feature: 重构 Cancel 及支持 Steering 能力 - #377

Open
weimch wants to merge 1 commit into
mainfrom
feature/cancel_steering_support
Open

weimch wants to merge 1 commit into
mainfrom
feature/cancel_steering_support

Conversation

@weimch

@weimch weimch commented Nov 19, 2026

Copy link
Copy Markdown
Contributor
  • Cancel支持多进程部署,使用共享内存同步信号
  • 支持Steering插话能力,用户可以在Agent运行过程中插话
  • 修复A2A/AGUI不当使用Cancel内部方法的问题
  • 补充相关设计文档见docs/design/03-cancel-steering.md、及steering、多进程使用示例

@helloopenworld

Copy link
Copy Markdown
Contributor

AI Code Review

审查结论

通过

审查范围:905698c..d747fd1(Feature: 重构 Cancel 及支持 Steering 能力,48 文件 +4982/-1474,13 个测试文件)。计划符合度:Cancel 重构(_LocalManager/_SharedManager、共享内存控制面、Steering 队列、skipped tool_result 补全、AG-UI/A2A 集成)与设计文档 03-cancel-steering.md 一致实现,register/unregister 时序、struct 布局与锁设计经逐字节与并发路径核对无缺陷。主要风险:(1) 协作式取消在模型层无检查点,长 LLM 调用期间取消延迟并阻塞同线程新请求(MODERATE);(2) 文档承诺多 worker "自动 attach" 共享内存但 server 层无实现,默认配置下跨进程取消静默失败(MODERATE);(3) 僵尸进程/PID 复用导致崩溃后槽位无法回收(MODERATE);(4) A2A v0/v1 取消 drain 不对称(LOW);(5) 共享槽位释放竞态可能误伤新 run(LOW);(6) HITL 取消后 pending 状态残留(LOW)。测试充分性:新增测试覆盖取消事件时序(slot 先释放)、steering 隐藏事件与模型历史、共享内存并发分配、AG-UI 不再调用 execution.cancel(assert_not_awaited)、A2A v1 drain 断言,但与上述风险对应的模型层长调用中断、v0 drain、多进程端到端、僵尸进程回收场景无测试覆盖。未发现阻止合入的 SEVERE 缺陷,门禁结论:PASSED(3 个 MODERATE + 3 个 LOW)。

发现的问题

较低

trpc_agent_sdk/server/a2a/executor/_a2a_agent_executor.py:221-222

问题: 本次变更在 v0 executor(_a2a_agent_executor.py:219-222)删除了 is_run_cancelled 预检查、统一切换到新的协作式取消语义,但同一重构在 v1 executor(_a2a_agent_executor.py:353-357)已将 AgentCancelledEvent 处理从 return 改为 cancelled=True; continue 以 drain 生成器并关闭 OTel span(注释明确该意图),设计文档 §4.1 亦规定消费方必须 continue/aclose;v0 的 AgentCancelledEvent 分支(约 299-306 行)仍保留直接 return,属于废弃了主动中断能力却未同步修复的不完整迁移。

触发条件: 客户端经 A2A 协议 v0 发送取消请求,run 达成 AgentCancelledEvent。

实际影响: runner.run_async 生成器在 enqueue 取消事件后即被丢弃,未 drain 的生成器只能等 GC 时由 asyncgen finalizer 在另一 task/context 中关闭,产生 "Failed to detach context" 类 OTel 告警(与设计文档 §4.1 描述一致),并延迟释放 runner 资源。

修正方向: 将 v0 的 AgentCancelledEvent 分支改为与 v1 相同的 continue 模式:置 cancelled 标志、drain 生成器、在循环后 if cancelled: return,避免直接 return 遗弃生成器。

中等

docs/mkdocs/zh/cancel.md:76-77

问题: docs/mkdocs/zh/cancel.md:77 声称"多 worker 部署时,AgUiAgent 创建的 Runner 会自动 attach 共享内存",但全仓库 git grep 确认 trpc_agent_sdk/server/(含 ag_ui、a2a、a2a_v1 及插件层)无任何 init_shared_mem/_SharedMem.attach/_SharedManager 调用;_SharedMem.attach()(_shared_mem.py:130)类方法零调用点,仅 examples/bench 显式初始化。_public.py:49 的模块级单例默认是 _LocalManager,服务层取消/steering 全部经 Runner 落到该单例。

触发条件: 按文档描述以默认配置部署 AG-UI/A2A 多 worker(如 uvicorn workers>1)而未在 master 启动 worker 前显式调用 init_shared_mem();取消/steering 请求到达非 owner 进程。

实际影响: 取消失败时 AG-UI 仅 logger.debug 后返回 False(_agui_agent.py:497-500),A2A 向客户端发送误导性的 "No active task found to cancel",steering 返回 NO_ACTIVE_RUN——跨进程取消/插话在"默认配置"下静默失效,与文档 76-77 行承诺的"自动 attach"不符;Agent 继续运行,用户无法取消。

修正方向: 在服务层(如 server.serve() 入口或 AgUiAgent 构造/_plugin/_utils.py 路由启动处)支持自动检测并调用共享内存初始化,或删除文档中"自动 attach"表述,改为明确要求部署方在 master 先调用 init_shared_mem()(与 cancel.md:165/184/309 的既有说明一致),避免误导。

中等

trpc_agent_sdk/cancel/_shared_mem.py:90-100

问题: _shared_mem.py:90-100 的 pid_is_alive 仅用 os.kill(pid, 0) 探测进程存活,不区分僵尸进程(zombie 对 os.kill(pid, 0) 返回成功即 True),也不会因 PID 被内核复用给无关进程而失效。该判定被 _find_or_reserve(340-361)、allocate(322-338)与 find(407-429)用作槽位回收与活跃校验的依据,与设计文档 §5.6"worker 异常退出后下一次 allocate 直接回收 entry"的意图相左。

触发条件: 共享模式下运行进程被 SIGKILL/崩溃退出且父进程尚未 waitpid 收割(僵尸窗口),或收割后 PID 被无关进程复用。同 session 客户端重试发起新 run。

实际影响: 崩溃 run 的 entry 保持 RUNNING 状态无法回收,同 session 新 run 被误判"Session ... already has an active run"而拒绝(_shared_mem.py:327);entry 表持续泄漏直至 max_active_runs 满,此时无关 session 的 register_run 全部抛 RuntimeError: ... is full;PID 复用后 find 误判活跃使跨 worker 取消命中错误目标。

修正方向: pid_is_alive 增加对僵尸进程的识别(如 os.waitpid(pid, os.WNOHANG) 返回 (pid, 0) 时视为已退出,或通过 /proc/<pid>/stat 读取进程状态字段),并在 _find_or_reserve 的 owner 回收路径中使用同一判定;同时给 allocate 的重复检查补充 zombie 特判。

较低

trpc_agent_sdk/cancel/_shared_manager.py:72-86

问题: 共享模式(init_shared_mem 后)下,owner 侧的取消分支在 yield AgentCancelledEvent 之前即 unregister_run 释放槽位(runners.py:697-702,被测试 test_cancel_releases_slot_before_terminal_event 固化);但 _shared_mem.py:407-429 的 find 无法区分同一 entry 的新旧代际(generation 仅 owner 本地可知),_SharedManager.cancel_run(_shared_manager.py:83-86)对跨进程到达的迟到/重试取消请求可能命中已被同 session 新 run 复用的 entry 并成功 publish_cancel,误伤新 run;同一竞态下 owner 路径(_shared_manager.py:77-81)无条件返回 True,publish_cancel 失败被掩盖。

触发条件: run 1 被取消后(槽位已释放),同 session 快速发起 run 2(复用同一 entry,generation+1),期间另一 worker 对旧 run session key 的取消请求(HTTP 重试、cancel 与新消息并发、前端重复点击)在 run 2 存活期内到达。

实际影响: 无辜的 run 2 被错误取消:正常产出 AgentCancelledEvent、会话写入 "Detect user cancel" 取消 marker,用户新请求未完成即终止;调用方收到 True 却不知道取消信号已被新 run 消费。

修正方向: 在共享 entry 中记录 run 启动时间戳或由 owner 侧维护"最近释放"标记,find/publish_cancel 对刚释放且已被新一代复用的 entry 返回失败;或在 AgentCancelledEvent 中携带 generation,使非 owner 的 publish_cancel 能识别目标代际并拒绝跨代发布。

较低

trpc_agent_sdk/server/ag_ui/_core/_agui_agent.py:1250-1254

问题: 本次变更将 last_event_is_error 判定改为排除 AgentCancelledEvent(_agui_agent.py:1252-1254)以避免取消后误发 RunErrorEvent,但同一循环中 has_tool_calls 的 pending 写回逻辑(_agui_agent.py:905-926 的 if has_tool_calls and not has_error 分支)不受该新排除影响:HITL 工具调用场景下取消事件不记入 has_error,导致流中已出现的 ToolCallEndEvent 对应的 tool_call_id 被重新写入 session 的 pending_tool_calls,与刚在 cancel_run 中执行完毕的清空操作(_agui_agent.py:504-511)互相矛盾,且 _start_new_execution 的 finally(_agui_agent.py:944-957)检查 _has_pending_tool_calls 后保留已结束的执行状态不删除。

触发条件: AG-UI 客户端在 HITL 场景(工具调用已发出、等待用户结果提交)中断开 SSE 连接触发协作取消;后台任务在取消过程中已完成翻译 ToolCallEndEvent。

实际影响: session 的 pending_tool_calls 残留未清理、_active_executions 中保留已完成 task 的僵尸执行条目(占用 _max_concurrent 计数、stale 清理需等 600s),后续同线程请求虽不阻塞但会基于残留 pending 状态继续 HITL 流程,用户看到"取消未生效"的假象。

修正方向: 在 pending tool_call 写回条件中同步排除取消场景(如增加 not isinstance(last_event, AgentCancelledEvent) 或跟踪 cancelled 标志),或在 cancel_run 后由 _start_new_execution finally 依据是否发生取消决定保留/清理 execution,保证取消路径的 pending 清理不被后台写回逆转。

Comment on lines 221 to 222

runner = await self._resolve_runner()

session_key = SessionKey(runner.app_name, user_id, session_id)
if await is_run_cancelled(session_key):
logger.warning("Session %s is cancelled, rejecting new execution", session_id)
await event_queue.enqueue_event(
create_cancellation_event(
task_id=context.task_id,
context_id=context.context_id,
message_text="Session was cancelled",
))
return

await self._handle_request(context, event_queue)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

问题: 本次变更在 v0 executor(_a2a_agent_executor.py:219-222)删除了 is_run_cancelled 预检查、统一切换到新的协作式取消语义,但同一重构在 v1 executor(_a2a_agent_executor.py:353-357)已将 AgentCancelledEvent 处理从 return 改为 cancelled=True; continue 以 drain 生成器并关闭 OTel span(注释明确该意图),设计文档 §4.1 亦规定消费方必须 continue/aclose;v0 的 AgentCancelledEvent 分支(约 299-306 行)仍保留直接 return,属于废弃了主动中断能力却未同步修复的不完整迁移。

触发条件: 客户端经 A2A 协议 v0 发送取消请求,run 达成 AgentCancelledEvent。

实际影响: runner.run_async 生成器在 enqueue 取消事件后即被丢弃,未 drain 的生成器只能等 GC 时由 asyncgen finalizer 在另一 task/context 中关闭,产生 "Failed to detach context" 类 OTel 告警(与设计文档 §4.1 描述一致),并延迟释放 runner 资源。

修正方向: 将 v0 的 AgentCancelledEvent 分支改为与 v1 相同的 continue 模式:置 cancelled 标志、drain 生成器、在循环后 if cancelled: return,避免直接 return 遗弃生成器。

Comment thread docs/mkdocs/zh/cancel.md Resolved
Comment thread trpc_agent_sdk/cancel/_shared_mem.py Resolved
Comment on lines 1250 to +1254
session_id=input.thread_id,
new_message=new_message,
run_config=run_config):
last_event_is_error = trpc_event.is_error() and not trpc_event.get_function_responses()
last_event_is_error = (trpc_event.is_error() and not isinstance(trpc_event, AgentCancelledEvent)
and not trpc_event.get_function_responses())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

问题: 本次变更将 last_event_is_error 判定改为排除 AgentCancelledEvent(_agui_agent.py:1252-1254)以避免取消后误发 RunErrorEvent,但同一循环中 has_tool_calls 的 pending 写回逻辑(_agui_agent.py:905-926 的 if has_tool_calls and not has_error 分支)不受该新排除影响:HITL 工具调用场景下取消事件不记入 has_error,导致流中已出现的 ToolCallEndEvent 对应的 tool_call_id 被重新写入 session 的 pending_tool_calls,与刚在 cancel_run 中执行完毕的清空操作(_agui_agent.py:504-511)互相矛盾,且 _start_new_execution 的 finally(_agui_agent.py:944-957)检查 _has_pending_tool_calls 后保留已结束的执行状态不删除。

触发条件: AG-UI 客户端在 HITL 场景(工具调用已发出、等待用户结果提交)中断开 SSE 连接触发协作取消;后台任务在取消过程中已完成翻译 ToolCallEndEvent。

实际影响: session 的 pending_tool_calls 残留未清理、_active_executions 中保留已完成 task 的僵尸执行条目(占用 _max_concurrent 计数、stale 清理需等 600s),后续同线程请求虽不阻塞但会基于残留 pending 状态继续 HITL 流程,用户看到"取消未生效"的假象。

修正方向: 在 pending tool_call 写回条件中同步排除取消场景(如增加 not isinstance(last_event, AgentCancelledEvent) 或跟踪 cancelled 标志),或在 cancel_run 后由 _start_new_execution finally 依据是否发生取消决定保留/清理 execution,保证取消路径的 pending 清理不被后台写回逆转。

@helloopenworld

Copy link
Copy Markdown
Contributor

评审结论
PR #377 整体方向合理,但存在跨 worker 取消失效、文档与实现不符等问题。建议修复前两项后再合入。

PR 要做的事情
重构 Cancel 模块,引入 _LocalManager 和 _SharedManager。
使用 /dev/shm 共享内存支持同机多 worker 间传递取消信号。
新增 Steering,允许运行期间追加用户输入。
调整 Runner 生命周期,提前注册 run,并在取消后补齐 skipped tool response。
修改 AG-UI、A2A 集成,改为协作式取消。
增加多进程示例、设计文档和 Cancel/Steering 测试。
发现的问题
P1:跨 worker Cancel 无法唤醒等待中的 Remote A2A
非 owner worker 取消时只设置共享内存标志,没有设置 owner 进程中的 asyncio.Event:

_shared_manager.py:72-126
a2a_v1/_remote_a2a_agent.py:282-306
a2a/_remote_a2a_agent.py:165-189
当 owner 正阻塞在远程 SSE 的 cancel_event.wait() 时,取消不会生效,必须等到下一个 raise_if_cancelled() checkpoint;最坏可能等到 HTTP 读取超时。

建议让共享模式的等待逻辑同时轮询共享 cancel flag,或引入 owner 侧 watcher 将共享状态同步到 asyncio.Event。

P1:用户文档声明了尚未实现的接口
docs/mkdocs/zh/cancel.md:74-78 声称:

A2A、AG-UI 提供 POST /steering
AgUiAgent 创建的 Runner 会自动 attach 共享内存
但服务端没有对应 steering 路由,也没有自动初始化或 attach 逻辑。按此文档部署,多 worker Cancel/Steering 会静默退化为每进程本地状态。

应实现这些能力,或者明确要求 master 在 fork worker 前调用 init_shared_mem(),并删除 /steering 已可用的描述。

P2:A2A v0 没有 drain Runner generator
A2A v0 收到 AgentCancelledEvent 后直接 return:

a2a executor:298-306
而 v1 已改为继续 drain:

a2a_v1 executor:346-360
v0 可能把 generator 留给 GC 在其他 task 中关闭,导致 OTel context detach 告警和资源延迟释放。建议与 v1 对齐。

P2:AG-UI 取消后可能重新写回 pending tool call
取消先清空 pending_tool_calls:

_agui_agent.py:502-512
但后台流结束时,只要之前出现过 ToolCallEndEvent 且没有 RunErrorEvent,又会重新写回:

_agui_agent.py:893-930
随后 execution 会因为存在 pending tool 而被保留:

_agui_agent.py:943-957
HITL 场景下会出现取消后残留 pending 状态和 execution。建议显式跟踪 cancelled 状态,取消时禁止重新写回。

P2:崩溃 worker 的共享槽位可能无法回收
pid_is_alive() 只使用 os.kill(pid, 0):

zombie 进程仍会被认为存活;
PID 被复用后会把无关进程误认为原 owner。
相关判断用于 allocate/find,可能造成 session 永久被判定为 active、共享表逐渐耗尽,甚至将取消发送给错误代际的 run。

建议至少检测 /proc//stat 的 zombie 状态;要彻底处理 PID 复用,需要同时保存进程启动时间或其他 owner identity。

兼容性风险:公开 Cancel API 是破坏性变更
本 PR 移除了 is_run_cancelled、cleanup_run 等导出,并修改:

register_run:异步三参数 → 同步 SessionKey
cancel_run:返回 Event → 返回 bool
清理 API 和工具调用取消语义
如果不是 major release,应提供兼容层;否则至少增加 breaking-change 和迁移文档。

@weimch
weimch force-pushed the feature/cancel_steering_support branch from d747fd1 to a842c5a Compare November 19, 2026 11:35
@helloopenworld

Copy link
Copy Markdown
Contributor

AI Code Review

审查结论

不通过

审查范围:905698c..a842c5a,共 48 个文件(+5149/−1474),核心为 Cancel 控制面重构(本地/共享内存双管理器)与 Steering 插话能力,涉及 Runner 生命周期、LlmAgent 主循环、A2A/AG-UI 服务端集成和共享内存实现(/dev/shm + fcntl 锁 + generation 防 ABA)。

计划符合性:整体与设计文档 docs/design/03-cancel-steering.md 一致——双管理器切换、共享内存 cancel 标志与 steering 队列、取消分支先 unregister_run 再 yield AgentCancelledEvent、AG-UI 停止直接取消后台任务。测试新增约 1800 行,覆盖本地/共享管理器、跨进程 cancel/steering、Runner 集成与清理路径,对本变更的多数成功与失败路径有保障。

主要风险(详见评论):(1) destroy_shared_mem() 从外部重置全局 _manager,fork 子进程(多 worker 部署)调用时会把本进程与父进程共享的 _SharedManager 替换成 _LocalManager,父子随后看到不同控制面(SEVERE)。(2) _SharedMem.enqueue 在 count 字段异常(全满或污染)时对合法槽位一律返回 QUEUE_FULL,且与 drain 已有的 corrupted 恢复逻辑不一致,可能使 steering 永久失败。(3) AG-UI run() 的 finally 在 pending tool calls(HITL)时保留 _active_executions 条目,而 cancel_run 不再处理执行状态,取消了 run 的 HITL 场景会遗留 stale execution 直到超时清理,期间同 thread 新请求被阻塞。(4) AgUiAgent.cancel_run 构造独立 Runner 实例走全局 _manager,运行时 init_shared_mem()/destroy_shared_mem() 切换后其取消路径与 LlmAgent 检查的可能不是同一控制面。(5) A2A/A2A v1 移除「session 已取消时拒绝新执行」保护后,取消中的 session 可立即开启新 run,取消语义被削弱。(6) _SharedMem.find 在表并发修改时 struct.error 被整体吞掉返回 None,取消/steering 请求被静默丢弃。(7) fork 子进程继承 _master_lock_fd 并可能在 close 时释放父进程的 master 锁,破坏 master 互斥。

背景说明(非本变更引入,未列入评论):A2A v2(trpc_agent_sdk/server/a2a/executor/_a2a_agent_executor.py)在收到 AgentCancelledEvent 时 return 而不排空 runner 生成器,与设计文档「消费方要把生成器读到自然结束」的约定不符;该行为位于本次变更未触碰的既有代码(本变更仅删除了该文件的 import 与 is_run_cancelled 前置检查,并只对 a2a_v1 修复了排空问题),属变更前已存在的缺陷,建议后续单独修复。

测试充分性:新增测试对主流程覆盖良好,但存在缺口——没有覆盖共享内存 record 被污染后 enqueue/drain 的恢复路径、没有覆盖 destroy_shared_mem 在 worker 进程中切换回 local 的行为、没有覆盖 fork 子进程对 master 锁的继承。

门禁结论:存在 1 个 SEVERE 和 5 个 MODERATE 问题(详见评论),不满足合入门禁,建议修复后重新审查。评论均验证过变更根因、可达路径与具体影响。

发现的问题

严重

trpc_agent_sdk/cancel/_public.py:136-149

问题: destroy_shared_mem() 是无条件执行 _manager = _LocalManager() 的模块级状态替换,而设计文档明确多 worker 部署通过 fork 子进程继承 master 的 _SharedManager 实例。fork 出的 worker 进程调用 destroy_shared_mem() 时,会把本进程与父进程共享的 _SharedManager 实例替换成新的 _LocalManager,父进程仍持有旧的 _SharedManager。

触发条件: 多 worker 部署(init_shared_mem() 后 fork 出子进程),任一子进程在其 finally/退出路径调用 destroy_shared_mem()。

实际影响: 子进程与父进程的 cancel/steering 控制面分叉:父进程还能通过共享标志看到 cancel,但子进程的 raise_if_cancelled/send_steering 走的是进程内 _LocalManager,跨进程 cancel/steering 静默失效;子进程随后 register_run 的数据不再进共享表,父进程取消逻辑找不到该 run。

修正方向: 让 destroy_shared_mem() 检测当前进程是否 fork 子进程(如比对 _mem._pid 与 os.getpid()),仅在实际创建/master 进程才切换回 _LocalManager;或文档明确禁止 worker 进程调用(示例中 destroy_shared_mem() 只在 master 调用)。

中等

trpc_agent_sdk/cancel/_shared_mem.py:487-529

问题: drain() 和 enqueue() 的 count 上限判断不一致。当队列全满时 enqueue 直接返回 QUEUE_FULL,而 count 是共享内存里可能被污染的字段(设计文档专门设计了 corrupted 记录丢弃路径,见 drain 中 count > queue_size 的重置逻辑),一旦 entry 的 count 因并发或历史复用被写坏,enqueue 会把合法槽位也判定为满,导致该 entry 的 steering 永久不可写。

触发条件: 共享内存 entry 的 count 字段异常(进程崩溃后 generation 复用、结构布局错位或并发写)时调用 send_steering。

实际影响: 所有后续 steering 永久返回 QUEUE_FULL,用户插话在 run 剩余生命周期内不可用,且没有任何日志;与 drain 已有的 corrupted 恢复逻辑不一致。

修正方向: 在 enqueue 中对 count > queue_size 单独处理(参照 drain 的 reset 逻辑),对「count 非法」与「队列真满」区分处理,并在非法时重置 count 后继续入队或返回明确的异常状态。

中等

trpc_agent_sdk/server/ag_ui/_core/_agui_agent.py:1248-1254

问题: event_generator 在客户端断开时(asyncio.CancelledError 路径)经 finally 调用 cancel_run,其语义从原先「取消 ExecutionState 并移除执行条目」改为「通过 Runner.cancel_run_async 协作式取消,但不再触碰 _active_executions」。而 run() 的 finally 只在「无 pending tool calls」时才删除 _active_executions 条目;取消时若存在 HITL 待处理工具调用,执行条目会一直保留到 _cleanup_stale_executions 的超时清理。

触发条件: AG-UI 会话存在 pending tool calls(HITL)时客户端断开/取消。

实际影响: 被取消的执行条目长期留在 _active_executions,期间同 thread 的新请求会在 run() 开头等待它完成(existing_execution and not existing_execution.is_complete),新请求被无谓阻塞;_max_concurrent 并发限制也可能因此误判。

修正方向: 在 cancel_run 成功返回后,若对应 _active_executions[session_id] 已因取消结束,主动移除该执行条目(或让 run() 的 finally 在取消场景也清理条目),与移除前行为等价。

中等

trpc_agent_sdk/server/ag_ui/_core/_agui_agent.py:481-508

问题: AgUiAgent.cancel_run 用 self._create_runner(...) 新建一个独立 Runner 实例,取消请求通过进程内全局 _public._manager 传播。当多 worker 部署在 server.serve() 前调用了 init_shared_mem(),_manager 已切换为 _SharedManager,此时 AG-UI 的取消走共享路径(find + publish_cancel),与 LlmAgent 检查的共享标志一致;但若运行中后续调用 destroy_shared_mem(),_manager 会退回 _LocalManager,而 AG-UI 取消仍通过新建 runner 走 _LocalManager,此时 cancel_run 在本地 _runs 找不到该 session 的 run(run 由另一 worker 持有),返回 False,取消请求被静默丢弃。

触发条件: 多 worker 部署调用过 init_shared_mem() 后、或单进程从未初始化共享内存时,客户端断开触发 AG-UI cancel_run。

实际影响: 客户端断开后取消信号丢失,后台 LlmAgent 继续执行到自然完成(或直到超时),与「断开即取消」的既有行为偏离;cancel_wait_timeout 文档宣称的行为无法达成。

修正方向: 保证 AG-UI 取消请求与 LlmAgent 使用同一控制面(同一 _manager):共享模式下 cancel_run 应直接依赖 Runner.cancel_run_async 的共享路径,或在 _public.cancel_run 对 _SharedManager 的 find 失败时回落到 _LocalManager 查询。

中等

trpc_agent_sdk/server/a2a_v1/executor/_a2a_agent_executor.py:242-260

问题: A2A v1 与 A2A v2 均删除了 is_run_cancelled 前置检查(原代码在 _handle_request 前判断 session 已取消则拒绝新执行并发出 cancellation 事件),但 Runner.run_async 的注册逻辑只在 register_run 时检查「是否已有活跃 run」(RuntimeError),不再检查「上次取消的残留标志」。取消中的 session 结束前,新的执行请求会直接进入 run_async 启动新的 LLM 调用。

触发条件: session 处于取消中(已发布 cancel 但 owner 清理尚未完成)时,同一 session 发起新的 A2A 请求。

实际影响: 取消语义被削弱:用户在等待取消完成的窗口内发起的新请求会直接开始执行,与旧行为(拒绝新执行并返回 cancellation 事件)不一致;如果 _find_to_reserve 在持有期间把释放中的 entry 复用了,新 run 可能观察到旧的 cancel 标志。

修正方向: 保留「session 已取消时拒绝新执行」的语义:在 Runner.run_async 注册前(或 register_run 内)检查共享/本地前一次取消标志,若已取消则直接返回 AgentCancelledEvent 或抛出明确异常,并补充对应测试。

中等

trpc_agent_sdk/cancel/_shared_mem.py:407-429

问题: _SharedMem.find() 首次无锁扫描在非 owner 进程并发 allocate/release 时可能遇到 struct.error(entry 处于半写入状态)或 IndexError,整个异常被 except (OSError, ValueError, IndexError, struct.error) 捕获返回 None。此时取消请求被静默标记为「无活跃 run」。

触发条件: 另一个 worker 正在分配/释放 entry(锁内写状态)时,本 worker 调用 cancel_run/send_steering 走 find 路径。

实际影响: 并发高峰期的取消/steering 请求被静默丢弃(返回 False/NO_ACTIVE_RUN),调用方(A2A cancel、AG-UI 断开)误以为 session 无活跃 run,信号丢失;无法区分「确实无 run」与「表临时损坏」。

修正方向: 为 find 内部扫描加锁保护(用 lock_alloc 包住扫描或逐 entry 加锁),或在 struct.error 时 find 返回明确错误而非 None,让调用方重试。

较低

trpc_agent_sdk/cancel/_shared_mem.py:278-286

问题: _ensure_process_state() 在 fork 子进程内重建 _entry_locks 和 _alloc_lock,但 _master_lock_fd(create() 在 master 进程 open 的 LOCK_PATH fd)在子进程继承后,子进程的 close()(destroy_shared_mem 在 worker 中被调,或 _SharedMem.close 的对象析构)会先 fcntl.lockf(LOCK_UN) 释放锁再 close fd。lockf 语义上是进程级锁:任一持有同一 fd 的进程释放锁会影响整个 fd 上的锁状态,导致 master 的 master-lock 被子进程意外释放,另一个 master 进程趁虚而入重新 unlink/重建 segment。

触发条件: fork 的多 worker 部署中,worker 进程调用 _SharedMem.close()(或 destroy_shared_mem)——设计文档明确 worker 进程应只 close() 不 unlink。

实际影响: master lock 的互斥保证被破坏,可能出现两个进程同时成为 master、互相 unlink 对方 segment,导致运行中段被重建、活跃 run 丢失。

修正方向: 在 _ensure_process_state() 或 _SharedMem.__init__ 中,fork 子进程把 _master_lock_fd 置为 None(不继承/不释放父进程的 lock fd),worker 只 close 自己的 mapping,不动 master lock。

Comment thread trpc_agent_sdk/cancel/_public.py Resolved
Comment on lines +487 to +529
def drain(self, slot: _Slot) -> List[Content]:
"""Take all steering messages from ``slot`` in FIFO order."""
if self._closed:
return []

try:
with self.lock_entry(slot.entry_index):
view = self.entry_view(slot.entry_index)
state, generation, _owner_pid, digest, _cancel, count = _ENTRY_META_STRUCT.unpack_from(view, 0)
if not self._matches(state, generation, digest, slot):
return []

queue_size = self.steering_queue_size
if count > queue_size:
logger.warning(
"Corrupted steering queue for entry %s; resetting",
slot.entry_index,
)
_U32.pack_into(view, _COUNT_OFFSET, 0)
return []

contents: List[Content] = []
for index in range(count):
record = record_offset(index, self.max_steering_bytes)
try:
length = _U32.unpack_from(view, record)[0]
if length > self.max_steering_bytes:
raise ValueError(f"record length {length} exceeds {self.max_steering_bytes}")
payload = bytes(view[record + _RECORD_HEADER_SIZE:record + _RECORD_HEADER_SIZE + length])
contents.append(Content.model_validate_json(payload.decode("utf-8")))
except (ValueError, IndexError, struct.error, UnicodeDecodeError) as ex:
logger.warning(
"Dropping corrupted steering record for entry %s: %s",
slot.entry_index,
ex,
)
_U32.pack_into(view, _COUNT_OFFSET, 0)
return contents

_U32.pack_into(view, _COUNT_OFFSET, 0)
return contents
except (OSError, ValueError):
return []

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

问题: drain() 和 enqueue() 的 count 上限判断不一致。当队列全满时 enqueue 直接返回 QUEUE_FULL,而 count 是共享内存里可能被污染的字段(设计文档专门设计了 corrupted 记录丢弃路径,见 drain 中 count > queue_size 的重置逻辑),一旦 entry 的 count 因并发或历史复用被写坏,enqueue 会把合法槽位也判定为满,导致该 entry 的 steering 永久不可写。

触发条件: 共享内存 entry 的 count 字段异常(进程崩溃后 generation 复用、结构布局错位或并发写)时调用 send_steering。

实际影响: 所有后续 steering 永久返回 QUEUE_FULL,用户插话在 run 剩余生命周期内不可用,且没有任何日志;与 drain 已有的 corrupted 恢复逻辑不一致。

修正方向: 在 enqueue 中对 count > queue_size 单独处理(参照 drain 的 reset 逻辑),对「count 非法」与「队列真满」区分处理,并在非法时重置 count 后继续入队或返回明确的异常状态。

Comment thread trpc_agent_sdk/cancel/_shared_mem.py Resolved
Comment on lines +278 to +286
def _ensure_process_state(self) -> None:
if os.getpid() == self._pid:
return
# A fork child inherits the mapping and fds. Recreate only the
# process-local locks: they may have been held by another thread at
# fork time, while the shared mapping itself stays valid.
self._pid = os.getpid()
self._alloc_lock = threading.Lock()
self._entry_locks = [threading.Lock() for _ in range(self.max_active_runs)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

问题: _ensure_process_state() 在 fork 子进程内重建 _entry_locks 和 _alloc_lock,但 _master_lock_fd(create() 在 master 进程 open 的 LOCK_PATH fd)在子进程继承后,子进程的 close()(destroy_shared_mem 在 worker 中被调,或 _SharedMem.close 的对象析构)会先 fcntl.lockf(LOCK_UN) 释放锁再 close fd。lockf 语义上是进程级锁:任一持有同一 fd 的进程释放锁会影响整个 fd 上的锁状态,导致 master 的 master-lock 被子进程意外释放,另一个 master 进程趁虚而入重新 unlink/重建 segment。

触发条件: fork 的多 worker 部署中,worker 进程调用 _SharedMem.close()(或 destroy_shared_mem)——设计文档明确 worker 进程应只 close() 不 unlink。

实际影响: master lock 的互斥保证被破坏,可能出现两个进程同时成为 master、互相 unlink 对方 segment,导致运行中段被重建、活跃 run 丢失。

修正方向: 在 _ensure_process_state() 或 _SharedMem.__init__ 中,fork 子进程把 _master_lock_fd 置为 None(不继承/不释放父进程的 lock fd),worker 只 close 自己的 mapping,不动 master lock。

@weimch weimch closed this Nov 20, 2026
@weimch weimch reopened this Nov 20, 2026
Comment thread docs/design/03-cancel-steering.md Resolved
Comment thread docs/design/03-cancel-steering.md Resolved
Comment thread docs/design/03-cancel-steering.md Resolved
Comment thread docs/design/03-cancel-steering.md Outdated
│ └── watcher_task │ │
│ │ cancel_requested=1 ◄─────────│ cancel_run(key)
│ │ │ 发布后立即返回
│ watcher: every 50ms │ │

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

这块轮询50ms是固定值,太小了,可以默认100ms,并且应该提出来让用户配置

- Cancel支持多进程部署,使用共享内存同步信号
- 支持Steering插话能力,用户可以在Agent运行过程中插话
- 修复A2A/AGUI不当使用Cancel内部方法的问题
- 补充相关设计文档见docs/design/03-cancel-steering.md、及steering、多进程使用示例
@weimch
weimch force-pushed the feature/cancel_steering_support branch from a842c5a to 0084f9e Compare November 23, 2026 04:23
@helloopenworld

Copy link
Copy Markdown
Contributor

AI Code Review

审查结论

不通过

审查范围:base 905698c..head 0084f9e("重构 Cancel 及支持 Steering 能力"),48 个文件、5156 增/1474 删。核心变更为 cancel 模块重构(删除 _cancel.py/_session_utils.py,新增 _local_manager/_shared_manager/_shared_mem/_public/_cleanup/_types),Runner 生命周期重构(register_run 同步化、unregister_run 提前释放、complete_incomplete_function_calls 补齐 skipped tool result),LlmAgent 注入 steering 消费,a2a/ag_ui 服务端适配,以及多 worker 共享内存示例与大量测试。计划符合度:steering 设计目标(FIFO 合并、hidden Event 持久化、跨 worker 共享表)均在代码与测试中实现,local/shared 双模式与文档一致。主要风险集中在:1) AG-UI HITL/客户端工具场景下取消补写伪造 function_response 与清理 pending_tool_calls 的相互干扰;2) a2a/AG-UI 取消路径中 runner 生成器未排空导致 slot 悬挂与后续 run 被 RuntimeError 拒绝;3) 共享内存条目 owner 崩溃后依赖 pid_is_alive 的重用判定在 PID 复用下失效;4) 共享模式取消轮询 watcher 仅在 get_cancel_event 时启动,依赖该路径取事件的 A2A RemoteAgent 流式取消可达但延迟受轮询间隔限制。测试充分性:新增 13 个测试文件(test_runner_cancel/test_shared_mem/test_steering/test_cleanup 等)覆盖了取消检查点、重复注册拒绝、tool call 补齐、steering FIFO 合并等主路径;但缺少 AG-UI 客户端工具(HITL)与取消交互、a2a 取消后 generator 排空、共享模式下 owner 崩溃回收、取消与 steering 同时到达等边界测试。门禁结论:FAILED — 存在阻碍合入的高置信缺陷(HITL 场景下取消产生双 function_response 造成历史损坏、a2a v1 取消后依然可被再次取消返回误报、共享表 PID 复用导致会话永久无法运行)。

发现的问题

严重

trpc_agent_sdk/cancel/_cleanup.py:41-72

问题: complete_incomplete_function_calls 把 session 中所有 invocation_id 匹配且无对应 response 的 function_call 一律补写一条伪造的 function_response(id=call.id, status="cancelled"),它无法区分"被取消丢弃的调用"与"合法的客户端工具/HITL 待完成调用"(AG-UI 的 client-side tool 与 a2a long-running callback 在其执行期间本来就没有 response)。

触发条件: AG-UI 会话中 Agent 发出客户端工具调用(ToolCallEndEvent 已记录到 pending_tool_calls),随后客户端断开 SSE 连接触发 Runner.cancel_run_async,Runner 在 RunCancelledException 分支调用本函数;同时 _agui_agent.py:cancel_run(本变更删除了 execution.cancel(),改为仅调 cancel_run_async 并清空 pending_tool_calls)把该 pending 状态清掉。

实际影响: 客户端之后提交真实工具结果时,session 历史中同一 function_call.id 已有伪造的 cancelled response(role="user"、visible=False 但模型可见),下一次 LLM 请求出现"一个 function_call + 两个 function_response",provider 拒绝请求或历史配对错乱;同时 pending_tool_calls 被清空导致 _start_new_execution finally 中 _has_pending_tool_calls 判定为 False 而删除 ExecutionState,HITL 恢复链路被破坏。

修正方向: 仅对"执行终止且确实未开始"的调用补齐 response,或改为恢复旧的"从历史中移除未完成调用"策略;对 AG-UI 客户端工具/HITL 场景应跳过补齐并保留 pending 状态,避免与 cancel_run 清空 pending_tool_calls 的逻辑叠加。

严重

trpc_agent_sdk/runners.py:693-700

问题: run_async 在 yield AgentCancelledEvent 之前就执行 cancel.unregister_run(session_key) 释放 slot,但取消信号是否实际生效完全取决于调用方是否会继续消费生成器。a2a v2 executor 在收到 AgentCancelledEvent 后立即 return(async for 退出会关闭生成器并运行 finally,此时 slot 才真正释放),而 a2a v1 改为 continue 排空;若调用方在事件后停止迭代且生成器未被 aclose()(例如 a2a v2 路径或用户直接 break),unregister_run 之前的所有 cleanup(补齐 tool call、写取消 marker、finally 的 unregister)全部不会执行,slot 悬挂。

触发条件: a2a v2 任务被取消:AgentCancelledEvent 分支 return,生成器在此处被垃圾回收,finally 未运行,_local_manager 中该 session 的 run 记录仍存在;用户随后对同一 session 发起新的 run_async。

实际影响: 新 run 在 register_run 处抛出 RuntimeError("Session ... already has an active run"),同类而 cancel_run_async 返回 False 且 ag_ui.cancel_run 跳过清理,会话永久无法再次执行;同时取消路径的 session 收尾(取消 marker、AgentCancelledEvent 之前的测试 test_cancel_releases_slot_before_terminal_event 只验证了消费到事件后再释放,未覆盖调用方提前停止迭代的悬挂场景)。

修正方向: 在 AgentCancelledEvent 分支之后的 finally 中确保生成器被显式关闭(或让 a2a v2 采用与 v1 相同的 continue 排空);或在 register_run 的 RuntimeError 路径上允许新 run 取代已悬挂的旧 run(按 generation/时间戳判定失效)。

严重

trpc_agent_sdk/cancel/_shared_mem.py:278-307

问题: 共享表的存活判定完全依赖 pid_is_alive(owner_pid)(os.kill(pid, 0)),owner 进程崩溃后其 PID 可能被操作系统回收给无关进程,此时 pid_is_alive 恒为 True,allocate/_find_or_reserve/find/is_cancelled 都会把该条目当作仍然活跃,条目永不回收。

触发条件: worker 进程在中途被强杀(OOM、kill -9、崩溃)后,Linux 迅速复用其 PID 给一个新起的守护进程;新的 worker 对同一 session key 调用 allocate,命中 state==_STATE_RUNNING && entry_digest==digest && pid_is_alive(owner_pid) 而抛出 RuntimeError。

实际影响: 该 session 从此永久无法再次运行(报"already has an active run"),且该条目的 cancel/steering 写入被导向无人读取的死 flag;崩溃条目累积后表被占满,_find_or_reserve 报 "run table is full",影响所有会话。

修正方向: 在 owner 存活判定之外增加强校验,例如记录 owner 启动时间戳或持有者可验证的 token(/proc/<pid>/stat 的 starttime 对比),或对 pid_is_alive 为 True 但创建时间过老的条目定期回收;至少应把 PID 复用检测纳入设计文档的容错验证。

中等

trpc_agent_sdk/server/a2a_v1/executor/_a2a_agent_executor.py:400-403

问题: a2a v1 取消后虽然 cancelled=True 并排空生成器,但 Runner.cancel_run_async 在共享模式下返回 True 是基于 publish_cancel 成功(_shared_manager.cancel_run 在本地无 run 时经 find() 找到 slot 后发布即返回),并未等待 owner 清理;排空完成后 slot 尚未释放的窗口内,用户再次取消同一任务会命中 _shared_manager._get_run 为 None、find() 返回 None 而返回 False,cancel() 于是发送 "No active task found to cancel"。

触发条件: 共享内存模式下 a2a v1 任务被取消,AgentCancelledEvent 已入队但 owner 进程的 unregister_run(finally)晚于客户端收到事件;客户端立即再次调用 cancel_task。

实际影响: 已取消任务被错误地报为"无活跃任务",客户端无法区分"任务已完成"与"任务仍在清理",取消反馈误导;在 pending_tool_calls 清理(_agui_agent.cancel_run 只在 success=True 时执行)依赖该返回值时,清理被跳过。

修正方向: 对共享模式,cancel 在 cancel_run_async 返回 False 时不要立即判定"无任务",而应先检查任务当前状态(TaskManager 中 task state 是否为 CANCELED/WORKING)再决定是否提示;或在 slot 释放前保持 find() 返回该 slot(owner 清理期内的条目仍可返回已取消标志)。

中等

trpc_agent_sdk/agents/_llm_agent.py:507-517

问题: steering 消费发生在 CHECKPOINT 1(第 491 行 raise_if_cancelled)之后、CHECKPOINT 2(第 540 行)之前,两条检查点之间没有取消检查;消费 steering 后如果取消已在排队,本应在下一轮循环开头被 raise_if_cancelled 拦住,但实际该轮已被 steering 事件"救活"并继续走到 LLM 调用。

触发条件: 用户先调用 cancel_run_async(cancel flag 已置位),随后(或同时)send_steering 写入队列;Agent 恰好在 CHECKPOINT 1 与 consume_steering 之间运行到该轮,steering 被消费、yield hidden 事件并继续构建请求。

实际影响: 已取消的运行继续向模型发送请求(浪费一次计费调用),取消语义被 steering 静默绕过;文档 docs/design/03-cancel-steering.md 明确约定"cancel 优先于 steering:先 raise_if_cancelled 再 consume_steering",此处实现与该序不一致。

修正方向: 在 consume_steering 之后、yield/构建请求之前再增加一次 await ctx.raise_if_cancelled()(或把 consume_steering 放到 CHECKPOINT 2 之后),保证取消优先。

中等

trpc_agent_sdk/cancel/_shared_manager.py:124-148

问题: 共享模式下的跨进程取消依赖 _watch_run_cancel 轮询 watcher 把共享 flag 镜像到本地 cancel_event,但 watcher 只在 get_cancel_event() 首次被调用时启动;raise_if_cancelled 自己会直接读 _mem.is_cancelled,所以纯 checkpoint 路径不受影响,但依赖 cancel_event.wait() 的流式路径(_remote_a2a_agent._stream_with_cancel_check 并发等待 cancel_event)只有在 watcher 运行且轮询到共享 flag 后才能被唤醒。

触发条件: 多 worker 部署中,worker B 对 worker A 正在运行的 A2A RemoteAgent 流式任务调用 cancel_run;worker A 的 _stream_with_cancel_check 已持有 cancel_event(watcher 已启动,cancel_poll_interval=0.1s),取消传播延迟为轮询间隔;若 A 端直到流结束才调用 get_cancel_event,则取消期间 cancel_event.wait() 永不置位。

实际影响: 跨 worker 取消在流式传输场景下延迟 0.1s~数秒,或(watcher 未启动时)完全失效,客户端断开只触发本来就会发生的流错误;与文档宣称的"跨 worker cancel 写共享字节立即生效"存在差距。

修正方向: 在 register_run 或 raise_if_cancelled 路径上惰性启动 watcher(而非仅在 get_cancel_event),或让 _watch_run_cancel 在 raise_if_cancelled 检查到共享 flag 后同步置位本地 event 并唤醒 waiters。

中等

trpc_agent_sdk/cancel/_local_manager.py:68-84

问题: _LocalManager.cancel_run 等待 cleanup_event 的最长 timeout(默认 1.0s)从调用方发出取消到实际生效的链路包含:run 任务被 cancel_event 置位唤醒 → 走到下一个 checkpoint 抛 RunCancelledException → run_async 执行补齐/写 marker/unregister_run。若 run 正处于长时同步工具调用或阻塞的 LLM 流式 I/O 中,checkpoint 不会执行,cleanup_event 在 timeout 内不置位,cancel_run 照常返回 True(仅超时日志)。

触发条件: AG-UI 客户端断开:_agui_agent.cancel_run 使用 _cancel_wait_timeout=3.0s 等待,而 LLM 流式响应耗时 >3s 且中间无 checkpoint;或工具执行阻塞数秒。

实际影响: cancel_run 返回 True("取消成功")但运行实际继续执行到工具/LLM 完成,客户端已断开无感知;pending_tool_calls 清理在新 run 到达前可能被旧 run 重新写入(_start_new_execution 在流结束后再次 _add_pending_tool_call_with_context),导致清理被覆盖、HITL 状态残留。

修正方向: 对 AG-UI 取消路径在 cancel_run_async 返回 True 但未能在 timeout 内确认清理完成时,仍等待 _stream_events 的最终 None 信号(或 ExecutionState 完成)再返回;或在 cancel_run 返回 True 的同时返回实际等待结果,让调用方决定是否保留 pending 清理。

较低

trpc_agent_sdk/cancel/_shared_mem.py:415-447

问题: drain 对每条 record 只校验了长度上界(length > max_steering_bytes),若生产者进程在写完 _U32 长度头后被杀死(或写入被截断),length 为一个小于 payload 真实长度的合法值,bytes(view[...]) 取出未初始化零字节,Content.model_validate_json 抛出的 pydantic.ValidationError 不在 except 捕获的 (ValueError, IndexError, struct.error, UnicodeDecodeError) 之列,异常直接穿出 drain,count 也未重置。

触发条件: 共享模式下 owner 进程在 enqueue 写 record 的中途崩溃(OOM/kill -9),另一个 worker 随后 drain 该 entry。

实际影响: 消费方请求循环被未捕获异常打断(一次取消/steering 读取导致调用方失败),且由于 count 未归零,后续每次 drain 都重复失败,该条目的 steering 队列永久坏死。

修正方向: 将 pydantic.ValidationError(或 Exception)纳入校验失败的分支,与其它损坏 record 一样 reset count 并跳过;或对 bytes() 长度不足的 record 立即判定损坏。

较低

trpc_agent_sdk/server/ag_ui/_plugin/_utils.py:76-90

问题: event_generator 的 finally 在 app_name is None or user_id is None 时仅记录 warning 并跳过 cancel_run;而 app_name/user_id 的赋值发生在 try 块开头,若 get_app_name/get_user_id 抛出异常(header 缺失/格式非法),finally 中取消被跳过,后台 run 没有收到取消信号。

触发条件: AG-UI 请求缺少应用/用户标识(非法 header),异常进入 except 分支发错误帧,客户端已断开(SSE 写失败),finally 中取消被跳过。

实际影响: 后台 _run_trpc_in_background 任务继续运行至 _execution_timeout(默认数分钟)才能被 _cleanup_stale_executions 回收,期间事件持续写入无人消费的 event_queue,对同一 thread 的新请求在 _start_new_execution 处等待旧任务完成。

修正方向: 在进入 try 前先尝试解析 app_name/user_id(失败则直接返回),或在 except 分支补发一次基于 input_data.thread_id 的取消(thread_id 在 finally 中始终可得)。

Comment on lines +41 to +72
response_ids = set()
for event in session.events:
for response in event.get_function_responses():
response_ids.add(response.id)

incomplete: List[FunctionCall] = []
seen = set()
for event in session.events:
if event.invocation_id != invocation_id:
continue
for call in event.get_function_calls():
if call.id in response_ids or call.id in seen:
continue
seen.add(call.id)
incomplete.append(call)

if not incomplete:
return []

parts: List[Part] = []
for call in incomplete:
message = _SKIPPED_TOOL_TEMPLATE.format(name=call.name, reason=reason)
part = Part.from_function_response(
name=call.name,
response={
"status": "cancelled",
"message": message,
},
)
if part.function_response is not None:
part.function_response.id = call.id
parts.append(part)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

问题: complete_incomplete_function_calls 把 session 中所有 invocation_id 匹配且无对应 response 的 function_call 一律补写一条伪造的 function_response(id=call.id, status="cancelled"),它无法区分"被取消丢弃的调用"与"合法的客户端工具/HITL 待完成调用"(AG-UI 的 client-side tool 与 a2a long-running callback 在其执行期间本来就没有 response)。

触发条件: AG-UI 会话中 Agent 发出客户端工具调用(ToolCallEndEvent 已记录到 pending_tool_calls),随后客户端断开 SSE 连接触发 Runner.cancel_run_async,Runner 在 RunCancelledException 分支调用本函数;同时 _agui_agent.py:cancel_run(本变更删除了 execution.cancel(),改为仅调 cancel_run_async 并清空 pending_tool_calls)把该 pending 状态清掉。

实际影响: 客户端之后提交真实工具结果时,session 历史中同一 function_call.id 已有伪造的 cancelled response(role="user"、visible=False 但模型可见),下一次 LLM 请求出现"一个 function_call + 两个 function_response",provider 拒绝请求或历史配对错乱;同时 pending_tool_calls 被清空导致 _start_new_execution finally 中 _has_pending_tool_calls 判定为 False 而删除 ExecutionState,HITL 恢复链路被破坏。

修正方向: 仅对"执行终止且确实未开始"的调用补齐 response,或改为恢复旧的"从历史中移除未完成调用"策略;对 AG-UI 客户端工具/HITL 场景应跳过补齐并保留 pending 状态,避免与 cancel_run 清空 pending_tool_calls 的逻辑叠加。

Comment thread trpc_agent_sdk/runners.py
Comment on lines +693 to +700
# Release the run slot before notifying the caller: consumers
# commonly stop iterating as soon as they see this event, and
# an abandoned async generator would otherwise hold the slot
# until it is garbage collected.
if run_registered:
cancel.unregister_run(session_key)
run_registered = False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

问题: run_async 在 yield AgentCancelledEvent 之前就执行 cancel.unregister_run(session_key) 释放 slot,但取消信号是否实际生效完全取决于调用方是否会继续消费生成器。a2a v2 executor 在收到 AgentCancelledEvent 后立即 return(async for 退出会关闭生成器并运行 finally,此时 slot 才真正释放),而 a2a v1 改为 continue 排空;若调用方在事件后停止迭代且生成器未被 aclose()(例如 a2a v2 路径或用户直接 break),unregister_run 之前的所有 cleanup(补齐 tool call、写取消 marker、finally 的 unregister)全部不会执行,slot 悬挂。

触发条件: a2a v2 任务被取消:AgentCancelledEvent 分支 return,生成器在此处被垃圾回收,finally 未运行,_local_manager 中该 session 的 run 记录仍存在;用户随后对同一 session 发起新的 run_async。

实际影响: 新 run 在 register_run 处抛出 RuntimeError("Session ... already has an active run"),同类而 cancel_run_async 返回 False 且 ag_ui.cancel_run 跳过清理,会话永久无法再次执行;同时取消路径的 session 收尾(取消 marker、AgentCancelledEvent 之前的测试 test_cancel_releases_slot_before_terminal_event 只验证了消费到事件后再释放,未覆盖调用方提前停止迭代的悬挂场景)。

修正方向: 在 AgentCancelledEvent 分支之后的 finally 中确保生成器被显式关闭(或让 a2a v2 采用与 v1 相同的 continue 排空);或在 register_run 的 RuntimeError 路径上允许新 run 取代已悬挂的旧 run(按 generation/时间戳判定失效)。

Comment on lines +278 to +307
state, current_generation, owner_pid, entry_digest, _cancel, _count = _ENTRY_META_STRUCT.unpack_from(
view, 0)
if state == _STATE_RUNNING and entry_digest == digest and pid_is_alive(owner_pid):
raise RuntimeError(f"Session {key.session_id} already has an active run")
generation = max(generation, current_generation) + 1
self._write_running(view, generation, digest)
return _Slot(index, generation, digest)

def _find_or_reserve(self, digest: bytes, key) -> tuple[int, int]:
capacity = self.max_active_runs
start = int.from_bytes(digest, "little") % capacity
first_free: Optional[tuple[int, int]] = None

for offset in range(capacity):
index = (start + offset) % capacity
view = self.entry_view(index)
state, generation, owner_pid, entry_digest, _cancel, _count = _ENTRY_META_STRUCT.unpack_from(view, 0)
if entry_digest == digest:
if state != _STATE_RUNNING or not pid_is_alive(owner_pid):
return index, generation
raise RuntimeError(f"Session {key.session_id} already has an active run")
if state != _STATE_RUNNING:
if first_free is None:
first_free = (index, generation)
elif not pid_is_alive(owner_pid) and first_free is None:
first_free = (index, generation)

if first_free is None:
raise RuntimeError(f"Shared memory run table is full (max_active_runs={capacity})")
return first_free

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

问题: 共享表的存活判定完全依赖 pid_is_alive(owner_pid)(os.kill(pid, 0)),owner 进程崩溃后其 PID 可能被操作系统回收给无关进程,此时 pid_is_alive 恒为 True,allocate/_find_or_reserve/find/is_cancelled 都会把该条目当作仍然活跃,条目永不回收。

触发条件: worker 进程在中途被强杀(OOM、kill -9、崩溃)后,Linux 迅速复用其 PID 给一个新起的守护进程;新的 worker 对同一 session key 调用 allocate,命中 state==_STATE_RUNNING && entry_digest==digest && pid_is_alive(owner_pid) 而抛出 RuntimeError。

实际影响: 该 session 从此永久无法再次运行(报"already has an active run"),且该条目的 cancel/steering 写入被导向无人读取的死 flag;崩溃条目累积后表被占满,_find_or_reserve 报 "run table is full",影响所有会话。

修正方向: 在 owner 存活判定之外增加强校验,例如记录 owner 启动时间戳或持有者可验证的 token(/proc/<pid>/stat 的 starttime 对比),或对 pid_is_alive 为 True 但创建时间过老的条目定期回收;至少应把 PID 复用检测纳入设计文档的容错验证。

Comment on lines +400 to 403
if cancelled:
return

if aggregator.task_state == TaskState.TASK_STATE_WORKING:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

问题: a2a v1 取消后虽然 cancelled=True 并排空生成器,但 Runner.cancel_run_async 在共享模式下返回 True 是基于 publish_cancel 成功(_shared_manager.cancel_run 在本地无 run 时经 find() 找到 slot 后发布即返回),并未等待 owner 清理;排空完成后 slot 尚未释放的窗口内,用户再次取消同一任务会命中 _shared_manager._get_run 为 None、find() 返回 None 而返回 False,cancel() 于是发送 "No active task found to cancel"。

触发条件: 共享内存模式下 a2a v1 任务被取消,AgentCancelledEvent 已入队但 owner 进程的 unregister_run(finally)晚于客户端收到事件;客户端立即再次调用 cancel_task。

实际影响: 已取消任务被错误地报为"无活跃任务",客户端无法区分"任务已完成"与"任务仍在清理",取消反馈误导;在 pending_tool_calls 清理(_agui_agent.cancel_run 只在 success=True 时执行)依赖该返回值时,清理被跳过。

修正方向: 对共享模式,cancel 在 cancel_run_async 返回 False 时不要立即判定"无任务",而应先检查任务当前状态(TaskManager 中 task state 是否为 CANCELED/WORKING)再决定是否提示;或在 slot 释放前保持 find() 返回该 slot(owner 清理期内的条目仍可返回已取消标志)。

Comment on lines +507 to +517
steering_content = await ctx.consume_steering()
if steering_content is not None:
steering_event = Event(
invocation_id=ctx.invocation_id,
author="user",
content=mark_steering_content(steering_content),
branch=ctx.branch,
visible=False,
)
yield steering_event
accumulate_content(steering_event)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

问题: steering 消费发生在 CHECKPOINT 1(第 491 行 raise_if_cancelled)之后、CHECKPOINT 2(第 540 行)之前,两条检查点之间没有取消检查;消费 steering 后如果取消已在排队,本应在下一轮循环开头被 raise_if_cancelled 拦住,但实际该轮已被 steering 事件"救活"并继续走到 LLM 调用。

触发条件: 用户先调用 cancel_run_async(cancel flag 已置位),随后(或同时)send_steering 写入队列;Agent 恰好在 CHECKPOINT 1 与 consume_steering 之间运行到该轮,steering 被消费、yield hidden 事件并继续构建请求。

实际影响: 已取消的运行继续向模型发送请求(浪费一次计费调用),取消语义被 steering 静默绕过;文档 docs/design/03-cancel-steering.md 明确约定"cancel 优先于 steering:先 raise_if_cancelled 再 consume_steering",此处实现与该序不一致。

修正方向: 在 consume_steering 之后、yield/构建请求之前再增加一次 await ctx.raise_if_cancelled()(或把 consume_steering 放到 CHECKPOINT 2 之后),保证取消优先。

Comment on lines +124 to +148
def get_cancel_event(self, key: SessionKey) -> Optional[asyncio.Event]:
"""Return the cancellation event for ``key``.
The first call for a run starts a per-run watcher task. The watcher
polls the shared cancel flag and sets the local event, so a cancel
published by another worker wakes local waiters.
"""
run = self._get_run(key)
if run is None:
return None
if run.cancel_event.is_set() or self._closed:
return run.cancel_event
if self._mem.is_cancelled(run.slot):
run.cancel_event.set()
return run.cancel_event

if run.watch_task is None or run.watch_task.done():
try:
loop = asyncio.get_running_loop()
except RuntimeError:
return run.cancel_event
run.watch_task = loop.create_task(
self._watch_run_cancel(run),
name=f"cancel-watch:{key.session_id}",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

问题: 共享模式下的跨进程取消依赖 _watch_run_cancel 轮询 watcher 把共享 flag 镜像到本地 cancel_event,但 watcher 只在 get_cancel_event() 首次被调用时启动;raise_if_cancelled 自己会直接读 _mem.is_cancelled,所以纯 checkpoint 路径不受影响,但依赖 cancel_event.wait() 的流式路径(_remote_a2a_agent._stream_with_cancel_check 并发等待 cancel_event)只有在 watcher 运行且轮询到共享 flag 后才能被唤醒。

触发条件: 多 worker 部署中,worker B 对 worker A 正在运行的 A2A RemoteAgent 流式任务调用 cancel_run;worker A 的 _stream_with_cancel_check 已持有 cancel_event(watcher 已启动,cancel_poll_interval=0.1s),取消传播延迟为轮询间隔;若 A 端直到流结束才调用 get_cancel_event,则取消期间 cancel_event.wait() 永不置位。

实际影响: 跨 worker 取消在流式传输场景下延迟 0.1s~数秒,或(watcher 未启动时)完全失效,客户端断开只触发本来就会发生的流错误;与文档宣称的"跨 worker cancel 写共享字节立即生效"存在差距。

修正方向: 在 register_run 或 raise_if_cancelled 路径上惰性启动 watcher(而非仅在 get_cancel_event),或让 _watch_run_cancel 在 raise_if_cancelled 检查到共享 flag 后同步置位本地 event 并唤醒 waiters。

Comment on lines +68 to +84
async def cancel_run(self, key: SessionKey, timeout: float = 1.0) -> bool:
"""Request cancellation and wait for the run to finish cleanup."""
run = self._get_run(key)
if run is None:
return False

run.cancel_event.set()
try:
await asyncio.wait_for(run.cleanup_event.wait(), timeout=timeout)
logger.info("Cancel completed for session %s", key.session_id)
except asyncio.TimeoutError:
logger.warning(
"Cancel wait timeout (%ss) reached for session %s. "
"The execution may still be running.",
timeout,
key.session_id,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

问题: _LocalManager.cancel_run 等待 cleanup_event 的最长 timeout(默认 1.0s)从调用方发出取消到实际生效的链路包含:run 任务被 cancel_event 置位唤醒 → 走到下一个 checkpoint 抛 RunCancelledException → run_async 执行补齐/写 marker/unregister_run。若 run 正处于长时同步工具调用或阻塞的 LLM 流式 I/O 中,checkpoint 不会执行,cleanup_event 在 timeout 内不置位,cancel_run 照常返回 True(仅超时日志)。

触发条件: AG-UI 客户端断开:_agui_agent.cancel_run 使用 _cancel_wait_timeout=3.0s 等待,而 LLM 流式响应耗时 >3s 且中间无 checkpoint;或工具执行阻塞数秒。

实际影响: cancel_run 返回 True("取消成功")但运行实际继续执行到工具/LLM 完成,客户端已断开无感知;pending_tool_calls 清理在新 run 到达前可能被旧 run 重新写入(_start_new_execution 在流结束后再次 _add_pending_tool_call_with_context),导致清理被覆盖、HITL 状态残留。

修正方向: 对 AG-UI 取消路径在 cancel_run_async 返回 True 但未能在 timeout 内确认清理完成时,仍等待 _stream_events 的最终 None 信号(或 ExecutionState 完成)再返回;或在 cancel_run 返回 True 的同时返回实际等待结果,让调用方决定是否保留 pending 清理。

Comment on lines +415 to +447
with self.lock_entry(slot.entry_index):
view = self.entry_view(slot.entry_index)
state, generation, _owner_pid, digest, _cancel, count = _ENTRY_META_STRUCT.unpack_from(view, 0)
if not self._matches(state, generation, digest, slot):
return SteeringStatus.NO_ACTIVE_RUN

queue_size = self.steering_queue_size
if count >= queue_size:
return SteeringStatus.QUEUE_FULL

record = record_offset(count, self.max_steering_bytes)
_U32.pack_into(view, record, len(payload))
view[record + _RECORD_HEADER_SIZE:record + _RECORD_HEADER_SIZE + len(payload)] = payload
_U32.pack_into(view, _COUNT_OFFSET, count + 1)
return SteeringStatus.ACCEPTED
except (OSError, ValueError, IndexError, struct.error):
return SteeringStatus.NO_ACTIVE_RUN

def drain(self, slot: _Slot) -> List[Content]:
"""Take all steering messages from ``slot`` in FIFO order."""
if self._closed:
return []

try:
with self.lock_entry(slot.entry_index):
view = self.entry_view(slot.entry_index)
state, generation, _owner_pid, digest, _cancel, count = _ENTRY_META_STRUCT.unpack_from(view, 0)
if not self._matches(state, generation, digest, slot):
return []

queue_size = self.steering_queue_size
if count > queue_size:
logger.warning(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

问题: drain 对每条 record 只校验了长度上界(length > max_steering_bytes),若生产者进程在写完 _U32 长度头后被杀死(或写入被截断),length 为一个小于 payload 真实长度的合法值,bytes(view[...]) 取出未初始化零字节,Content.model_validate_json 抛出的 pydantic.ValidationError 不在 except 捕获的 (ValueError, IndexError, struct.error, UnicodeDecodeError) 之列,异常直接穿出 drain,count 也未重置。

触发条件: 共享模式下 owner 进程在 enqueue 写 record 的中途崩溃(OOM/kill -9),另一个 worker 随后 drain 该 entry。

实际影响: 消费方请求循环被未捕获异常打断(一次取消/steering 读取导致调用方失败),且由于 count 未归零,后续每次 drain 都重复失败,该条目的 steering 队列永久坏死。

修正方向: 将 pydantic.ValidationError(或 Exception)纳入校验失败的分支,与其它损坏 record 一样 reset count 并跳过;或对 bytes() 长度不足的 record 立即判定损坏。

Comment on lines +76 to +90
# Trigger cancellation of the background TRPC run. The run stops
# cooperatively through Runner; do not cancel the asyncio task here.
if app_name is None or user_id is None:
logger.warning(
"Skipping cancel_run for thread %s: app_name or user_id is unavailable",
session_id,
)
else:
try:
await agui_agent.cancel_run(
session_id=session_id,
app_name=app_name,
user_id=user_id,
)
except Exception as ex: # pylint: disable=broad-except

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

问题: event_generator 的 finally 在 app_name is None or user_id is None 时仅记录 warning 并跳过 cancel_run;而 app_name/user_id 的赋值发生在 try 块开头,若 get_app_name/get_user_id 抛出异常(header 缺失/格式非法),finally 中取消被跳过,后台 run 没有收到取消信号。

触发条件: AG-UI 请求缺少应用/用户标识(非法 header),异常进入 except 分支发错误帧,客户端已断开(SSE 写失败),finally 中取消被跳过。

实际影响: 后台 _run_trpc_in_background 任务继续运行至 _execution_timeout(默认数分钟)才能被 _cleanup_stale_executions 回收,期间事件持续写入无人消费的 event_queue,对同一 thread 的新请求在 _start_new_execution 处等待旧任务完成。

修正方向: 在进入 try 前先尝试解析 app_name/user_id(失败则直接返回),或在 except 分支补发一次基于 input_data.thread_id 的取消(thread_id 在 finally 中始终可得)。

@helloopenworld

Copy link
Copy Markdown
Contributor

发现的问题
P1:A2A CancelTask 实际按 session 取消,可能误取消后续任务
A2A 协议取消的是具体 task_id,但实现最终只使用:

(app_name, user_id, session_id)
没有携带 task、invocation 或共享内存 generation:

Runner.cancel_run_async
A2A v1 cancel
_SharedManager.cancel_run
触发场景:

Task A 结束或被取消;
同一 session 启动 Task B;
Task A 的重试/延迟 CancelTask 到达;
find(SessionKey) 找到 Task B,最终取消 Task B。
共享表内部虽然有 generation,但调用方无法指定目标 generation。建议控制面引入 run/invocation identity,至少 A2A 应校验当前 task 对应的 invocation。

P1:文档声明了不存在的 Steering HTTP 接口
中文文档声称:

A2A 提供 POST /steering
AgUiService 提供 POST /steering
AgUiAgent 会自动使用共享内存
见 cancel.md:74-78。

但 trpc_agent_sdk/server 中没有任何 steering 路由,也没有 AG-UI 自动调用 init_shared_mem() 的代码。按文档部署会得到 404,且未显式初始化时跨 worker Cancel/Steering 无法工作。

应实现这些接口,或者将文档改为“需要业务自行暴露接口,并在 fork worker 前调用 init_shared_mem()”。

P2:A2A v0 取消后没有 drain Runner generator
A2A v0 收到 AgentCancelledEvent 后直接 return:

a2a executor:298-306
A2A v1 则明确继续消费 generator,以便在当前 task/context 中完成关闭:

a2a_v1 executor:346-360
v0 仍可能依赖 async-generator GC 完成收尾,造成资源延迟释放或 OpenTelemetry context detach 告警。应与 v1 对齐。

P2:worker 崩溃后的共享槽位可能无法回收
pid_is_alive 只调用 os.kill(pid, 0)。

这无法处理:

zombie 进程仍被判断为存活;
PID 被其他无关进程复用。
该判断用于 allocate/_find_or_reserve/find。结果可能是:

崩溃 run 永久占槽;
同 session 新 run 一直收到 “already has an active run”;
表逐渐耗尽;
Cancel/Steering 命中已经不属于原 worker 的 entry。
建议记录 PID start time 或随机 owner token,并结合 /proc//stat 校验进程身份和 zombie 状态。

P2:共享模式的 timeout 与用户文档不一致
实现明确表示共享路径忽略 timeout,写入 Cancel flag 后立即返回:

_SharedManager.cancel_run
Runner.cancel_run_async
但文档仍说 cancel_wait_timeout 会等待 owner 到达 checkpoint:

cancel.md:895-899
cancel.md:1143-1147
多 worker 下返回 True 只代表信号发布成功,不代表 run 已停止或 session 已完成清理。调用方可能过早启动后续任务。

P2:公开 Cancel API 存在未声明的破坏性变更
PR 删除或修改了:

is_run_cancelled
cleanup_run
cleanup_incomplete_function_calls
handle_cancellation_session_cleanup
register_run:异步三参数改为同步 SessionKey
cancel_run:返回 Event 改为返回 bool
当前导出见 cancel/init.py。

下游自定义 Server 升级后可能直接出现 ImportError、TypeError 或等待语义变化。建议增加 breaking-change 说明和迁移指南;若要求向后兼容,则需要保留过渡 API。

总体结论
当前版本已经修复跨 worker Event 唤醒问题,Cancel/Steering 主链路设计也基本完整。但建议合入前至少处理:

A2A task 与 session 级取消身份不匹配;
文档中不存在的 /steering 和自动共享内存承诺;
A2A v0 generator drain;
公开 API 迁移说明。
定向测试因环境缺少 google.genai 和 a2a 依赖,在 pytest 收集阶段终止;上述问题基于当前提交的调用链、共享内存生命周期和协议语义复核。

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants