Clear exc.__traceback__ after handled exceptions to prevent memory leak#3205
Open
baconcheese113 wants to merge 1 commit into
Open
Clear exc.__traceback__ after handled exceptions to prevent memory leak#3205baconcheese113 wants to merge 1 commit into
baconcheese113 wants to merge 1 commit into
Conversation
…ry leak When `wrap_app_handling_exceptions` catches and handles an exception, the traceback retains references to the ASGI send/receive closures and per-request state. If the exception object is long-lived (e.g. a module-level HTTPException reused across requests), this pins per-request objects in memory permanently, causing a leak that GC cannot collect. Clear `exc.__traceback__` after the handler runs and the response is sent. Unhandled exceptions (re-raised via `raise exc`) are not affected.
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.
Summary
wrap_app_handling_exceptionscatches and successfully handles an exception,exc.__traceback__retains a reference to the frame's locals, which include the ASGIsend/receiveclosures and per-request stateHTTPExceptionreused across requests — common in auth libraries), this pins per-request objects in memory permanently. GC cannot collect these because the module holds a strong non-cyclic reference to the exceptionexc.__traceback__ = Noneafter the handler runs and the response is sent. Unhandled exceptions (raise exc) are not affected — their traceback is preserved for propagationReference chain that causes the leak
Precedent
asyncio.open_connection. Fixed by clearing references after exception handling. Backported to 3.10/3.11.self.parserafter connection loss.Test plan
__traceback__is notNoneafter handling)__traceback__isNoneafter handling)raise exc) still preserve their tracebacktest_handled_exception_clears_tracebackpasses on both asyncio and trio