Repository navigation
[Async stack 2/6] asyncio composition and durable timers - #358
andystaples wants to merge 1 commit into
Conversation
1b5625c to
1e5bf2f
Compare
0cfb7b3 to
44eccfc
Compare
Rebased onto main as a single commit. Includes: - Add asyncio composition and durable timers for coroutine orchestrators - Fix same-runtime task-group cancellation replay order - Use exact microsecond ceiling for durable call_at deadlines - Harden durable loop API coverage and task bookkeeping - Cover every inherited asyncio loop API in the durable loop Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
Valid wrapped synchronous partials fail registration due to incorrect cycle detection, and shared-handle waiter cleanup becomes quadratic during replay.
2 open issues
What changed in this PR
This layer extends the core SDK’s coroutine dispatch with replay-safe asyncio composition and durable timers. It is part of the coordinated async stack, intended to be squash-merged together.
Changes:
- Adds task composition, deterministic cancellation ordering, and retirement of completed tasks and observed failures.
- Backs asyncio sleeps and timeouts with durable timers and provides actionable errors for unsupported loop operations.
- Adds replay, cancellation, memory-retention, and scaling coverage, plus async authoring documentation.
| File | Description |
|---|---|
tests/durabletask/test_orchestration_generator_cleanup.py |
Updates the expected teardown warning. |
tests/durabletask/test_generator_replay_compat.py |
Checks compatibility with existing generator histories. |
tests/durabletask/test_coroutine_orchestrators.py |
Covers coroutine dispatch, callable classification, and replay parity. |
tests/durabletask/test_asyncio_orchestrators.py |
Tests composition, timers, cancellation, memory retirement, and scaling. |
durabletask/worker.py |
Integrates coroutine classification, dispatch, and cleanup. |
durabletask/task.py |
Adds awaitable durable handles, borrowed waiters, and orchestrator type aliases. |
durabletask/internal/shared.py |
Classifies synchronous and asynchronous orchestrator callables. |
durabletask/internal/asyncio_loop.py |
Implements deterministic scheduling, durable timers, and unsupported-operation guards. |
docs/supported-patterns.md |
Connects durable patterns to async authoring and cancellation behavior. |
docs/features.md |
Introduces coroutine orchestration alongside generators. |
docs/async-orchestrators.md |
Documents async APIs, replay constraints, cancellation, and dispatch cleanup. |
Review effort: Balanced
| return await future | ||
| finally: | ||
| # Cancelling one waiter never cancels a shared durable operation. | ||
| entry[1].remove(future) |
| wrapped_fallbacks: list[Any] = [] | ||
| node: Any = fn | ||
| while True: | ||
| if node is None: | ||
| if not wrapped_fallbacks: | ||
| return False | ||
| node = wrapped_fallbacks.pop() | ||
| identity = id(node) | ||
| if identity in seen: | ||
| raise ValueError("wrapper loop when classifying async callable") | ||
| seen[identity] = node | ||
| if inspect.iscoroutinefunction(node): | ||
| return True | ||
| if inspect.isgeneratorfunction(node) or inspect.isasyncgenfunction(node): | ||
| return False | ||
| if hasattr(node, "__wrapped__"): | ||
| wrapped_fallbacks.append(node.__wrapped__) | ||
| if isinstance(node, partial): | ||
| node = node.func | ||
| elif (inspect.isfunction(node) or inspect.ismethod(node) | ||
| or inspect.isbuiltin(node) or inspect.ismethodwrapper(node)): | ||
| node = None | ||
| else: | ||
| node = getattr(node, "__call__", None) |
cd0afdb to
adc2ff1
Compare
Bernd Verst (berndverst)
left a comment
There was a problem hiding this comment.
Per-completion replay and durable timers are useful additions. Before this ships, I'd address the Python 3.11 wait_for cancellation race and preserve FIFO between cancellation wakeups and ordinary callbacks. Both can change which durable activities get scheduled. Relative sleep delays also need to be rounded before conversion through the float clock so they don't fire early.
|
|
||
|
|
||
| @pytest.mark.parametrize("kind", ["sleep", "wait_for", "timeout"]) | ||
| def test_durable_timer_and_timeout(kind: str) -> None: |
There was a problem hiding this comment.
Can we add a test where an activity completion resolves a local future and immediately cancels the task in wait_for? On Python 3.11, wait_for returns the future's value and the cancelled task schedules its next durable activity. The same history delivers CancelledError on 3.13 and 3.14, and asyncio.timeout also delivers it on 3.11. Please make external cancellation safe here or narrow the 3.11 contract and recommend asyncio.timeout instead.
| try: | ||
| while self._ready: | ||
| while self._ready or self._cancel_ready: | ||
| self._ready.extend(handle for _, _, handle in sorted(self._cancel_ready)) |
There was a problem hiding this comment.
Appending the cancellation batch at drain time lets a later call_soon() callback overtake an already-queued cancellation wakeup. I replayed child.cancel(); loop.call_soon(...) after an activity completion: the callback takes action ID 2 and the child's finally takes ID 3, reversing FIFO. Can we preserve the batch's place in the ready queue while still sorting task-group wakeups? Please cover the interleaving with a replay test.
| ) -> asyncio.TimerHandle: | ||
| if not math.isfinite(delay): | ||
| raise ValueError("Durable delays must be finite.") | ||
| return self.call_at(self.time() + max(0, delay), callback, *args, context=context) |
There was a problem hiding this comment.
The exact ceiling in call_at can't recover precision lost in this addition. At the test clock, asyncio.sleep(1.0000001) emits a timer for exactly +1s, so the requested relative delay can finish slightly early. Can we round call_later's delay up to microseconds and add it to the exact orchestration clock? call_at can keep its separate absolute-float conversion.

Warning
Do not merge this PR, or any other PR in this stack, on its own. The stack was split out of the closed #293 to make review easier. Once every PR in the stack is approved, the whole stack will be squash-merged together.
Stack layer 2/6, built on the coroutine dispatch layer (#357).
Summary
This layer adds general
asynciocomposition and durable timers to the replay-safe event loop that coroutine orchestrators run on.Task composition
_DurableAsyncTask. A task is retired once its result or exception has been observed, so replaying discardedgatherbatches and handled failures does not keep decoded payloads or tracebacks alive.TaskGroupiterates a set of tasks to cancel them, so this keeps cancellation order independent of memory addresses; the reason is documented in code.TaskGroup,gather,wait_for, andasyncio.timeoutcompose over durable work:TaskGroupis cancelled stay the same across replays.asyncio.Taskconstructed directly rather than throughasyncio.create_task) no longer raises during garbage collection. Directly constructed tasks are documented as unsupported.Durable timers
call_laterandcall_atare backed by durable timers and return_DurableTimerHandle, which compares by identity.asyncio.sleepand timeouts use the existing chunking for long timers.Unsupported work
NotImplementedError.get_exception_handler()returnsNone, because callback failures always fail the dispatch. A test enumeratesasyncio.AbstractEventLoopso that any public loop API that is neither implemented nor in the table, including one added by a future Python version, fails the suite.asyncio.waitandasyncio.as_completedare not rejected at run time; the contract documents them as unsupported because their ordering is not replay-stable.Docs (
docs/async-orchestrators.md)loop.time()are effectively zero, and that tasks must be created withasyncio.create_taskor a task group.Code docs
asyncio_loop.pymodule docstring, and clarifies theTask.wait()docstring forasyncio.create_taskand task groups.Scope
Left for later layers
close()from layer 1/6, extended only to release the new timer and cancellation state.OrchestrationContext. The coldAsyncOrchestrationContextarrives in layer 4/6 ([Async stack 4/6] Add cold async orchestration context #361), which updates these tests to use it.Tests
tests/durabletask/test_asyncio_orchestrators.py, covering:AbstractEventLoopAPI