Skip to content

Give each multidict its own block of versions on free-threaded builds - #1605

Merged
asvetlov merged 4 commits into
aio-libs:masterfrom
asvetlov:ft-version-blocks
Sep 26, 2026
Merged

asvetlov merged 4 commits into
aio-libs:masterfrom
asvetlov:ft-version-blocks

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 26, 2026 •

Copy link
Copy Markdown
Member

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

  • 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, existing contributor)
  • 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 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, .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.

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.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 26, 2026
@codspeed

codspeed Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:ft-version-blocks (346624e) with master (8e5c14c)

Open in CodSpeed

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

greptile-apps Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Refactors version tracking for free-threaded multidict builds.

No outstanding findings block merging.

Reviews (4) · Last reviewed commit: "Skip the threaded version test on pure-P..."

Comment thread multidict/_multilib/freethreading.h Resolved
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
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

codecov Bot commented Sep 26, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (05315a4) to head (346624e).
⚠️ Report is 1 commits behind head on master.

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     
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 98b367f into aio-libs:master Sep 26, 2026
62 checks passed
@asvetlov
asvetlov deleted the ft-version-blocks branch September 26, 2026 20:43
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>
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