Debian Codegraph @

tests/test_subshells.py

raw
1 """Test kernel subshells."""
2
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
5 from __future__ import annotations
6
7 import platform
8 import time
9 from collections import Counter
10 from queue import Empty
11
12 import pytest
13 from jupyter_client.blocking.client import BlockingKernelClient
14
15 from .utils import (
16 TIMEOUT,
17 assemble_output,
18 flush_channels,
19 get_replies,
20 get_reply,
21 new_kernel,
22 wait_for_idle,
23 )
24
25 # Helpers
26
27
28 def create_subshell_helper(kc: BlockingKernelClient):
29 msg = kc.session.msg("create_subshell_request")
30 kc.control_channel.send(msg)
31 msg_id = msg["header"]["msg_id"]
32 reply = get_reply(kc, msg_id, TIMEOUT, channel="control")
33 return reply["content"]
34
35
36 def delete_subshell_helper(kc: BlockingKernelClient, subshell_id: str):
37 msg = kc.session.msg("delete_subshell_request", {"subshell_id": subshell_id})
38 kc.control_channel.send(msg)
39 msg_id = msg["header"]["msg_id"]
40 reply = get_reply(kc, msg_id, TIMEOUT, channel="control")
41 return reply["content"]
42
43
44 def list_subshell_helper(kc: BlockingKernelClient):
45 msg = kc.session.msg("list_subshell_request")
46 kc.control_channel.send(msg)
47 msg_id = msg["header"]["msg_id"]
48 reply = get_reply(kc, msg_id, TIMEOUT, channel="control")
49 return reply["content"]
50
51
52 def execute_request(
53 kc: BlockingKernelClient, code: str, subshell_id: str | None, silent: bool = False
54 ):
55 msg = kc.session.msg("execute_request", {"code": code, "silent": silent})
56 msg["header"]["subshell_id"] = subshell_id
57 kc.shell_channel.send(msg)
58 return msg
59
60
61 def execute_request_subshell_id(
62 kc: BlockingKernelClient, code: str, subshell_id: str | None, terminator: str = "\n"
63 ):
64 msg = execute_request(kc, code, subshell_id)
65 msg_id = msg["header"]["msg_id"]
66 stdout, _ = assemble_output(kc.get_iopub_msg, None, msg_id)
67 return stdout.strip()
68
69
70 def execute_thread_count(kc: BlockingKernelClient) -> int:
71 code = "print(threading.active_count())"
72 return int(execute_request_subshell_id(kc, code, None))
73
74
75 def execute_thread_ids(kc: BlockingKernelClient, subshell_id: str | None = None) -> tuple[str, str]:
76 code = "print(threading.get_ident(), threading.main_thread().ident)"
77 return execute_request_subshell_id(kc, code, subshell_id).split()
78
79
80 # Tests
81
82
83 def test_no_subshells():
84 with new_kernel() as kc:
85 # Test operation of separate channel thread without using any subshells.
86 execute_request_subshell_id(kc, "a = 2*3", None)
87 res = execute_request_subshell_id(kc, "print(a)", None)
88 assert res == "6"
89
90
91 def test_supported():
92 with new_kernel() as kc:
93 msg_id = kc.kernel_info()
94 reply = get_reply(kc, msg_id, TIMEOUT)
95 assert "supported_features" in reply["content"]
96 assert "kernel subshells" in reply["content"]["supported_features"]
97
98
99 def test_subshell_id_lifetime():
100 with new_kernel() as kc:
101 assert list_subshell_helper(kc)["subshell_id"] == []
102 subshell_id = create_subshell_helper(kc)["subshell_id"]
103 assert list_subshell_helper(kc)["subshell_id"] == [subshell_id]
104 delete_subshell_helper(kc, subshell_id)
105 assert list_subshell_helper(kc)["subshell_id"] == []
106
107
108 def test_thread_counts():
109 with new_kernel() as kc:
110 execute_request_subshell_id(kc, "import threading", None)
111 nthreads = execute_thread_count(kc)
112
113 subshell_id = create_subshell_helper(kc)["subshell_id"]
114 nthreads2 = execute_thread_count(kc)
115 assert nthreads2 > nthreads
116
117 delete_subshell_helper(kc, subshell_id)
118 nthreads3 = execute_thread_count(kc)
119 assert nthreads3 == nthreads
120
121
122 def test_thread_ids():
123 with new_kernel() as kc:
124 execute_request_subshell_id(kc, "import threading", None)
125 subshell_id = create_subshell_helper(kc)["subshell_id"]
126
127 thread_id, main_thread_id = execute_thread_ids(kc)
128 assert thread_id == main_thread_id
129
130 thread_id, main_thread_id = execute_thread_ids(kc, subshell_id) # This is the problem
131 assert thread_id != main_thread_id
132
133 delete_subshell_helper(kc, subshell_id)
134
135
136 @pytest.mark.parametrize("are_subshells", [(False, True), (True, False), (True, True)])
137 @pytest.mark.parametrize("overlap", [True, False])
138 def test_run_concurrently_sequence(are_subshells, overlap, request):
139 if request.config.getvalue("--cov"):
140 pytest.skip("Skip time-sensitive subshell tests if measuring coverage")
141
142 with new_kernel() as kc:
143 subshell_ids = [
144 create_subshell_helper(kc)["subshell_id"] if is_subshell else None
145 for is_subshell in are_subshells
146 ]
147
148 # Import time module before running time-sensitive subshell code
149 # and use threading.Barrier to synchronise start of subshell code.
150 execute_request_subshell_id(
151 kc, "import threading as t, time; b=t.Barrier(2); print('ok')", None
152 )
153
154 sleep = 0.5
155 if overlap:
156 codes = [
157 f"b.wait(); start0=True; end0=False; time.sleep({sleep}); end0=True",
158 f"b.wait(); time.sleep({sleep / 2}); assert start0; assert not end0; time.sleep({sleep}); assert end0",
159 ]
160 else:
161 codes = [
162 f"b.wait(); start0=True; end0=False; time.sleep({sleep}); assert end1",
163 f"b.wait(); time.sleep({sleep / 2}); assert start0; assert not end0; end1=True",
164 ]
165
166 msgs = []
167 for subshell_id, code in zip(subshell_ids, codes, strict=False):
168 msg = kc.session.msg("execute_request", {"code": code})
169 msg["header"]["subshell_id"] = subshell_id
170 kc.shell_channel.send(msg)
171 msgs.append(msg)
172
173 replies = get_replies(kc, [msg["msg_id"] for msg in msgs], timeout=None)
174
175 for subshell_id in subshell_ids:
176 if subshell_id:
177 delete_subshell_helper(kc, subshell_id)
178
179 for reply in replies:
180 assert reply["content"]["status"] == "ok", reply
181
182
183 def test_create_while_execute():
184 with new_kernel() as kc:
185 # Send request to execute code on main subshell.
186 msg = kc.session.msg("execute_request", {"code": "import time; time.sleep(0.05)"})
187 kc.shell_channel.send(msg)
188
189 # Create subshell via control channel.
190 control_msg = kc.session.msg("create_subshell_request")
191 kc.control_channel.send(control_msg)
192 control_reply = get_reply(kc, control_msg["header"]["msg_id"], TIMEOUT, channel="control")
193 subshell_id = control_reply["content"]["subshell_id"]
194 control_date = control_reply["header"]["date"]
195
196 # Get result message from main subshell.
197 shell_date = get_reply(kc, msg["msg_id"])["header"]["date"]
198
199 delete_subshell_helper(kc, subshell_id)
200
201 assert control_date < shell_date
202
203
204 @pytest.mark.skipif(
205 platform.python_implementation() == "PyPy",
206 reason="does not work on PyPy",
207 )
208 def test_shutdown_with_subshell():
209 # Based on test_kernel.py::test_shutdown
210 with new_kernel() as kc:
211 km = kc.parent
212 subshell_id = create_subshell_helper(kc)["subshell_id"]
213 assert list_subshell_helper(kc)["subshell_id"] == [subshell_id]
214 kc.shutdown()
215 for _ in range(100): # 10 s timeout
216 if km.is_alive():
217 time.sleep(0.1)
218 else:
219 break
220 assert not km.is_alive()
221
222
223 @pytest.mark.parametrize("are_subshells", [(False, True), (True, False), (True, True)])
224 def test_execute_stop_on_error(are_subshells):
225 # Based on test_message_spec.py::test_execute_stop_on_error, testing that exception
226 # in one subshell aborts execution queue in that subshell but not others.
227 with new_kernel() as kc:
228 subshell_ids = [
229 create_subshell_helper(kc)["subshell_id"] if is_subshell else None
230 for is_subshell in are_subshells
231 ]
232
233 msg_ids = []
234
235 msg = execute_request(
236 kc, "import asyncio; await asyncio.sleep(1); raise ValueError()", subshell_ids[0]
237 )
238 msg_ids.append(msg["header"]["msg_id"])
239 msg = execute_request(kc, "print('hello')", subshell_ids[0])
240 msg_ids.append(msg["header"]["msg_id"])
241 msg = execute_request(kc, "print('goodbye')", subshell_ids[0])
242 msg_ids.append(msg["header"]["msg_id"])
243
244 msg = execute_request(kc, "import time; time.sleep(1.5)", subshell_ids[1])
245 msg_ids.append(msg["header"]["msg_id"])
246 msg = execute_request(kc, "print('other')", subshell_ids[1])
247 msg_ids.append(msg["header"]["msg_id"])
248
249 replies = get_replies(kc, msg_ids)
250
251 assert replies[0]["parent_header"]["subshell_id"] == subshell_ids[0]
252 assert replies[1]["parent_header"]["subshell_id"] == subshell_ids[0]
253 assert replies[2]["parent_header"]["subshell_id"] == subshell_ids[0]
254 assert replies[3]["parent_header"]["subshell_id"] == subshell_ids[1]
255 assert replies[4]["parent_header"]["subshell_id"] == subshell_ids[1]
256
257 assert replies[0]["content"]["status"] == "error"
258 assert replies[1]["content"]["status"] == "aborted"
259 assert replies[2]["content"]["status"] == "aborted"
260 assert replies[3]["content"]["status"] == "ok"
261 assert replies[4]["content"]["status"] == "ok"
262
263 # Check abort is cleared.
264 msg = execute_request(kc, "print('check')", subshell_ids[0])
265 reply = get_reply(kc, msg["msg_id"])
266 assert reply["parent_header"]["subshell_id"] == subshell_ids[0]
267 assert reply["content"]["status"] == "ok"
268
269 # Cleanup
270 for subshell_id in subshell_ids:
271 if subshell_id:
272 delete_subshell_helper(kc, subshell_id)
273
274
275 @pytest.mark.parametrize("are_subshells", [(False, True), (True, False), (True, True)])
276 def test_idle_message_parent_headers(are_subshells):
277 with new_kernel() as kc:
278 # import time module on main shell.
279 msg = kc.session.msg("execute_request", {"code": "import time"})
280 kc.shell_channel.send(msg)
281
282 subshell_ids = [
283 create_subshell_helper(kc)["subshell_id"] if is_subshell else None
284 for is_subshell in are_subshells
285 ]
286
287 # Wait for all idle status messages to be received.
288 for _ in range(1 + sum(are_subshells)):
289 wait_for_idle(kc)
290
291 msg_ids = []
292 for subshell_id in subshell_ids:
293 msg = execute_request(kc, "time.sleep(0.5)", subshell_id)
294 msg_ids.append(msg["msg_id"])
295
296 # Expect 4 status messages (2 busy, 2 idle) on iopub channel for the two execute_requests
297 statuses = []
298 timeout = TIMEOUT # Combined timeout to receive all the status messages
299 t0 = time.time()
300 while True:
301 status = kc.get_iopub_msg(timeout=timeout)
302 if status["msg_type"] != "status" or status["parent_header"]["msg_id"] not in msg_ids:
303 continue
304 statuses.append(status)
305 if len(statuses) == 4:
306 break
307 t1 = time.time()
308 timeout -= t1 - t0
309 t0 = t1
310
311 execution_states = Counter(msg["content"]["execution_state"] for msg in statuses)
312 assert execution_states["busy"] == 2
313 assert execution_states["idle"] == 2
314
315 parent_msg_ids = Counter(msg["parent_header"]["msg_id"] for msg in statuses)
316 assert parent_msg_ids[msg_ids[0]] == 2
317 assert parent_msg_ids[msg_ids[1]] == 2
318
319 parent_subshell_ids = Counter(msg["parent_header"].get("subshell_id") for msg in statuses)
320 assert parent_subshell_ids[subshell_ids[0]] == 2
321 assert parent_subshell_ids[subshell_ids[1]] == 2
322
323 # Cleanup
324 for subshell_id in subshell_ids:
325 if subshell_id:
326 delete_subshell_helper(kc, subshell_id)
327
328
329 def test_silent_flag_in_subshells():
330 """Verifies that the 'silent' flag suppresses output in main and subshell contexts."""
331 with new_kernel() as kc:
332 subshell_id = None
333 try:
334 flush_channels(kc)
335 # Test silent execution in main shell
336 msg_main_silent = execute_request(kc, "a=1", None, silent=True)
337 reply_main_silent = get_reply(kc, msg_main_silent["header"]["msg_id"])
338 assert reply_main_silent["content"]["status"] == "ok"
339
340 # Test silent execution in subshell
341 subshell_id = create_subshell_helper(kc)["subshell_id"]
342 msg_sub_silent = execute_request(kc, "b=2", subshell_id, silent=True)
343 reply_sub_silent = get_reply(kc, msg_sub_silent["header"]["msg_id"])
344 assert reply_sub_silent["content"]["status"] == "ok"
345
346 # Check for no iopub messages (other than status) from the silent requests
347 for msg_id in [msg_main_silent["header"]["msg_id"], msg_sub_silent["header"]["msg_id"]]:
348 while True:
349 try:
350 msg = kc.get_iopub_msg(timeout=0.2)
351 if msg["header"]["msg_type"] == "status":
352 continue
353 pytest.fail(
354 f"Silent execution produced unexpected IOPub message: {msg['header']['msg_type']}"
355 )
356 except Empty:
357 break
358
359 # Test concurrent silent and non-silent execution
360 msg_silent = execute_request(
361 kc, "import time; time.sleep(0.5); c=3", subshell_id, silent=True
362 )
363 msg_noisy = execute_request(kc, "print('noisy')", None, silent=False)
364
365 # Wait for both replies
366 get_replies(kc, [msg_silent["header"]["msg_id"], msg_noisy["header"]["msg_id"]])
367
368 # Verify that we only receive stream output from the noisy message
369 stdout, stderr = assemble_output(
370 kc.get_iopub_msg, parent_msg_id=msg_noisy["header"]["msg_id"]
371 )
372 assert "noisy" in stdout
373 assert not stderr
374
375 # Verify there is no output from the concurrent silent message
376 while True:
377 try:
378 msg = kc.get_iopub_msg(timeout=0.2)
379 if (
380 msg["header"]["msg_type"] == "status"
381 and msg["parent_header"].get("msg_id") == msg_silent["header"]["msg_id"]
382 ):
383 continue
384 if msg["parent_header"].get("msg_id") == msg_silent["header"]["msg_id"]:
385 pytest.fail(
386 "Silent execution in concurrent setting produced unexpected IOPub message"
387 )
388 except Empty:
389 break
390 finally:
391 # Ensure subshell is always deleted
392 if subshell_id:
393 delete_subshell_helper(kc, subshell_id)