Skip to content

Use atomic ops for version incrementation in free-threading mode - #1446

Merged
asvetlov merged 8 commits into
aio-libs:masterfrom
asvetlov:fix-1444-atomic-version
Sep 12, 2026
Merged

asvetlov merged 8 commits into
aio-libs:masterfrom
asvetlov:fix-1444-atomic-version

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 12, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

NEXT_VERSION() bumps state->global_version, a counter shared by
every MultiDict/CIMultiDict instance in the process, since it
lives on the module state rather than the object. Each object's own
lock only serializes access to that one object, so under a
free-threaded build two threads mutating two different instances
could bump the shared counter at the same time with a plain ++,
losing an update and handing out a duplicate (or non-monotonic)
version number from getversion(). The fix routes the increment
through an atomic fetch-add under Py_GIL_DISABLED
(atomic_fetch_add_uint64_relaxed(), added to atomic_helpers.h
alongside the existing Py_ssize_t/pointer helpers), leaving the
GIL-enabled build's plain increment untouched.

The pure-Python implementation has the identical shape of bug (a
module-level _version array shared by every instance, bumped with
an unsynchronized v[0] += 1), but it has no other thread-safety
machinery of its own, so fixing just this one counter there is out
of scope for this PR; left as-is.

Verified the race and the fix empirically (not just via the test
suite) with a throwaway stress script under a free-threaded build:
16 threads each mutating their own multidict and recording every
getversion() reading. Before the fix, roughly 5-30% of readings
collided across runs; after the fix, all readings were unique across
several runs.

Are there changes in behavior for the user?

No visible behavior change; getversion() values remain an
opaque, per-mutation token. This only fixes a free-threaded-build
race where two unrelated multidicts could momentarily be assigned
the same version number.

Is it a substantial burden for the maintainers to support this?

No. It's a small, self-contained fix mirroring the existing atomic-op
pattern already used elsewhere in atomic_helpers.h.

Related issue number

Fixes #1444

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
  • 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 (Sonnet 5); reviewed by asvetlov.

Agent run details (optional, for reviewers)

Tests: pytest -q, all green on the C extension under a normal build, a free-threaded 3.14t build, and a free-threaded debug build (MULTIDICT_DEBUG_BUILD=1); also confirmed the pure-Python leg still passes (--no-c-extensions) and correctly deselects the new test.
New test: tests/test_multidict.py::test_version_thread_safety, marked c_extension.
Lint: pre-commit run (ruff check/format, clang-format, mypy) passed on the changed files.
Docs: make doc-spelling passed with no wordlist additions needed.

Pure Python left unfixed on purpose (see "What do these changes do?" above); happy to file a follow-up issue for it if wanted.

state->global_version (C extension) and the module-level _version
counter (pure Python) are both shared by every multidict instance,
while each object's own lock only serializes access to that one
object. Under a free-threaded build, two threads mutating two
different instances could bump the shared counter at the same time
and lose an update, handing out a duplicate or non-monotonic version
number from getversion().

Fixes aio-libs#1444
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 12, 2026
@codspeed

codspeed Bot commented Sep 12, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 13.15%

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

⚡ 2 improved benchmarks
✅ 246 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_cimultidict_getall_istr_hit[c] 36.9 ms 32.3 ms +14.35%
⚡ test_multidict_getall_str_hit[cs-c] 37.5 ms 33.5 ms +11.97%

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:fix-1444-atomic-version (5175577) with master (9024ac2)

Open in CodSpeed

@codecov

codecov Bot commented Sep 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (9024ac2) to head (5175577).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1446   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           29        29           
  Lines         4241      4259   +18     
  Branches       323       324    +1     
=========================================
+ Hits          4241      4259   +18     
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.

The GIL already serializes the increment on a regular build, so
threading.Lock() around it there is pure overhead. Use
contextlib.nullcontext() instead whenever sys._is_gil_enabled()
reports the GIL enabled (or is absent, on older, GIL-only builds),
and the real lock only on a free-threaded build with the GIL off.
The pure-Python implementation has the identical shared-counter
shape (a module-level _version array bumped by every instance) but
no locking of its own anywhere else, so fixing just this one counter
there doesn't buy real thread-safety and is out of scope here. Move
the regression test out of test_version.py (which parametrizes over
both backends) into test_multidict.py alongside the other
c_extension-marked free-threading tests, using MultiDict/getversion
directly instead of the dual-backend fixtures.
Comment thread multidict/_multilib/state.h Resolved
@asvetlov
asvetlov marked this pull request as ready for review September 12, 2026 16:27
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 12, 2026 16:27
x64/ARM64 have a native 64-bit atomic add intrinsic; only 32-bit
x86 lacks it and needs the compare-exchange retry loop. Mirrors the
existing SIZEOF_VOID_P split in atomic_fetch_add_ssize_relaxed()
just above.
@greptile-apps

greptile-apps Bot commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

No actionable issues were identified; the free-threaded runtime path still requires verification in a compatible interpreter before release confidence can be established.

There are no severity-bearing findings.

Files Needing Attention: No files require changes from this review.

T-Rex T-Rex Logs

What T-Rex did

  • Reviewed the free-threaded version-token allocation branch and verified the unsigned 64-bit atomic fetch-add helper across supported compilers.
  • Executed tests/test_multidict.py::test_version_thread_safety using the compiled C extension; the test passed on CPython 3.11.6.
  • Checked interpreter state and found Py_GIL_DISABLED=None with no free-threaded CPython executable installed, so the free-threaded path could not be built or run.

View all artifacts

T-Rex Ran code and verified through T-Rex

Reviews (1): Last reviewed commit: "Merge remote-tracking branch 'origin/fix..." | Re-trigger Greptile

@asvetlov
asvetlov enabled auto-merge (squash) September 12, 2026 16:36
@asvetlov
asvetlov merged commit cc8c06a into aio-libs:master Sep 12, 2026
56 of 57 checks passed
@asvetlov
asvetlov deleted the fix-1444-atomic-version branch September 12, 2026 16:40
rodrigobnogueira added a commit to rodrigobnogueira/multidict that referenced this pull request Sep 12, 2026
aio-libs#1431 through aio-libs#1446 made the C extension safe to use from several threads
on a free-threaded build, and shipped without a test that exercises it
that way. These two do: one iterates a multidict while other threads
mutate it, the other extends from a source that other threads are
resizing. Both segfault on every run against the tree before that series
and pass on it now, so a regression shows up as a crash on the
free-threaded CI legs rather than as nothing.
rodrigobnogueira added a commit to rodrigobnogueira/multidict that referenced this pull request Sep 12, 2026
aio-libs#1431 through aio-libs#1446 made the C extension safe to use from several threads
on a free-threaded build, and shipped without a test that exercises it
that way. These two do: one iterates a multidict while other threads
mutate it, the other extends from a source that other threads are
resizing. Both segfault on every run against the tree before that series
and pass on it now, so a regression shows up as a crash on the
free-threaded CI legs rather than as nothing.
asvetlov added a commit that referenced this pull request Sep 13, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Adds per-instance locking to the pure-Python `MultiDict`/`CIMultiDict`
fallback (`multidict/_multidict_py.py`) so it gives the same
crash-free, corruption-free guarantee as the C extension under a
free-threaded (no-GIL) build. Every method that touches an instance's
hash table takes that instance's own `RLock` (created once in
`__new__`, reused across a later re-init); two-object operations
(`update()`, `extend()`, `merge()`, `__eq__()`, copy construction) lock
both objects together in a fixed, deadlock-safe order; view iterators
take the lock per step rather than for the whole iteration, so a
concurrent mutation between steps surfaces as the same "changed during
iteration" `RuntimeError` a single-threaded caller already gets today
instead of a deadlock; and the version counter shared by every
instance gets its own lock. On a regular GIL-enabled interpreter the
locked methods are the exact same function objects as before this
change -- no wrapper, no lock, no measurable overhead.

## Are there changes in behavior for the user?

Yes, but only on a free-threaded build: concurrent use of a
pure-Python `MultiDict`/`CIMultiDict` from multiple threads is now
safe against crashes and data corruption, matching the C extension.
On a regular (GIL-enabled) build there is no behavior or performance
change.

## Is it a substantial burden for the maintainers to support this?

No. The change is self-contained to `_multidict_py.py`, gated entirely
behind a runtime free-threading check computed once at import, and
mirrors the locking approach already reviewed and merged for the C
extension (#1438, #1441, #1445, #1446). The C extension itself is
unaffected; this only touches the pure-Python fallback.

## Related issue number

N/A -- no linked issue. Continues the free-threading hardening already
done for the C extension.

## 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, this repo has no `CONTRIBUTORS.txt`)
- [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`

<details>
<summary>Agent run details (optional, for reviewers)</summary>

Tests: `pytest -q` passes on both backends; the pure-Python leg was
additionally run under a free-threaded interpreter (CPython 3.13.7t,
`PYTHON_GIL=0`) multiple times with coverage active, plus a standalone
stress script driving 16 threads through thousands of concurrent
mutations, with no crashes or corruption.

Lint: `ruff check`, `ruff format --check`, and `mypy` (3.11 and 3.13,
via `pre-commit`) all pass on the changed files.

Docs: `make doc-spelling` passes.

Note: while calibrating test load, a pre-existing, unrelated race in
`update()`/`extend()`/`merge()`/`clear()` was found -- reachable even
on a plain GIL-enabled interpreter under heavy concurrent use (pure
Python bytecode isn't atomic even under the GIL). Confirmed present on
unmodified `master` too, so it predates and is out of scope for this
PR; a follow-up is planned separately. Two of the new tests that would
otherwise be flaky against it are skipped on non-free-threaded builds,
with the reason stated inline.

</details>

Drafted with Claude Code; reviewed by asvetlov.
asvetlov added a commit that referenced this pull request Sep 14, 2026
## What do these changes do?

Adds two race tests for the C extension on free-threaded builds: one
iterates a multidict while other threads mutate it, the other extends
from a source that other threads are resizing.

#1431 through #1446 made these paths safe. Against the tree before that
series both tests segfault on every run; against current master they
pass. There is no other threaded test in the suite, so this is what
would turn a regression into a red free-threaded CI leg instead of
silence.

The C changes this PR originally carried are superseded by that series
and have been dropped.

## Are there changes in behavior for the user?

No.

## Is it a substantial burden for the maintainers to support this?

No. One test file and a `contrib` fragment; the tests are
`c_extension`-marked and take about a quarter of a second.

## Related issue number

Follows #1431, #1433, #1438, #1441, #1445, #1446.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [ ] Documentation reflects the changes -- N/A
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` -- N/A
- [x] Add a new news fragment into the `CHANGES/` folder

---------

Co-authored-by: Andrew Svetlov <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[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.

Use atomic ops for version incrementation in free-threading mode

1 participant