Skip to content

gh-146452: Fix pickle segfault when pickling dict with concurrent mutation#146470

Open
overlorde wants to merge 2 commits intopython:mainfrom
overlorde:fix-issue-146452
Open

gh-146452: Fix pickle segfault when pickling dict with concurrent mutation#146470
overlorde wants to merge 2 commits intopython:mainfrom
overlorde:fix-issue-146452

Conversation

@overlorde
Copy link
Contributor

@overlorde overlorde commented Mar 26, 2026

batch_dict_exact() in _pickle.c iterates dict items using PyDict_Next() which returns borrowed references. Without a critical section, a concurrent dict mutation can invalidate the borrowed reference before Py_INCREF, causing a segfault.

The fix wraps PyDict_Next() + Py_INCREF in Py_BEGIN_CRITICAL_SECTION(obj) to prevent the dict from being mutated while converting borrowed refs to owned refs. Same approach as the existing set iteration path in the same file (line 3656).

Crashes on both 3.14t (stock install) and main (with ASan). Reproducer in the linked issue.

  • Existing test_pickle passes (1000 tests, no regressions)
  • Added test_free_threading/test_pickle.py that segfaults without the fix and passes with it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant