Skip to content

Report the entries of retired tables to the collector - #1566

Merged
asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:claude/traverse-retired-entries
Sep 24, 2026
Merged

asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:claude/traverse-retired-entries

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

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, 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'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. The walk takes no lock, like the walk of
md->keys beside it, and must not: the collector calls tp_traverse with the
world 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 #1562
adds 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, and
cycles 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

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes N/A, no user-facing API changed
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt N/A, this repo has no such file
  • Add a new news fragment into the CHANGES/ folder
  • make doc-spelling passes and any new technical words are added to docs/spelling_wordlist.txt

Drafted 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 (300ms
at the end of _md_reader_enter(), 100ms after the exchange, 300ms before the
push-back) so a clear() leaves its table on the list. The driver builds
node -> d -> entry -> node, clears d against one reader, drops the names
and collects:

# with #1562 alone
attempt 0: traverse reports the value: False; node leaked after gc.collect(): True
# with this commit
attempt 0: traverse reports the value: True; node leaked after gc.collect(): False

3 of 3 attempts each way.

Of the two committed tests, test_get_referents_reports_each_entry_once is
deterministic and guards the unsafe direction: it fails ([2, 2, 2, ...] == [1, 1, 1, ...]) against a build with a deliberate second Py_VISIT of each
value, which is what a retired table that still had nentries set would
produce. test_collect_cycle_through_retired_entries_thread_safety runs the
racing 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 a
clear(), where a value can only be reported through a retired table, and it
is 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 job
built 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 x followed by a
weakref 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:

free-threaded, MULTIDICT_DEBUG_BUILD=1   2616 passed, 125 skipped
GIL                                      2628 passed, 113 skipped
GIL, CPython 3.10.17                     2628 passed, 113 skipped
MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions
                                         1266 passed, 17 skipped
MULTIDICT_TSAN_BUILD=1, TSan CPython 3.14.7t, retirement, referents,
cycle and clear tests                    7 passed, 0 warnings

Lint: pre-commit run, all hooks passed. Docs: make doc-spelling, build
succeeded.

Performance, benchmarks/callgrind_driver.py --impl multidict_c --include-multidict-only on the free-threaded build, both arms built in the
same tree and venv, base being this branch's parent: all 26 cells flat to
0.09%, update identical at 48899.0 Ir. tools/codegen_diff.py from a fresh
worktree reports 0 of 203 functions changed with the GIL enabled and 33 of 205
free-threaded. multidict_tp_traverse is this change, 59 to 99 instructions;
all but two of the rest are .cold partitions that moved with unchanged
instruction counts. The exceptions are bitmap_next, one instruction shorter,
and md_update_from_dict, 14 longer, which is the dict-update path the
update cell measures as unchanged, so those instructions are not on the path
it takes.

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 24, 2026
@asvetlov
asvetlov marked this pull request as ready for review September 24, 2026 11:44
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 24, 2026 11:44
@asvetlov
asvetlov force-pushed the claude/traverse-retired-entries branch from 533d178 to 57f5904 Compare September 24, 2026 11:46
@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The remaining test-coverage concern is non-blocking; it does not make the PR unsafe to merge.

What we checked:

  • Validated the contract-level claim that CPython 3.14.7 stops the world around the tp_traverse calls made by gc.get_referents. T-Rex
  • Noted that the stress run did not traverse a populated retired table, so it cannot prove retirement-window behavior. T-Rex
  • Inspected the supplied artifacts, including the Python snippet and four log artifacts, to map evidence to the stated proofs. T-Rex
  • Documented that the available evidence supports stop-the-world behavior in the traversal case but highlights the remaining gap for retirement-window behavior and suggests targeted follow-up. T-Rex

Reviews (3) · Last reviewed commit: "Say what the cycle test does and does no..."

Comment thread tests/test_multidict.py Resolved
@greptile-apps

This comment has been minimized.

@codspeed

codspeed Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:claude/traverse-retired-entries (4efb8db) with master (62df00f)

Open in CodSpeed

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
asvetlov force-pushed the claude/traverse-retired-entries branch from b17508b to 4efb8db Compare September 24, 2026 12:15
@codecov

codecov Bot commented Sep 24, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (62df00f) to head (4efb8db).

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     
Flag Coverage Δ
CI-GHA 100.00% <100.00%> (ø)
pytest 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@asvetlov
asvetlov merged commit ce1049c into aio-libs:master Sep 24, 2026
61 of 62 checks passed
@asvetlov
asvetlov deleted the claude/traverse-retired-entries branch September 24, 2026 12:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant