diff --git a/docs/async-orchestrators.md b/docs/async-orchestrators.md index 294a8a1c..4845a64c 100644 --- a/docs/async-orchestrators.md +++ b/docs/async-orchestrators.md @@ -195,19 +195,31 @@ The dispatch-local loop supports FIFO ready callbacks, local futures and tasks, `asyncio.create_task`, `asyncio.gather`, `asyncio.sleep`, `asyncio.TaskGroup`, and `asyncio.timeout` / `timeout_at`. `asyncio.wait_for` uses the same task/future scheduling and durable timers. +On Python 3.11, `asyncio.wait_for` can swallow a cancellation: if the awaited +operation completes and the waiting task is cancelled before it resumes, +`wait_for` returns the result instead of raising `CancelledError`. The +cancelled branch keeps running and can schedule more durable work. Python 3.12+ +raises `CancelledError`. On Python 3.11, use `asyncio.timeout()` when +cancellation must stop the branch. Third-party async libraries are not part of this compatibility contract, even when individual code paths happen to use supported asyncio primitives. Create branches from ordered inputs. Ready work follows FIFO scheduling; history completions are delivered in history order, draining ready work after each completion. Task-group cancellation wakeups are ordered by local task -creation, not set/object-hash iteration. Local tasks are dispatch resources, -not new durable instances. +creation, not set/object-hash iteration, and keep their FIFO position relative +to other ready callbacks. Local tasks are dispatch resources, +not new durable instances. Create them with `asyncio.create_task` or a task +group; do not construct `asyncio.Task` directly, because such tasks are not +tracked by the dispatch and are not cancelled or cleaned up with it. `loop.time()` uses seconds from a fixed UTC epoch and the current orchestration clock, never machine monotonic time. `loop.call_at` and `call_later` schedule -durable timers for future finite deadlines. Timer conversion rounds up when -necessary so a durable timer does not precede its floating-point deadline. +durable timers for future finite deadlines. `call_at` rounds its +floating-point deadline up to the next microsecond when necessary, so a durable +timer never precedes it. `call_later` (and so `asyncio.sleep`) rounds a +positive relative delay up to whole microseconds and adds it to the exact +orchestration time. Core/Functions long timers reuse the existing chunking; Azure Managed retains its native long timers. Past deadlines are ready callbacks. `sleep(0)` yields to ready coroutines without a durable timer. Clock advancement and timers @@ -351,6 +363,12 @@ automatic recording or interception of arbitrary await expressions. `is_replaying` is not a substitute for recording results. Activities remain at-least-once work: side effects require appropriate idempotency/deduplication. +Successive orchestration dispatches and their activities can run on different +workers. Replay reconstructs local tasks and futures from ordered durable +history; it does not rely on task identities or memory retained by a previous +worker. Activity completion order is the order recorded in history, not worker +placement. + Framework adapters can compose supported durable operations using async helpers. Adapters remain responsible for registering ordinary model/tool activities, encoding/decoding framework payloads, and supplying replay-stable @@ -369,8 +387,9 @@ construction order is not execution order. Supporting several Python versions does not guarantee recorded-history portability between them. Pin the runtime and dependencies for active -instances and validate histories before upgrades; see the Python version -warning above. +instances and validate histories before upgrades. All workers processing an +instance must use that pinned environment; see the Python version warning +above. The Functions `orchestrator_generator_wrapper` helper drives generator orchestrators only. Use the real replay executor/provider or the in-memory diff --git a/durabletask/internal/asyncio_loop.py b/durabletask/internal/asyncio_loop.py index ef97c4aa..44b218fb 100644 --- a/durabletask/internal/asyncio_loop.py +++ b/durabletask/internal/asyncio_loop.py @@ -15,7 +15,14 @@ - ``asyncio.Handle._run``: run a ready callback with asyncio's own context and exception-handler semantics. - ``asyncio.Task._log_traceback``: report unobserved local-task failures during - dispatch cleanup without marking them as retrieved. + dispatch cleanup without marking them as retrieved, and keep such tasks + tracked until then. +- ``__self__`` of Task step/wakeup callbacks (including the C implementation's + step wrapper and bound ``task_wakeup``): identify which local task a + callback resumes, so task-group cancellation wakeups run in task-creation + order. +- ``AbstractEventLoop._timer_handle_cancelled``: the hook ``TimerHandle.cancel`` + calls on its loop, used to withdraw the durable timer observer. """ from __future__ import annotations @@ -23,16 +30,19 @@ import asyncio import contextvars import logging +import math from collections import deque from collections.abc import Callable, Coroutine, Generator -from datetime import UTC, datetime -from typing import Any, TypeVar +from datetime import UTC, datetime, timedelta +from fractions import Fraction +from typing import Any, TypeVar, cast from durabletask import task T = TypeVar("T") _EPOCH = datetime(1970, 1, 1) +_MICROSECOND = timedelta(microseconds=1) class _CompletionObserver(task.CompositeTask[None]): @@ -50,11 +60,96 @@ def detach(self) -> None: self._notify_parent() +class _DurableAsyncTask(asyncio.Task[T]): + def __init__( + self, coro: Coroutine[Any, Any, T] | Generator[Any, None, T], *, + sequence: int, loop: DurableEventLoop, name: str | None, + context: contextvars.Context | None, + ) -> None: + self._sequence = sequence + super().__init__(coro, loop=loop, name=name, context=context) + + def __hash__(self) -> int: + # Load-bearing for replay determinism: TaskGroup keeps its children in a + # set and iterates it to cancel them. Hashing by creation sequence makes + # that traversal, and the cancellation wakeups it schedules, follow task + # creation order instead of memory addresses that differ across workers. + return self._sequence + + def __await__(self) -> Generator[Any, None, T]: + try: + return (yield from super().__await__()) + finally: + self._retire_if_observed() + + __iter__ = __await__ + + def result(self) -> T: + try: + return super().result() + finally: + self._retire_if_observed() + + def exception(self) -> BaseException | None: + try: + return super().exception() + finally: + self._retire_if_observed() + + def _retire_if_observed(self) -> None: + loop = self.get_loop() + assert isinstance(loop, DurableEventLoop) + loop.retire_task(self) + + def cancel(self, msg: Any = None) -> bool: + loop = self.get_loop() + assert isinstance(loop, DurableEventLoop) + previous = loop.cancelling_task + loop.cancelling_task = self + try: + return super().cancel(msg) + finally: + loop.cancelling_task = previous + + +class _DurableTimerHandle(asyncio.TimerHandle): + def __eq__(self, other: object) -> bool: + return self is other + + __hash__ = object.__hash__ + + def __init__( + self, when: float, callback: Callable[..., Any], args: tuple[Any, ...], + loop: DurableEventLoop, context: contextvars.Context | None, + ) -> None: + super().__init__(when, callback, args, loop, context=context) + self.durable_timer: task.TimerTask | None = None + + def cancel(self) -> None: + super().cancel() + if self.durable_timer is not None: + self.durable_timer.cancel() + + +class _CancelBatch: + """Consecutive task-cancellation wakeups queued by one loop step. + + The batch holds the ready-queue position of its first wakeup, so later + callbacks cannot overtake it, while its wakeups run in task-creation order. + Any other handle queued after it closes the batch. + """ + + __slots__ = ("entries",) + + def __init__(self) -> None: + self.entries: list[tuple[int, int, asyncio.Handle]] = [] + + class DurableEventLoop(asyncio.AbstractEventLoop): """A FIFO microtask loop; it never polls a selector or advances wall time. - Only history events can complete durable waits. asyncio owns coroutine - stepping; this loop owns the ordering of ready callbacks. + Only history events can complete durable waits/timers. asyncio owns coroutine + stepping, gather and structured cancellation; this loop owns their ordering. """ def __init__( @@ -64,22 +159,30 @@ def __init__( self.ctx = ctx self._is_complete = is_complete self._logger = logger or logging.getLogger(__name__) - self._ready: deque[asyncio.Handle] = deque() - self._tasks: list[asyncio.Task[Any]] = [] - self._waits: dict[int, tuple[task.Task[Any], list[asyncio.Future[Any]]]] = {} + self._ready: deque[asyncio.Handle | _CancelBatch] = deque() + self._cancel_batch: _CancelBatch | None = None + self._tasks: dict[asyncio.Task[Any], int] = {} + self._task_sequence = 0 + self.cancelling_task: asyncio.Task[Any] | None = None + # Insertion-ordered waiters per durable task: FIFO delivery, O(1) removal. + self._waits: dict[int, tuple[task.Task[Any], dict[asyncio.Future[Any], None]]] = {} self._observers: dict[int, _CompletionObserver] = {} self._completions: deque[Callable[[], None]] = deque() + self._timers: dict[_DurableTimerHandle, _CompletionObserver] = {} self._closed = False self._closing = False self._fatal: BaseException | None = None self._root: asyncio.Task[Any] | None = None - def time(self) -> float: - # A fixed UTC epoch avoids local-time and platform timestamp differences. + def _now(self) -> datetime: now = self.ctx.current_utc_datetime if now.tzinfo is not None: now = now.astimezone(UTC).replace(tzinfo=None) - return (now - _EPOCH).total_seconds() + return now + + def time(self) -> float: + # A fixed UTC epoch avoids local-time and platform timestamp differences. + return (self._now() - _EPOCH).total_seconds() def get_debug(self) -> bool: return False @@ -96,6 +199,10 @@ def create_future(self) -> asyncio.Future[Any]: def get_task_factory(self) -> None: return None + def get_exception_handler(self) -> None: + # Callback failures always fail the dispatch; there is no custom handler. + return None + def create_task( self, coro: Coroutine[Any, Any, T] | Generator[Any, None, T], *, name: str | None = None, context: contextvars.Context | None = None, **kwargs: Any, @@ -106,34 +213,103 @@ def create_task( if kwargs: coro.close() raise TypeError("Custom/eager task execution is not supported in durable orchestrators.") - future = asyncio.Task(coro, loop=self, name=name, context=context) - self._tasks.append(future) + sequence = self._task_sequence + self._task_sequence += 1 + future = _DurableAsyncTask(coro, sequence=sequence, loop=self, name=name, context=context) + self._tasks[future] = sequence + future.add_done_callback(self.retire_task) return future + def retire_task(self, future: asyncio.Task[Any]) -> None: + # A failed task may be observed after its done callbacks have run. + # Inspect without retrieving exceptions so unobserved failures still log. + if not self._closing and future.done() and not getattr(future, "_log_traceback", False): + self._tasks.pop(future, None) + def call_soon( self, callback: Callable[..., Any], *args: Any, context: contextvars.Context | None = None, ) -> asyncio.Handle: handle = asyncio.Handle(callback, args, self, context=context) - self._ready.append(handle) + if self.cancelling_task is not None: + # TaskGroup cancels a set of tasks. Do not let object hashes + # determine the order in which their finally blocks execute. + owner = getattr(callback, "__self__", None) + index = self._tasks.get( + self.cancelling_task, getattr(self.cancelling_task, "_sequence", self._task_sequence)) + if isinstance(owner, asyncio.Task): + index = self._tasks.get(cast(asyncio.Task[Any], owner), index) + batch = self._cancel_batch + if batch is None or self._ready[-1] is not batch: + # Extend a batch only while it is the queue tail, so wakeups + # never move ahead of a callback or due timer queued after it. + batch = self._cancel_batch = _CancelBatch() + self._ready.append(batch) + batch.entries.append((index, len(batch.entries), handle)) + else: + self._ready.append(handle) return handle - def call_later(self, delay: float, callback: Callable[..., Any], *args: Any, - context: contextvars.Context | None = None) -> asyncio.TimerHandle: - raise NotImplementedError( - "Loop timers, including asyncio.sleep() with a positive delay, are not " - "supported by the durable orchestration loop. Await ctx.create_timer(...) for a durable timer.") + def call_later( + self, delay: float, callback: Callable[..., Any], *args: Any, + context: contextvars.Context | None = None, + ) -> asyncio.TimerHandle: + if not math.isfinite(delay): + raise ValueError("Durable delays must be finite.") + # Round the relative delay up on the exact orchestration clock; adding + # it to the float loop time would lose sub-microsecond precision. + delay_us = max(0, math.ceil(Fraction(delay) * 1_000_000)) + deadline_us = (self._now() - _EPOCH) // _MICROSECOND + delay_us + return self._schedule_timer( + self.time() + max(0, delay), deadline_us, delay_us == 0, callback, args, context) + + def call_at( + self, when: float, callback: Callable[..., Any], *args: Any, + context: contextvars.Context | None = None, + ) -> asyncio.TimerHandle: + if not math.isfinite(when): + raise ValueError("Durable deadlines must be finite.") + # Exact rational ceiling: float round-trips can emit a deadline that + # precedes the requested one by a fraction of a microsecond. + deadline_us = math.ceil(Fraction(when) * 1_000_000) + now_us = (self._now() - _EPOCH) // _MICROSECOND + due = when <= self.time() or deadline_us <= now_us + return self._schedule_timer(when, deadline_us, due, callback, args, context) + + def _schedule_timer( + self, when: float, deadline_us: int, due: bool, callback: Callable[..., Any], + args: tuple[Any, ...], context: contextvars.Context | None, + ) -> asyncio.TimerHandle: + handle = _DurableTimerHandle(when, callback, args, self, context) + if due: + self._ready.append(handle) + else: + if self._closing: + raise RuntimeError("Dispatch cleanup cannot schedule durable timers.") + deadline = _EPOCH + timedelta(microseconds=deadline_us) + handle.durable_timer = self.ctx.create_timer(deadline) + self._timers[handle] = _CompletionObserver( + handle.durable_timer, + lambda: self._completions.append(lambda: self._complete_timer(handle))) + return handle + + def _timer_handle_cancelled(self, handle: asyncio.TimerHandle) -> None: + if isinstance(handle, _DurableTimerHandle): + observer = self._timers.pop(handle, None) + if observer is not None: + observer.detach() - def call_at(self, when: float, callback: Callable[..., Any], *args: Any, - context: contextvars.Context | None = None) -> asyncio.TimerHandle: - return self.call_later(when - self.time(), callback, *args, context=context) + def _complete_timer(self, handle: _DurableTimerHandle) -> None: + self._timers.pop(handle, None) + if not handle.cancelled(): + self._ready.append(handle) async def wait_durable(self, durable: task.Task[T]) -> T: if durable.is_complete: return durable.get_result() future = self.create_future() - entry = self._waits.setdefault(id(durable), (durable, [])) - entry[1].append(future) + entry = self._waits.setdefault(id(durable), (durable, {})) + entry[1][future] = None if id(durable) not in self._observers: self._observers[id(durable)] = _CompletionObserver( durable, lambda: self._completions.append(lambda: self._complete_wait(durable))) @@ -141,10 +317,13 @@ async def wait_durable(self, durable: task.Task[T]) -> T: return await future finally: # Cancelling one waiter never cancels a shared durable operation. - entry[1].remove(future) + entry[1].pop(future, None) if not entry[1]: self._waits.pop(id(durable), None) - self._observers.pop(id(durable)).detach() + # Dispatch close may already have detached and cleared observers. + observer = self._observers.pop(id(durable), None) + if observer is not None: + observer.detach() def _complete_wait(self, durable: task.Task[Any]) -> None: entry = self._waits.get(id(durable)) @@ -184,7 +363,7 @@ def resume(self) -> None: "Await durable activities, events or timers; external I/O is unsupported.") def _has_durable_work(self) -> bool: - return any(not durable.is_complete for durable, _ in self._waits.values()) + return any(not durable.is_complete for durable, _ in self._waits.values()) or bool(self._timers) def _drain(self) -> None: previous_loop = asyncio._get_running_loop() @@ -194,7 +373,13 @@ def _drain(self) -> None: asyncio._set_running_loop(self) try: while self._ready: - handle = self._ready.popleft() + # Each step's cancellation wakeups form their own batch. + self._cancel_batch = None + item = self._ready.popleft() + if isinstance(item, _CancelBatch): + self._ready.extendleft(handle for _, _, handle in sorted(item.entries, reverse=True)) + continue + handle = item if not handle.cancelled(): handle._run() if self._fatal is not None: @@ -247,9 +432,53 @@ def close(self) -> None: finally: self._closed = True self._ready.clear() - for observer in self._observers.values(): + self._cancel_batch = None + for observer in (*self._observers.values(), *self._timers.values()): observer.detach() self._completions.clear() self._observers.clear() self._waits.clear() + self._timers.clear() self._tasks.clear() + + +_IO_HINT = "External I/O is unsupported in orchestrators; move it to an ordinary activity." +_THREAD_HINT = "Threads/executors are unsupported in orchestrators; use an activity." +_LOOP_HINT = "The worker owns the durable loop's lifecycle and configuration." + +# Every asyncio loop API this loop does not implement fails with one actionable +# error instead of AbstractEventLoop's bare NotImplementedError. +_UNSUPPORTED_LOOP_APIS: dict[str, str] = { + **dict.fromkeys(( + "create_connection", "create_server", "create_datagram_endpoint", + "create_unix_connection", "create_unix_server", "connect_accepted_socket", + "connect_read_pipe", "connect_write_pipe", "start_tls", "sendfile", + "getaddrinfo", "getnameinfo", "sock_connect", "sock_accept", "sock_recv", + "sock_recv_into", "sock_recvfrom", "sock_recvfrom_into", "sock_sendall", + "sock_sendto", "sock_sendfile", "subprocess_exec", "subprocess_shell", + "add_reader", "remove_reader", "add_writer", "remove_writer", + "add_signal_handler", "remove_signal_handler", + ), _IO_HINT), + **dict.fromkeys(( + "run_in_executor", "set_default_executor", "shutdown_default_executor", + "call_soon_threadsafe", + ), _THREAD_HINT), + **dict.fromkeys(( + "run_forever", "run_until_complete", "stop", "set_task_factory", + "set_exception_handler", "default_exception_handler", "set_debug", + "shutdown_asyncgens", + ), _LOOP_HINT), +} + + +def _unsupported_loop_api(name: str, hint: str) -> Callable[..., Any]: + def unsupported(self: DurableEventLoop, *args: Any, **kwargs: Any) -> Any: + raise RuntimeError(f"loop.{name}() is not supported in durable orchestrators. {hint}") + + unsupported.__name__ = unsupported.__qualname__ = name + return unsupported + + +for _name, _hint in _UNSUPPORTED_LOOP_APIS.items(): + if _name not in vars(DurableEventLoop): + setattr(DurableEventLoop, _name, _unsupported_loop_api(_name, _hint)) diff --git a/durabletask/task.py b/durabletask/task.py index e74fcac3..ae246cf0 100644 --- a/durabletask/task.py +++ b/durabletask/task.py @@ -630,8 +630,10 @@ def __await__(self) -> Generator[Any, Any, T]: async def wait(self) -> T: """Borrow this operation's result through a fresh native coroutine. - Calling this method does not schedule another durable operation. Each - call creates an independent waiter. + Suitable for ``asyncio.create_task`` and task groups. Calling this + method does not schedule another durable operation. Each call creates + an independent waiter; cancelling it does not cancel the underlying + operation, timer, or event subscription, or any other waiter. """ return await self diff --git a/tests/durabletask/test_asyncio_orchestrators.py b/tests/durabletask/test_asyncio_orchestrators.py new file mode 100644 index 00000000..e52531d0 --- /dev/null +++ b/tests/durabletask/test_asyncio_orchestrators.py @@ -0,0 +1,923 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Deterministic asyncio behavior through the real history executor.""" + +import asyncio +import gc +import inspect +import json +import os +import subprocess +import sys +from contextvars import ContextVar +from dataclasses import dataclass +from datetime import datetime, timedelta +from decimal import ROUND_CEILING, Decimal, localcontext +from functools import partial +from types import SimpleNamespace +from typing import Any, cast +from weakref import ReferenceType, ref + +import pytest + +from durabletask import task +from durabletask.internal import helpers +from durabletask.internal import orchestrator_service_pb2 as pb +from durabletask.internal.asyncio_loop import _UNSUPPORTED_LOOP_APIS, DurableEventLoop # pyright: ignore[reportPrivateUsage] +from tests.durabletask.test_coroutine_orchestrators import ( + NOW, + _completion, # pyright: ignore[reportPrivateUsage] + _execute, # pyright: ignore[reportPrivateUsage] + _start, # pyright: ignore[reportPrivateUsage] +) + + +@pytest.mark.parametrize("fail_branch", [False, True]) +def test_task_group_branches_inherit_context_and_replay_stable_actions(fail_branch: bool) -> None: + context: ContextVar[task.OrchestrationContext] = ContextVar("orchestration") + + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> Any: + token = context.set(ctx) + try: + results: dict[str, Any] = {} + + async def branch(name: str) -> None: + current = context.get() + assert current is ctx + results[name] = await current.call_activity(name, input=current.instance_id) + + async with asyncio.TaskGroup() as group: + group.create_task(branch("first")) + group.create_task(branch("second")) + return await context.get().call_activity("finish", input=[results["first"], results["second"]]) + finally: + context.reset(token) + + def replay(old: list[pb.HistoryEvent], new: list[pb.HistoryEvent]): + first = _execute(orchestrator, old, new) + assert _execute(orchestrator, old, new).actions == first.actions + with pytest.raises(LookupError): + context.get() + return first + + start = _start() + initial = replay([], start) + assert [action.scheduleTask.name for action in initial.actions] == ["first", "second"] + assert all(json.loads(action.scheduleTask.input.value) == "coroutine-test" for action in initial.actions) + old = start + [helpers.new_task_scheduled_event(1, "first"), + helpers.new_task_scheduled_event(2, "second")] + second_done = [helpers.new_task_completed_event(2, '"second result"')] + assert replay(old, second_done).actions == [] + first_done = [helpers.new_task_failed_event(1, ValueError("recorded branch failure"))] if fail_branch else [ + helpers.new_task_completed_event(1, '"first result"')] + result = replay(old + second_done, first_done) + if fail_branch: + complete = _completion(result) + assert complete.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED + assert "recorded branch failure" in str(complete.failureDetails) + else: + assert len(result.actions) == 1 + assert result.actions[0].scheduleTask.name == "finish" + assert json.loads(result.actions[0].scheduleTask.input.value) == ["first result", "second result"] + complete = _completion(replay(old + second_done + first_done, [ + helpers.new_task_scheduled_event(3, "finish"), + helpers.new_task_completed_event(3, '"done"')])) + assert json.loads(complete.result.value) == "done" + + +def test_gather_resumes_each_branch_without_waiting_for_batch() -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> list[Any]: + async def branch(name: str) -> Any: + value: Any = await ctx.call_activity(name) + await asyncio.sleep(0) + return await ctx.call_activity(name + "-next", input=value) + + return list(await asyncio.gather(branch("a"), branch("b"))) + + start = _start() + actions = _execute(orchestrator, [], start).actions + assert [a.scheduleTask.name for a in actions] == ["a", "b"] + old = start + [helpers.new_task_scheduled_event(i, name) for i, name in [(1, "a"), (2, "b")]] + second = [helpers.new_task_completed_event(2, '"b"')] + actions = _execute(orchestrator, old, second).actions + assert [(a.id, a.scheduleTask.name) for a in actions] == [(3, "b-next")] + third = [helpers.new_task_scheduled_event(3, "b-next"), + helpers.new_task_completed_event(1, '"a"'), + helpers.new_task_scheduled_event(4, "a-next"), + helpers.new_task_completed_event(4, '"a-done"'), + helpers.new_task_completed_event(3, '"b-done"')] + assert json.loads(_completion(_execute(orchestrator, old + second, third)).result.value) == [ + "a-done", "b-done"] + + +@pytest.mark.parametrize("return_exceptions", [False, True]) +def test_gather_failure_does_not_cancel_sibling(return_exceptions: bool) -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> Any: + async def sibling() -> str: + await ctx.call_activity("slow") + return await ctx.call_activity("continued", return_type=str) + + failure = asyncio.create_task(ctx.call_activity("fail", return_type=str).wait()) + pending = asyncio.create_task(sibling()) + try: + values = await asyncio.gather( + failure, pending, return_exceptions=return_exceptions) + return [isinstance(values[0], task.TaskFailedError), values[1]] + except task.TaskFailedError: + assert not pending.cancelled() + return await pending + + old = _start() + [helpers.new_task_scheduled_event(1, "fail"), + helpers.new_task_scheduled_event(2, "slow")] + failed = [helpers.new_task_failed_event(1, ValueError("boom"))] + assert _execute(orchestrator, old, failed).actions == [] + completed = [helpers.new_task_completed_event(2, "null")] + assert _execute(orchestrator, old + failed, completed).actions[0].scheduleTask.name == "continued" + result = _completion(_execute(orchestrator, old + failed + completed, [ + helpers.new_task_scheduled_event(3, "continued"), helpers.new_task_completed_event(3, '"ok"')])) + assert json.loads(result.result.value) == ([True, "ok"] if return_exceptions else "ok") + + +def test_task_group_failure_cancels_waiters_not_durable_work() -> None: + cleaned: list[str] = [] + + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: + async def branch(name: str) -> None: + try: + await ctx.call_activity(name) + finally: + await asyncio.sleep(0) + cleaned.append(name) + + async with asyncio.TaskGroup() as group: + group.create_task(branch("fail")) + group.create_task(branch("slow")) + + old = _start() + [helpers.new_task_scheduled_event(1, "fail"), + helpers.new_task_scheduled_event(2, "slow")] + result = _completion(_execute(orchestrator, old, [helpers.new_task_failed_event(1, ValueError("boom"))])) + assert result.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED + assert cleaned == ["fail", "slow"] + + +@pytest.mark.parametrize("kind", ["sleep", "wait_for", "timeout"]) +def test_durable_timer_and_timeout(kind: str) -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> str: + try: + if kind == "sleep": + await asyncio.sleep(2) + elif kind == "wait_for": + await asyncio.wait_for(ctx.wait_for_external_event("never"), timeout=2) + else: + async with asyncio.timeout(2): + await ctx.wait_for_external_event("never") + except TimeoutError: + return "timed out" + return "slept" + + actions = _execute(orchestrator, [], _start()).actions + assert len(actions) == 1 + deadline = actions[0].createTimer.fireAt.ToDatetime() + assert deadline == NOW + timedelta(seconds=2) + old = _start() + [helpers.new_timer_created_event(1, deadline)] + new = [helpers.new_orchestrator_started_event(deadline), helpers.new_timer_fired_event(1, deadline)] + assert json.loads(_completion(_execute(orchestrator, old, new)).result.value) == ( + "slept" if kind == "sleep" else "timed out") + + +def test_sleep_zero_fifo_without_timer() -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> list[int]: + observed: list[int] = [] + + async def branch(index: int) -> None: + observed.append(index) + await asyncio.sleep(0) + observed.append(index + 2) + + await asyncio.gather(branch(0), branch(1)) + return observed + + result = _execute(orchestrator, [], _start()) + assert len(result.actions) == 1 + assert json.loads(_completion(result).result.value) == [0, 1, 2, 3] + + +def test_discarded_gather_batches_release_decoded_results_during_replay() -> None: + references: list[ReferenceType[Any]] = [] + + @dataclass + class Payload: + value: int + + def __post_init__(self) -> None: + references.append(ref(self)) + + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> str: + for batch in range(8): + await asyncio.gather(*(ctx.call_activity("work", return_type=Payload) for _ in range(4))) + await asyncio.sleep(0) + gc.collect() + assert len(references) == (batch + 1) * 4 + # The history handler still holds the most recent decoded result + # while resume() drains this batch's callbacks. + assert sum(reference() is not None for reference in references) <= 1 + return "done" + + history = _start() + for batch in range(8): + ids = range(batch * 4 + 1, batch * 4 + 5) + history += [helpers.new_task_scheduled_event(index, "work") for index in ids] + history += [helpers.new_task_completed_event(index, json.dumps({"value": index})) for index in ids] + complete = _completion(_execute(orchestrator, history[:-1], history[-1:])) + assert complete.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED, complete.failureDetails + assert json.loads(complete.result.value) == "done" + gc.collect() + assert all(reference() is None for reference in references) + + +@pytest.mark.parametrize("observe", [ + "await", "gather", "gather-exceptions", "result", "exception", "task-group", +]) +def test_observed_failures_release_traceback_payloads_during_replay(observe: str) -> None: + references: list[ReferenceType[Any]] = [] + + @dataclass + class Payload: + value: int + + def __post_init__(self) -> None: + references.append(ref(self)) + + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> str: + async def branch() -> None: + payload = await ctx.call_activity("work", return_type=Payload) + raise ValueError(f"Failed with payload {payload.value}") + + for batch in range(8): + if observe == "task-group": + group = asyncio.TaskGroup() + try: + async with group: + group.create_task(branch()) + except* ValueError: + pass + del group + else: + pending = asyncio.create_task(branch()) + await asyncio.sleep(0) + # Observe only after the failed task's initial retirement callback. + await ctx.call_activity("gate") + if observe == "gather-exceptions": + await asyncio.gather(pending, return_exceptions=True) + elif observe == "exception": + assert isinstance(pending.exception(), ValueError) + else: + try: + if observe == "await": + await pending + elif observe == "gather": + await asyncio.gather(pending) + else: + pending.result() + except ValueError: + pass + del pending + await asyncio.sleep(0) + gc.collect() + assert len(references) == batch + 1 + assert sum(reference() is not None for reference in references) <= 1 + return "done" + + history = _start() + sequence = 0 + for batch in range(8): + sequence += 1 + work_id = sequence + history.append(helpers.new_task_scheduled_event(work_id, "work")) + if observe != "task-group": + sequence += 1 + history.append(helpers.new_task_scheduled_event(sequence, "gate")) + history.append(helpers.new_task_completed_event(work_id, json.dumps({"value": batch}))) + if observe != "task-group": + history.append(helpers.new_task_completed_event(sequence, "null")) + complete = _completion(_execute(orchestrator, history[:-1], history[-1:])) + assert complete.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED, complete.failureDetails + assert json.loads(complete.result.value) == "done" + gc.collect() + assert all(reference() is None for reference in references) + + +def test_retired_tasks_do_not_reuse_cancellation_order() -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> str: + async def completed() -> None: + pass + + async def branch(index: int) -> None: + try: + await ctx.wait_for_external_event(str(index)) + finally: + await ctx.call_activity("compensate", input=index) + + asyncio.create_task(completed()) + first = asyncio.create_task(branch(0)) + await asyncio.sleep(0) + await asyncio.sleep(0) + second = asyncio.create_task(branch(1)) + await asyncio.sleep(0) + second.cancel() + first.cancel() + await asyncio.gather(first, second, return_exceptions=True) + return "done" + + initial = _execute(orchestrator, [], _start()) + assert [json.loads(action.scheduleTask.input.value) for action in initial.actions] == [0, 1] + assert _execute(orchestrator, [], _start()).actions == initial.actions + old = _start() + [helpers.new_task_scheduled_event(index, "compensate") for index in (1, 2)] + new = [helpers.new_task_completed_event(index, "null") for index in (1, 2)] + assert json.loads(_completion(_execute(orchestrator, old, new)).result.value) == "done" + + +def test_shared_operation_survives_local_waiter_cancellation() -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> Any: + durable = ctx.call_activity("shared", return_type=str) + + async def wait() -> Any: + return await durable + + first = asyncio.create_task(wait()) + second = asyncio.create_task(wait()) + await asyncio.sleep(0) + first.cancel() + await asyncio.gather(first, return_exceptions=True) + return await second + + old = _start() + [helpers.new_task_scheduled_event(1, "shared")] + assert json.loads(_completion(_execute(orchestrator, old, [ + helpers.new_task_completed_event(1, '"ok"')])).result.value) == "ok" + + +def test_local_durable_cancellation_wakes_waiter_without_history() -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> str: + timer = ctx.create_timer(timedelta(days=1)) + + async def waiter() -> None: + await timer + + pending = asyncio.create_task(waiter()) + await asyncio.sleep(0) + timer.cancel() + try: + await pending + except task.TaskCancelledError: + return "cancelled" + return "unexpected" + + result = _execute(orchestrator, [], _start()) + assert len(result.actions) == 1 + assert json.loads(_completion(result).result.value) == "cancelled" + + +def test_unhandled_local_root_cancellation_fails_not_abandons() -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: + raise asyncio.CancelledError + + complete = _completion(_execute(orchestrator, [], _start())) + assert complete.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED + assert complete.failureDetails.errorType.endswith("TaskCancelledError") + + +@pytest.mark.parametrize("delay", [0.0000003, 0.000001, 0.0000013, 2.25]) +def test_timer_rounding_never_precedes_loop_deadline(delay: float) -> None: + observed: list[float] = [] + + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: + loop = asyncio.get_running_loop() + observed.append(loop.time() + delay) + await asyncio.sleep(delay) + + actions = _execute(orchestrator, [], _start()).actions + assert len(actions) == 1 + deadline = actions[0].createTimer.fireAt.ToDatetime() + assert (deadline - datetime(1970, 1, 1)).total_seconds() >= observed[0] + + +@pytest.mark.parametrize("offset", [0.000003, 0.0000003, 0.000001, 0.0000013, 1.0, 2.25]) +def test_call_at_deadline_is_exact_microsecond_ceiling(offset: float) -> None: + requested: list[float] = [] + + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: + loop = asyncio.get_running_loop() + when = loop.time() + offset + requested.append(when) + fired = loop.create_future() + loop.call_at(when, fired.set_result, None) + await fired + + actions = _execute(orchestrator, [], _start()).actions + assert len(actions) == 1 + fire_at = actions[0].createTimer.fireAt + assert fire_at.nanos % 1000 == 0 + emitted_us = fire_at.seconds * 1_000_000 + fire_at.nanos // 1000 + # Decimal(float) is exact, so this oracle shares no float arithmetic with the loop. + with localcontext() as exact: + exact.prec = 400 + requested_seconds = Decimal(requested[0]) + oracle_us = int((requested_seconds * 1_000_000).to_integral_value(rounding=ROUND_CEILING)) + assert emitted_us == oracle_us + assert Decimal(emitted_us) / 1_000_000 >= requested_seconds + + +def test_call_at_known_float_deadline_rounds_up_to_next_microsecond() -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: + loop = asyncio.get_running_loop() + fired = loop.create_future() + loop.call_at(loop.time() + 0.000003, fired.set_result, None) + await fired + + actions = _execute(orchestrator, [], _start()).actions + assert actions[0].createTimer.fireAt.ToDatetime() == NOW + timedelta(microseconds=4) + + +@pytest.mark.parametrize("offset", [0.0, -1.0]) +def test_call_at_due_deadline_runs_without_durable_timer(offset: float) -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> str: + loop = asyncio.get_running_loop() + fired = loop.create_future() + loop.call_at(loop.time() + offset, fired.set_result, "fired") + return await fired + + result = _execute(orchestrator, [], _start()) + assert json.loads(_completion(result).result.value) == "fired" + + +@pytest.mark.parametrize("when", [1e20, float(sys.float_info.max)]) +def test_call_at_out_of_range_deadline_fails(when: float) -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: + asyncio.get_running_loop().call_at(when, lambda: None) + + complete = _completion(_execute(orchestrator, [], _start())) + assert complete.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED + assert complete.failureDetails.errorType.endswith("OverflowError") + + +def test_async_sleep_uses_shared_long_timer_chunking() -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> str: + await asyncio.sleep(7 * 86400) + return "done" + + old = _start() + for timer_id, days in [(1, 3), (2, 6), (3, 7)]: + result = _execute(orchestrator, [], old) + assert len(result.actions) == 1 + action = result.actions[0] + assert action.id == timer_id + deadline = NOW + timedelta(days=days) + assert action.createTimer.fireAt.ToDatetime() == deadline + old += [helpers.new_timer_created_event(timer_id, deadline), + helpers.new_orchestrator_started_event(deadline), + helpers.new_timer_fired_event(timer_id, deadline)] + assert json.loads(_completion(_execute(orchestrator, old[:-1], old[-1:])).result.value) == "done" + + +@pytest.mark.parametrize("api", ["thread", "io", "foreign-loop"]) +def test_unsupported_work_fails_actionably(api: str) -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: + if api == "thread": + await asyncio.to_thread(lambda: None) + elif api == "io": + await asyncio.open_connection("localhost", 1) + else: + foreign = asyncio.new_event_loop() + try: + await foreign.create_future() + finally: + foreign.close() + + complete = _completion(_execute(orchestrator, [], _start())) + assert complete.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED + assert any(text in complete.failureDetails.errorMessage for text in ( + "use an activity", "ordinary activity", "different loop")) + + +@pytest.mark.parametrize("name", sorted(_UNSUPPORTED_LOOP_APIS)) +def test_every_unsupported_loop_api_fails_actionably(name: str) -> None: + ctx = cast(task.OrchestrationContext, SimpleNamespace(current_utc_datetime=NOW)) + loop = DurableEventLoop(ctx, is_complete=lambda: False) + with pytest.raises(RuntimeError, match=rf"loop\.{name}\(\) is not supported") as error: + getattr(loop, name)() + assert str(error.value).endswith(_UNSUPPORTED_LOOP_APIS[name]) + + +@pytest.mark.parametrize("name", sorted( + name for name, member in inspect.getmembers(asyncio.AbstractEventLoop) + if not name.startswith("_") and callable(member))) +def test_no_loop_api_inherits_bare_not_implemented_error(name: str) -> None: + # Fails when a new Python adds a loop API that is neither implemented nor tabled. + implementation = getattr(DurableEventLoop, name) + inherited = implementation is getattr(asyncio.AbstractEventLoop, name) + assert name in _UNSUPPORTED_LOOP_APIS or not inherited, ( + f"loop.{name}() inherits AbstractEventLoop's bare NotImplementedError; " + "implement it or add it to _UNSUPPORTED_LOOP_APIS.") + + +def test_untracked_task_finalized_after_dispatch_close_is_quiet(monkeypatch: pytest.MonkeyPatch) -> None: + unraisable: list[Any] = [] + monkeypatch.setattr(sys, "unraisablehook", unraisable.append) + untracked: list[asyncio.Task[Any]] = [] + + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: + untracked.append(asyncio.Task(ctx.call_activity("background").wait())) + await ctx.call_activity("work") + + _execute(orchestrator, [], _start()) + untracked.clear() + gc.collect() + assert not [hook for hook in unraisable if isinstance(hook.exc_value, KeyError)] + + +def test_task_group_cancellation_durable_cleanup_has_stable_action_order() -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: + async def branch(index: int) -> None: + try: + await ctx.call_activity("work", input=index) + finally: + # This is real task-group cancellation during replay, not + # dispatch teardown: durable compensation is still allowed. + await ctx.call_activity("compensate", input=index) + + async with asyncio.TaskGroup() as group: + for index in range(4): + group.create_task(branch(index)) + + old = _start() + [helpers.new_task_scheduled_event(index, "work") for index in range(1, 5)] + failure = [helpers.new_task_failed_event(1, ValueError("boom"))] + # The failing branch first enters its durable finally, so deliver that + # completion before task-group sibling cancellation starts. + first = _execute(orchestrator, old, failure) + assert [(a.id, a.scheduleTask.name, json.loads(a.scheduleTask.input.value)) for a in first.actions] == [ + (5, "compensate", 0)] + old += failure + [helpers.new_task_scheduled_event(5, "compensate"), + helpers.new_task_completed_event(5, "null")] + expected = [helpers.new_schedule_task_action(index + 6, "compensate", json.dumps(index + 1), None) + for index in range(3)] + for _ in range(10): + assert _execute(orchestrator, [], old).actions == expected + + +async def _shared_future_cancellation_orchestrator( + ctx: task.OrchestrationContext, _: Any, *, direct_future: bool, gather_wait: bool, +) -> str: + loop = asyncio.get_running_loop() + futures: list[asyncio.Future[None]] = [ + asyncio.Future[None]() if direct_future else loop.create_future() for _ in range(2)] + + def on_cancelled(index: int, future: asyncio.Future[None]) -> None: + assert future.cancelled() + ctx.call_activity(f"cancelled-{index}") + + for index, future in enumerate(futures): + future.add_done_callback(partial(on_cancelled, index)) + + async def wait(future: asyncio.Future[None]) -> None: + if gather_wait: + await asyncio.gather(future) + else: + await future + + async def fail() -> None: + await asyncio.sleep(0) + raise ValueError("cancel siblings") + + try: + async with asyncio.TaskGroup() as group: + for future in futures * 2: + group.create_task(wait(future)) + group.create_task(fail()) + except* ValueError: + pass + return await ctx.call_activity("join", return_type=str) + + +@pytest.mark.parametrize("direct_future", [False, True]) +@pytest.mark.parametrize("gather_wait", [False, True]) +def test_shared_future_cancellation_callbacks_replay_on_fresh_executors( + direct_future: bool, gather_wait: bool, +) -> None: + orchestrator = partial( + _shared_future_cancellation_orchestrator, direct_future=direct_future, gather_wait=gather_wait) + start = _start() + initial = _execute(orchestrator, [], start) + assert sorted(a.scheduleTask.name for a in initial.actions[:-1]) == ["cancelled-0", "cancelled-1"] + assert initial.actions[-1].scheduleTask.name == "join" + recorded = start + [ + helpers.new_task_scheduled_event(action.id, action.scheduleTask.name) + for action in initial.actions + ] + # Activity workers may complete in any order. Each dispatch reconstructs + # all local tasks and futures from history, as on a different worker. + completed = [ + helpers.new_task_completed_event(initial.actions[1].id, "null"), + helpers.new_task_completed_event(initial.actions[0].id, "null"), + ] + for _ in range(30): + assert _execute(orchestrator, [], start).actions == initial.actions + assert _execute(orchestrator, recorded, completed).actions == [] + complete = _completion(_execute( + orchestrator, recorded + completed, + [helpers.new_task_completed_event(initial.actions[-1].id, '"joined"')])) + assert complete.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED, complete.failureDetails + assert json.loads(complete.result.value) == "joined" + + +def test_shared_future_cancellation_history_replays_in_other_worker_processes() -> None: + orchestrator = partial( + _shared_future_cancellation_orchestrator, direct_future=True, gather_wait=False) + start = _start() + initial = _execute(orchestrator, [], start) + history = start + [ + helpers.new_task_scheduled_event(action.id, action.scheduleTask.name) + for action in initial.actions + ] + history += [ + helpers.new_task_completed_event(initial.actions[1].id, "null"), + helpers.new_task_completed_event(initial.actions[0].id, "null"), + ] + payload = json.dumps({ + "initial": [action.SerializeToString().hex() for action in initial.actions], + "history": [event.SerializeToString().hex() for event in history], + "join_id": initial.actions[-1].id, + }) + code = """ +import json +import sys +from functools import partial +from durabletask.internal import helpers, orchestrator_service_pb2 as pb +from tests.durabletask.test_asyncio_orchestrators import _shared_future_cancellation_orchestrator +from tests.durabletask.test_coroutine_orchestrators import _completion, _execute, _start + +data = json.load(sys.stdin) +orchestrator = partial(_shared_future_cancellation_orchestrator, direct_future=True, gather_wait=False) +initial = _execute(orchestrator, [], _start()) +assert [action.SerializeToString().hex() for action in initial.actions] == data["initial"] +history = [pb.HistoryEvent.FromString(bytes.fromhex(event)) for event in data["history"]] +result = _completion(_execute( + orchestrator, history, [helpers.new_task_completed_event(data["join_id"], '"joined"')])) +assert result.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED, result.failureDetails +assert json.loads(result.result.value) == "joined" +""" + for seed in ("0", "999"): + process = subprocess.run( + [sys.executable, "-c", code], input=payload, capture_output=True, text=True, + env={**os.environ, "PYTHONHASHSEED": seed}, timeout=30) + assert process.returncode == 0, process.stdout + process.stderr + + +def test_cancelling_last_loop_timer_cannot_hide_foreign_wait() -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: + handle = asyncio.get_running_loop().call_later(1, lambda: None) + handle.cancel() + await asyncio.Future() + + complete = _completion(_execute(orchestrator, [], _start())) + assert complete.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED + assert "blocked without durable work" in complete.failureDetails.errorMessage + + +@pytest.mark.parametrize("observed", [False, True]) +@pytest.mark.parametrize("probe_pending", [False, True]) +def test_background_failure_is_reported_unless_observed( + observed: bool, probe_pending: bool, caplog: pytest.LogCaptureFixture) -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> str: + async def fail() -> None: + raise ValueError("background failure") + + pending = asyncio.create_task(fail()) + if probe_pending: + with pytest.raises(asyncio.InvalidStateError): + pending.result() + with pytest.raises(asyncio.InvalidStateError): + pending.exception() + await asyncio.sleep(0) + if observed: + await asyncio.gather(pending, return_exceptions=True) + del pending + await asyncio.sleep(0) + gc.collect() + return "done" + + assert json.loads(_completion(_execute(orchestrator, [], _start())).result.value) == "done" + assert ("background failure" in caplog.text) is not observed + + +@pytest.mark.parametrize("count", [128, 4096]) +def test_fanout_waiter_inspections_scale_linearly( + count: int, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None: + inspections = 0 + + def is_complete(durable: task.Task[Any]) -> bool: + nonlocal inspections + inspections += 1 + return durable._is_complete # pyright: ignore[reportPrivateUsage] + + monkeypatch.setattr(task.Task, "is_complete", property(is_complete)) + + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> list[Any]: + async def branch(index: int) -> Any: + return await ctx.call_activity("work", input=index) + + return await asyncio.gather(*(branch(index) for index in range(count))) + + result = _execute(orchestrator, [], _start()) + assert [action.id for action in result.actions] == list(range(1, count + 1)) + assert inspections < count * 20 + assert not caplog.records + + +@pytest.mark.parametrize("timer", [False, True]) +def test_callback_stop_iteration_fails_instead_of_completing_orchestrator(timer: bool) -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: + def fail() -> None: + raise StopIteration("callback stopped") + + loop = asyncio.get_running_loop() + if timer: + loop.call_later(1, fail) + else: + loop.call_soon(fail) + await ctx.wait_for_external_event("never") + + start = _start() + if timer: + deadline = NOW + timedelta(seconds=1) + old = start + [helpers.new_timer_created_event(1, deadline)] + new = [helpers.new_orchestrator_started_event(deadline), helpers.new_timer_fired_event(1, deadline)] + else: + old, new = [], start + complete = _completion(_execute(orchestrator, old, new)) + assert complete.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED + assert complete.failureDetails.errorType == "builtins.RuntimeError" + assert complete.failureDetails.innerFailure.errorType == "builtins.StopIteration" + assert complete.failureDetails.innerFailure.errorMessage == "callback stopped" + + +@pytest.mark.parametrize("cancelled", [None, 0, 1]) +def test_identical_timer_callbacks_complete_and_cancel_independently(cancelled: int | None) -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> int: + loop = asyncio.get_running_loop() + result = loop.create_future() + completed: list[None] = [] + expected = 2 if cancelled is None else 1 + + def callback() -> None: + completed.append(None) + if len(completed) == expected: + result.set_result(len(completed)) + + handles = [loop.call_at(loop.time() + 1, callback) for _ in range(2)] + assert handles[0] != handles[1] + assert len(set(handles)) == 2 + if cancelled is not None: + handles[cancelled].cancel() + return await result + + start = _start() + initial = _execute(orchestrator, [], start) + remaining = [index + 1 for index in range(2) if index != cancelled] + assert [action.id for action in initial.actions] == remaining + deadline = NOW + timedelta(seconds=1) + old = start + [helpers.new_timer_created_event(index, deadline) for index in remaining] + for offset, timer_id in enumerate(remaining): + new = [helpers.new_orchestrator_started_event(deadline), helpers.new_timer_fired_event(timer_id, deadline)] + result = _execute(orchestrator, old, new) + assert _execute(orchestrator, old, new).actions == result.actions + if offset < len(remaining) - 1: + assert result.actions == [] + else: + assert json.loads(_completion(result).result.value) == len(remaining) + old += new + + +@pytest.mark.parametrize("kind", ["wait_for", "timeout"]) +def test_cancellation_racing_local_completion_in_timed_wait(kind: str) -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> str: + loop = asyncio.get_running_loop() + gate: asyncio.Future[int] = loop.create_future() + + async def waiter() -> None: + if kind == "wait_for": + await asyncio.wait_for(gate, timeout=10) + else: + async with asyncio.timeout(10): + await gate + await ctx.call_activity("after") + + branch = asyncio.create_task(waiter()) + await ctx.call_activity("trigger") + # The completion resolves the local future and cancels its waiter in one step. + gate.set_result(1) + branch.cancel() + try: + await branch + except asyncio.CancelledError: + return "cancelled" + return "finished" + + old = _start() + [helpers.new_task_scheduled_event(1, "trigger")] + result = _execute(orchestrator, old, [helpers.new_task_completed_event(1, "null")]) + if kind == "wait_for" and sys.version_info < (3, 12): + # CPython 3.11's wait_for returns the completed result instead of + # raising CancelledError, so the cancelled branch keeps running. + assert [(a.id, a.scheduleTask.name) for a in result.actions if a.HasField("scheduleTask")] == [ + (3, "after")] + else: + assert json.loads(_completion(result).result.value) == "cancelled" + + +@pytest.mark.parametrize("schedule", ["call_soon", "call_later"]) +def test_cancellation_wakeup_keeps_fifo_order_with_later_callbacks(schedule: str) -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: + loop = asyncio.get_running_loop() + + async def child(name: str) -> None: + try: + await ctx.wait_for_external_event("never") + finally: + ctx.call_activity(f"{name}-finally") + + first = asyncio.create_task(child("first")) + second = asyncio.create_task(child("second")) + await ctx.call_activity("start") + first.cancel() + if schedule == "call_soon": + loop.call_soon(ctx.call_activity, "callback") + else: + loop.call_later(0, ctx.call_activity, "callback") + # A later cancellation must not overtake the callback queued before it. + second.cancel() + for branch in (first, second): + with pytest.raises(asyncio.CancelledError): + await branch + await ctx.call_activity("last") + + old = _start() + [helpers.new_task_scheduled_event(1, "start")] + new = [helpers.new_task_completed_event(1, "null")] + expected = [(2, "first-finally"), (3, "callback"), (4, "second-finally"), (5, "last")] + for _ in range(3): + result = _execute(orchestrator, old, new) + assert [(a.id, a.scheduleTask.name) for a in result.actions] == expected + + +@pytest.mark.parametrize("delay", [1.0000001, 0.0000001, 2.0000004]) +def test_call_later_rounds_relative_delay_up_from_exact_clock(delay: float) -> None: + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: + await asyncio.sleep(delay) + + actions = _execute(orchestrator, [], _start()).actions + assert len(actions) == 1 + with localcontext() as exact: + exact.prec = 400 + delay_us = int((Decimal(delay) * 1_000_000).to_integral_value(rounding=ROUND_CEILING)) + assert actions[0].createTimer.fireAt.ToDatetime() == NOW + timedelta(microseconds=delay_us) + + +class _CountingFuture(asyncio.Future[Any]): + comparisons = 0 + + def __eq__(self, other: object) -> bool: + _CountingFuture.comparisons += 1 + return self is other + + __hash__ = asyncio.Future.__hash__ + + +@pytest.mark.parametrize("count", [64, 1024]) +def test_shared_handle_waiter_removal_is_constant_time( + count: int, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(DurableEventLoop, "create_future", lambda self: _CountingFuture(loop=self)) + _CountingFuture.comparisons = 0 + + async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> list[int]: + shared = ctx.call_activity("shared", return_type=int) + abandoned = [asyncio.create_task(shared.wait()) for _ in range(count)] + await asyncio.sleep(0) + # Withdraw the newest waiter first, one step at a time. + for waiter in reversed(abandoned): + waiter.cancel() + await asyncio.sleep(0) + await asyncio.gather(*abandoned, return_exceptions=True) + order: list[int] = [] + + async def borrow(index: int) -> int: + value = await shared + order.append(index) + return value + index + + values = await asyncio.gather(*(borrow(index) for index in range(count))) + assert order == list(range(count)) + return values[:3] + + old = _start() + [helpers.new_task_scheduled_event(1, "shared")] + result = _execute(orchestrator, old, [helpers.new_task_completed_event(1, "10")]) + assert json.loads(_completion(result).result.value) == [10, 11, 12] + assert _CountingFuture.comparisons < count diff --git a/tests/durabletask/test_coroutine_orchestrators.py b/tests/durabletask/test_coroutine_orchestrators.py index c021c9a4..584513c5 100644 --- a/tests/durabletask/test_coroutine_orchestrators.py +++ b/tests/durabletask/test_coroutine_orchestrators.py @@ -774,12 +774,3 @@ def test_loop_time_accepts_naive_and_aware_orchestration_clocks(now: datetime, o ctx = cast(task.OrchestrationContext, SimpleNamespace(current_utc_datetime=now)) loop = DurableEventLoop(ctx, is_complete=lambda: False) assert loop.time() == (NOW - datetime(1970, 1, 1)).total_seconds() - offset - - -def test_positive_asyncio_sleep_reports_durable_timer_alternative() -> None: - async def orchestrator(ctx: task.OrchestrationContext, _: Any) -> None: - await asyncio.sleep(1) - - complete = _completion(_execute(orchestrator, [], _start())) - assert complete.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED - assert "ctx.create_timer" in complete.failureDetails.errorMessage