Skip to content

Retry the retired-table drain after pushing tables back - #1565

Merged
asvetlov merged 4 commits into
aio-libs:masterfrom
asvetlov:claude/drain-retired-pushback-recheck
Sep 24, 2026
Merged

asvetlov merged 4 commits into
aio-libs:masterfrom
asvetlov:claude/drain-retired-pushback-recheck

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

On the free-threaded build, a drain that reads the active-readers gate as
nonzero pushes the tables it holds back onto md->retired and leaves them to
the reader the gate showed it. That reader can have run its own drain already,
between _md_drain_retired_slow()'s exchange and its push-back, and found the
list empty; nothing is then left to free those tables. They sit there until
the multidict is next used, and if it is dropped instead, the references their
entries own are never released. Rereading the gate after the push-back tells
the two apart: nonzero means the reader it sees decrements after that read,
hence after the push-back, so its own drain observes the tables, while zero
means nothing else will and another pass is what frees them.

This is the window #1555 was reached through, so it is an alternative fix for
that leak as well as a fix for tables sitting on the list longer than they
should. It is complementary to #1562 rather than a replacement: this closes
the window, #1562 backstops the invariant at teardown whatever the drain does,
and the two do not conflict.

Are there changes in behavior for the user?

No, other than retired tables being freed when they should be. C extension
only; the pure-Python implementation has no retirement scheme. Builds with the
GIL enabled emit byte-identical code.

Is it a substantial burden for the maintainers to support this?

No. One reread of an atomic already being read on that path, on a branch taken
only when a drain finds a reader in flight.

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 three sleeps compiled in behind -DMULTIDICT_WIDEN_DRAIN: 300ms
at the end of _md_reader_enter(), 100ms after the exchange, and 300ms before
the push-back. A thread waits 50ms and then does one d.get() while the main
thread clears a multidict holding one weakref'd value, then drops it.

On 6c1c9a8 the table is pushed back and never freed, and the value survives
teardown, 3/3 attempts. With this branch the reread fires and the retry frees
it inside clear() itself, 0/3, on every attempt in one extra pass:

[w] drain: took head=0x3d7d62f1200
[w] drain: readers_active=1
[w] reader exit prev_active=1
[w] drain: pushing back 0x3d7d62f1200
[w] drain: recheck gate=0
[w] drain: took head=0x3d7d62f1200
[w] drain: readers_active=0
[w] free_retired 0x3d7d62f1200

The committed test cannot force that ordering, so it runs the shape (a
clear() against continuous lock-free reads, then teardown with no further
operation) 50 times over.

Tests, CPython 3.14.7 unless noted, one venv and one tree per leg:

free-threaded, MULTIDICT_DEBUG_BUILD=1   2614 passed, 125 skipped
GIL                                      2626 passed, 113 skipped
GIL, CPython 3.10.17                     2626 passed, 113 skipped
MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions
                                         1266 passed, 17 skipped
MULTIDICT_TSAN_BUILD=1, TSan CPython 3.14.7t, retirement and clear tests
                                         13 passed, 0 warnings

Lint: pre-commit run --from-ref 6c1c9a8 --to-ref HEAD, 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: every one of the 26 cells within 0.14%, and clear,
copy, ctor_items, iter_items, getall and popitem exactly flat, so
docs/benchmark.rst needs no refresh. tools/codegen_diff.py --ref 6c1c9a8
from a fresh worktree reports 0 of 203 functions changed with the GIL enabled
and 14 of 206 free-threaded, of which 13 are .cold partitions that moved
with unchanged instruction counts and call targets; the fourteenth is
_md_drain_retired_slow() itself, at 158 instructions before and after.

Worth knowing for anyone measuring this: the first shape tried here split the
function in two, an _md_drain_retired_attempt() returning whether it pushed
back plus a while loop over it. That is the same fix, but it moved GCC's
inlining enough to cost iter_items 8% (and to win 4 Ir per entry on
clear, ctor_items and copy), reproducibly, across 60 changed functions.
The backward jump inside the one function avoids all of it. Also note
tools/codegen_diff.py must be run from a tree with no build/ directory:
its own in-place build is otherwise stale, and it will report dozens of
changed functions for source that is byte-identical to the ref.

On the free-threaded build, a drain that reads the active-readers gate as
nonzero pushes the tables it holds back onto md->retired and leaves them
to the reader the gate showed. That reader can have run its own drain
already, between the exchange and the push-back, and found the list
empty, in which case nothing is left to free them: they sit there until
the multidict is next used, and if it is dropped instead, the references
its entries own are never released.

Rereading the gate after the push-back separates that from the case the
push-back is for. Nonzero means the reader it sees decrements after the
read, so after the push-back, and its own drain observes the tables;
zero means nothing else will, and another pass is what frees them. The
emitted code is unchanged on builds with the GIL enabled, and
_md_drain_retired_slow() itself keeps its instruction count.
@asvetlov
asvetlov marked this pull request as ready for review September 24, 2026 11:21
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 24, 2026 11:21
@codspeed

codspeed Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:claude/drain-retired-pushback-recheck (119fe31) with master (ae427c6)

Open in CodSpeed

Same fix as on the branch for aio-libs#1562, where review pointed it out: an
exception in the reader before it signalled readiness blocked the test in
an unbounded wait, and one out of clear() skipped the stop signal and the
join, leaving a non-daemon thread reading a multidict the test had
finished with.
@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

No blocking finding is outstanding. The existing test-coverage concern is non-blocking.

Reviews (2) · Last reviewed commit: "Merge remote-tracking branch 'upstream/m..."

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

This comment has been minimized.

…red-pushback-recheck

# Conflicts:
#	tests/test_multidict.py
@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 (f08f768) to head (119fe31).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1565   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           41        41           
  Lines         7084      7148   +64     
  Branches       615       625   +10     
=========================================
+ Hits          7084      7148   +64     
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 62df00f into aio-libs:master Sep 24, 2026
61 of 62 checks passed
@asvetlov
asvetlov deleted the claude/drain-retired-pushback-recheck branch September 24, 2026 12:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant