Skip to content

Skip the retired-table drain when nothing is retired - #1546

Merged
asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:claude/drain-retired-fast-path
Sep 24, 2026
Merged

asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:claude/drain-retired-fast-path

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

On the free-threaded build every lock-free reader that brings
num_active_readers back to zero calls _md_drain_retired(), which
without a second thread is every single lookup. The first thing that
function does is a sequentially consistent exchange on md->retired,
and that list is empty almost every time.

The drain now checks the list with a load first and the rest of it sits
behind a call, so a lookup with nothing to free pays one load instead of
an out-of-line call and a read-modify-write. The load stays sequentially
consistent: a writer that pushes and then reads num_active_readers as
nonzero leaves the table for whoever brings that count to zero, so the
reader doing so must not be able to miss the push, and only a seq_cst
load is ordered against the push in the single total order. On x86-64
that is the same plain mov, so it is free; the cost being skipped is
the exchange.

Instructions per operation, CPython 3.14.7 free-threaded:

Operation Before After
key in md 283 253 (-10.6%)
md[key] 317 292 (-7.9%)
md.get(key), miss 499 474 (-5.0%)

CIMultiDict moves -8.1%, -6.2% and -3.3% on the same three. No other
benchmarked operation changes beyond the measurement's noise floor.
Wall clock improves more than the instruction counts do, because
Callgrind cannot see the removed lock-prefixed exchange. Measured back
to back against a build of the merge base, two passes each: key in md
35.5/35.3 ns before against 29.0/28.7 after, md[key] 37.1/36.9 against
30.9/30.6, so about -18%. CIMultiDict moves within the noise of this
machine on wall clock and I would not claim a figure for it.

This is free-threaded only. atomic_helpers.h is entirely inside
#ifdef Py_GIL_DISABLED, and tools/codegen_diff.py reports 0 of 190 functions differ for the GIL build. It is also C-extension only: the
pure-Python backend has no table retirement to skip.

The second commit regenerates docs/benchmark.rst. Those numbers were
last collected on the branch of #1532, so the refresh also absorbs
#1533 through #1538; the free-threaded read rows are the part this
change accounts for.

Are there changes in behavior for the user?

No, other than free-threaded reads being faster.

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

No. The retirement protocol is unchanged; one branch is added in front
of it, and the reasoning for why the window is safe is in the comment
above the gate.

Related issue number

None; found while comparing multidict against dict on the
operations both have.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt — N/A
  • 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

On unit tests: no new test is added because the existing
test_drain_retired_defers_busy_table_thread_safety() and
test_setitem_update_thread_safety() already drive this path from both
sides, forcing a retirement on nearly every insert while lock-free
readers run; they exercise the gate taken and not taken.

Drafted with Claude Opus 5 in Claude Code; reviewed by @asvetlov.

Agent run details (optional, for reviewers)

Three variants were measured before this one was picked. Marking the
slow path COLD rather than NOINLINE bought the same read win but
cost d.clear() 12% and d.copy() 4%: cold implies optimize-for-size
and _md_free_retired()'s per-entry decref loop lives down there.
Adding the gate without moving the body out of line recovered only 1-2%,
which says the out-of-line call, not the exchange, was most of the cost.

Builds: one venv and one tree copy per leg, rebased on 9f28f61.

tools/codegen_diff.py --ref 9f28f61
  python3.14    0 of 190 functions differ
  python3.14t  35 of 196 functions differ (_md_drain_retired -> _md_drain_retired_slow
               and its former inline sites)

pytest, 3.14.7 GIL           2353 passed, 107 skipped
pytest, 3.14.7t              2342 passed, 118 skipped
pytest, pure Python          1138 passed, 11 skipped, 1141 deselected
pytest, 3.10.17 (cibw marks) 2260 passed, 21 skipped, 179 deselected
TSan, 3.14.7t-tsan           2331 passed, 0 ThreadSanitizer warnings, 8m30s
ASan+UBSan, 3.14.7 debug     2342 passed, 107 skipped
make doc-spelling            build succeeded
pre-commit (clang-format)    passed

Benchmarks are benchmarks/callgrind_driver.py, bracketed, drift_ir 0,
valgrind 3.26.0, Intel Core Ultra 7 155H.

On the free-threaded build every lock-free reader that brings
num_active_readers back to zero calls _md_drain_retired(), which without
a second thread is every lookup. The first thing it does is a
sequentially consistent exchange on md->retired, and that list is empty
almost every time.

Check the list with a relaxed load first and move the rest of the drain
behind a call, so a lookup that has nothing to free pays one load rather
than an out-of-line call and a read-modify-write. Nothing is stranded by
the narrower window: a table retired after the load reads the same as
one retired just after the exchange, and _md_retire() drains again once
its push is visible.

Instruction counts on CPython 3.14, free-threaded: `key in md` -10.6%,
`md[key]` -7.9%, a missing `md.get(key)` -5.0%, and -8.1%, -6.2% and
-3.3% for the CIMultiDict equivalents. No other benchmarked operation
moves beyond the measurement's noise floor. The GIL build emits
byte-identical code, confirmed with tools/codegen_diff.py.
The numbers on this page were collected before the retired-table drain
change, and before aio-libs#1533 through aio-libs#1538 landed, so the refresh moves more
cells than that change alone touches; the free-threaded read rows are
the ones it accounts for.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 23, 2026
@codspeed

codspeed Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:claude/drain-retired-fast-path (6862de9) with master (3336132)

Open in CodSpeed

@codecov

codecov Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (9f28f61) to head (6862de9).
⚠️ Report is 7 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##            master     #1546    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           40        41     +1     
  Lines         6852      6974   +122     
  Branches       596       606    +10     
==========================================
+ Hits          6852      6974   +122     
Flag Coverage Δ
CI-GHA 100.00% <ø> (ø)
pytest 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 marked this pull request as ready for review September 24, 2026 06:30
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 24, 2026 06:30
@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

No outstanding findings block merging.

Reviews (2) · Last reviewed commit: "Keep the drain gate's load sequentially ..."

Comment thread multidict/_multilib/hashtable.h Resolved
Comment thread multidict/_multilib/hashtable.h Resolved
Review catch. A relaxed load there can miss a push: a writer that retires
a table and then reads num_active_readers as nonzero leaves the table for
whoever brings that count to zero, and the reader doing so must observe
the push. Both the push and that read are seq_cst, so the push precedes
the writer's read, which precedes the reader's decrement, which precedes
the gate's load in the single total order; a relaxed load carries no such
guarantee and could strand the table until md's next operation.

A sequentially consistent load closes that and costs nothing measurable:
on x86-64 it is the same plain mov, and the three read benchmarks are
bit-identical to the relaxed version (getitem 292, contains 253, get miss
474). The expensive part this skips was always the exchange, not the load.

atomic_load_ptr() is already seq_cst, so the relaxed pointer helper the
first commit added is no longer needed and goes away again.
@asvetlov
asvetlov merged commit a249b3c into aio-libs:master Sep 24, 2026
62 checks passed
@asvetlov
asvetlov deleted the claude/drain-retired-fast-path branch September 24, 2026 07:43
asvetlov added a commit to asvetlov/multidict that referenced this pull request Sep 24, 2026
Takes master's copies of hashtable.h, atomic_helpers.h and the 1546
fragment: aio-libs#1546 landed there, so the copies this branch carried are
redundant and master's also has aio-libs#1539, aio-libs#1549 and aio-libs#1550 on top.
asvetlov added a commit that referenced this pull request Sep 24, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

The `istr` section already tells people to build their keys once and
reuse them, but not what that buys. This adds the instruction counts,
for both builds, next to the plain `str` equivalents, and points out
that a key which is not already lower case saves more still, since it
has to be copied into a lower-cased string whose hash is not cached.

Numbers come from `benchmarks/callgrind_driver.py
--include-multidict-only`,
the same harness and machine as the tables in `docs/benchmark.rst`.

#1546 has landed, so this is down to its own two files. The figures were
re-measured against master afterwards, since #1539, #1549 and #1550 also
moved them; `d.add()` shifted most, 876 to 765 on the GIL build.

## Are there changes in behavior for the user?

No, documentation only.

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

No, though the table joins `docs/benchmark.rst` in needing a refresh
when the figures move.

## Related issue number

None.

## Checklist

- [x] I think the code is well written — N/A, documentation only
- [ ] Unit tests for the changes exist — N/A
- [x] Documentation reflects the changes
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` — N/A
- [x] Add a new news fragment into the `CHANGES/` folder
- [x] `make doc-spelling` passes and any new technical words are added
to `docs/spelling_wordlist.txt`

Drafted with Claude Opus 5 in Claude Code; reviewed by @asvetlov.

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
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