gh-157377: Don't flush the thread-local allocation count in gc.get_count - #157381
Open
ngoldbaum wants to merge 2 commits into
Open
gh-157377: Don't flush the thread-local allocation count in gc.get_count#157381ngoldbaum wants to merge 2 commits into
ngoldbaum wants to merge 2 commits into
Conversation
| gc->alloc_count = 0; | ||
| // Don't flush: record_allocation() checks the threshold only when it fills. | ||
| int young = _Py_atomic_load_int_relaxed(&gcstate->young.count); | ||
| young += (int)gc->alloc_count; |
Contributor
There was a problem hiding this comment.
I think young needs to be clamped with if (young < 0) young = 0; otherwise negative values can be reported like:
xs = [[] for _ in range(600)]; gc.collect(); del xs[:400]
gc.get_count() -> (-173, 0, 0) # with the PR applied
Contributor
Author
ngoldbaum
force-pushed
the
fix-gc-get-count
branch
from
September 13, 2026 14:46
755fc56 to
81ca259
Compare
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.
On the free-threaded build,
gc.get_count()flushed the allocation counter into the global young count and reset it. Modifying the local count leads to pathological cases like in the linked issue. It could also flush negative local counts into the global count, which bypassed the clamp from gh-142048 and led to under-collection compared with not callingget_count().With this change,
get_count()returns the global count plus the local counter without modifying either. The reported value still includes the caller's buffered allocations, and scheduling behaves exactly as ifget_count()had never been called.gc.get_count()can starve GC scheduling on the free-threaded build #157377