gh-148263: Fix refcount leak in weakref proxy operations#148486
Open
prakashsellathurai wants to merge 11 commits intopython:mainfrom
Open
gh-148263: Fix refcount leak in weakref proxy operations#148486prakashsellathurai wants to merge 11 commits intopython:mainfrom
prakashsellathurai wants to merge 11 commits intopython:mainfrom
Conversation
Wulian233
reviewed
Apr 13, 2026
Contributor
There was a problem hiding this comment.
We don't need such a long description, usually just one sentence
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.
Issue
When a weakref proxy was used in binary, ternary, or rich comparison operations and one of the operands turned out to be a dead proxy, the reference count of any already-unwrapped arguments was incremented by the
UNWRAPmacro but never released causing a memory leak of ~1 ref per call.This affected ~20 binary operators (
+,-,*,/,|,&,^, etc.), ternarypow(), and rich comparisons.Reproducer showing ~1 leaked ref per call on the main branch:
Fix
UNWRAPmacro with a proper inline function_proxy_unwrap()that tracks whether each argument was successfully incref'd via adid_increfflag.goto clean_uperror paths inWRAP_BINARY,WRAP_TERNARY, andproxy_richcomparethat correctlyPy_DECREFany already-acquired references before returningNULL.WRAP_UNARYandWRAP_METHODto use_proxy_unwrap()for consistency. No ref leak is observed in those paths today, but dependent changes in the mainline would fail without this migration since they rely on the new unwrap function rather than the old macro.Validation:
Reproducer script -> https://gist.github.com/prakashsellathurai/ea7ba0ec8a5cf049881464d34de31411
before (mainline )
After this change