Skip to content

Commit 42ce4c0

Browse files
committed
fix: close owned agent stdio streams on shutdown
1 parent aade9c0 commit 42ce4c0

5 files changed

Lines changed: 205 additions & 49 deletions

File tree

‎src/acp/core.py‎

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from __future__ import annotations
99

1010
import asyncio
11+
from contextlib import nullcontext
1112
from typing import Any
1213

1314
from .agent.connection import AgentSideConnection
@@ -58,22 +59,26 @@ async def run_agent(
5859
**connection_kwargs: Additional keyword arguments to pass to the
5960
:class:`AgentSideConnection` constructor.
6061
"""
61-
from .stdio import stdio_streams
62-
63-
if input_stream is None and output_stream is None:
64-
output_stream, input_stream = await stdio_streams(limit=stdio_buffer_limit_bytes)
65-
conn = AgentSideConnection(
66-
agent,
67-
input_stream,
68-
output_stream,
69-
listening=False,
70-
use_unstable_protocol=use_unstable_protocol,
71-
**connection_kwargs,
62+
from .stdio import _owned_stdio_streams
63+
64+
streams = (
65+
_owned_stdio_streams(stdio_buffer_limit_bytes)
66+
if input_stream is None and output_stream is None
67+
else nullcontext((output_stream, input_stream))
7268
)
73-
try:
74-
await conn.listen()
75-
finally:
76-
await asyncio.shield(conn.close())
69+
async with streams as (reader, writer):
70+
conn = AgentSideConnection(
71+
agent,
72+
writer,
73+
reader,
74+
listening=False,
75+
use_unstable_protocol=use_unstable_protocol,
76+
**connection_kwargs,
77+
)
78+
try:
79+
await conn.listen()
80+
finally:
81+
await asyncio.shield(conn.close())
7782

7883

7984
def connect_to_agent(

‎src/acp/experimental/negotiation.py‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import asyncio
44
from collections.abc import Callable
5+
from contextlib import nullcontext
56
from typing import Any
67

78
from pydantic import BaseModel
@@ -203,17 +204,21 @@ async def run(
203204
stdio_buffer_limit_bytes: int = 50 * 1024 * 1024,
204205
**connection_kwargs: Any,
205206
) -> None:
206-
if input_stream is None and output_stream is None:
207-
from acp.stdio import stdio_streams
207+
from acp.stdio import _owned_stdio_streams
208208

209-
output_stream, input_stream = await stdio_streams(limit=stdio_buffer_limit_bytes)
210-
connection = self._connect(
211-
input_stream,
212-
output_stream,
213-
listening=False,
214-
**connection_kwargs,
209+
streams = (
210+
_owned_stdio_streams(stdio_buffer_limit_bytes)
211+
if input_stream is None and output_stream is None
212+
else nullcontext((output_stream, input_stream))
215213
)
216-
try:
217-
await connection._listen()
218-
finally:
219-
await asyncio.shield(connection.close())
214+
async with streams as (reader, writer):
215+
connection = self._connect(
216+
writer,
217+
reader,
218+
listening=False,
219+
**connection_kwargs,
220+
)
221+
try:
222+
await connection._listen()
223+
finally:
224+
await asyncio.shield(connection.close())

‎src/acp/experimental/v2/agent.py‎

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import asyncio
44
from collections.abc import Callable
5+
from contextlib import nullcontext
56
from functools import partial
67
from typing import Any, Literal, cast
78

@@ -239,18 +240,22 @@ async def run_agent(
239240
stdio_buffer_limit_bytes: int = 50 * 1024 * 1024,
240241
**connection_kwargs: Any,
241242
) -> None:
242-
if input_stream is None and output_stream is None:
243-
from acp.stdio import stdio_streams
244-
245-
output_stream, input_stream = await stdio_streams(limit=stdio_buffer_limit_bytes)
246-
connection = AgentSideConnection(
247-
agent,
248-
input_stream,
249-
output_stream,
250-
_listening=False,
251-
**connection_kwargs,
243+
from acp.stdio import _owned_stdio_streams
244+
245+
streams = (
246+
_owned_stdio_streams(stdio_buffer_limit_bytes)
247+
if input_stream is None and output_stream is None
248+
else nullcontext((output_stream, input_stream))
252249
)
253-
try:
254-
await connection._listen()
255-
finally:
256-
await asyncio.shield(connection.close())
250+
async with streams as (reader, writer):
251+
connection = AgentSideConnection(
252+
agent,
253+
writer,
254+
reader,
255+
_listening=False,
256+
**connection_kwargs,
257+
)
258+
try:
259+
await connection._listen()
260+
finally:
261+
await asyncio.shield(connection.close())

‎src/acp/stdio.py‎

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -121,17 +121,31 @@ async def _windows_stdio_streams(
121121
async def _posix_stdio_streams(
122122
loop: asyncio.AbstractEventLoop,
123123
limit: int | None = None,
124-
) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
124+
) -> tuple[asyncio.StreamReader, asyncio.StreamWriter, aio_transports.ReadTransport]:
125125
# Reader from stdin
126126
reader = asyncio.StreamReader(limit=limit) if limit is not None else asyncio.StreamReader()
127127
reader_protocol = asyncio.StreamReaderProtocol(reader)
128-
await loop.connect_read_pipe(lambda: reader_protocol, sys.stdin)
128+
read_transport, _ = await loop.connect_read_pipe(lambda: reader_protocol, sys.stdin)
129129

130130
# Writer to stdout with protocol providing _drain_helper
131131
write_protocol = _WritePipeProtocol()
132-
transport, _ = await loop.connect_write_pipe(lambda: write_protocol, sys.stdout)
132+
try:
133+
transport, _ = await loop.connect_write_pipe(lambda: write_protocol, sys.stdout)
134+
except BaseException:
135+
read_transport.close()
136+
raise
133137
writer = asyncio.StreamWriter(transport, write_protocol, None, loop)
134-
return reader, writer
138+
return reader, writer, read_transport
139+
140+
141+
async def _open_stdio_streams(
142+
limit: int | None,
143+
) -> tuple[asyncio.StreamReader, asyncio.StreamWriter, aio_transports.ReadTransport | None]:
144+
loop = asyncio.get_running_loop()
145+
if platform.system() == "Windows":
146+
reader, writer = await _windows_stdio_streams(loop, limit=limit)
147+
return reader, writer, None
148+
return await _posix_stdio_streams(loop, limit=limit)
135149

136150

137151
async def stdio_streams(limit: int | None = None) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:
@@ -144,10 +158,31 @@ async def stdio_streams(limit: int | None = None) -> tuple[asyncio.StreamReader,
144158
Args:
145159
limit: Optional buffer limit for the stdin reader.
146160
"""
147-
loop = asyncio.get_running_loop()
148-
if platform.system() == "Windows":
149-
return await _windows_stdio_streams(loop, limit=limit)
150-
return await _posix_stdio_streams(loop, limit=limit)
161+
reader, writer, _ = await _open_stdio_streams(limit)
162+
return reader, writer
163+
164+
165+
@asynccontextmanager
166+
async def _owned_stdio_streams(
167+
limit: int,
168+
*,
169+
close_timeout: float = 2.0,
170+
) -> AsyncIterator[tuple[asyncio.StreamReader, asyncio.StreamWriter]]:
171+
reader, writer, read_transport = await _open_stdio_streams(limit)
172+
try:
173+
yield reader, writer
174+
finally:
175+
if read_transport is not None:
176+
read_transport.close()
177+
writer.close()
178+
try:
179+
await asyncio.wait_for(asyncio.shield(writer.wait_closed()), timeout=close_timeout)
180+
except asyncio.TimeoutError:
181+
writer.transport.abort()
182+
with contextlib.suppress(ConnectionError):
183+
await asyncio.shield(writer.wait_closed())
184+
except ConnectionError:
185+
pass
151186

152187

153188
@asynccontextmanager

‎tests/real_user/test_stdio_shutdown.py‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,119 @@
11
import asyncio
2+
import asyncio.subprocess as aio_subprocess
23
import contextlib
4+
import json
35
import signal
46
import sys
7+
import textwrap
58

69
import pytest
710

811
from acp.transports import spawn_stdio_transport
912

1013

14+
@pytest.mark.asyncio
15+
@pytest.mark.parametrize(("runner", "version"), [("v1", 1), ("v2", 2), ("dual", 1), ("dual", 2)])
16+
async def test_agent_shutdown_after_stdio_eof(runner: str, version: int) -> None:
17+
script = textwrap.dedent("""
18+
import asyncio
19+
import sys
20+
21+
from acp import run_agent, schema
22+
from acp.experimental import v2
23+
from acp.experimental.negotiation import AgentProtocolRouter
24+
25+
class V1Agent:
26+
async def initialize(self, protocol_version, **kwargs):
27+
return schema.InitializeResponse(protocol_version=protocol_version)
28+
29+
class V2Agent:
30+
async def initialize(self, protocol_version, **kwargs):
31+
return v2.schema.InitializeResponse(
32+
protocol_version=protocol_version,
33+
info=v2.schema.Implementation(name="test-agent", version="0"),
34+
)
35+
36+
async def main():
37+
runner = sys.argv[1]
38+
if runner == "v1":
39+
await run_agent(V1Agent())
40+
elif runner == "v2":
41+
await v2.run_agent(V2Agent())
42+
else:
43+
await AgentProtocolRouter(v1=lambda _: V1Agent(), v2=lambda _: V2Agent()).run()
44+
45+
asyncio.run(main())
46+
""")
47+
params = {"protocolVersion": version}
48+
if version == 2:
49+
params = {"protocolVersion": version, "info": {"name": "test-client", "version": "0"}}
50+
initialize = {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": params}
51+
52+
async with spawn_stdio_transport(sys.executable, "-W", "error::ResourceWarning", "-c", script, runner) as (
53+
reader,
54+
writer,
55+
process,
56+
):
57+
writer.write(json.dumps(initialize).encode() + b"\n")
58+
await writer.drain()
59+
response = json.loads(await asyncio.wait_for(reader.readline(), timeout=5))
60+
assert response["id"] == 1
61+
assert response["result"]["protocolVersion"] == version
62+
63+
assert process.stderr is not None
64+
stderr = await asyncio.wait_for(process.stderr.read(), timeout=5)
65+
assert process.returncode == 0, stderr.decode()
66+
assert stderr == b"", stderr.decode()
67+
68+
69+
@pytest.mark.asyncio
70+
async def test_agent_shutdown_does_not_hang_on_full_unread_stdout_pipe() -> None:
71+
if sys.platform == "win32":
72+
pytest.skip("POSIX pipe backpressure test")
73+
script = textwrap.dedent("""
74+
import asyncio
75+
from acp import run_agent, schema
76+
77+
class LargeResponseAgent:
78+
async def initialize(self, protocol_version, **kwargs):
79+
return schema.InitializeResponse(
80+
protocol_version=protocol_version,
81+
agent_info=schema.Implementation(name="agent", version="x" * (512 * 1024)),
82+
)
83+
84+
asyncio.run(run_agent(LargeResponseAgent()))
85+
""")
86+
initialize = {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": 1}}
87+
process = await asyncio.create_subprocess_exec(
88+
sys.executable,
89+
"-W",
90+
"error::ResourceWarning",
91+
"-c",
92+
script,
93+
stdin=aio_subprocess.PIPE,
94+
stdout=aio_subprocess.PIPE,
95+
stderr=aio_subprocess.PIPE,
96+
)
97+
assert process.stdin is not None
98+
assert process.stdout is not None
99+
assert process.stderr is not None
100+
try:
101+
process.stdin.write(json.dumps(initialize).encode() + b"\n")
102+
await process.stdin.drain()
103+
# Let the agent fill the stdout pipe without draining it, then close stdin.
104+
await asyncio.sleep(0.1)
105+
process.stdin.close()
106+
await process.stdin.wait_closed()
107+
returncode = await asyncio.wait_for(process.wait(), timeout=5)
108+
stderr = await asyncio.wait_for(process.stderr.read(), timeout=5)
109+
assert returncode == 0, stderr.decode()
110+
assert stderr == b"", stderr.decode()
111+
finally:
112+
if process.returncode is None:
113+
process.kill()
114+
await process.wait()
115+
116+
11117
@pytest.mark.asyncio
12118
@pytest.mark.parametrize("ignore_terminate", [False, True])
13119
async def test_shutdown_with_unread_stdin(ignore_terminate: bool) -> None:

0 commit comments

Comments
 (0)