Skip to content

Fix a data race on the MultiDict version counter - #1514

Merged
asvetlov merged 5 commits into
aio-libs:masterfrom
asvetlov:fix-md-version-atomic
Sep 22, 2026
Merged

asvetlov merged 5 commits into
aio-libs:masterfrom
asvetlov:fix-md-version-atomic

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

md_version() read md->version with a plain, non-atomic load, while
every mutation site wrote it with a plain store under the object's own
critical section. On a free-threaded build, getversion() (which calls
md_version() without taking that critical section) could race a
concurrent writer. Both sides now use the relaxed atomic load/store pair
already used for the object's item count, so the read and every write
site go through atomic_load_uint64_relaxed() /
atomic_store_uint64_relaxed().

Are there changes in behavior for the user?

No. getversion() still returns the same opaque, per-mutation token;
this only removes a data race on free-threaded builds.

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

No, it mirrors the existing atomic-op pattern in atomic_helpers.h.

Related issue number

Related to #1444, which fixed the analogous race on the shared global
counter but left the per-object md->version field itself unaddressed.

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 GIL build (2160 passed), a free-threaded 3.14t build (2148 passed), and the pure-Python build (2160 passed, unchanged since this is C-extension only).
New test: tests/test_free_threading.py::test_race_condition_getversion_vs_mutation, marked c_extension.
Sanitizer: confirmed with MULTIDICT_TSAN_BUILD=1 against a TSan-instrumented free-threaded CPython. Before the fix, TSan reliably flagged the exact race (_md_replace write vs. md_version/getversion read); after the fix, TSan is silent on the new test and on the full suite (2139 passed, 0 warnings).
Lint: pre-commit (ruff check/format, clang-format, mypy) passed on the changed files.
Docs: make doc-spelling passed with no wordlist additions needed.

md_version() read md->version with a plain load while every mutation
site wrote it with a plain store under the object's own critical
section, so getversion() could race a concurrent writer on
Py_GIL_DISABLED builds. Both sides now go through the same relaxed
atomic load/store pair len() already uses for md->used.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 22, 2026
@asvetlov
asvetlov marked this pull request as ready for review September 22, 2026 08:19
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 22, 2026 08:19
@codspeed

codspeed Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 298 untouched benchmarks


Comparing asvetlov:fix-md-version-atomic (10c13a5) with master (a4479a6)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

Not safe to merge until the repository's required test-coverage policy is met.

Reviews (5) · Last reviewed commit: "Address Greptile review: atomic re-read ..."

Comment thread tests/test_free_threading.py Resolved
Comment thread tests/test_free_threading.py Resolved
@greptile-apps

This comment has been minimized.

@codecov

codecov Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (a4479a6) to head (10c13a5).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1514   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           38        38           
  Lines         6347      6381   +34     
  Branches       574       579    +5     
=========================================
+ Hits          6347      6381   +34     
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

Copy link
Copy Markdown
Member Author

@aiolibsbot rr

The writer had a fixed iteration count and the readers looped until
stop was set, so on a GIL build the writer could run to completion
and set stop before any reader was ever scheduled, leaving `seen`
empty for reasons unrelated to the atomic version fix. Give the
readers the fixed count instead and let the writer loop until every
reader is done, mirroring the extend-vs-mutation test's existing
pattern, plus a start barrier so no thread gets a head start.
# Conflicts:
#	multidict/_multilib/hashtable.h
The version-backwards check in the new getversion race test, and the
pre-existing reader RuntimeError handler in the iterator race test,
never execute on a passing run; mark both no-cover, matching the
sibling except blocks already annotated that way.
@aiolibsbot

Copy link
Copy Markdown
Contributor

@asvetlov: @aiolibsbot rr

Re-reviewed. No plain store to md->version remains; every surviving plain read sits under the critical section. Four non-blocking suggestions posted, top one: atomic_load_uint64_relaxed() tears on 32-bit MSVC, unlike atomic_fetch_add_uint64_relaxed() above it. Approving.

@aiolibsbot

aiolibsbot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

PR Review — Fix a data race on the MultiDict version counter

Correct and complete fix; four non-blocking suggestions, none of which hold up the merge.

The diff does what it says and does it thoroughly. Verified against the tree at HEAD:

  • No plain store to md->version survives anywhere in multidict/ (git grep 'md->version\s*=' returns only a comparison in identity.h:145), so the load/store pair really is closed, not half-converted.
  • The remaining plain reads (hashtable.h:1035, 1508, 1832, 2804, finder.h:44/105, update_marks.h:53/68) are all taken while the object's critical section is held, including the post-__del__ re-checks, so leaving them non-atomic is right rather than an oversight; md_version() was genuinely the only unlocked reader (_multidict.c:1919 is its sole caller).
  • The new helpers slot into all four backend branches of atomic_helpers.h, matching the existing atomic_fetch_add_uint64_relaxed() layout, and the GIL-enabled branch degrades to a plain access so no call site needs an #ifdef.
  • The test is a real regression vehicle, not decoration: the TSan job runs the whole tests directory under halt_on_error=1, and the barrier plus stop-flag rework removes the schedule dependence @greptile-apps flagged earlier.
  • CHANGES fragment follows the house style: past tense, :func:~multidict.getversion`` resolves against .. module:: multidict in `docs/multidict.rst`, signed with `:user:`.

Suggestions:

  • atomic_load/store_uint64_relaxed() on the MSVC branch uses a plain volatile access, which tears on 32-bit x86; the atomic_fetch_add_uint64_relaxed() right above it already handles that case explicitly. Narrow impact (needs the high word to change), not a regression.
  • The 11 repetitions of atomic_store_uint64_relaxed(&md->version, NEXT_VERSION(md->state)) want a _md_bump_version() helper, matching the existing _md_store_keys() / _md_store_used() convention in the same file.
  • assert seen in the new test is now true by construction; assert len(set(seen)) > 1 would actually prove the writer overlapped the readers.
  • Pre-existing: getversion() passes a uint64_t to PyLong_FromUnsignedLong(), truncating to 32 bits on Windows and diverging from the pure-Python backend.

Not re-raised: the # pragma: no cover placement, per @asvetlov's "it's for tests only".


🟢 Suggestions

1. MSVC uint64 load/store is not atomic on 32-bit x86
multidict/_multilib/atomic_helpers.h:366-376

The new MSVC-branch helpers use a plain volatile access for a 64-bit value:

  • On _M_IX86 (win32), a volatile uint64_t read/write compiles to two 32-bit accesses, so it can tear. The relaxed contract the helper's name promises is not delivered there.
  • The function directly above it, atomic_fetch_add_uint64_relaxed(), already handles exactly this with an explicit #if SIZEOF_VOID_P == 8 split and a _InterlockedCompareExchange64 fallback, so the file itself establishes that 32-bit MSVC is in scope.
  • win32 wheels are built at release time (CIBW_SKIP only excludes *-win32 on non-tag runs, .github/workflows/ci-cd.yml:174), and cibuildwheel 3.x builds the free-threaded ABIs by default, so a cp3XXt-win32 wheel plausibly ships.

Practical impact is small: md->version starts at 0 and only tears once the high word changes, i.e. after ~2^32 mutations, and this is not a regression (the field was a plain access on every platform before). But the helper is now a general primitive, and the next 64-bit hot field to use it would tear silently.

Mirror CPython's pyatomic_msc.h, which the surrounding comment already cites: _InterlockedOr64((volatile __int64*)obj, 0) for the load and _InterlockedExchange64 for the store under #if SIZEOF_VOID_P != 8. Alternatively, document in the comment why tearing is acceptable for this field.

static inline uint64_t
atomic_load_uint64_relaxed(const uint64_t* obj)
{
    return *(volatile const uint64_t*)obj;
}
2. Wrap the version bump in a `_md_store_version()` helper
multidict/_multilib/hashtable.h:726-727

atomic_store_uint64_relaxed(&md->version, NEXT_VERSION(md->state)) is now repeated verbatim at 11 sites, and the expression is long enough that two of them had to be re-wrapped by clang-format (this one leaves // never reuse other's version dangling on the continuation line).

The file already has the right shape for this one field over: _md_store_keys() (line 200) and _md_store_used() (line 209) exist precisely so that "every write to this field goes through the matching atomic op" is enforced in one place rather than at each call site. md->version is now the third such field and is the odd one out.

A _md_bump_version(md) helper next to _md_store_used(), carrying the same explanatory comment, collapses the 11 repetitions and makes a future plain md->version = ... stand out as obviously wrong. It also gives one place to document why the reads under the object's critical section stay plain.

    atomic_store_uint64_relaxed(
        &md->version, NEXT_VERSION(md->state));  // never reuse other's version

Checklist

  • Every plain write to md->version converted to the atomic store
  • Remaining plain reads of md->version are lock-protected
  • Atomic helpers are correct on every supported backend/arch — suggestion #1
  • New test is a genuine regression detector (runs under the TSan job)
  • CHANGES fragment present, correct category, resolvable Sphinx roles
  • PR description matches the diff; no scope creep
  • Change leaves the surrounding code no messier — suggestion #2

Silent Failure Analysis

🟠 **3. HIGH** — dead error branch (atomic store paired with plain load)
multidict/_multilib/hashtable.h:1729-1734

Risk: The guard that detects a concurrent resize now compares a non-atomic read of md->version against the value the line above just stored atomically, so the compiler may forward the store into the load and fold the condition to false, silently deleting the goto restart that prevents walking a freed table — and even if kept, a plain load has no guarantee of observing another thread's atomic store.

atomic_store_uint64_relaxed(&md->version, version);
_md_del_at(md, iter.slot, entry);
// the decref can run a __del__ that lets another thread resize
if (UNLIKELY(md->keys != keys || md->version != version)) {
    goto restart;
}

Fix: Read through atomic_load_uint64_relaxed(&md->version) (or md_version(md)) in this check, the same way the store side was converted.

🟡 **4. MEDIUM** — incomplete atomics conversion — unchecked mixed access
multidict/_multilib/hashtable.h:1094

Risk: The PR converts every write of md->version to an atomic store but leaves ~20 reads as plain loads, all of them in "changed during iteration" guards that sit after calls which can run arbitrary Python (__del__/__eq__) and therefore release the critical section; a stale or optimized-away read makes the RuntimeError never fire, turning a detected mutation into silent memory unsafety.

if (pos->version != md->version) {
    PyErr_SetString(PyExc_RuntimeError,
                    "MultiDict is changed during iteration");

Fix: Route all reads of md->version through md_version()/atomic_load_uint64_relaxed() so the field has a single, consistently atomic access discipline.

🟡 **5. MEDIUM** — fire-and-forget thread — failures never surfaced
tests/test_free_threading.py:179-190

Risk: Unlike the reader (and unlike the writer in the existing test above it), this thread records nothing into errors, so if md["k"] = ... raises, the exception only reaches threading.excepthook on stderr while the test still passes with zero mutation pressure.

def writer() -> None:
    ready.wait()
    i = 0
    while not stop.is_set():
        md["k"] = f"v{i}"
        i += 1

Fix: Wrap the writer body in try/except Exception as e: errors.append(...) so a broken mutation path fails the assertion instead of just printing.

🟡 **6. MEDIUM** — vacuous assertion masking a no-op test
tests/test_free_threading.py:217-218

Risk: seen is unconditionally filled with 20,000 entries per reader regardless of whether the writer ever ran, so the test cannot distinguish "race exercised, versions advanced" from "writer died instantly and nothing was mutated" — the regression it guards could silently stop being covered.

assert not errors, f"Unexpected errors during concurrent execution: {errors}"
assert seen

Fix: Assert that the version actually advanced during the run (e.g. assert max(seen) > min(seen)) so a dead writer fails the test.


Automated review by Kōan (Claude) HEAD=be7cc6c 5 min 44s

@greptile-apps

greptile-apps Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Thanks for the thorough re-review. The two remaining suggestions are valid follow-ups, but neither is blocking for this fix: the 32-bit MSVC tearing window is extremely narrow, and the helper refactor is cleanup rather than a correctness issue. The race fix itself is complete and the test/TSan coverage is sufficient.

@greptile-apps

greptile-apps Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

The high-severity finding at multidict/_multilib/hashtable.h:1729 is valid and should be fixed before merge: after _md_del_at() can run __del__ and permit another thread to mutate the object, the comparison still performs a plain read of md->version against an atomic store. Use atomic_load_uint64_relaxed(&md->version) (or md_version(md)) in that guard.

The remaining findings are non-blocking test-hardening suggestions. Capturing writer exceptions would ensure failed mutations are reported through the test rather than only through threading.excepthook; asserting that the version advanced would also confirm that mutation pressure actually occurred. Finding 4 is not broadly applicable because the other plain reads are protected by their critical sections, while this post-__del__ check is unlocked.

The MSVC 32-bit uint64_t load/store concern is a separate portability issue: those helpers can tear on 32-bit x86 and should mirror the existing _InterlockedCompareExchange64/_InterlockedExchange64 handling if win32 free-threaded builds are supported.

@aiolibsbot

Copy link
Copy Markdown
Contributor

Rebase with requested adjustments

Branch fix-md-version-atomic was rebased onto master and review feedback was applied.

Warning

Force-push safety check — the rewrite of fix-md-version-atomic needs attention.

Commits whose patch changed in-flight and whose content could not be verified as preserved — check these survived:

  • bd5cf9f Fix a data race on md->version in free-threaded builds

Previous PR head: be7cc6c4350ae02cc8f56812da25b2546bce5f0e — everything it contained is recoverable: git fetch origin be7cc6c4350ae02cc8f56812da25b2546bce5f0e && git switch -c koan-prerebase-be7cc6c4350a FETCH_HEAD

Changes applied

  • Changes complete.
  • Converted every remaining plain read of md->version to atomic_load_uint64_relaxed() across hashtable.h, finder.h, identity.h, update_marks.h, per review items 3 and 4. Covers the goto restart guard in md_pop_all (hashtable.h:1732), where a plain load next to an atomic store let the compiler fold the condition to false, and the ~20 "changed during iteration" guards that follow calls able to run arbitrary Python. Field now has one consistent access discipline.
  • Wrapped the writer thread body in try/except appending to errors (tests/test_free_threading.py), per review item 5, so a broken mutation path fails the test instead of only hitting threading.excepthook.
  • Replaced the vacuous assert seen with assert max(seen) > min(seen) per review item 6; readers fill seen regardless of the writer, so the old assertion could not detect a dead writer.
  • Ran clang-format on the touched headers; gcc -fsyntax-only -std=c11 and ruff check/format pass.

Not changed (and why)

  • greptile "Cover the exception path" (# pragma: no cover on the worker handler): agreed with asvetlov that it stands. Branch fires only on a genuine race; nothing in-process can drive it deterministically, and detection lives in the TSan job. greptile acknowledged the test-only scope. The new writer handler carries the same pragma for the same reason.
  • greptile "Synchronize reader startup": already fixed before this pass in commit 1755271, which added the `thread

Stats

7 files changed, 179 insertions(+), 43 deletions(-)
Actions performed
  • Already-solved check: negative (confidence=high, reasoning=Master still has plain md->version = ... stores at every mutation site and a plain load in `md_ver)
  • Resolved merge conflicts (1 round(s))
  • Rebased fix-md-version-atomic onto upstream/master
  • Applied review feedback
  • Pre-push CI check: no CI runs found
  • Force-pushed fix-md-version-atomic to origin
  • Private review gate skipped: disabled by config
  • Force-push guard: original PR content was dropped, modified, or raced — see the warning at the top of this comment
  • CI check enqueued in ## CI (async)

CI status

CI will be checked asynchronously.


Automated by Kōan

…aring

_md_pop_all_locked's restart check compared md->version with a plain
read after _md_del_at(), which can run a __del__ that suspends the
critical section and lets another thread bump the version through the
atomic store just above. Use atomic_load_uint64_relaxed there too.

Also fixed atomic_load_uint64_relaxed/atomic_store_uint64_relaxed on
32-bit x86 MSVC: a plain 64-bit load/store there is two 32-bit
accesses and can tear. Route both through _InterlockedCompareExchange64,
matching the existing 32-bit fallback in atomic_fetch_add_uint64_relaxed.
Comment thread tests/test_free_threading.py Resolved
@asvetlov
asvetlov merged commit e1f3292 into aio-libs:master Sep 22, 2026
61 checks passed
@asvetlov
asvetlov deleted the fix-md-version-atomic branch September 22, 2026 17:31
asvetlov added a commit to asvetlov/multidict that referenced this pull request Sep 22, 2026
… fix

master (aio-libs#1514) made md_version() an atomic relaxed read, matching
md_len(). Update the note and the Atomic bucket's definition in the
new Thread safety section accordingly, since it previously described
this counter as a best-effort, unsynchronized read that is no longer
accurate.
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.

2 participants