Skip to content

Compute a key's identity outside the critical section - #1538

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:claude/api-methods-critical-section-538fd1
Sep 23, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:claude/api-methods-critical-section-538fd1

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

The single-key methods took md's critical section in _multidict.c and
capsule.h, and only then turned the key into its identity and hashed it.
That work reads the key plus md->is_ci and md->state, both 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.

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
section themselves around a _locked helper, the shape md_get_one() and
md_contains() already use. md_replace() stops taking a reflist_t from
its caller; that parameter only existed because the caller owned the section.
md_walk() splits into md_walk_with_hash() plus a wrapper so getall() and
MultiDict_ForEach() hoist the hash too; the set operators in views.h build
an 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.RLock over whole method bodies for a different reason, non-atomic
bytecode 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_SECTION from ten call sites and leaves
the write path shaped like the read path.

Related issue number

N/A

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes — N/A, no user-visible API change
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt — N/A, no such file in this repo
  • 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
Agent run details (optional, for reviewers)

Tests, all on this branch rebased onto 3e5aa5b:

Build Result
C extension, free-threaded 3.14.7t 2326 passed
Pure Python, MULTIDICT_NO_EXTENSIONS=1 ... --no-c-extensions 1130 passed
pytest -m hypothesis 143 passed
MULTIDICT_DEBUG_BUILD=1, free-threaded 2326 passed
MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1, GIL 3.13.2 2326 passed
MULTIDICT_TSAN_BUILD=1, TSan CPython 3.14.7t 2313 passed, same as 3e5aa5b

Lint: pre-commit run on the touched files passes; make doc-spelling passes.

Performance, valgrind --tool=callgrind with PYTHONHASHSEED=0 on a 3.13.2
GIL build, comparing 3e5aa5b against this branch. Each figure is the range
over three key shapes: MultiDict with str keys, CIMultiDict with str
keys, CIMultiDict with istr keys. Instructions per operation, so lower is
better.

Operation Delta
__delitem__ -1.4% to -1.9%
__setitem__, new key -1.0% to -1.4%
setdefault -0.6% to -0.7%
getall -0.3% to -0.7%
__setitem__, existing key -0.4% to -0.6%
pop -0.1% to -0.5%
add 0.0%
popall 0.0%

Two results worth flagging, since neither was obvious:

md_calc_identity_hash() carries __attribute__((always_inline)) because
without it GCC emits it out of line and add regresses 0.9%. With it, add
is exactly flat.

md_replace() owning its reflist_t rather than taking one is what removes
the __setitem__ cost. Keeping the caller's parameter left the
existing-key case at +1.35%.

Since always_inline in identity.h has moved the inliner's budget around
before, the paths this change does not touch were measured the same way:
__getitem__, __contains__, getone(), construction from a dict and from
an item list, copy(), update() and iterating items(). All twenty-four
figures land within 0.06% of 3e5aa5b, so the budget stayed put this time.

tools/codegen_diff.py --ref upstream/master reports 91 of 191 functions
changed 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 emitted
standalone and md_replace() now is, so inlining is redistributed across the
callers. Compiled .text for _multidict.c grows 59 bytes, 117328 to 117387.

The TSan run reports the same two failures as 3e5aa5b does,
test_pure_python_reciprocal_view_ops_no_deadlock and
test_pure_python_reciprocal_raw_iterator_ops_no_deadlock. Both are a
20-second Thread.join timeout in pure-Python code this branch does not
touch, which TSan's slowdown cannot meet. Of the races TSan reports, 21 on
3e5aa5b and 22 here, every one is inside CPython's faulthandler walking
another 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.

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 23, 2026
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.
@asvetlov
asvetlov force-pushed the claude/api-methods-critical-section-538fd1 branch from d0aa320 to d2460ea Compare September 23, 2026 13:43
@codspeed

codspeed Bot commented Sep 23, 2026

Copy link
Copy Markdown

Merging this PR will improve performance by 11.87%

⚠️ 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

⚡ 1 improved benchmark
✅ 309 untouched benchmarks

Performance Changes

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)

Open in CodSpeed

@asvetlov
asvetlov marked this pull request as ready for review September 23, 2026 18:26
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 23, 2026 18:26
@greptile-apps

greptile-apps Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

Not safe to merge until the required regression test is added.

Reviews (1) · Last reviewed commit: "Compute a key's identity outside the cri..."

Comment thread multidict/_multilib/hashtable.h Resolved
@greptile-apps

greptile-apps Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

Comments Outside Diff

These 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.

  • P1 C-backend critical-section behavior lacks an added or extended test ▶

    • Bug
      • Commit d2460ea moves identity/hash computation outside MultiDict critical sections in multidict/_multilib/hashtable.h, but its diff has no added or modified test path. Therefore the new behavior is not exercised by an added/extended test in this commit.
    • Cause
      • The commit changes six non-test files and no files under tests/, despite the repository directive requiring changed behavior to be exercised by a test added or extended with the change.
    • Fix
      • Add or extend a targeted C-backend test that exercises the affected key identity/hash paths and proves identity/hash work occurs outside the critical section; run it with the relevant C-extension configuration and record the result.

@asvetlov
asvetlov merged commit 372d632 into aio-libs:master Sep 23, 2026
62 checks passed
@asvetlov
asvetlov deleted the claude/api-methods-critical-section-538fd1 branch September 23, 2026 18:39
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 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>
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