Fix scoped resource leak on cancellation in exit-stack cleanup#142
Merged
maldoinc merged 1 commit intoJun 16, 2026
Merged
Conversation
clean_exit_stack and async_clean_exit_stack caught only `except Exception` while iterating the exit stack. asyncio.CancelledError (and KeyboardInterrupt / SystemExit) are BaseException, not Exception, so when a generator's teardown re-raised the exception being unwound it escaped the loop early, skipping the remaining generators and exit_stack.clear(). On a cancelled `async with container.enter_scope()` block (asyncio.wait_for timeout, task cancellation) every earlier-registered scoped resource leaked, matching neither the documented behaviour nor contextlib.AsyncExitStack. Add an `except BaseException` branch to both loops: swallow the re-raised exc_val so cleanup of the remaining generators continues (and the stack is cleared), while propagating any genuinely new BaseException. New BaseExceptions are not appended to the errors list since ContainerCloseError subclasses ExceptionGroup on 3.11+, which rejects non-Exception members. Fixes maldoinc#141
Owner
|
Thank you @glitch-ux. This is now released in 2.11.3 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Fixes a scoped-resource leak during cancellation. Both
clean_exit_stackandasync_clean_exit_stackinwireup/ioc/_exit_stack.pyiterated the exit stack catching onlyexcept Exception.asyncio.CancelledError(andKeyboardInterrupt/SystemExit) areBaseException, notException, so when a generator'sfinallyre-raised the exception being unwound, it escaped the loop early — skipping cleanup of every earlier-registered generator and theexit_stack.clear()call.In practice, a cancelled
async with container.enter_scope()block (anasyncio.wait_fortimeout, atask.cancel(), structured-concurrency cancellation) tore down only the last scoped resource and leaked the rest.Fixes #141.
Reproduction (before this PR)
teardowns['B']—Aleaks['B', 'A']— matchescontextlib.AsyncExitStackHow
Add an
except BaseExceptionbranch after the existingexcept Exceptionin both cleanup loops:exc_valis swallowed so cleanup of the remaining generators continues and the stack is cleared; it keeps propagating naturally through__aexit__afterwards (which returnsNone).BaseExceptionraised during teardown is re-raised rather than appended toerrors, becauseContainerCloseErrorsubclassesExceptionGroupon Python 3.11+ and would reject non-Exceptionmembers.async_clean_exit_stacknow trips ruffC901(complexity 11 > 10), so it carries a# noqa: C901, consistent withfactory_compiler.py/_wrapper_compiler.py.Tests
Added to
test/unit/test_exit_stack.py:test_clean_exit_stack_continues_teardown_when_unwinding_base_exception— sync path.test_async_clean_exit_stack_continues_teardown_on_cancellation— async path withasyncio.CancelledError(the reported scenario).test_async_clean_exit_stack_propagates_new_base_exception_from_teardown— locks in that a genuinely newBaseExceptionstill propagates.The first two fail on
masterand pass with this change.Checks
make check-ruff,make check-fmt,make check-mypy, andmake test(355 passed) are all green locally. No new dependencies; targets Python 3.10+.