Repository navigation
Report the entries of retired tables to the collector - #1566
Merged
asvetlov merged 3 commits intoSep 24, 2026
Merged
Conversation
asvetlov
marked this pull request as ready for review
September 24, 2026 11:44
asvetlov
force-pushed
the
claude/traverse-retired-entries
branch
from
September 24, 2026 11:46
533d178 to
57f5904
Compare
Contributor
|
This comment has been minimized.
This comment has been minimized.
asvetlov
added a commit
to asvetlov/multidict
that referenced
this pull request
Sep 24, 2026
Review of aio-libs#1566 pointed out that the test joins its reader before collecting, so the last reader exit drains the retired table and releases its entries first, and the assertion then passes without the walk this change adds ever having a table to go over. That is right, and measuring it puts the odds of catching one at roughly 1% of clears, too rare to assert on and too machine-dependent for CI, so the docstring now says so and points at the deterministic half of the pair instead of leaving the reader to assume this one gates the fix.
On the free-threaded build, a table the drain leaves on md->retired still owns its entries' references, and md_traverse() reported the entries of md->keys only. A reference cycle running through one of those entries was therefore invisible to the collector: it read the values as reachable from outside the cycle and kept the whole thing alive, and since the multidict is only freed by the collector in that case, nothing later released them either. Reporting them is sound because no entry is ever reported twice: _md_resize() zeroes the old table's nentries when it hands ownership to the new table, so only md_clear() retires a table with entries left in it, and md->keys is empty by then. Reading the list without a lock is what the walk of md->keys already relies on, and nothing here may block, since the collector calls this with the world stopped and a stopped thread can hold any lock this would take.
Review of aio-libs#1566 pointed out that the test joins its reader before collecting, so the last reader exit drains the retired table and releases its entries first, and the assertion then passes without the walk this change adds ever having a table to go over. That is right, and measuring it puts the odds of catching one at roughly 1% of clears, too rare to assert on and too machine-dependent for CI, so the docstring now says so and points at the deterministic half of the pair instead of leaving the reader to assume this one gates the fix.
asvetlov
force-pushed
the
claude/traverse-retired-entries
branch
from
September 24, 2026 12:15
b17508b to
4efb8db
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1566 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 41 41
Lines 7148 7190 +42
Branches 625 631 +6
=========================================
+ Hits 7148 7190 +42
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
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 do these changes do?
On the free-threaded build, a table the drain leaves on
md->retiredstillowns its entries' references, and
md_traverse()reported the entries ofmd->keysonly. A reference cycle running through one of those entries wastherefore invisible to the collector, which read the values as reachable from
outside the cycle and kept the whole thing alive; and since a multidict in a
cycle is only ever freed by the collector, nothing later released them either.
Reporting those entries is what lets the cycle be collected.
Nothing is reported twice, which is the direction that would be unsafe:
_md_resize()zeroes the old table'snentrieswhen it hands ownership to thenew table, so only
md_clear()retires a table with entries left in it, andmd->keysis empty by then. The walk takes no lock, like the walk ofmd->keysbeside it, and must not: the collector callstp_traversewith theworld stopped, and a stopped thread can hold any lock this would take.
Stacked on #1562, whose first two commits are included here: reporting the
references is what lets the collector reach
tp_clear(), and the drain #1562adds there is what releases them. Either alone leaves the cycle uncollected.
Are there changes in behavior for the user?
gc.get_referents()on a multidict now lists what a retired table holds, andcycles through such an entry become collectable. C extension only; the
pure-Python implementation has no retirement scheme, and the interpreter
traverses its containers itself. Builds with the GIL enabled emit
byte-identical code.
Is it a substantial burden for the maintainers to support this?
No. It is a walk of a list that is almost always empty, on a path the
collector calls.
Related issue number
Refs #1555
Checklist
CONTRIBUTORS.txtN/A, this repo has no such fileCHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtDrafted with Claude Opus 5 in Claude Code; to be reviewed by @asvetlov before
it leaves draft.
Agent run details (optional, for reviewers)
Proof, with the drain window widened behind
-DMULTIDICT_WIDEN_DRAIN(300msat the end of
_md_reader_enter(), 100ms after the exchange, 300ms before thepush-back) so a
clear()leaves its table on the list. The driver buildsnode -> d -> entry -> node, clearsdagainst one reader, drops the namesand collects:
3 of 3 attempts each way.
Of the two committed tests,
test_get_referents_reports_each_entry_onceisdeterministic and guards the unsafe direction: it fails (
[2, 2, 2, ...] == [1, 1, 1, ...]) against a build with a deliberate secondPy_VISITof eachvalue, which is what a retired table that still had
nentriesset wouldproduce.
test_collect_cycle_through_retired_entries_thread_safetyruns theracing shape 50 times and does not fail on an unfixed build.
Review was right that the cycle test does not establish the traversal: it
joins its reader before collecting, and the last reader exit drains the table
first, so the walk usually has an empty list to go over. I looked for a
reliable observation and there is not one to be had without a hook compiled
into the extension. The one that exists is
gc.get_referents()right after aclear(), where a value can only be reported through a retired table, and itis cleanly attributable but far too rare: with 8 reader threads over 300
clears on an idle 22-core machine, this branch reported an entry 3 times and
master 0, twice each. Other shapes measured 0, including a single reader
parked in a 4MB key comparison (147us inside the counted region) and polling
500 times per clear. So a test that asserted the observation would be flaky,
and one that skipped when it did not observe would pass silently on a revert.
The docstring now states this rather than implying the test gates the fix.
A deterministic version needs a test-only delay compiled into
_md_drain_retired_slow(), which is the widener used above, plus a CI jobbuilt with it. That is worth doing for this whole family of races, and is its
own change rather than part of this one. Worth knowing for anyone measuring
retention from Python: on the free-threaded build,
del xfollowed by aweakref check is not enough, since deferred refcounting keeps the object alive
until a collection; without a
gc.collect()first, a probe like this reads 98%retention where the true figure is about 1%.
Tests, CPython 3.14.7 unless noted, one venv and one tree per leg:
Lint:
pre-commit run, all hooks passed. Docs:make doc-spelling, buildsucceeded.
Performance,
benchmarks/callgrind_driver.py --impl multidict_c --include-multidict-onlyon the free-threaded build, both arms built in thesame tree and venv, base being this branch's parent: all 26 cells flat to
0.09%,
updateidentical at 48899.0 Ir.tools/codegen_diff.pyfrom a freshworktree reports 0 of 203 functions changed with the GIL enabled and 33 of 205
free-threaded.
multidict_tp_traverseis this change, 59 to 99 instructions;all but two of the rest are
.coldpartitions that moved with unchangedinstruction counts. The exceptions are
bitmap_next, one instruction shorter,and
md_update_from_dict, 14 longer, which is the dict-update path theupdatecell measures as unchanged, so those instructions are not on the pathit takes.