Skip to content

Keep one thread-local version counter on free-threaded builds - #1599

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:version-counter-single-tls
Sep 26, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:version-counter-single-tls

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 26, 2026 •

Copy link
Copy Markdown
Member

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

  • I think the code is well written
  • Unit tests for the changes exist (the existing test_version_thread_safety checks uniqueness across 16 threads and crosses many batch boundaries)
  • Documentation reflects the changes (N/A, internal only)
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt (N/A)
  • 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); pending review by @asvetlov before leaving draft.

Agent run details (optional, for reviewers)

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 #1598 for the combined pyperf numbers.

Not tested: musl, macOS, Windows and Android builds.

Two thread-locals cost two __tls_get_addr() calls per mutation under the
default TLS model. A single counter that never hands out a multiple of
VERSION_BATCH marks a spent batch by itself, so one increment reads and
advances it.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 26, 2026
@asvetlov
asvetlov marked this pull request as ready for review September 26, 2026 14:49
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 26, 2026 14:49
@codspeed

codspeed Bot commented Sep 26, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:version-counter-single-tls (56f3817) with master (602dedc)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Optimizes thread-local version counter in free-threaded builds.

No blocking issues were identified; the change appears safe to merge.

What we checked:

  • Ran the same version-check probe against the PR revision with the GIL disabled, using six waves of concurrent workers. T-Rex
  • The PR revision passed 118,514 version checks across six waves, covering batch boundaries, fresh threads, multiple mappings, and unchanged mappings. T-Rex
  • The probe failed against the rebuilt parent revision when it returned batch-base version 512. T-Rex
  • The probe passed against PR Keep one thread-local version counter on free-threaded builds #1599, confirming the boundary logic change at multidict/_multilib/freethreading.h:94-113. T-Rex
  • Artifacts from both proofs are provided to review the probe results, including the concurrent version-check probe run and the log details for parent and PR revisions. T-Rex

Reviews (1) · Last reviewed commit: "Keep one thread-local version counter on..."

@asvetlov
asvetlov merged commit b5d4053 into aio-libs:master Sep 26, 2026
62 checks passed
@asvetlov
asvetlov deleted the version-counter-single-tls branch September 26, 2026 15:04
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>
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