Skip to content

Fix a data race on entry->hash in to_dict()'s mark cleanup - #1450

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:fix-restore-all-hashes-race
Sep 13, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:fix-restore-all-hashes-race

Conversation

@asvetlov

Copy link
Copy Markdown
Member

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

  • 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)

Race confirmed with ThreadSanitizer (clang 21, -fsanitize=thread,
LD_PRELOADed 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.

_md_restore_all_hashes() cleared to_dict()'s temporary "seen" mark on
every entry with a plain, non-atomic store, while a lock-free
__contains__/get() on another thread loads the same field with an
atomic operation and no lock at all under the free-threaded build.
This routes the clear 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() (aio-libs#1448).

C-extension only; the pure-Python to_dict() has no equivalent
hash-marking scheme.
@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 improve performance by 11.29%

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

⚡ 4 improved benchmarks
✅ 244 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_multidict_getall_str_hit[cs-c] 38 ms 33.6 ms +13.13%
⚡ test_multidict_getall_str_hit[ci-c] 38.8 ms 34.7 ms +11.75%
⚡ test_cimultidict_getall_istr_hit[c] 36.8 ms 33.1 ms +11.12%
⚡ test_cimultidict_getall_istr_hit_nonascii[c] 28 ms 25.7 ms +9.2%

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-restore-all-hashes-race (5a0beb2) with master (80632eb)

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 (80632eb) to head (5a0beb2).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1450   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           31        31           
  Lines         4471      4489   +18     
  Branches       341       344    +3     
=========================================
+ Hits          4471      4489   +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.

@asvetlov
asvetlov marked this pull request as ready for review September 13, 2026 23:21
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 13, 2026 23:21
@asvetlov
asvetlov merged commit a5ea24c into aio-libs:master Sep 13, 2026
55 of 56 checks passed
@asvetlov
asvetlov deleted the fix-restore-all-hashes-race branch September 13, 2026 23:21
@greptile-apps

greptile-apps Bot commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

No actionable issue was established, and nothing found in this change blocks merging.

No review comments or severity-bearing execution findings remain. The focused native regression passed, though the free-threaded runtime path is unavailable in this environment.

Files Needing Attention: None.

T-Rex T-Rex Logs

What T-Rex did

  • Validated that the focused regression is introduced by this PR and is absent from HEAD^.
  • Ran the supplied test against the checked-out native extension and confirmed it passes.
  • Captured environment details to explain why the result does not indicate free-threaded safety.

View all artifacts

T-Rex Ran code and verified through T-Rex

Reviews (1): Last reviewed commit: "Fix a data race on entry->hash in to_dic..." | Re-trigger Greptile

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