|
| 1 | +"""Portable task deadline and cancellation control. |
| 2 | +
|
| 3 | +Cancellation is cooperative at the Python coroutine boundary. A successful |
| 4 | +receipt means that cancellation was requested; it cannot promise that vendor |
| 5 | +tools have rolled back side effects that already happened. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import asyncio |
| 11 | +from collections.abc import Awaitable, Callable |
| 12 | +from dataclasses import dataclass |
| 13 | +from datetime import datetime, timezone |
| 14 | +from typing import Any, TypeVar |
| 15 | + |
| 16 | +from agent_runtime_kit._errors import AgentRuntimeError, AgentTaskTimeoutError |
| 17 | +from agent_runtime_kit._types import ( |
| 18 | + AgentRuntimeKind, |
| 19 | + AgentTask, |
| 20 | + CancellationDisposition, |
| 21 | + CancellationReceipt, |
| 22 | + FinishReason, |
| 23 | +) |
| 24 | +from agent_runtime_kit.events import safe_emit, task_failed_event |
| 25 | + |
| 26 | +_T = TypeVar("_T") |
| 27 | +_OPERATION_CLEANUP_TIMEOUT = 5.0 |
| 28 | + |
| 29 | + |
| 30 | +@dataclass |
| 31 | +class _ActiveRun: |
| 32 | + task: asyncio.Task[Any] |
| 33 | + cancellation_requested: bool = False |
| 34 | + |
| 35 | + |
| 36 | +class RuntimeTaskController: |
| 37 | + """Track active runs for one runtime and enforce their deadlines.""" |
| 38 | + |
| 39 | + def __init__(self, kind: AgentRuntimeKind | str) -> None: |
| 40 | + self.kind = AgentRuntimeKind.coerce(kind) |
| 41 | + self._active: dict[str, _ActiveRun] = {} |
| 42 | + self._quarantined: set[asyncio.Future[Any]] = set() |
| 43 | + |
| 44 | + async def run( |
| 45 | + self, |
| 46 | + task: AgentTask, |
| 47 | + operation: Callable[[], Awaitable[_T]], |
| 48 | + ) -> _T: |
| 49 | + """Run ``operation`` under task-id registration and deadline control.""" |
| 50 | + |
| 51 | + current = asyncio.current_task() |
| 52 | + if current is None: # pragma: no cover - asyncio always supplies one here |
| 53 | + raise AgentRuntimeError("task control requires an active asyncio task") |
| 54 | + self._quarantined = {item for item in self._quarantined if not item.done()} |
| 55 | + if self._quarantined: |
| 56 | + raise AgentRuntimeError( |
| 57 | + f"{self.kind} has a cancelled operation still cleaning up; " |
| 58 | + "wait for cleanup before starting another run" |
| 59 | + ) |
| 60 | + # These registry operations deliberately contain no await. asyncio tasks |
| 61 | + # share one event-loop thread, so the check-and-set is atomic without a |
| 62 | + # cancellable lock acquisition. The same is true of cleanup below. |
| 63 | + existing = self._active.get(task.task_id) |
| 64 | + if existing is not None: |
| 65 | + raise AgentRuntimeError( |
| 66 | + f"task_id {task.task_id!r} is already active for {self.kind}" |
| 67 | + ) |
| 68 | + self._active[task.task_id] = _ActiveRun(current) |
| 69 | + |
| 70 | + try: |
| 71 | + return await self._run_with_deadline(task, operation) |
| 72 | + finally: |
| 73 | + active = self._active.get(task.task_id) |
| 74 | + if active is not None and active.task is current: |
| 75 | + del self._active[task.task_id] |
| 76 | + |
| 77 | + async def cancel( |
| 78 | + self, |
| 79 | + task_id: str, |
| 80 | + *, |
| 81 | + _expected_task: asyncio.Task[Any] | None = None, |
| 82 | + ) -> CancellationReceipt: |
| 83 | + """Request cancellation of an active coroutine without blocking on it.""" |
| 84 | + |
| 85 | + active = self._active.get(task_id) |
| 86 | + if active is None or ( |
| 87 | + _expected_task is not None and active.task is not _expected_task |
| 88 | + ): |
| 89 | + return self._receipt(task_id, CancellationDisposition.NOT_ACTIVE) |
| 90 | + if active.cancellation_requested: |
| 91 | + return self._receipt(task_id, CancellationDisposition.ALREADY_REQUESTED) |
| 92 | + active.cancellation_requested = True |
| 93 | + accepted = active.task.cancel() |
| 94 | + if not accepted: |
| 95 | + return self._receipt( |
| 96 | + task_id, |
| 97 | + CancellationDisposition.FAILED, |
| 98 | + "the active asyncio task had already completed", |
| 99 | + ) |
| 100 | + return self._receipt(task_id, CancellationDisposition.REQUESTED) |
| 101 | + |
| 102 | + async def _run_with_deadline( |
| 103 | + self, |
| 104 | + task: AgentTask, |
| 105 | + operation: Callable[[], Awaitable[_T]], |
| 106 | + ) -> _T: |
| 107 | + deadline = task.deadline |
| 108 | + if deadline is None: |
| 109 | + try: |
| 110 | + return await operation() |
| 111 | + except asyncio.CancelledError: |
| 112 | + await self._emit_interrupted(task) |
| 113 | + raise |
| 114 | + |
| 115 | + remaining = (deadline - datetime.now(tz=timezone.utc)).total_seconds() |
| 116 | + if remaining <= 0: |
| 117 | + # An already-expired task never starts, including its started event. |
| 118 | + # Emit the terminal first so cancellation of a blocking observability |
| 119 | + # sink cannot strand the lifecycle after a misleading start. |
| 120 | + await self._emit_timed_out(task, deadline) |
| 121 | + raise AgentTaskTimeoutError(self.kind, task.task_id, deadline) |
| 122 | + |
| 123 | + operation_task: asyncio.Future[_T] = asyncio.ensure_future(operation()) |
| 124 | + timed_out = False |
| 125 | + try: |
| 126 | + done, _ = await asyncio.wait( |
| 127 | + {operation_task}, |
| 128 | + timeout=remaining, |
| 129 | + return_when=asyncio.FIRST_COMPLETED, |
| 130 | + ) |
| 131 | + if operation_task in done: |
| 132 | + return await operation_task |
| 133 | + |
| 134 | + # Transition before emitting: cancellation of a slow sink must never |
| 135 | + # turn one timeout into a second, contradictory interrupted terminal. |
| 136 | + timed_out = True |
| 137 | + if not await _cancel_and_settle(operation_task): |
| 138 | + self._quarantine(operation_task) |
| 139 | + await self._emit_timed_out(task, deadline) |
| 140 | + raise AgentTaskTimeoutError(self.kind, task.task_id, deadline) |
| 141 | + except asyncio.CancelledError: |
| 142 | + if not await _cancel_and_settle(operation_task): |
| 143 | + self._quarantine(operation_task) |
| 144 | + if not timed_out: |
| 145 | + await self._emit_interrupted(task) |
| 146 | + raise |
| 147 | + |
| 148 | + async def _emit_interrupted(self, task: AgentTask) -> None: |
| 149 | + await safe_emit( |
| 150 | + task, |
| 151 | + task_failed_event( |
| 152 | + task, |
| 153 | + self.kind, |
| 154 | + error="task cancellation requested", |
| 155 | + finish_reason=FinishReason.INTERRUPTED.value, |
| 156 | + ), |
| 157 | + ) |
| 158 | + |
| 159 | + async def _emit_timed_out(self, task: AgentTask, deadline: datetime) -> None: |
| 160 | + await safe_emit( |
| 161 | + task, |
| 162 | + task_failed_event( |
| 163 | + task, |
| 164 | + self.kind, |
| 165 | + error=f"task exceeded deadline {deadline.isoformat()}", |
| 166 | + finish_reason=FinishReason.TIMED_OUT.value, |
| 167 | + ), |
| 168 | + ) |
| 169 | + |
| 170 | + def _receipt( |
| 171 | + self, |
| 172 | + task_id: str, |
| 173 | + disposition: CancellationDisposition, |
| 174 | + message: str | None = None, |
| 175 | + ) -> CancellationReceipt: |
| 176 | + return CancellationReceipt( |
| 177 | + task_id=task_id, |
| 178 | + kind=self.kind, |
| 179 | + disposition=disposition, |
| 180 | + message=message, |
| 181 | + ) |
| 182 | + |
| 183 | + def _quarantine(self, operation: asyncio.Future[Any]) -> None: |
| 184 | + self._quarantined.add(operation) |
| 185 | + |
| 186 | + def release(completed: asyncio.Future[Any]) -> None: |
| 187 | + self._quarantined.discard(completed) |
| 188 | + _consume_operation_result(completed) |
| 189 | + |
| 190 | + operation.add_done_callback(release) |
| 191 | + |
| 192 | + |
| 193 | +async def run_legacy_with_deadline( |
| 194 | + task: AgentTask, |
| 195 | + kind: AgentRuntimeKind | str, |
| 196 | + operation: Callable[[], Awaitable[_T]], |
| 197 | +) -> _T: |
| 198 | + """Enforce deadlines for third-party runtimes without native task control.""" |
| 199 | + |
| 200 | + # A fresh controller is intentional: AgentKit owns cancellation tracking for |
| 201 | + # legacy runtimes, while this helper owns only this invocation's deadline and |
| 202 | + # terminal event semantics. |
| 203 | + controller = RuntimeTaskController(kind) |
| 204 | + return await controller.run(task, operation) |
| 205 | + |
| 206 | + |
| 207 | +async def _cancel_and_settle(operation: asyncio.Future[Any]) -> bool: |
| 208 | + """Give a cancelled operation bounded, repeat-cancel-safe cleanup time.""" |
| 209 | + |
| 210 | + operation.cancel() |
| 211 | + deadline = asyncio.get_running_loop().time() + _OPERATION_CLEANUP_TIMEOUT |
| 212 | + while not operation.done(): |
| 213 | + remaining = deadline - asyncio.get_running_loop().time() |
| 214 | + if remaining <= 0: |
| 215 | + operation.cancel() |
| 216 | + return False |
| 217 | + try: |
| 218 | + await asyncio.wait_for(asyncio.shield(operation), timeout=remaining) |
| 219 | + except asyncio.CancelledError: |
| 220 | + continue |
| 221 | + except asyncio.TimeoutError: |
| 222 | + operation.cancel() |
| 223 | + return False |
| 224 | + except Exception: |
| 225 | + break |
| 226 | + _consume_operation_result(operation) |
| 227 | + return True |
| 228 | + |
| 229 | + |
| 230 | +def _consume_operation_result(operation: asyncio.Future[Any]) -> None: |
| 231 | + try: |
| 232 | + operation.exception() |
| 233 | + except BaseException: |
| 234 | + return |
0 commit comments