Repository navigation
Conversation
The single-key methods took md's critical section in _multidict.c and capsule.h and only then converted the key to its identity and hashed it. That work reads the key plus md->is_ci and md->state, all fixed for the object's lifetime, so it never needed the lock. On a free-threaded build it can also run Python (a str subclass's lower(), a finalizer), which hits a safepoint and suspends the section anyway, so holding it across that bought nothing. md_add(), md_del(), md_set_default(), md_pop_one(), md_replace(), md_get_all() and md_pop_all() now compute the pair first and take the critical section themselves around a _locked helper, the shape md_get_one() and md_contains() already use. md_del() reports whether it removed anything and raises the KeyError afterwards, like md_pop_one() does. md_replace() no longer takes a reflist_t from its caller: that parameter only existed because the caller owned the section, and keeping the accumulator local drops it from both call sites. md_walk() splits into md_walk_with_hash() plus a wrapper, so getall() and MultiDict_ForEach() hoist the hash as well. The set operators in views.h build an identity per item inside a walk of their own and keep calling md_walk(). md_calc_identity_hash() is always_inline: left to itself GCC emits it out of line, and the call costs more than the helper saves. Callgrind instruction counts, PYTHONHASHSEED=0, 3.13 GIL build, over MultiDict with str keys and CIMultiDict with str and istr keys: setitem on a new key -1.0 to -1.4%, delitem -1.4 to -1.9%, setdefault -0.6 to -0.7%, getall -0.3 to -0.7%, setitem over an existing key -0.4 to -0.6%, pop -0.1 to -0.5%, add and popall unchanged.
d0aa320 to
d2460ea
Compare
Merging this PR will improve performance by 11.87%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ⚡ | test_create_multidict_with_dict[ci-c] |
99.4 µs | 88.8 µs | +11.87% |
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:claude/api-methods-critical-section-538fd1 (d2460ea) with master (fdceefa)
|
Comments Outside DiffThese findings sit on lines the diff does not cover, so they could not be posted inline. Each one leaves this list once its file changes.
|
<!-- Thank you for your contribution! --> ## 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 - [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 - [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` 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. <details> <summary>Agent run details (optional, for reviewers)</summary> 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. </details>
What do these changes do?
The single-key methods took
md's critical section in_multidict.candcapsule.h, and only then turned the key into its identity and hashed it.That work reads the key plus
md->is_ciandmd->state, both fixed for theobject's lifetime, so it never needed the lock; on a free-threaded build it
can also run Python (a
strsubclass'slower(), a finalizer), which hits asafepoint and suspends the section anyway.
md_add(),md_del(),md_set_default(),md_pop_one(),md_replace(),md_get_all()andmd_pop_all()now compute the pair first and take thesection themselves around a
_lockedhelper, the shapemd_get_one()andmd_contains()already use.md_replace()stops taking areflist_tfromits caller; that parameter only existed because the caller owned the section.
md_walk()splits intomd_walk_with_hash()plus a wrapper sogetall()andMultiDict_ForEach()hoist the hash too; the set operators inviews.hbuildan identity per item inside a walk of their own and keep calling
md_walk().The pure-Python backend is deliberately untouched. It holds a
threading.RLockover whole method bodies for a different reason, non-atomicbytecode on every build, and this is internal lock granularity with no
observable behaviour change, so there is nothing for dual-backend discipline
to mirror.
Are there changes in behavior for the user?
No.
Is it a substantial burden for the maintainers to support this?
No. It removes a
Py_BEGIN_CRITICAL_SECTIONfrom ten call sites and leavesthe write path shaped like the read path.
Related issue number
N/A
Checklist
CONTRIBUTORS.txt— N/A, no such file in this repoCHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtAgent run details (optional, for reviewers)
Tests, all on this branch rebased onto
3e5aa5b:MULTIDICT_NO_EXTENSIONS=1 ... --no-c-extensionspytest -m hypothesisMULTIDICT_DEBUG_BUILD=1, free-threadedMULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1, GIL 3.13.2MULTIDICT_TSAN_BUILD=1, TSan CPython 3.14.7t3e5aa5bLint:
pre-commit runon the touched files passes;make doc-spellingpasses.Performance,
valgrind --tool=callgrindwithPYTHONHASHSEED=0on a 3.13.2GIL build, comparing
3e5aa5bagainst this branch. Each figure is the rangeover three key shapes:
MultiDictwithstrkeys,CIMultiDictwithstrkeys,
CIMultiDictwithistrkeys. Instructions per operation, so lower isbetter.
__delitem____setitem__, new keysetdefaultgetall__setitem__, existing keypopaddpopallTwo results worth flagging, since neither was obvious:
md_calc_identity_hash()carries__attribute__((always_inline))becausewithout it GCC emits it out of line and
addregresses 0.9%. With it,addis exactly flat.
md_replace()owning itsreflist_trather than taking one is what removesthe
__setitem__cost. Keeping the caller's parameter left theexisting-key case at +1.35%.
Since
always_inlineinidentity.hhas moved the inliner's budget aroundbefore, the paths this change does not touch were measured the same way:
__getitem__,__contains__,getone(), construction from a dict and froman item list,
copy(),update()and iteratingitems(). All twenty-fourfigures land within 0.06% of
3e5aa5b, so the budget stayed put this time.tools/codegen_diff.py --ref upstream/masterreports 91 of 191 functionschanged on the GIL build and 95 of 196 free-threaded, which is expected here:
md_del(),md_set_default()and_md_add_with_hash()are no longer emittedstandalone and
md_replace()now is, so inlining is redistributed across thecallers. Compiled
.textfor_multidict.cgrows 59 bytes, 117328 to 117387.The TSan run reports the same two failures as
3e5aa5bdoes,test_pure_python_reciprocal_view_ops_no_deadlockandtest_pure_python_reciprocal_raw_iterator_ops_no_deadlock. Both are a20-second
Thread.jointimeout in pure-Python code this branch does nottouch, which TSan's slowdown cannot meet. Of the races TSan reports, 21 on
3e5aa5band 22 here, every one is inside CPython'sfaulthandlerwalkinganother thread's frames while those timeouts fire; none has a multidict frame.
No contended multi-threaded benchmark was run; the repo has none, and the
single-threaded figures above cannot show the reduced lock hold time this is
actually for.
Drafted with Claude Opus 5 in Claude Code. Left as a draft for @asvetlov to
review before it goes out.