|
| 1 | +"""Backend-agnostic detached task spawning. |
| 2 | +
|
| 3 | +``Query`` manages background tasks (the read loop, ``stream_input``, |
| 4 | +control-request handlers) that must be cancellable from any task context |
| 5 | +— including async-generator finalizers, which Python may run in a |
| 6 | +different task than the one that called ``start()``. anyio's |
| 7 | +``TaskGroup`` cannot be used for this because its cancel scope has task |
| 8 | +affinity: exiting it from a different task either raises ``RuntimeError: |
| 9 | +Attempted to exit cancel scope in a different task than it was entered |
| 10 | +in`` or busy-spins in ``_deliver_cancellation`` on the asyncio backend. |
| 11 | +
|
| 12 | +Under asyncio this is solved with plain ``loop.create_task()``, but that |
| 13 | +raises ``RuntimeError: no running event loop`` under trio. This module |
| 14 | +provides ``spawn_detached()`` which dispatches via sniffio to the |
| 15 | +appropriate backend primitive, returning a uniform ``TaskHandle``. |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +from collections.abc import Callable, Coroutine |
| 21 | +from contextlib import suppress |
| 22 | +from typing import Any |
| 23 | + |
| 24 | +import sniffio |
| 25 | + |
| 26 | + |
| 27 | +class TaskHandle: |
| 28 | + """Backend-agnostic handle to a detached background task. |
| 29 | +
|
| 30 | + Safe to ``.cancel()`` from any task — no anyio cancel-scope task |
| 31 | + affinity. |
| 32 | + """ |
| 33 | + |
| 34 | + def cancel(self) -> None: |
| 35 | + """Request cancellation of the wrapped task.""" |
| 36 | + raise NotImplementedError |
| 37 | + |
| 38 | + def done(self) -> bool: |
| 39 | + """Return True if the wrapped task has finished.""" |
| 40 | + raise NotImplementedError |
| 41 | + |
| 42 | + def add_done_callback(self, callback: Callable[[TaskHandle], None]) -> None: |
| 43 | + """Register ``callback(self)`` to run when the task finishes.""" |
| 44 | + raise NotImplementedError |
| 45 | + |
| 46 | + async def wait(self) -> None: |
| 47 | + """Wait for the task to finish. |
| 48 | +
|
| 49 | + Suppresses the backend's cancellation exception (the task was |
| 50 | + cancelled by us) but re-raises any other exception the task |
| 51 | + raised. |
| 52 | + """ |
| 53 | + raise NotImplementedError |
| 54 | + |
| 55 | + |
| 56 | +class _AsyncioTaskHandle(TaskHandle): |
| 57 | + """Thin wrapper around ``asyncio.Task``.""" |
| 58 | + |
| 59 | + def __init__(self, task: Any) -> None: |
| 60 | + self._task = task |
| 61 | + |
| 62 | + def cancel(self) -> None: |
| 63 | + self._task.cancel() |
| 64 | + |
| 65 | + def done(self) -> bool: |
| 66 | + return bool(self._task.done()) |
| 67 | + |
| 68 | + def add_done_callback(self, callback: Callable[[TaskHandle], None]) -> None: |
| 69 | + self._task.add_done_callback(lambda _t: callback(self)) |
| 70 | + |
| 71 | + async def wait(self) -> None: |
| 72 | + import asyncio |
| 73 | + |
| 74 | + with suppress(asyncio.CancelledError): |
| 75 | + await self._task |
| 76 | + |
| 77 | + |
| 78 | +class _TrioTaskHandle(TaskHandle): |
| 79 | + """Wraps a trio system task with its own ``CancelScope``.""" |
| 80 | + |
| 81 | + def __init__(self) -> None: |
| 82 | + import trio |
| 83 | + |
| 84 | + self._cancel_scope = trio.CancelScope() |
| 85 | + self._done_event = trio.Event() |
| 86 | + self._exception: BaseException | None = None |
| 87 | + self._callbacks: list[Callable[[TaskHandle], None]] = [] |
| 88 | + |
| 89 | + def cancel(self) -> None: |
| 90 | + # CancelScope.cancel() is sync and safe to call from any task. |
| 91 | + self._cancel_scope.cancel() |
| 92 | + |
| 93 | + def done(self) -> bool: |
| 94 | + return self._done_event.is_set() |
| 95 | + |
| 96 | + def add_done_callback(self, callback: Callable[[TaskHandle], None]) -> None: |
| 97 | + if self.done(): |
| 98 | + callback(self) |
| 99 | + else: |
| 100 | + self._callbacks.append(callback) |
| 101 | + |
| 102 | + def _mark_done(self, exc: BaseException | None) -> None: |
| 103 | + self._exception = exc |
| 104 | + self._done_event.set() |
| 105 | + for cb in self._callbacks: |
| 106 | + # Suppress BaseException so a misbehaving callback can never |
| 107 | + # propagate out of the system-task _runner (which would crash |
| 108 | + # trio with TrioInternalError). The actual callbacks used here |
| 109 | + # are set.discard / dict.pop, so this is purely defensive. |
| 110 | + with suppress(BaseException): |
| 111 | + cb(self) |
| 112 | + self._callbacks.clear() |
| 113 | + |
| 114 | + async def wait(self) -> None: |
| 115 | + import trio |
| 116 | + |
| 117 | + await self._done_event.wait() |
| 118 | + if self._exception is not None and not isinstance( |
| 119 | + self._exception, trio.Cancelled |
| 120 | + ): |
| 121 | + raise self._exception |
| 122 | + |
| 123 | + |
| 124 | +def spawn_detached(coro: Coroutine[Any, Any, Any]) -> TaskHandle: |
| 125 | + """Spawn ``coro`` as a detached background task on the current backend. |
| 126 | +
|
| 127 | + - **asyncio**: ``asyncio.get_running_loop().create_task(coro)``. |
| 128 | + - **trio**: ``trio.lowlevel.spawn_system_task`` wrapping ``coro`` in a |
| 129 | + per-task ``CancelScope`` so the handle supports ``.cancel()``. |
| 130 | + """ |
| 131 | + backend = sniffio.current_async_library() |
| 132 | + if backend == "asyncio": |
| 133 | + import asyncio |
| 134 | + |
| 135 | + loop = asyncio.get_running_loop() |
| 136 | + return _AsyncioTaskHandle(loop.create_task(coro)) |
| 137 | + if backend == "trio": |
| 138 | + import trio |
| 139 | + |
| 140 | + handle = _TrioTaskHandle() |
| 141 | + |
| 142 | + async def _runner() -> None: |
| 143 | + exc: BaseException | None = None |
| 144 | + try: |
| 145 | + with handle._cancel_scope: |
| 146 | + await coro |
| 147 | + except BaseException as e: # noqa: BLE001 |
| 148 | + # System tasks must not raise (would crash trio). Store |
| 149 | + # the exception on the handle; ``.wait()`` re-raises it. |
| 150 | + exc = e |
| 151 | + finally: |
| 152 | + handle._mark_done(exc) |
| 153 | + |
| 154 | + trio.lowlevel.spawn_system_task(_runner) |
| 155 | + return handle |
| 156 | + # Unsupported backend: close the coroutine so we don't leak a "coroutine |
| 157 | + # was never awaited" RuntimeWarning on top of the RuntimeError. |
| 158 | + coro.close() |
| 159 | + raise RuntimeError( |
| 160 | + f"Unsupported async backend: {backend!r}. " |
| 161 | + "claude_agent_sdk requires asyncio or trio." |
| 162 | + ) |
0 commit comments