Skip to content

Drain the retired hash tables when a cleared multidict is deallocated - #1562

Merged
asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:claude/multidict-issue-1555-b6bbcd
Sep 24, 2026
Merged

asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:claude/multidict-issue-1555-b6bbcd

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

On the free-threaded build, md_clear() returned early once md->keys was
&empty_htkeys, so nothing on that path drained md->retired. The drain
leaves a table on that list whenever it finds a lock-free reader in flight,
for the next drain to free, and the only drain sites are reader exits and
retirements; a multidict dropped right after a clear() that left its table
there gets neither, so the table, and the references its entries still owned,
were never freed. Draining in that early return makes the object's own
teardown the last drain, and that drain does free the table: a lock-free
reader reaches a multidict through a live reference, so its count is zero by
the time the refcount is.

Getting a table onto that list and leaving it there needs the coarse
active-readers gate to flip between the two times _md_drain_retired_slow()
reads it. The first read sees zero and takes the list, a reader then enters,
the second read sees it, so the table goes to the push-back at the end of the
function, and that reader's own exit drain runs before the push-back lands and
finds the list empty. Nothing is left to drain, and since #1542 the shell the
object is recycled into is memset, so the next owner cannot pick the table up
either. Forcing that ordering takes an artificially widened window; the recipe
and the resulting trace are in the footer.

Are there changes in behavior for the user?

No, beyond the leak going away. The fix is C-extension only, and only the
free-threaded build has a retirement scheme; builds with the GIL enabled emit
byte-identical code.

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

No. It is one load on a path that is not hot, and no benchmarked operation
moves.

Related issue number

Fixes #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 of the bug. Three sleeps compiled in behind -DMULTIDICT_WIDEN_DRAIN:
300ms at the end of _md_reader_enter(), 100ms in
_md_drain_retired_slow() between the exchange and the readers_active
read, and 300ms before the push-back CAS. The driver builds a multidict
holding one weakref'd value, starts a thread that waits 50ms and then does a
single d.get(), calls clear(), joins, drops the multidict and collects.

Base (f28b2c0), leaked 3/3 attempts:

[w] drain: took head=0x4ec8a2f1200
[w] reader enter keys=<&empty_htkeys>
[w] drain: readers_active=1
[w] reader exit prev_active=1
[w] drain: pushing back 0x4ec8a2f1200

With this branch, leaked 0/3; the second took head is the teardown drain:

[w] drain: took head=0x4d2a42f1200
[w] reader enter keys=<&empty_htkeys>
[w] drain: readers_active=1
[w] reader exit prev_active=1
[w] drain: pushing back 0x4d2a42f1200
[w] drain: took head=0x4d2a42f1200
[w] free_retired 0x4d2a42f1200

The committed test cannot force that ordering, so it runs the shape (a
clear() racing reader traffic, then teardown with nothing left to drain)
50 times over and asserts nothing the cleared table held survives. What it
does cover deterministically is that the added drain runs against a table a
reader may still be walking, rather than only against an empty list.

Tests, all on 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, -k "thread_safety or
drain or retired or clear"                 153 passed, 13 skipped

That TSan run reports 57 warnings and exits 66. Every one of them is
CPython's own faulthandler racing the threads whose stacks it is dumping
(dump_traceback, dump_frame, _PyFrame_SafeGetCode,
_PyFrame_SafeGetLasti), after pytest-timeout fires on
test_pure_python_view_set_ops_thread_safety, which takes 444s under TSan.
No multidict frame appears in any racing access; multidict only shows up
inside the dumped Python tracebacks. Run on their own, the three
retirement tests report zero warnings.

Two things this PR does not fix, both pre-existing and worth their own
issues:

  • The push-back at the end of _md_drain_retired_slow() does not re-read
    the active-readers count afterwards, so a table can sit on the list until
    the object's next operation even while no reader is left. Harmless in
    itself now that teardown drains, but it is the window this leak was
    reached through.
  • md_traverse() visits md->keys only, so the references a retired table
    holds are invisible to the GC. That under-reports, which is the safe
    direction, but a reference cycle running through a value stranded on
    md->retired cannot be collected.

Lint: pre-commit run --from-ref f28b2c0 --to-ref HEAD, all hooks passed.
Docs: make doc-spelling, build succeeded.

Performance, benchmarks/callgrind_driver.py --impl multidict_c --include-multidict-only, free-threaded, base and branch built in the same
tree and venv so only the source differs: every one of the 26 cells within
0.10%, ctor_empty and clear exactly flat. docs/benchmark.rst therefore
needs no refresh. tools/codegen_diff.py --ref f28b2c0 reports 0 of 203
functions changed on the GIL build. It reports 52 of 206 on the
free-threaded build, from md_clear() no longer being split into a
.part.0; the call targets and instruction counts of the hot paths are
unchanged and the measurements above cover them. Both numbers need a fresh
worktree: run from a tree with a populated build/, the tool's own
in-place build is stale and its report is meaningless (a control with
identical source reported the same 52).

An alternative that keeps md_clear() byte-identical, putting the drain at
the multidict_tp_dealloc() call site instead, measured 3 Ir worse on
ctor_empty, ctor_small and copy_small and perturbed 74 functions
rather than 52, so it is not what landed.

On the free-threaded build, md_clear() returned early once md->keys was
&empty_htkeys, and deallocation runs no drain of its own. A clear() whose
drain found a lock-free reader in flight leaves its table on md->retired
for a later drain to free, so a multidict dropped right after such a
clear reached tp_dealloc with that table, and the entry references it
still owned, never freed.

Draining in that early return closes it: the object's own teardown is
then the last drain, and a lock-free reader reaches a multidict through a
live reference, so the reader count is zero by the time the refcount is,
and the drain does free the table.
@asvetlov
asvetlov marked this pull request as ready for review September 24, 2026 10:44
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 24, 2026 10:44
@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

No blocking issue remains. The outstanding test-coverage concern is non-blocking.

Reviews (2) · Last reviewed commit: "Let the regression test fail rather than..."

Comment thread tests/test_multidict.py Resolved
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/multidict-issue-1555-b6bbcd (d7b66c8) with master (6c1c9a8)

Open in CodSpeed

Review of aio-libs#1562 pointed out that the reader thread was left to chance: an
exception 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. The
readiness wait is now bounded, the stop signal happens whatever clear()
does, and the reader runs on an executor whose result is checked, so a
failure inside it reaches the report.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 24, 2026
asvetlov added a commit to asvetlov/multidict that referenced this pull request Sep 24, 2026
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.
@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 (f28b2c0) to head (d7b66c8).
⚠️ Report is 4 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1562   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           41        41           
  Lines         7074      7106   +32     
  Branches       615       620    +5     
=========================================
+ Hits          7074      7106   +32     
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 ae427c6 into aio-libs:master Sep 24, 2026
62 checks passed
@asvetlov
asvetlov deleted the claude/multidict-issue-1555-b6bbcd branch September 24, 2026 11:41
asvetlov added a commit that referenced this pull request Sep 24, 2026
<!-- Thank you for your contribution! -->

## 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

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes N/A, no user-facing API changed
- [x] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` N/A, this repo has no such file
- [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; to be reviewed by @asvetlov
before
it leaves draft.

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

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.

</details>
asvetlov added a commit that referenced this pull request Sep 24, 2026
<!-- Thank you for your contribution! -->

## 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

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes N/A, no user-facing API changed
- [x] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` N/A, this repo has no such file
- [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; to be reviewed by @asvetlov
before
it leaves draft.

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

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.

</details>
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.

Tables left on md->retired are never freed if the object is deallocated after an explicit clear()

1 participant