Skip to content

[Async stack 2/6] asyncio composition and durable timers - #358

Open
andystaples wants to merge 1 commit into
andystaples-async-stack-1-coroutine-dispatchfrom
andystaples-async-stack-2-asyncio-composition
Open

andystaples wants to merge 1 commit into
andystaples-async-stack-1-coroutine-dispatchfrom
andystaples-async-stack-2-asyncio-composition

Conversation

@andystaples

@andystaples andystaples commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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 asyncio composition and durable timers to the replay-safe event loop that coroutine orchestrators run on.

Task composition

  • Adds _DurableAsyncTask. A task is retired once its result or exception has been observed, so replaying discarded gather batches and handled failures does not keep decoded payloads or tracebacks alive.
  • Tasks hash by creation sequence. TaskGroup iterates a set of tasks to cancel them, so this keeps cancellation order independent of memory addresses; the reason is documented in code.
  • Cancellation callbacks run in a deterministic order, keyed by when each task was created. Retired tasks never reuse that ordering.
  • TaskGroup, gather, wait_for, and asyncio.timeout compose over durable work:
    • Cancelling a local waiter does not cancel the underlying shared durable operation.
    • The actions emitted when a TaskGroup is cancelled stay the same across replays.
  • A waiter finalized after the dispatch has closed (for example, an asyncio.Task constructed directly rather than through asyncio.create_task) no longer raises during garbage collection. Directly constructed tasks are documented as unsupported.

Durable timers

  • call_later and call_at are backed by durable timers and return _DurableTimerHandle, which compares by identity.
  • Deadlines are rounded up to the next microsecond, so a timer never fires before the loop's deadline. Timezone-aware orchestration clocks are normalized.
  • Deadlines already in the past run immediately, and non-finite delays raise an error.
  • Cancelling a handle cancels its durable timer.
  • asyncio.sleep and timeouts use the existing chunking for long timers.

Unsupported work

  • Every asyncio loop API the durable loop does not implement (executors, cross-thread scheduling, sockets, pipes, subprocesses, readers/writers, signal handlers, TLS, sendfile, task factories, exception handlers, debug mode, async-generator shutdown, and loop lifecycle) fails through one table with an actionable error, instead of a bare NotImplementedError. get_exception_handler() returns None, because callback failures always fail the dispatch. A test enumerates asyncio.AbstractEventLoop so 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.wait and asyncio.as_completed are not rejected at run time; the contract documents them as unsupported because their ordering is not replay-stable.

Docs (docs/async-orchestrators.md)

  • States that successive dispatches can run on different workers and that all workers processing an instance must use the pinned environment.
  • Notes that delays below the resolution of loop.time() are effectively zero, and that tasks must be created with asyncio.create_task or a task group.

Code docs

  • Extends the list of private asyncio hooks in the asyncio_loop.py module docstring, and clarifies the Task.wait() docstring for asyncio.create_task and task groups.

Scope

Left for later layers

Tests

  • Adds tests/durabletask/test_asyncio_orchestrators.py, covering:
    • composition
    • memory retirement
    • shared-wait cancellation
    • timers
    • unsupported work, including every unimplemented AbstractEventLoop API
    • fanout scaling

@andystaples
andystaples added this pull request to stack #365 November 11, 2026 20:39
@andystaples andystaples changed the title [Async stack 2/7] asyncio composition and durable timers [Async stack 2/6] asyncio composition and durable timers Nov 11, 2026
@andystaples
andystaples marked this pull request as draft November 12, 2026 16:30
@andystaples
andystaples force-pushed the andystaples-async-stack-2-asyncio-composition branch from 1b5625c to 1e5bf2f Compare November 12, 2026 16:48
Comment thread durabletask/internal/asyncio_loop.py Resolved
@andystaples
andystaples force-pushed the andystaples-async-stack-2-asyncio-composition branch from 0cfb7b3 to 44eccfc Compare November 12, 2026 20:32
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>
@andystaples
andystaples marked this pull request as ready for review November 23, 2026 19:03
Copilot AI balanced review requested due to automatic review settings November 23, 2026 19:04

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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)
Comment on lines +88 to +111
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)
@andystaples
andystaples force-pushed the andystaples-async-stack-2-asyncio-composition branch from cd0afdb to adc2ff1 Compare November 23, 2026 19:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants