You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I hit this on ipykernel 7.4.0 (latest release; _cancel_on_sigint is unchanged on main) and I think I found the cause.
While an async cell runs, _cancel_on_sigint installs a Python-level SIGINT handler. CPython only runs Python signal handlers when the main thread executes bytecode, but during await asyncio.sleep(10) the main thread is parked in the event loop's selector. Nothing in the kernel registers a wakeup fd (signal.set_wakeup_fd returns -1 there), so the C-level handler just sets its flag and the selector keeps sleeping. handle_sigint — and with it the cancellation — only runs when something else wakes the loop: the sleep ending, another timer, another fd becoming readable. That would also explain why interrupting async cells sometimes seems to work: any other activity on the loop (a background task ticking, a child process exiting because it got the process-group SIGINT) wakes it up.
asyncio's own loop.add_signal_handler() avoids this by registering a socketpair with signal.set_wakeup_fd(). Doing the same inside the kernel fixes it in my tests. Minimal reproduction with the stock AsyncKernelManager.interrupt_kernel():
"""ipykernel: interrupting `await asyncio.sleep(10)` only takes effect when the sleep ends."""importasyncio, timefromjupyter_client.managerimportAsyncKernelManagerWAKEUP="""import asyncio, signal, socketr, w = socket.socketpair()r.setblocking(False); w.setblocking(False)asyncio.get_running_loop().add_reader(r.fileno(), lambda: r.recv(4096))signal.set_wakeup_fd(w.fileno(), warn_on_full_buffer=False)"""asyncdefrun(client, code):
msg_id=client.execute(code)
whileTrue:
reply=awaitclient.get_shell_msg(timeout=60)
ifreply["parent_header"].get("msg_id") ==msg_id:
returnreply["content"]
asyncdefinterrupted_sleep(km, client):
msg_id=client.execute("import asyncio\nawait asyncio.sleep(10)")
awaitasyncio.sleep(1)
t0=time.perf_counter()
awaitkm.interrupt_kernel()
whileTrue:
reply=awaitclient.get_shell_msg(timeout=60)
ifreply["parent_header"].get("msg_id") ==msg_id:
returntime.perf_counter() -t0, reply["content"]["status"], reply["content"].get("ename")
asyncdefmain():
km=AsyncKernelManager(kernel_name="python3")
awaitkm.start_kernel()
client=km.client(); client.start_channels(); awaitclient.wait_for_ready(timeout=30)
try:
print("signal.set_wakeup_fd in the kernel:", (awaitrun(client, "import signal\nfd = signal.set_wakeup_fd(-1); signal.set_wakeup_fd(fd); assert fd == -1")))
took, status, ename=awaitinterrupted_sleep(km, client)
print(f"without a wakeup fd: reply after {took:.2f}s status={status} ename={ename}")
awaitrun(client, WAKEUP)
took, status, ename=awaitinterrupted_sleep(km, client)
print(f"with a wakeup fd: reply after {took:.2f}s status={status} ename={ename}")
finally:
client.stop_channels(); awaitkm.shutdown_kernel(now=True)
asyncio.run(main())
without a wakeup fd: reply after 9.11s status=error ename=CancelledError
with a wakeup fd: reply after 0.02s status=error ename=CancelledError
Two notes from testing the workaround inside kernels:
While the kernel is idle SIGINT is SIG_IGN, so the wakeup fd receives nothing then; in-flight background tasks kept running across the interrupt, and interrupting a blocking sync cell (time.sleep) still raises KeyboardInterrupt as before.
A coroutine that blocks the loop itself (async def f(): time.sleep(5) / await f(), the case discussed in interrupt issues with async code #1239) is a separate problem: the cancellation can only land at the next await, so a wakeup fd does not help there.
If this direction makes sense, registering the wakeup fd on the kernel's io loop (as add_signal_handler does) looks like a small change.
Activity
davidbrochart commentedon Jan 2, 2023
This also happens with:
Which means that this test is incomplete.
MichengLiang commentedon Nov 26, 2026
I hit this on ipykernel 7.4.0 (latest release;
_cancel_on_sigintis unchanged onmain) and I think I found the cause.While an async cell runs,
_cancel_on_sigintinstalls a Python-level SIGINT handler. CPython only runs Python signal handlers when the main thread executes bytecode, but duringawait asyncio.sleep(10)the main thread is parked in the event loop's selector. Nothing in the kernel registers a wakeup fd (signal.set_wakeup_fdreturns-1there), so the C-level handler just sets its flag and the selector keeps sleeping.handle_sigint— and with it the cancellation — only runs when something else wakes the loop: the sleep ending, another timer, another fd becoming readable. That would also explain why interrupting async cells sometimes seems to work: any other activity on the loop (a background task ticking, a child process exiting because it got the process-group SIGINT) wakes it up.asyncio's own
loop.add_signal_handler()avoids this by registering a socketpair withsignal.set_wakeup_fd(). Doing the same inside the kernel fixes it in my tests. Minimal reproduction with the stockAsyncKernelManager.interrupt_kernel():Output (Linux, Python 3.13.16, ipykernel 7.4.0, jupyter_client 8.10.0):
Two notes from testing the workaround inside kernels:
SIG_IGN, so the wakeup fd receives nothing then; in-flight background tasks kept running across the interrupt, and interrupting a blocking sync cell (time.sleep) still raisesKeyboardInterruptas before.async def f(): time.sleep(5)/await f(), the case discussed in interrupt issues with async code #1239) is a separate problem: the cancellation can only land at the nextawait, so a wakeup fd does not help there.If this direction makes sense, registering the wakeup fd on the kernel's io loop (as
add_signal_handlerdoes) looks like a small change.