Skip to content

Drain md->retired from reader exit, not just resize/clear - #1445

Merged
asvetlov merged 5 commits into
aio-libs:masterfrom
asvetlov:fix-1443-retired-table-drain
Sep 12, 2026
Merged

asvetlov merged 5 commits into
aio-libs:masterfrom
asvetlov:fix-1443-retired-table-drain

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

On the free-threaded build, a resize/clear() retires its old hash table onto md->retired instead of freeing it immediately when a lock-free reader might still be using it, and only _md_retire() ever drained that list, as a side effect of a later resize/clear() checking whether the active-readers gate had reached 0. _md_reader_exit() never triggered a drain itself, so under read traffic frequent enough that the gate rarely lands on exactly 0 at the moment some other resize/clear() happens to check it, a retired table could sit on md->retired for the rest of the object's life: an unbounded memory leak under sustained concurrent read and write load.

_md_reader_exit() now drains md->retired itself when its own decrement brings the gate to 0. That makes md->retired a genuine lock-free stack (pushes from _md_retire() and pop-alls from _md_drain_retired() now run concurrently with each other, not just with readers walking a table), so pushing needs a CAS loop instead of a plain link, and _md_retire() has to push before checking whether the gate is already at 0 rather than after; checking first left a window where a concurrent reader's own check could run in between and find nothing yet to reclaim.

This is a C-extension-only, free-threaded-build-only concern; the pure-Python implementation has no retirement scheme to regress.

Are there changes in behavior for the user?

No observable behavior change; this only affects internal memory reclamation timing on the free-threaded build.

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

No. The change is localized to _md_reader_exit()/_md_retire()/_md_drain_retired() in hashtable.h plus two small pointer-atomic helpers in atomic_helpers.h (GCC/Clang, C11, and MSVC backends), with a dedicated regression test.

Related issue number

Fixes #1443

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes
  • N/A If you provide code modification, please add yourself to CONTRIBUTORS.txt
  • 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 Code (Sonnet 5); reviewed by asvetlov.

Agent run details (optional, for reviewers)

Tests: full suite passed on the free-threaded debug build (MULTIDICT_DEBUG_BUILD=1, Python 3.14.7 free-threaded, python -X gil=0 -m pytest -q), the free-threaded release build, the default GIL-enabled C extension build, and the pure-Python build (MULTIDICT_NO_EXTENSIONS=1).

New test (test_reader_exit_drains_retired_thread_safety) was verified to fail reliably (10/10 runs) against the pre-fix code and pass reliably (20/20 runs) against the fix.

Lint: pre-commit run (ruff, clang-format, mypy) passed on all changed files. make doc-spelling passed.

Only _md_retire() ever drained md->retired, as a side effect of a
later resize/clear checking whether the active-readers gate had
reached 0. _md_reader_exit() never triggered a drain itself, so under
read traffic frequent enough that the gate rarely lands on exactly 0
at the moment some other resize/clear happens to check it, a retired
table could sit there for the rest of the object's life: an unbounded
memory leak under sustained concurrent read+write load.

_md_reader_exit() now drains md->retired itself when its own decrement
brings the gate to 0. That makes md->retired a genuine lock-free stack
(pushes from _md_retire(), pop-alls from _md_drain_retired(), now
running concurrently with each other), so pushing needs a CAS loop
instead of a plain link, and _md_retire() has to push before checking
whether the gate is already at 0 rather than after, closing a window
where a concurrent reader's own check could otherwise run in between
and find nothing yet to reclaim.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 12, 2026
@asvetlov
asvetlov marked this pull request as ready for review September 12, 2026 06:59
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 12, 2026 06:59
@codspeed

codspeed Bot commented Sep 12, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 12.49%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 3 improved benchmarks
✅ 245 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_cimultidict_getall_istr_hit[c] 37 ms 32.4 ms +14.07%
⚡ test_multidict_getall_str_hit[cs-c] 37.7 ms 33.7 ms +11.93%
⚡ test_multidict_getall_str_hit[ci-c] 39 ms 35 ms +11.48%

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing asvetlov:fix-1443-retired-table-drain (ad18718) with master (e1a6df5)

Open in CodSpeed

The lock-free stack behavior these described is already covered by
the top-of-file design comment above _md_reader_enter().
@greptile-apps

greptile-apps Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge.

No outstanding issues remain. The earlier regression-coverage concern is addressed because the test now waits for every reader to complete warm-up lookups before clearing the mapping. greptile-apps[bot] resolved the thread without explanation.

Reviews (3): Last reviewed commit: "Drop redundant weak-CAS comments in atom..." | Re-trigger Greptile

Comment thread tests/test_multidict.py Resolved
@codecov

codecov Bot commented Sep 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (e1a6df5) to head (ad18718).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1445   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           29        29           
  Lines         4214      4241   +27     
  Branches       318       323    +5     
=========================================
+ Hits          4214      4241   +27     
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.

Addressed Greptile review feedback on PR aio-libs#1445: a plain
ThreadPoolExecutor.submit() only queues the reader call, it does not
establish that the thread has actually started by the time clear()
runs, so a valid schedule could let clear() land before any reader is
live and take the always-safe immediate-free path without exercising
retirement at all.

Each reader now signals a per-thread Event after a small warm-up batch
of reads and keeps running, unblocked, straight into its main loop;
clear() only proceeds once every reader has signaled. Also bumped from
8 to 16 concurrent readers, which empirically raises the fraction of
runs that land clear() while a reader is genuinely inside the lock-free
section from single digits to consistently over 90% against the
pre-fix code, while keeping the test's cost comparable to its
siblings.
@asvetlov

Copy link
Copy Markdown
Member Author

Addressed the reader-synchronization finding: the test now has each reader signal a per-thread threading.Event after a warm-up batch of reads and then keep running, unblocked, straight into its main loop. clear() only proceeds once every reader has signaled, so it can no longer land before any reader has actually started. Also raised the reader count from 8 to 16, which empirically brings the fraction of runs that land clear() while a reader is genuinely inside the lock-free section to consistently over 90% against the pre-fix code (40/40 clean runs against the fix, 0 false failures).

The weak-vs-strong CAS retry contract is standard C11/GCC-builtin
behavior and doesn't need restating at each of the three backend
definitions.
@asvetlov
asvetlov merged commit 9024ac2 into aio-libs:master Sep 12, 2026
56 of 57 checks passed
@asvetlov
asvetlov deleted the fix-1443-retired-table-drain branch September 12, 2026 15:52
asvetlov added a commit that referenced this pull request Sep 13, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Adds per-instance locking to the pure-Python `MultiDict`/`CIMultiDict`
fallback (`multidict/_multidict_py.py`) so it gives the same
crash-free, corruption-free guarantee as the C extension under a
free-threaded (no-GIL) build. Every method that touches an instance's
hash table takes that instance's own `RLock` (created once in
`__new__`, reused across a later re-init); two-object operations
(`update()`, `extend()`, `merge()`, `__eq__()`, copy construction) lock
both objects together in a fixed, deadlock-safe order; view iterators
take the lock per step rather than for the whole iteration, so a
concurrent mutation between steps surfaces as the same "changed during
iteration" `RuntimeError` a single-threaded caller already gets today
instead of a deadlock; and the version counter shared by every
instance gets its own lock. On a regular GIL-enabled interpreter the
locked methods are the exact same function objects as before this
change -- no wrapper, no lock, no measurable overhead.

## Are there changes in behavior for the user?

Yes, but only on a free-threaded build: concurrent use of a
pure-Python `MultiDict`/`CIMultiDict` from multiple threads is now
safe against crashes and data corruption, matching the C extension.
On a regular (GIL-enabled) build there is no behavior or performance
change.

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

No. The change is self-contained to `_multidict_py.py`, gated entirely
behind a runtime free-threading check computed once at import, and
mirrors the locking approach already reviewed and merged for the C
extension (#1438, #1441, #1445, #1446). The C extension itself is
unaffected; this only touches the pure-Python fallback.

## Related issue number

N/A -- no linked issue. Continues the free-threading hardening already
done for the C extension.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` (N/A, this repo has no `CONTRIBUTORS.txt`)
- [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`

<details>
<summary>Agent run details (optional, for reviewers)</summary>

Tests: `pytest -q` passes on both backends; the pure-Python leg was
additionally run under a free-threaded interpreter (CPython 3.13.7t,
`PYTHON_GIL=0`) multiple times with coverage active, plus a standalone
stress script driving 16 threads through thousands of concurrent
mutations, with no crashes or corruption.

Lint: `ruff check`, `ruff format --check`, and `mypy` (3.11 and 3.13,
via `pre-commit`) all pass on the changed files.

Docs: `make doc-spelling` passes.

Note: while calibrating test load, a pre-existing, unrelated race in
`update()`/`extend()`/`merge()`/`clear()` was found -- reachable even
on a plain GIL-enabled interpreter under heavy concurrent use (pure
Python bytecode isn't atomic even under the GIL). Confirmed present on
unmodified `master` too, so it predates and is out of scope for this
PR; a follow-up is planned separately. Two of the new tests that would
otherwise be flaky against it are skipped on non-free-threaded builds,
with the reason stated inline.

</details>

Drafted with Claude Code; reviewed by asvetlov.
asvetlov added a commit that referenced this pull request Sep 14, 2026
## What do these changes do?

Adds two race tests for the C extension on free-threaded builds: one
iterates a multidict while other threads mutate it, the other extends
from a source that other threads are resizing.

#1431 through #1446 made these paths safe. Against the tree before that
series both tests segfault on every run; against current master they
pass. There is no other threaded test in the suite, so this is what
would turn a regression into a red free-threaded CI leg instead of
silence.

The C changes this PR originally carried are superseded by that series
and have been dropped.

## Are there changes in behavior for the user?

No.

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

No. One test file and a `contrib` fragment; the tests are
`c_extension`-marked and take about a quarter of a second.

## Related issue number

Follows #1431, #1433, #1438, #1441, #1445, #1446.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [ ] Documentation reflects the changes -- N/A
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` -- N/A
- [x] Add a new news fragment into the `CHANGES/` folder

---------

Co-authored-by: Andrew Svetlov <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[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.

Free-threaded build: retired hash tables (md->retired) can accumulate unboundedly under sustained concurrent reads

1 participant