Skip to content

Commit 02c59e8

Browse files
committed
Catch errors on main subshell stop and remove redundant cancel scope.
1 parent 8fc455c commit 02c59e8

File tree

1 file changed

+21
-18
lines changed

1 file changed

+21
-18
lines changed

ipykernel/kernelbase.py

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@
4242
import zmq_anyio
4343
from anyio import (
4444
TASK_STATUS_IGNORED,
45-
CancelScope,
4645
Event,
4746
create_memory_object_stream,
4847
create_task_group,
@@ -441,30 +440,34 @@ async def shell_main(self, subshell_id: str | None):
441440
if socket not in self._send_exec_request:
442441
send_stream, receive_stream = create_memory_object_stream(max_buffer_size=math.inf)
443442
self._send_exec_request[socket] = send_stream
444-
async with create_task_group() as tg:
445-
if not socket.started.is_set():
446-
await tg.start(socket.start)
447-
tg.start_soon(self._process_shell, socket)
448-
tg.start_soon(self._execute_request_loop, receive_stream)
449-
if not subshell_id:
450-
# Main subshell
451-
with contextlib.suppress(RuntimeError):
452-
self.set_trait("asyncio_event_loop", asyncio.get_running_loop())
453-
async with create_task_group() as tg_main:
454-
with CancelScope(shield=True) as scope:
443+
try:
444+
async with create_task_group() as tg:
445+
if not socket.started.is_set():
446+
await tg.start(socket.start)
447+
tg.start_soon(self._process_shell, socket)
448+
tg.start_soon(self._execute_request_loop, receive_stream)
449+
if not subshell_id:
450+
# Main subshell
451+
with contextlib.suppress(RuntimeError):
452+
self.set_trait("asyncio_event_loop", asyncio.get_running_loop())
453+
async with create_task_group() as tg_main:
454+
tg_main.cancel_scope.shield = True
455455
self._tg_main = tg_main
456456
async with BlockingPortal() as portal:
457457
# Provide a portal for general threadsafe access
458458
self._portal = portal
459459
self._main_subshell_ready.set()
460460
await to_thread.run_sync(self.shell_stop.wait)
461461
await portal.stop(True)
462-
scope.cancel()
463-
tg_main.cancel_scope.cancel()
464-
tg.cancel_scope.cancel()
465-
self._send_exec_request.pop(socket, None)
466-
await send_stream.aclose()
467-
await receive_stream.aclose()
462+
tg_main.cancel_scope.cancel()
463+
tg.cancel_scope.cancel()
464+
except BaseException:
465+
if not self.shell_stop.is_set():
466+
raise
467+
finally:
468+
self._send_exec_request.pop(socket, None)
469+
await send_stream.aclose()
470+
await receive_stream.aclose()
468471

469472
async def _execute_request_loop(self, receive_stream: MemoryObjectReceiveStream):
470473
async with receive_stream:

0 commit comments

Comments
 (0)