Repository navigation
Expand file tree
/
Copy pathtest_force_stop.py
More file actions
305 lines (258 loc) · 10.6 KB
/
Copy pathtest_force_stop.py
File metadata and controls
305 lines (258 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# Copyright (c) Microsoft Corporation. All rights reserved.
"""Public TCP-backed tests for SDK-local force-stop retirement."""
import asyncio
import gc
import json
import logging
import threading
import weakref
from collections.abc import AsyncIterator
from datetime import UTC, datetime
import pytest
from copilot import CopilotClient, RuntimeConnection
from copilot._sdk_protocol_version import SDK_PROTOCOL_VERSION
from copilot.session import PermissionHandler
class Peer:
def __init__(self):
self.requests: list[str] = []
self.sends_received = asyncio.Event()
self.expected_sends = 1
self.completion_supported = True
self.send_count = 0
self.failures: list[Exception] = []
self.writers: list[asyncio.StreamWriter] = []
self.tasks: list[asyncio.Task] = []
async def serve(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
self.writers.append(writer)
try:
while True:
try:
header = await reader.readuntil(b"\r\n\r\n")
except asyncio.IncompleteReadError as error:
if error.partial:
raise
return
lengths = [
int(line.split(b":", 1)[1])
for line in header.split(b"\r\n")
if line.lower().startswith(b"content-length:")
]
assert len(lengths) == 1
assert 0 < lengths[0] <= 128 * 1024
request = json.loads(await reader.readexactly(lengths[0]))
method = request["method"]
self.requests.append(method)
result = None
rpc_error = None
if method == "connect":
result = {
"ok": True,
"protocolVersion": SDK_PROTOCOL_VERSION,
"version": "force-stop-test",
}
elif method == "ping":
result = {
"message": "pong",
"timestamp": datetime.now(UTC).isoformat(),
"protocolVersion": SDK_PROTOCOL_VERSION,
}
elif method == "session.create":
result = {"sessionId": request["params"]["sessionId"]}
elif method == "session.send":
self.send_count += 1
result = {"messageId": f"message-{self.send_count}"}
elif method == "session.sendAndWait":
if self.completion_supported:
self.send_count += 1
if self.send_count == self.expected_sends:
self.sends_received.set()
continue
rpc_error = {"code": -32601, "message": "Method not found"}
elif method == "$/cancelRequest":
continue
elif method == "session.detach":
result = {"success": True}
else:
raise AssertionError(f"Unexpected RPC: {method}")
body = json.dumps(
{
"jsonrpc": "2.0",
"id": request["id"],
**({"error": rpc_error} if rpc_error else {"result": result}),
}
).encode()
writer.write(f"Content-Length: {len(body)}\r\n\r\n".encode() + body)
await writer.drain()
if self.send_count == self.expected_sends:
self.sends_received.set()
except Exception as error:
self.failures.append(error)
finally:
writer.close()
await writer.wait_closed()
@pytest.fixture
async def connected_peer() -> AsyncIterator[tuple[CopilotClient, Peer]]:
peer = Peer()
def accepted(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
peer.tasks.append(asyncio.create_task(peer.serve(reader, writer)))
server = await asyncio.start_server(accepted, "127.0.0.1", 0)
client = CopilotClient(
mode="coding-agent",
runtime=RuntimeConnection.for_tcp("127.0.0.1", server.sockets[0].getsockname()[1]),
)
try:
await client.start()
yield client, peer
finally:
try:
await client.force_stop()
finally:
server.close()
await server.wait_closed()
for writer in peer.writers:
writer.close()
if peer.tasks:
await asyncio.gather(*peer.tasks)
assert peer.failures == []
@pytest.mark.parametrize("count", [1, 2])
@pytest.mark.parametrize("completion_supported", [True, False])
async def test_force_stop_rejects_acknowledged_plain_waits(
connected_peer, count, completion_supported
):
client, peer = connected_peer
peer.expected_sends = count
peer.completion_supported = completion_supported
session = await client.create_session(
session_id="retirement-session", permissions={"on_request": PermissionHandler.approve_all}
)
waits = [
asyncio.create_task(session.send_and_wait("hold the response", timeout=float("inf")))
for _ in range(count)
]
try:
await asyncio.wait_for(peer.sends_received.wait(), 5)
# The later reply proves every preceding send reached the peer.
await client.ping()
await client.force_stop()
for wait in waits:
with pytest.raises(RuntimeError, match="Session closed before response completed"):
await wait
await session.disconnect()
assert "session.detach" not in peer.requests
finally:
for wait in waits:
wait.cancel()
await asyncio.gather(*waits, return_exceptions=True)
class Capture:
def __call__(self, *_args, **_kwargs):
return None
async def captured_session(client: CopilotClient, kind: str):
capture = Capture()
reference = weakref.ref(capture)
options = {"permissions": {"on_request": PermissionHandler.approve_all}}
if kind == "permission":
options["permissions"] = {"on_request": capture}
elif kind == "user_input":
options["interaction"] = {"on_user_input_request": capture}
elif kind == "hook":
options["hooks"] = {"handlers": {"on_session_end": capture}}
session = await client.create_session(session_id="captured-session", **options)
if kind == "event":
session.on(capture)
return session, reference
@pytest.mark.parametrize("kind", ["event", "permission", "user_input", "hook"])
async def test_force_stop_releases_retained_session_callbacks(connected_peer, kind):
client, _peer = connected_peer
session, reference = await captured_session(client, kind)
assert reference() is not None
await client.force_stop()
gc.collect()
assert reference() is None
with pytest.raises(RuntimeError, match="Session is disconnected"):
session.on(Capture())
PARSE_WARNING = "Failed to parse incoming JSON-RPC message"
class HeldHeaderRead:
"""Reader side of the socket file that holds the header read after the next frame.
Once released, the held read either reads the closed socket file, or reads the
closed socket itself, as a reader already inside the file's read does.
"""
def __init__(self, stream, sock=None):
self._stream = stream
self._sock = sock
self._frame_read = False
self.holding = threading.Event()
self.release = threading.Event()
def __getattr__(self, name):
return getattr(self._stream, name)
def read(self, size):
self._frame_read = True
return self._stream.read(size)
def readline(self):
if self._frame_read:
self.holding.set()
# The test releases the read only after closing the transport; a timed release
# would let a slow run read the still-open socket and test another interleaving.
self.release.wait()
if self._sock is not None:
self._sock.recv(1)
return self._stream.readline()
def count_close_reports(client: CopilotClient) -> list[bool]:
reports: list[bool] = []
rpc = client._client
report_close = rpc.on_close
def on_close():
reports.append(True)
report_close()
rpc.on_close = on_close
return reports
def parse_warnings(caplog) -> list[logging.LogRecord]:
return [record for record in caplog.records if record.getMessage() == PARSE_WARNING]
@pytest.mark.parametrize(
"reader", ["waiting-for-frame", "between-frames-closed-file", "between-frames-closed-socket"]
)
async def test_force_stop_reports_close_without_parse_warning(connected_peer, caplog, reader):
client, _peer = connected_peer
caplog.set_level(logging.DEBUG, logger="copilot")
process = client._process
rpc = client._client
reports = count_close_reports(client)
held = None
try:
if reader.startswith("between-frames"):
# The reply to the ping is the last frame the reader takes before force_stop
# closes the socket underneath its next header read.
sock = process._socket if reader == "between-frames-closed-socket" else None
held = HeldHeaderRead(process.stdout, sock)
process.stdout = held
await client.ping()
await asyncio.to_thread(held.holding.wait)
else:
await client.ping()
await asyncio.sleep(0.1)
terminate = process.terminate
def terminate_then_finish_read():
terminate()
if held is not None:
held.release.set()
rpc._read_thread.join()
process.terminate = terminate_then_finish_read
await client.force_stop()
finally:
if held is not None:
held.release.set()
assert not rpc._read_thread.is_alive()
assert reports == [True]
assert parse_warnings(caplog) == []
async def test_malformed_frame_while_connected_still_logs_parse_warning(connected_peer, caplog):
client, peer = connected_peer
caplog.set_level(logging.DEBUG, logger="copilot")
reports = count_close_reports(client)
rpc = client._client
peer.writers[0].write(b"Content-Length: 6\r\n\r\n{oops}")
await peer.writers[0].drain()
await asyncio.to_thread(rpc._read_thread.join)
assert not rpc._read_thread.is_alive()
assert reports == [True]
warnings = parse_warnings(caplog)
assert len(warnings) == 1
assert isinstance(warnings[0].exc_info[1], json.JSONDecodeError)