Repository navigation
Give each multidict its own block of versions on free-threaded builds - #1605
Merged
Merged
Conversation
A mutation read and advanced a thread-local counter, which is a __tls_get_addr() call in a shared object. md->version now doubles as the cursor into a 256-version block the multidict owns, advanced under its critical section; the thread-local counter is only touched when a multidict takes a new block. The GIL build is unchanged.
asvetlov
marked this pull request as ready for review
September 26, 2026 19:00
Contributor
|
Gather the free-threaded versioning scheme into one comment: why a mutation must not reach thread-local storage, the three levels a version comes from, and why no block or batch base is handed out. Add tests that cross block and batch boundaries within one multidict, across many multidicts and across threads, checking that versions stay unique. On free-threaded builds they fail if a new multidict is not given a block of its own, or if a thread reuses a batch.
# Conflicts: # multidict/_multilib/hashtable.h
5 of 6 tasks
The pure-Python version counter is deliberately unlocked on GIL builds, the same pre-existing race _gil_build_race_skip covers in test_multidict.py, and PyPy switches threads often enough to hand two threads the same version.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1605 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 43 43
Lines 7940 7978 +38
Branches 663 669 +6
=========================================
+ Hits 7940 7978 +38
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? `getversion()` built its result with `PyLong_FromUnsignedLong()`. `unsigned long` is 32 bits on every Windows build, 64-bit included, and on 32-bit platforms, so the `uint64_t` version came back truncated to its low 32 bits there. It now uses `PyLong_FromUnsignedLongLong()`. A test-only `_setversion()` hook, next to `_freelist_clear()`, lets the test set a version above 2**32 without making 2**32 mutations. ## Are there changes in behavior for the user? Yes, on Windows and 32-bit platforms: `getversion()` returns the full 64-bit version. Before, two different versions that shared their low 32 bits compared equal. That took about 4.3e9 mutations with the current global counter, but only about 16.7 million new multidicts once #1605 lands, since each multidict then takes a block of 256 versions. `MultiDict_GetVersion()` in the C API already returned the full `uint64_t` and is unchanged. The pure-Python implementation is not affected. ## Is it a substantial burden for the maintainers to support this? No. It is a one-call fix plus a test hook. ## Related issue number Found while reviewing #1605. ## 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> On Linux x86-64 `unsigned long` is 64 bits, so the bug does not show locally; the Windows CI jobs exercise it for real. To check that the test catches truncation, it was run against a build that simulates a 32-bit `unsigned long` with `PyLong_FromUnsignedLong((uint32_t)load_version(md))`: both parametrized cases fail there and pass with the fix. 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. The new test is skipped on the pure-Python leg through `pytest.importorskip("multidict._multidict")`. `make doc-spelling`: passes. </details> --------- Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
asvetlov
added a commit
that referenced
this pull request
Sep 27, 2026
<!-- Thank you for your contribution! --> ## What do these changes do? On GIL builds the pure-Python `_incr_version()` read, incremented and stored the shared version counter across several bytecodes, so two threads mutating different multidicts at once could be handed the same version. The counter is now an `itertools.count`, and the GIL build takes `next()` from it, which is a single C call. The free-threaded build keeps `_VERSION_LOCK` around the same `next()`, since `itertools.count` is not documented as thread-safe there. `test_pure_python_version_thread_safety` no longer carries `_gil_build_race_skip`. It lowers the switch interval to 1e-4 s while its threads run, which fails reliably on PyPy before the fix. CPython 3.10 and 3.14 GIL builds never showed the race, since they only switch threads at calls and backward jumps and the old increment had neither in the window. The C extension is unaffected; its counter was made atomic in #1446. ## Are there changes in behavior for the user? No, apart from pure-Python versions no longer colliding across threads. ## Is it a substantial burden for the maintainers to support this? No; the change is three lines and makes the increment simpler. ## Related issue number Related to #1605, whose pure-Python GIL-build skip in `test_versions_unique_across_threads` can be removed once both land. ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist - [x] Documentation reflects the changes (N/A, no documented behaviour changed) - [ ] 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); reviewed by @asvetlov. <details> <summary>Agent run details (optional, for reviewers)</summary> Reproduction, PyPy 3.10.16, `test_pure_python_version_thread_safety` under pytest-cov: 4/4 failed before the fix, 4/4 passed after, about 4 s per run. Standalone, 16 threads x 2000 `__setitem__` at a 1e-4 switch interval gave 59 to 231 duplicate versions per run before, 0 after. Full suite, each leg in its own venv and tree copy: - CPython 3.14.7, C extension: 2792 passed, 170 skipped - CPython 3.14.7t, C extension: 2778 passed, 184 skipped - CPython 3.10.17, C extension: 2792 passed, 170 skipped - CPython 3.14.7, `MULTIDICT_NO_EXTENSIONS=1 ... --no-c-extensions`: 1321 passed, 16 skipped - PyPy 3.10.16, pure Python: 1297 passed, 40 skipped (`test_circular_imports` needed multidict installed into the venv, then passed) Lint: `pre-commit` (ruff, mypy) and `make doc-spelling` pass. Instructions per operation, `benchmarks/callgrind_driver.py --impl multidict_py --include-multidict-only`, CPython 3.14.7 GIL build (no wall-clock run): | operation | before | after | change | | --- | ---: | ---: | ---: | | `add` | 22743.5 | 20870.0 | -8.24% | | `add_istr` | 24220.7 | 22349.9 | -7.72% | | `popitem` | 11920.9 | 10987.7 | -7.83% | | `ctor_items` | 2476497.0 | 2287618.6 | -7.63% | | `pop` | 15420.9 | 14519.4 | -5.85% | | `setdefault_new` | 34690.1 | 32819.2 | -5.39% | | `delitem` | 19617.6 | 18723.2 | -4.56% | | `setitem_replace` | 26166.9 | 25215.0 | -3.64% | | `setitem_insert` | 27042.9 | 26106.1 | -3.46% | Read-only operations moved by less than 0.3%. </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 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 oldlock xaddwas 4. That call accounted for nearly all of thector_smallregression (+18.6 Ir per inserted pair) and 18 of the 26 Irpoplost.Each multidict now owns a block of 256 versions, and
md->versionis 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))becamebump_version(md). On the GIL build that is still++state->global_version, andtools/codegen_diff.pyreports 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%):cls(items)cls(items), 20 itemscls()d.copy(), 20 itemsd[key] = v, existing keyd[key] = v, new keyd.setdefault(key, v), new keydel d[key]d.pop(key)d.popitem()d.update(other)d.clear()iter(d)d.add(key, v)d[key] = v,istrkeyd.add(key, v),istrkeyctor_smallis 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.hchanges. The pure-Python implementation has no version batching, so it is not affected.Related issue number
Follows up on #1587 and #1599.
Checklist
CONTRIBUTORS.txt(N/A, existing contributor)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)
Measured with
benchmarks/callgrind_driver.py --impl multidict_c --include-multidict-only, one git worktree and one venv per build,.sorebuilt 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_addrcall 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 costcls()+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-threadedctor_small6765,pop515.8,delitem374.2; GIL unchanged from #1604 alone.Tests:
pytestpasses 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.pyandtest_mutable_multidict.pypass with 0 reports.make doc-spelling: passes.