Skip to content

Commit b617575

Browse files
committed
fix(pi-agent-cli): a repeated stop signal gets the default action
The stop-signal handlers made SIGTERM/SIGHUP harder to act on: if the graceful stop hangs (asyncio.run waits for a thread that cannot be cancelled) the agent could only be killed with SIGKILL. The handlers now remove themselves on the first signal, so a second one terminates the process as before. test_acp_shutdown.py: a stuck-thread mode of the scripted agent and a test that the second SIGTERM kills it (-15). Mutation-checked: without the self-removal the test times out.
1 parent 52a787f commit b617575

5 files changed

Lines changed: 43 additions & 6 deletions

File tree

‎docs/PLAN/PLAN-RUST-AGENT-RUNTIME-REMOVAL.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ zypi(Rust) pi_agent_cli(Python,通
175175
Python(`pi_agent_cli`):
176176

177177
- [ ] 1.P1(r5 部分:`title` = 会话第一条 user message,`updated_at` = 会话文件 mtime,`50ccfb1`;**`cursor` 分页没做**——pager 不跟 `nextCursor`,只要 Python 分页,列表就会被截断,所以要先让 pager 跟游标)`list_sessions`:真实 title、`updated_at`(最后活动)、`cursor` 分页(ACP `session/list` 字段,[RFD](https://github.com/agentclientprotocol/agent-client-protocol/blob/main/docs/rfds/session-list.mdx))。
178-
- [x] 1.P2 优雅退出(r5,`f14e321`):处理 stdin EOF / SIGTERM,回收工具进程组。实测(macOS,脚本化的 bash 调用):stdin EOF 本来就是优雅的——`run_agent` 返回,`asyncio.run` 取消在途 turn,bash 工具杀进程组,退出码 0、工具不残留;SIGTERM 则立刻终止进程(−15),工具残留。现在 `__main__.serve()` 把 SIGTERM 与 SIGHUP(`421d497`:终端消失、或 zypi 作为会话首进程被杀时,内核把 SIGHUP 发给前台进程组,agent 在其中,默认动作让它立刻死掉)接到同一条路径(POSIX;Windows 没有 `add_signal_handler` 与 SIGHUP,只靠 EOF)。SIGKILL 无法处理,工具仍会残留,所以 Rust 一侧不能一上来就 SIGKILL(1.R3)。契约:`tests/test_acp_shutdown.py`(EOF、SIGTERM、SIGHUP 都要退出码 0 且回收工具;去掉 SIGTERM 处理器后该用例以 −15 失败)。
178+
- [x] 1.P2 优雅退出(r5,`f14e321`):处理 stdin EOF / SIGTERM,回收工具进程组。实测(macOS,脚本化的 bash 调用):stdin EOF 本来就是优雅的——`run_agent` 返回,`asyncio.run` 取消在途 turn,bash 工具杀进程组,退出码 0、工具不残留;SIGTERM 则立刻终止进程(−15),工具残留。现在 `__main__.serve()` 把 SIGTERM 与 SIGHUP(`421d497`:终端消失、或 zypi 作为会话首进程被杀时,内核把 SIGHUP 发给前台进程组,agent 在其中,默认动作让它立刻死掉)接到同一条路径(POSIX;Windows 没有 `add_signal_handler` 与 SIGHUP,只靠 EOF)。处理器只生效一次(第一个信号后就摘掉),所以停到一半卡住的 agent(比如 `asyncio.run` 在等一个取消不了的线程)仍可被第二个 SIGTERM 杀掉。SIGKILL 无法处理,工具仍会残留,所以 Rust 一侧不能一上来就 SIGKILL(1.R3)。契约:`tests/test_acp_shutdown.py`(EOF、SIGTERM、SIGHUP 都要退出码 0 且回收工具;重复的信号要能杀掉卡住的 agent;去掉 SIGTERM 处理器后第一个用例以 −15 失败,去掉自摘除后最后一个用例超时)。
179179
- [ ] 1.P3 `set_session_mode`(或 `configOptions` 的 `mode`)取代仅靠 `ext_notification` 的权限模式切换,映射由矩阵定。
180180
- [ ] 1.P4 `mcp_servers`:显式忽略并在文档声明(Phase 4 非目标),或实现。
181181
- [ ] 1.P5(r5 部分:`initialize` 公布了 `session/close` 与 `session/resume`,但 `run_agent` 没开 `use_unstable_protocol`,SDK 对这两个方法回「Method not found」,`5163592` 已改;其余公布项与 pager 需求的对照没做)`initialize` 的 capabilities / `_meta`:只公布 pager 实际需要且已登记(P2)的键。
@@ -459,6 +459,7 @@ r3 执行了「拆除 Rust runtime + 恢复 `/model`」;r4 在其上补了阶
459459
| 本机,`5163592` | `pytest -m "not real_llm"`;`ruff check .` / `ruff format --check .` | ✓ 617 通过(r4 的 598 之外新增 `session_list` 11 个、stdio 契约 8 个);通过 |
460460
| 本机,`f14e321` | `pytest -m "not real_llm"`;`ruff check .` / `ruff format --check .`;`test_acp_shutdown.py` 连跑 3 次;去掉 SIGTERM 处理器再跑(变异检查) | ✓ 619 通过;通过;3 次都稳定;SIGTERM 用例以 −15 失败,EOF 用例仍通过 |
461461
| 本机,`421d497` | `pytest packages/pi-agent-cli -m "not real_llm"`;`ruff check .` / `ruff format --check .` | ✓ 116 通过(SIGHUP 用例 +1,全仓 620);通过 |
462+
| 本机,信号处理器自摘除 | `test_acp_shutdown.py` 4 个用例;去掉自摘除再跑(变异检查) | ✓ 通过;「重复的信号」用例超时失败 |
462463
| macOS 本机,`e8557e5` | `cargo test -p pi-pager --lib acp::spawn`(含 2 个新测试);`cargo build -p pi-pager-bin`(`CARGO_INCREMENTAL=0`、2 个 job) | ✓ 10 通过 / 0 失败;构建 0 告警(之后只有 rustfmt 的折行,未重编) |
463464
| 本机 PTY,`e8557e5` / `421d497` | `/tmp/rr/tui_orphan.py <模式>`:`PI_AGENT_COMMAND` 指向 `tests/_tool_agent.py`,发一句话让 agent 跑 `exec sleep 300`,工具运行时按模式退出 zypi,查 `sleep` 是否还在;另跑一遍 mock 的 `/exit` | 见下表;mock 的 `/exit`:退出码 0,无残留进程,终端上没有 Traceback / BrokenPipe |
464465

‎packages/pi-agent-cli/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ The Rust TUI (`zypi`) spawns the Python agent via (priority order):
4040

4141
## Stopping the agent
4242

43-
The agent must reap the tools it is running when its client goes away: the TUI closes the agent's stdin and kills it only after a grace period (`acp/spawn.rs`, `AGENT_EOF_GRACE`). `serve()` ends on EOF on stdin (`run_agent` returns, `asyncio.run` cancels the turns in flight, each `bash` tool kills its process group) and on SIGTERM / SIGHUP (the main task is cancelled, same path); all exit 0. SIGHUP matters because a terminal that goes away, or a TUI killed while it is the session leader, sends it to the foreground process group, which includes the agent; its default action kills the agent before it can reap anything. SIGKILL cannot be handled and orphans the tools. `tests/test_acp_shutdown.py` runs `tests/_tool_agent.py` (the real `serve()` with a scripted `bash` call) and checks EOF, SIGTERM and SIGHUP; POSIX only.
43+
The agent must reap the tools it is running when its client goes away: the TUI closes the agent's stdin and kills it only after a grace period (`acp/spawn.rs`, `AGENT_EOF_GRACE`). `serve()` ends on EOF on stdin (`run_agent` returns, `asyncio.run` cancels the turns in flight, each `bash` tool kills its process group) and on SIGTERM / SIGHUP (the main task is cancelled, same path); all exit 0. SIGHUP matters because a terminal that goes away, or a TUI killed while it is the session leader, sends it to the foreground process group, which includes the agent; its default action kills the agent before it can reap anything. A repeated signal gets the default action (the handlers remove themselves on the first one), so an agent that hangs while it stops — a thread that cannot be cancelled keeps `asyncio.run` from returning — can still be killed. SIGKILL cannot be handled and orphans the tools. `tests/test_acp_shutdown.py` runs `tests/_tool_agent.py` (the real `serve()` with a scripted `bash` call, or a stuck thread) and checks EOF, SIGTERM, SIGHUP and the repeated signal; POSIX only.
4444

4545
## System prompt pipeline
4646

‎packages/pi-agent-cli/pi_agent_cli/__main__.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,18 @@ async def serve(agent: PiAcpAgent) -> None:
4646
main_task = asyncio.current_task()
4747
if main_task is not None:
4848
loop = asyncio.get_running_loop()
49+
50+
def request_stop() -> None:
51+
# A repeated signal gets the default action, so an agent that hangs while it
52+
# shuts down (a thread that cannot be cancelled) can still be stopped.
53+
for stop_signal in _STOP_SIGNALS:
54+
with contextlib.suppress(NotImplementedError, RuntimeError):
55+
loop.remove_signal_handler(stop_signal)
56+
main_task.cancel()
57+
4958
for stop_signal in _STOP_SIGNALS:
5059
with contextlib.suppress(NotImplementedError, RuntimeError):
51-
loop.add_signal_handler(stop_signal, main_task.cancel)
60+
loop.add_signal_handler(stop_signal, request_stop)
5261
# `session/close` and `session/resume` are unstable in the SDK and answered with
5362
# "Method not found" unless this flag is set, although `initialize` advertises both.
5463
with contextlib.suppress(asyncio.CancelledError):

‎packages/pi-agent-cli/tests/_tool_agent.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,16 @@
22
33
The command records the shell pid in ``PI_TEST_TOOL_PIDFILE`` and then ``exec``s ``sleep``, so the
44
pid in that file is the pid of the tool process itself. ``permission = "auto"`` keeps the tool
5-
call from waiting for the client. Run it as ``python _tool_agent.py`` with ``PI_HOME`` set.
5+
call from waiting for the client. With ``PI_TEST_STUCK_THREAD`` set the turn instead blocks in a
6+
thread that cannot be cancelled (the file then holds the agent's pid), to test a shutdown that
7+
hangs. Run it as ``python _tool_agent.py`` with ``PI_HOME`` set.
68
"""
79

810
from __future__ import annotations
911

1012
import asyncio
1113
import os
14+
import time
1215
from pathlib import Path
1316

1417
from pi_agent_cli.__main__ import serve
@@ -25,6 +28,11 @@
2528
async def _long_bash_once_stream(model, context, options=None):
2629
if any(getattr(m, "role", None) == "toolResult" for m in context.messages):
2730
return await mock_text_stream(model, context, options)
31+
if os.environ.get("PI_TEST_STUCK_THREAD"):
32+
# A blocking call that cannot be cancelled: `asyncio.run` waits for it at shutdown, so
33+
# the agent hangs there. The pidfile holds the agent's own pid in this mode.
34+
Path(PIDFILE).write_text(str(os.getpid()))
35+
await asyncio.to_thread(time.sleep, 120)
2836
stream = AssistantMessageEventStream()
2937
tc: ToolCallContent = {
3038
"type": "toolCall",

‎packages/pi-agent-cli/tests/test_acp_shutdown.py‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,18 @@ async def _assert_tool_reaped(pid: int) -> None:
7373

7474

7575
@asynccontextmanager
76-
async def agent_running_a_tool(home: Path) -> AsyncIterator[tuple[asyncio.subprocess.Process, int]]:
77-
"""An agent process in the middle of a ``bash`` call; yields it and the tool's pid."""
76+
async def agent_running_a_tool(
77+
home: Path, *, stuck_thread: bool = False
78+
) -> AsyncIterator[tuple[asyncio.subprocess.Process, int]]:
79+
"""An agent process in the middle of a ``bash`` call; yields it and the tool's pid.
80+
81+
With ``stuck_thread`` the turn blocks in an uncancellable thread instead, and the pid is the
82+
agent's own.
83+
"""
7884
pidfile = home / "tool.pid"
7985
env = {"PI_HOME": str(home), "PI_TEST_TOOL_PIDFILE": str(pidfile)}
86+
if stuck_thread:
87+
env["PI_TEST_STUCK_THREAD"] = "1"
8088
async with spawn_agent_process(
8189
_SilentClient(),
8290
sys.executable,
@@ -122,3 +130,14 @@ async def test_stop_signals_stop_the_agent_and_reap_the_running_tool(tmp_path, s
122130
await asyncio.wait_for(process.wait(), EXIT_TIMEOUT)
123131
assert process.returncode == 0
124132
await _assert_tool_reaped(tool_pid)
133+
134+
135+
async def test_a_repeated_signal_stops_an_agent_whose_shutdown_hangs(tmp_path):
136+
"""The first SIGTERM starts a graceful stop; if that hangs, the second one must still kill."""
137+
async with agent_running_a_tool(tmp_path, stuck_thread=True) as (process, _agent_pid):
138+
process.send_signal(signal.SIGTERM)
139+
with pytest.raises(asyncio.TimeoutError):
140+
await asyncio.wait_for(asyncio.shield(process.wait()), 1.5) # still shutting down
141+
process.send_signal(signal.SIGTERM)
142+
await asyncio.wait_for(process.wait(), EXIT_TIMEOUT)
143+
assert process.returncode == -signal.SIGTERM

0 commit comments

Comments
 (0)