Skip to content

Fix a data race on entry->hash between getall()/update() and lock-free reads - #1448

Merged
asvetlov merged 4 commits into
aio-libs:masterfrom
asvetlov:fix-entry-hash-race-race
Sep 13, 2026
Merged

asvetlov merged 4 commits into
aio-libs:masterfrom
asvetlov:fix-entry-hash-race-race

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

getall()/popall() (via md_find_next()/md_finder_cleanup()) and
update()/extend()/merge() (via md_post_update()) mark and unmark
a matching entry's hash while holding self's critical section. That
excludes other mutators but not a lock-free reader: __contains__ and
get()/getone()/__getitem__ load the same field with an atomic op
and no lock at all. The mark/unmark writes were plain, non-atomic
stores, racing that atomic load under the free-threaded build. This
routes them through the existing _md_entry_store_hash() helper,
matching the pattern _md_replace()/_md_update() already use for the
same mark bit.

Note this is unrelated to and much cheaper than the approach tried in
#1442 (which replaced the marking scheme entirely and was withdrawn for
a large performance regression): the fix here keeps the existing
in-place marking and only makes the one racy write atomic, at the cost
of a relaxed atomic store in place of a plain one.

Are there changes in behavior for the user?

No. This only affects the free-threaded build's internal memory-model
correctness; there is no change to observable behavior.

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 hashtable.h.

Related issue number

N/A

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: no CONTRIBUTORS.txt in this repo)
  • 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
Agent run details (optional, for reviewers)

Tests: pytest -q against the default C-extension build (1839 passed),
a free-threaded debug build (MULTIDICT_DEBUG_BUILD=1 on CPython
3.14.7 free-threaded, 1834 passed, 5 skipped), and the pure-Python leg
(MULTIDICT_NO_EXTENSIONS=1, pytest -q --no-c-extensions, 926
passed). New test:
tests/test_multidict.py::test_getall_update_vs_lock_free_reads_thread_safety,
marked c_extension, races getall()/update() against lock-free
contains()/get() on never-deleted keys.

Lint: pre-commit run (ruff, clang-format, mypy) passed on the changed
files.

Docs: make doc-spelling passed with no wordlist additions needed.

Drafted with Claude Code (Sonnet 5); reviewed by asvetlov.

…e reads

getall()/popall() (via md_find_next()/md_finder_cleanup()) and
update()/extend()/merge() (via md_post_update()) mark and unmark a
matching entry's hash while holding self's critical section. That
excludes other mutators but not a lock-free reader: __contains__ and
get()/getone()/__getitem__ load the same field with an atomic op and
no lock at all. The mark/unmark writes were plain, non-atomic stores,
racing that atomic load under the free-threaded build. Route them
through the existing _md_entry_store_hash() helper, matching the
pattern _md_replace()/_md_update() already use for the same mark bit.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 13, 2026
@codspeed

codspeed Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 248 untouched benchmarks


Comparing asvetlov:fix-entry-hash-race-race (e6f2ef5) with master (1f8fef9)

Open in CodSpeed

@codecov

codecov Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (1f8fef9) to head (e6f2ef5).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1448   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           31        31           
  Lines         4449      4471   +22     
  Branches       337       341    +4     
=========================================
+ Hits          4449      4471   +22     
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 marked this pull request as ready for review September 13, 2026 20:47
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 13, 2026 20:47
@asvetlov
asvetlov enabled auto-merge (squash) September 13, 2026 20:47
@asvetlov
asvetlov disabled auto-merge September 13, 2026 20:51
@asvetlov
asvetlov enabled auto-merge (squash) September 13, 2026 20:51
@greptile-apps

greptile-apps Bot commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge based on the available build and concurrent regression evidence.

No actionable findings were established.

Files Needing Attention: None.

T-Rex T-Rex Logs

What T-Rex did

  • Ran the regression test for test_getall_update_vs_lock_free_reads_thread_safety using the specified Python interpreter and working directory, and observed 1 passed in 0.04s with exit code 0.
  • Inspected the test run environment to confirm the interpreter, Python version, and extension origin were loaded as expected.
  • Verified the configuration shows Py_GIL_DISABLED=None and free_threaded_path_exercisable=False, so the free-threaded atomic path was not engaged.
  • Performed an editable reinstall of multidict, which rebuilt and installed successfully with exit code 0.

View all artifacts

T-Rex Ran code and verified through T-Rex

Reviews (1): Last reviewed commit: "Merge branch 'master' into fix-entry-has..." | Re-trigger Greptile

@asvetlov
asvetlov merged commit 80632eb into aio-libs:master Sep 13, 2026
56 of 57 checks passed
@asvetlov
asvetlov deleted the fix-entry-hash-race-race branch September 13, 2026 20:58
asvetlov added a commit that referenced this pull request Sep 13, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`to_dict()` (via `md_to_dict()`) marks every entry's hash while it walks
the table to collect keys, then clears all the marks in one pass via
`_md_restore_all_hashes()`, while holding `self`'s critical section.
That
excludes other mutators but not a lock-free reader: `__contains__` and
`get()`/`getone()`/`__getitem__` load the same field with an atomic op
and no lock at all. `_md_restore_all_hashes()`'s clear was a plain,
non-atomic store, racing that atomic load under the free-threaded
build. This routes it through the existing `_md_entry_store_hash()`
helper, matching the pattern already used for the sibling mark/unmark
sites in `md_find_next()`/`md_finder_cleanup()`/`md_post_update()`
fixed by #1448.

This is a C-extension-only fix: the pure-Python `to_dict()` has no
equivalent hash-marking scheme, so there is nothing to change there.

## Are there changes in behavior for the user?

No. This only affects the free-threaded build's internal memory-model
correctness; there is no change to observable behavior.

## 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 `hashtable.h`.

## Related issue number

Found via a Greptile review comment on #1447; not otherwise linked to
an issue.

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

Race confirmed with ThreadSanitizer (clang 21, `-fsanitize=thread`,
`LD_PRELOAD`ed into a CPython 3.14.7 free-threaded build): on the
pre-fix code, TSan reports a data race between the plain store in
`_md_restore_all_hashes()` (hashtable.h:1748) and the atomic load in
`_md_entry_load_hash()` reached from both `get()`
(`_md_get_one_lockfree`) and `__contains__` (`_md_contains_lockfree`).
After the fix, that report is gone; only an unrelated, pre-existing
CPython-internal biased-refcounting race remains, present identically
before and after.

New test:
`tests/test_multidict.py::test_to_dict_vs_lock_free_reads_thread_safety`,
marked `c_extension`, races `to_dict()` against lock-free
`contains()`/`get()` on never-deleted keys.

Tests: `pytest -q` against the default C-extension build (1897
passed), a free-threaded debug build (`MULTIDICT_DEBUG_BUILD=1` on
CPython 3.14.7 free-threaded, `--c-extensions`, 1892 passed, 5
skipped), and the pure-Python leg (`MULTIDICT_NO_EXTENSIONS=1`, 1897
passed).

Lint: `pre-commit run` (ruff, clang-format, mypy) passed on the changed
files.

Docs: `make doc-spelling` passed with no wordlist additions needed.

Drafted with Claude Code (Sonnet 5); reviewed by asvetlov.

</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