Repository navigation
[Async stack 3/6] Dispatch cleanup for coroutine orchestrators - #360
andystaples wants to merge 4 commits into
Conversation
fb01656 to
fe8e8bf
Compare
fe8e8bf to
466196e
Compare
ed84f44 to
c164cb6
Compare
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
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.
8dcea28 to
635be8b
Compare
635be8b to
4213842
Compare
Bernd Verst (berndverst)
left a comment
There was a problem hiding this comment.
The teardown fixes cover the original cases. Two gaps remain: generators first opened during forced close can miss their finalizers, and the retry sweep can do quadratic work outside its cleanup budget when many generators stay active.
4213842 to
c6005fa
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 <[email protected]>
Forced closes run on the durable loop in the task's context, running async generators are closed after their anext() stops, cleanup-task failures are recorded in execution order, the generator sweep inspects each generator once, truncation is reported only when work remains, and teardown can no longer wait for or consume external events. Co-authored-by: Copilot App <[email protected]>
… test Co-authored-by: Copilot App <[email protected]>
Running generators are retried only once no newly discovered generator is ready, with each retry charged to the sweep budget. Forced close refuses to start async generators, since no later sweep could close them. Co-authored-by: Copilot App <[email protected]>
c6005fa to
1c9cb9c
Compare
Bernd Verst (berndverst)
left a comment
There was a problem hiding this comment.
The deferred generator sweep now scales as intended. One cleanup gap remains: retrying the same generator after the first-iteration error can still open a resource after the final sweep.
| def _asyncgen_firstiter(self, generator: Any) -> None: | ||
| if self._forcing: | ||
| # Refuse before the generator opens a resource that nothing could close. | ||
| raise RuntimeError( |
There was a problem hiding this comment.
CPython calls the firstiter hook only once, even if it raises. If a forced finalizer catches this RuntimeError and then retries anext() on the same generator, the second call skips the hook, runs the body, and leaves the resource untracked after the last sweep. I reproduced a live ag_frame after dispatch. Could we synchronously close the fresh generator before raising, and extend the regression test to retry the same object and assert the body never runs?

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. Each sweep pass inspects only newly discovered generators. A generator whoseanext()is still in progress is closed once that step stops; such generators are rechecked only after no newly discovered generator is ready, and each recheck counts against the cleanup budget. Coroutines that ignore cancellation are force-closed last, still on the durable loop with its hooks installed, as their own task and in their task's context. They cannot start new async generators there, because no later sweep could close them.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, external event waits, and buffered-event consumption 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).