Skip to content

Cannot interrupt top-level coroutine #881

Open

Description

@davidbrochart

It looks like interrupting a cell execution which consists of awaiting a top-level coroutine, e.g.:

import asyncio

async def main():
    await asyncio.sleep(5)

await main()

doesn't take effect immediately, but once the coroutine completes execution.

See #880 for a test that reveals this bug.

Activity

  1. davidbrochart commented on Jan 2, 2023

    @davidbrochart
    CollaboratorAuthor

    This also happens with:

    import asyncio
    
    await asyncio.sleep(5)

    Which means that this test is incomplete.

  2. MichengLiang commented on Nov 26, 2026

    @MichengLiang

    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."""
    import asyncio, time
    from jupyter_client.manager import AsyncKernelManager
    
    WAKEUP = """
    import asyncio, signal, socket
    r, 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)
    """
    
    async def run(client, code):
        msg_id = client.execute(code)
        while True:
            reply = await client.get_shell_msg(timeout=60)
            if reply["parent_header"].get("msg_id") == msg_id:
                return reply["content"]
    
    async def interrupted_sleep(km, client):
        msg_id = client.execute("import asyncio\nawait asyncio.sleep(10)")
        await asyncio.sleep(1)
        t0 = time.perf_counter()
        await km.interrupt_kernel()
        while True:
            reply = await client.get_shell_msg(timeout=60)
            if reply["parent_header"].get("msg_id") == msg_id:
                return time.perf_counter() - t0, reply["content"]["status"], reply["content"].get("ename")
    
    async def main():
        km = AsyncKernelManager(kernel_name="python3")
        await km.start_kernel()
        client = km.client(); client.start_channels(); await client.wait_for_ready(timeout=30)
        try:
            print("signal.set_wakeup_fd in the kernel:", (await run(client, "import signal\nfd = signal.set_wakeup_fd(-1); signal.set_wakeup_fd(fd); assert fd == -1")))
            took, status, ename = await interrupted_sleep(km, client)
            print(f"without a wakeup fd: reply after {took:.2f}s  status={status} ename={ename}")
            await run(client, WAKEUP)
            took, status, ename = await interrupted_sleep(km, client)
            print(f"with a wakeup fd:    reply after {took:.2f}s  status={status} ename={ename}")
        finally:
            client.stop_channels(); await km.shutdown_kernel(now=True)
    
    asyncio.run(main())

    Output (Linux, Python 3.13.16, ipykernel 7.4.0, jupyter_client 8.10.0):

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions