Skip to content

Keep the module alive while a multidict can still read its state - #1563

Merged
asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:claude/multidict-ci-failure-901fcf
Sep 24, 2026
Merged

asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:claude/multidict-ci-failure-901fcf

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

A multidict caches the module state as a bare mod_state*, and the only
thing keeping the module alive was the heap type's own reference.
CPython's type_clear() does Py_CLEAR(ht_module), so a collection that
clears a multidict type before the multidicts themselves lets
module_dealloc() free the state while md_clear() is still about to
read it. Each multidict now holds a strong reference to its module,
released after md_clear(), and module_clear() closes the pools so no
shell is parked once the types that a drain would need are gone.

C extension only; the pure-Python backend has no module state to outlive.

Found while looking at an intermittent Windows wheel-test crash: the
suite passes in full, then the process exits with 3221225477
(0xC0000005), for example in
this cp310-win_amd64 run.
Reproduced under AddressSanitizer on CPython 3.10 as a heap-use-after-free
read in next_version(), on memory freed by module_dealloc().

Are there changes in behavior for the user?

No, other than the crash no longer happening.

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

No. It is one field and a reference, on paths that already existed.

Related issue number

None; found from a CI failure.

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

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

Agent run details (optional, for reviewers)

Reproducer, against the unfixed extension built with
MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1:

ERROR: AddressSanitizer: heap-use-after-free
READ of size 8 at 0x7ad819e26108 thread T0
    #0 next_version multidict/_multilib/freethreading.h:205
    #1 md_clear     multidict/_multilib/hashtable.h:2000
    #2 multidict_tp_clear multidict/_multidict.c:675
    #3 delete_garbage Modules/gcmodule.c:1017
freed by thread T0 here:
    #1 module_dealloc Objects/moduleobject.c:689

test_multidict_torn_down_with_its_module is that reproducer; it aborts
under ASan without the fix and passes with it.
test_multidict_refers_to_its_module fails on any build without it.

Tests, all on this branch:

Leg Result
3.10, C extension 2627 passed
3.14.7t, free-threaded 2615 passed
pure Python, isolated tree and venv 1258 passed
3.10 ASan and UBSan, pools on 2615 passed, no reports
3.10 ASan and UBSan, MULTIDICT_NO_FREELIST=1 2615 passed, no reports
pre-commit run, make doc-spelling pass

Not run: the hypothesis suite and TSan.

Benchmarks, callgrind, PYTHONHASHSEED=0, CPython 3.14.7 GIL and
free-threaded, against 7b84e1b:

Cell GIL Free-threaded
cls() / MultiDict +3.2% (590 to 609) +3.7% (822 to 852)
cls() / CIMultiDict +2.6% (730 to 749) +3.3% (911 to 941)
d.copy(), 20 items +1.0% +1.1%
everything else under 0.5% under 0.5%

Writing Py_NewRef(mod) inline in the constructors instead cost +420 Ir
per 200-item build on the free-threaded leg (+4.3% clear, +1.4%
copy), entirely through inlining churn rather than the refcount: a
build with the struct field and no refcounting cost +7 Ir. Hence the
NOINLINE md_set_module().

A multidict caches the module state as a bare pointer, and the only
thing keeping the module alive was the heap type's own reference.
type_clear() drops that reference, so a collection that clears a
multidict type before the multidicts themselves lets module_dealloc()
free the state while md_clear() is still about to read it; that showed
up as an access violation at interpreter exit on Windows.

Each multidict now holds a strong reference to its module, released
after md_clear(). module_clear() also closes the pools, so no shell is
parked once the types it would need to free it are gone.
Keeping a module reference on every multidict costs an allocation-bound
operation a refcount pair: ``cls()`` moves by about 3% and the 20-item
``cls(items)`` and ``d.copy()`` rows by about 1%, on both builds.

The rest of the table is re-measured rather than changed; rows the
commit cannot touch, including the ``dict`` column, differ by under
half a percent because the interpreter builds behind the previous
numbers were not byte-identical to these.
@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 10:59
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 24, 2026 10:59
@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-ci-failure-901fcf (90c4b71) with master (6c1c9a8)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

No established issue blocks merging.

What we checked:

  • Prepared the Python lifecycle probe to validate C API construction, subclass copying, and use-after module removal. T-Rex
  • Tried to run the lifecycle probe in two environments; both attempts returned Not connected before the process started and produced no output. T-Rex
  • Executed the module-cycle GC reproduction script against the built C extension; after three forced collections per graph, all module and dict weak references were dead, gc.garbage was empty, and the process exited with code 0. T-Rex

Reviews (1) · Last reviewed commit: "Name the news fragment after the pull re..."

@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 (7b84e1b) to head (90c4b71).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1563   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           41        41           
  Lines         7074      7084   +10     
  Branches       615       615           
=========================================
+ Hits          7074      7084   +10     
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 f08f768 into aio-libs:master Sep 24, 2026
61 of 62 checks passed
@asvetlov
asvetlov deleted the claude/multidict-ci-failure-901fcf branch September 24, 2026 11:39
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