Repository navigation
Reserve version numbers in per-thread batches on free-threaded builds - #1587
Merged
Merged
Conversation
asvetlov
marked this pull request as ready for review
September 25, 2026 14:13
Contributor
|
This comment has been minimized.
This comment has been minimized.
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1587 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 41 41
Lines 7739 7797 +58
Branches 648 650 +2
=========================================
+ Hits 7739 7797 +58
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
5 of 6 tasks
asvetlov
added a commit
that referenced
this pull request
Sep 26, 2026
<!-- Thank you for your contribution! --> ## What do these changes do? #1587 gave each thread a batch of versions in two thread-local variables, `version_next` and `version_end`. Under the default TLS model every access to a thread-local in a shared object goes through `__tls_get_addr()`, and GCC recomputes the address rather than keep it in a register, so each mutation made two such calls where it used to make one `lock xadd`. On a single thread that cost about 34 instructions per mutation. A single `version_last` now does the job. A batch never hands out its own base, a multiple of `VERSION_BATCH`, so reaching one means the batch is spent, and starting the variable at `VERSION_BATCH - 1` makes the first call refill. One `++version_last` reads and advances it, which is one TLS lookup. Versions stay unique and increasing within a thread, the same guarantees as before. The GIL build and the pure-Python implementation are unaffected. Instructions per operation, free-threaded 3.14.7t (Callgrind, `benchmarks/callgrind_driver.py`): | operation | `MultiDict` | `CIMultiDict` | |---|---:|---:| | `ctor_items` | 73,543 -> 70,308 (-4.4%) | 85,771 -> 82,536 (-3.8%) | | `ctor_small` | 7,529 -> 7,175 (-4.7%) | 8,717 -> 8,363 (-4.1%) | | `setitem_replace` | 527 -> 511 (-3.0%) | 584 -> 568 (-2.7%) | | `setitem_insert` | 634 -> 617 (-2.6%) | 690 -> 674 (-2.4%) | | `delitem` | 425 -> 409 (-3.8%) | 482 -> 466 (-3.3%) | | `pop` | 565 -> 549 (-2.9%) | 622 -> 606 (-2.6%) | ## Are there changes in behavior for the user? No. ## Is it a substantial burden for the maintainers to support this? No, it is smaller than what it replaces. ## Related issue number N/A ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist (the existing `test_version_thread_safety` checks uniqueness across 16 threads and crosses many batch boundaries) - [x] Documentation reflects the changes (N/A, internal only) - [ ] 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` Drafted with Claude Code (Claude Opus 5.5); pending review by @asvetlov before leaving draft. <details> <summary>Agent run details (optional, for reviewers)</summary> Tests: - C extension, 3.14.7: 2790 passed, 170 skipped - C extension, 3.14.7t: 2777 passed, 183 skipped - C extension, 3.10.17: 2790 passed, 170 skipped - Pure Python, 3.14.7 (`MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions`): 1320 passed, 17 skipped Lint: pre-commit hooks pass. `make doc-spelling` passes. Bisecting f08f768..91d5329 per first-parent commit with Callgrind put about 34 instructions per mutation on 8aee2a5 (#1587). `objdump` showed two `__tls_get_addr@plt` calls per version bump, 41 in the `.so`; this branch has one per call site. Holding the address in a local does not help, GCC rematerializes it, which is why the fix is one read-modify-write instead. `-mtls-dialect=gnu2` (TLS descriptors) would cut the rest, but is a GCC-only build flag and left out. The thread-local now has an initializer, so it lives in `.tdata` rather than `.tbss`; the `.so` still uses the default TLS model and has no `STATIC_TLS` flag. Wall clock was measured only together with two sibling PRs (the `update()` reference change and the inlining annotations); see those for the combined pyperf numbers. Not tested: musl, macOS, Windows and Android builds. </details>
5 of 6 tasks
asvetlov
added a commit
that referenced
this pull request
Sep 26, 2026
…#1605) <!-- Thank you for your contribution! --> ## What do these changes do? On free-threaded builds every mutation took its version from a thread-local counter (#1587, #1599). In a shared object that is a `__tls_get_addr()` call per mutation, about 23 instructions where the old `lock xadd` was 4. That call accounted for nearly all of the `ctor_small` regression (+18.6 Ir per inserted pair) and 18 of the 26 Ir `pop` lost. Each multidict now owns a block of 256 versions, and `md->version` is the cursor into it, advanced under the multidict's own critical section. Thread-local storage is touched only when a multidict needs a new block: when it is created, and then after 255 mutations. Each thread still reserves a batch from the process-wide counter, now 65536 versions (256 blocks) at a time. A block's base is never handed out. That keeps a new multidict (version 0) and a spent block distinguishable with one mask test, and versions stay unique across multidicts. `store_version(md, next_version(md->state))` became `bump_version(md)`. On the GIL build that is still `++state->global_version`, and `tools/codegen_diff.py` reports 0 of 230 functions changed there. Callgrind `ir_per_op`, `multidict_c`, free-threaded 3.14.7t, against 2f84475 (rows that moved by more than 0.1%): | operation | before | after | | | --- | --- | --- | --- | | `cls(items)` | 69893.4 | 66265.3 | -5.2% | | `cls(items)`, 20 items | 7135.6 | 6765.0 | -5.2% | | `cls()` | 878.3 | 888.3 | +1.1% | | `d.copy()`, 20 items | 2763.8 | 2744.8 | -0.7% | | `d[key] = v`, existing key | 505.1 | 495.1 | -2.0% | | `d[key] = v`, new key | 610.5 | 597.8 | -2.1% | | `d.setdefault(key, v)`, new key | 730.1 | 711.4 | -2.6% | | `del d[key]` | 408.6 | 392.5 | -3.9% | | `d.pop(key)` | 537.8 | 519.8 | -3.3% | | `d.popitem()` | 664.7 | 646.6 | -2.7% | | `d.update(other)` | 44708.0 | 44514.0 | -0.4% | | `d.clear()` | 8977.6 | 8957.0 | -0.2% | | `iter(d)` | 784.0 | 786.0 | +0.3% | | `d.add(key, v)` | 706.6 | 689.9 | -2.4% | | `d[key] = v`, `istr` key | 1028.8 | 1015.8 | -1.3% | | `d.add(key, v)`, `istr` key | 1044.5 | 1027.7 | -1.6% | `ctor_small` is back to 6765, against 6763 before #1587. `cls()` pays the one out-of-line call a new multidict now makes to take its block. ## Are there changes in behavior for the user? No. `getversion()` is documented for equality tests only. Versions stay unique across multidicts and still change on every mutation. As before, they are not ordered across threads. ## Is it a substantial burden for the maintainers to support this? No. It replaces one counter scheme with another of the same size, and only the free-threaded branch of `freethreading.h` changes. The pure-Python implementation has no version batching, so it is not affected. ## Related issue number Follows up on #1587 and #1599. ## 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, existing contributor) - [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 Code (Claude Opus 5.5); reviewed by @asvetlov. <details> <summary>Agent run details (optional, for reviewers)</summary> Measured with `benchmarks/callgrind_driver.py --impl multidict_c --include-multidict-only`, one git worktree and one venv per build, `.so` rebuilt from scratch and timestamp-checked, and base and change built in the same tree. GIL 3.14.7: every row is identical. A base-to-base control across the two trees differed by at most 0.26%. `objdump`: free-threaded `__tls_get_addr` call sites went from 25, spread over every mutating function, to 2, both in the cold `_new_version_block()` / `_refill_version_batch()`. The first cut of `_new_version_block()` read and wrote the thread-local separately, which was two TLS lookups and cost `cls()` +3.0%. One `+=` brought that down to +1.1%. On top of #1604 (merged into this branch, one-line conflict in `_md_del_locked()`): free-threaded `ctor_small` 6765, `pop` 515.8, `delitem` 374.2; GIL unchanged from #1604 alone. Tests: `pytest` passes on 3.14.7, 3.14.7t, 3.10.17 and pure Python (3.13.2), each in its own tree copy and venv. ThreadSanitizer (`MULTIDICT_TSAN_BUILD=1`, 3.14.7t-tsan): `test_free_threading.py`, `test_version.py` and `test_mutable_multidict.py` pass with 0 reports. `make doc-spelling`: passes. </details>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What do these changes do?
On the free-threaded build every mutation bumped one counter shared by every multidict with an atomic fetch-add. Threads mutating their own, unrelated multidicts still fought over that one cache line, and with six threads a
d[key] = valuespent about three quarters of its time there.Each thread now reserves 256 versions at a time from a process-wide counter and hands them out from thread-local storage, the same scheme free-threaded CPython uses for its dict version tags. Versions stay unique across all multidicts and keep increasing within a thread, but are no longer ordered across threads;
getversion()is documented as equality-only and the C code only ever compares with!=. The counter moved out of module state so a batch left over in a thread can never overlap a newer module state's range. The thread-locals use the default TLS model: initial-exec would save a few ns per mutation, but it draws on glibc's small static TLS reserve fordlopen(), and when that is exhausted the import fails and multidict silently falls back to pure Python. The GIL build is unchanged, and the pure-Python implementation has no equivalent contention to fix.Wall clock, 3.14.7t, ns per mutation, each thread on its own dict and keys, pinned to separate P-cores, median of 5 interleaved rounds:
d[k] = vd[k] = vd[k] = vd[k] = vadd+deladd+delget()(control)Are there changes in behavior for the user?
Faster concurrent mutation on free-threaded builds. Versions from different threads are no longer ordered relative to each other, which was never part of the documented contract.
Is it a substantial burden for the maintainers to support this?
No, it is about thirty lines confined to
next_version()and aTHREAD_LOCALmacro.Related issue number
N/A
Checklist
test_version_thread_safetychecks uniqueness across 16 threads and crosses many batch boundaries)CONTRIBUTORS.txt(N/A)CHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtDrafted with Claude Code (Claude Opus 5.5); reviewed by @asvetlov.
Agent run details (optional, for reviewers)
Tests, rebased on cd03110:
MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions): 1302 passed, 11 skippedLint: pre-commit hooks pass.
make doc-spellingpasses.TLS model, 3.14.7t, ns per mutation with 1 / 6 threads (
d[k] = v): initial-exec 41.9 / 59.8, default 46.2 / 61.7,Py_tss_t45.3 / 65.2. Initial-exec was dropped after review: it setsSTATIC_TLSon the.so, and a reproduction showed the C extension failing to load, with a silent pure-Python fallback, once other modules had exhausted glibc's static TLS reserve.Py_tss_twas no faster than the default model. The.sonow has a 16-byte TLS segment and noSTATIC_TLSflag.Not tested: musl, macOS, Windows and Android builds, and ASan/TSan builds.