Repository navigation
[Async stack 3/6] Dispatch cleanup for coroutine orchestrators - #360
andystaples wants to merge 1 commit into
Conversation
fb01656 to
fe8e8bf
Compare
fe8e8bf to
466196e
Compare
ed84f44 to
c164cb6
Compare
Rebased onto main as a single commit. Includes: - Harden async orchestration dispatch cleanup - Harden async dispatch cleanup ownership and signal precedence - Bound async-generator cleanup discovery budget - Make async cleanup budgets cumulative and close idempotent - Reject closing the durable loop from orchestrator code Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
Cleanup can falsely report truncation when queues empty at the step limit, while repeated scans of already-closed generators can cause quadratic teardown delays.
2 open issues
What changed in this PR
This layer adds dispatch teardown for coroutine orchestrators in the core SDK, cleaning up local async work while protecting the previously decided orchestration response.
Changes:
- Adds bounded task and async-generator cleanup, host-hook restoration, and cleanup-error prioritization.
- Prevents durable work and extra entity-release messages during teardown.
- Documents cleanup behavior and adds regression coverage plus Windows testing across Python 3.11–3.15.
| File | Description |
|---|---|
tests/durabletask/test_asyncio_orchestrators.py |
Tests cleanup limits, finalizers, error handling, hooks, and entity locks. |
durabletask/worker.py |
Guards durable scheduling and entity releases during async cleanup. |
durabletask/internal/exceptions.py |
Centralizes control-flow exception classification. |
durabletask/internal/asyncio_loop.py |
Implements bounded teardown and async-generator ownership. |
docs/async-orchestrators.md |
Explains cleanup limits, ownership, and failure behavior. |
.github/workflows/durabletask.yml |
Adds Windows async-runtime and cleanup test coverage. |
Review effort: Balanced
| break | ||
| self._deliver_completions() | ||
| steps += 1 | ||
| if self._closing and steps >= cleanup_limit: |
| for generator in pending: | ||
| closed[id(generator)] = generator | ||
| self.create_task(generator.aclose()) |
d50a68f to
8dcea28
Compare
Bernd Verst (berndverst)
left a comment
There was a problem hiding this comment.
Snapshotting the response before teardown is the right direction. Already-issued durable work keeps its action order, and local cleanup doesn't cancel remote work. I'd hold this layer until forced cleanup stays off the host loop, running async generators get another chance to close, and teardown prevents event consumption and preserves the first unexpected cleanup failure.
| for future in tuple(self._tasks): | ||
| if not future.done(): | ||
| try: | ||
| future.get_coro().close() |
There was a problem hiding this comment.
This forced close() runs after _drain() has restored the host loop and task. Under asyncio.run, a cancellation-resistant branch's outer finally sees the host loop and host ContextVar values. I reproduced a plain asyncio.get_running_loop().call_soon(...) escaping dispatch cleanup and running after _execute returns. Please run forced closes inside the same dispatch-loop and async-generator hook guard, and preserve the task context when running its finalizer. Add an outer-loop fixture for the forced path, not just cooperative cancellation.
| self._report_unquiesced_cleanup() | ||
| return | ||
| for generator in pending: | ||
| closed[id(generator)] = generator |
There was a problem hiding this comment.
Marking the generator closed before aclose() succeeds prevents the second sweep from trying again. I reproduced a generator whose active anext() catches dispatch cancellation, waits on a local asyncio.Event, and yields again after another tracked generator's finalizer sets that event. The first aclose() fails with "asynchronous generator is already running"; the dispatch returns with its frame still live and its finally never run, without exhausting the budget. Please defer running generators and retry once they stop, within the same budget.
| elif not future.cancelled(): | ||
| error = future.exception() | ||
| if error is not None and (future not in completed_at_close or future in unobserved_at_close): | ||
| self._record_cleanup_error( |
There was a problem hiding this comment.
Task exceptions are recorded only after the drains, so a later callback can displace the first unexpected cleanup failure. A cleanup task that queues a callback and raises a custom BaseException first loses to the callback's subsequent GeneratorExit: dispatch raises instead of reporting the original failure. Please capture cleanup-task failures in execution order while draining and retain the explicit KeyboardInterrupt/SystemExit override.
| return current_actions | ||
|
|
||
| def next_sequence_number(self) -> int: | ||
| if self._async_cleanup: |
There was a problem hiding this comment.
The sequence-number guard misses wait_for_external_event(), which doesn't allocate an ID. A finalizer can pop and deserialize a buffered event and read it with get_result(), or register a new wait before the await guard runs. The snapshotted actions don't change, but the read and custom converter can still run during local teardown. Please guard event registration and consumption before touching the buffer, and cover both a buffered and an unreceived event.

Warning
Do not merge this PR, or any PR in this stack, individually. The whole stack will be squash-merged only after every stack PR is approved.
Layer 3/6 of the review stack that splits the closed #293. The base is layer 2/6, #358.
Scope
Dispatch teardown for the per-dispatch durable event loop:
DurableEventLoopinstalls the async-generator hooks for each dispatch and restores the host's previous hooks afterwards.close()drains, then cancels, pending tasks and closes tracked async generators.close()is idempotent. Only the worker closes the loop: orchestrator code that callsloop.close()while the loop is running gets an actionableRuntimeError, as asyncio does for a running loop, and the dispatch's normal teardown still runs.KeyboardInterruptorSystemExittakes precedence, even when grouped or raised after other errors. The existing dispatch response is preserved, and background and cleanup errors are logged.wait_durablecannot schedule durable work once the loop is closing. The orchestration context also rejects sequence-number allocation during async cleanup, and exiting an entity critical section during teardown does not schedule extra release messages.workerinto the shareddurabletask.internal.exceptions.is_control_flow_exception. ItsBaseExceptionGrouphandling is unchanged.Docs
docs/async-orchestrators.mdgains a warning callout describing the cleanup cap and truncation, and documents async-generator ownership during dispatch, explicitaclose()/contextlib.aclosing(...), and teardown handling of entity critical sections and process-control exits.CI
Adds an
async-runtime-windowsjob to.github/workflows/durabletask.ymlthat runs the asyncio, replay, and dispatch cleanup tests on Windows across Python 3.11-3.15. Layer 4/6 (#361) extends it withtest_async_context.py.Intermediate adaptations reversed in layer 4/6
Async orchestrators still receive the eager
task.OrchestrationContextat this layer, so tests annotate contexts astask.OrchestrationContextinstead oftask.AsyncOrchestrationContext, and operations that will later go throughctx.as_task_context()(for examplecall_activity(...)andcreate_timer(...)that need eager handles) are called directly onctx.No changelog changes; release notes are added in layer 6/6 (#364).