Title: Segfault in _pickle.c:batch_dict_exact when pickling dict with concurrent mutation (free-threading) · Issue #146452 · python/cpython · GitHub
Open Graph Title: Segfault in _pickle.c:batch_dict_exact when pickling dict with concurrent mutation (free-threading) · Issue #146452 · python/cpython
X Title: Segfault in _pickle.c:batch_dict_exact when pickling dict with concurrent mutation (free-threading) · Issue #146452 · python/cpython
Description: Bug report Bug description I've been testing the free-threaded build for thread safety issues in unaudited modules (ref #116738 — _pickle.c is unchecked). Found a segfault when pickle.dumps() runs concurrently with dict mutations on the ...
Open Graph Description: Bug report Bug description I've been testing the free-threaded build for thread safety issues in unaudited modules (ref #116738 — _pickle.c is unchecked). Found a segfault when pickle.dumps() runs ...
X Description: Bug report Bug description I've been testing the free-threaded build for thread safety issues in unaudited modules (ref #116738 — _pickle.c is unchecked). Found a segfault when pickle.dumps() r...
Opengraph URL: https://github.com/python/cpython/issues/146452
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Segfault in _pickle.c:batch_dict_exact when pickling dict with concurrent mutation (free-threading)","articleBody":"# Bug report\n\n### Bug description\n\nI've been testing the free-threaded build for thread safety issues in unaudited modules (ref #116738 — `_pickle.c` is unchecked). Found a segfault when `pickle.dumps()` runs concurrently with dict mutations on the same dict.\n\nThe crash happens in `batch_dict_exact` at `Modules/_pickle.c:3496` — it iterates dict items via `_PyDict_Next` which gives borrowed references, but there's no critical section on the dict. If another thread pops or replaces a key mid-iteration, the borrowed reference goes stale and `Py_INCREF` hits a freed/NULL pointer.\n\nSometimes it raises `RuntimeError: dictionary changed size during iteration` cleanly, but other times the reference gets invalidated before the size check and it just segfaults.\n\n### Reproducer\n\n```python\nimport pickle\nimport threading\n\nshared = {str(i): list(range(50)) for i in range(100)}\n\nfor trial in range(2000):\n barrier = threading.Barrier(3)\n\n def dumper():\n try:\n barrier.wait()\n pickle.dumps(shared)\n except Exception:\n pass\n\n def mutator():\n try:\n barrier.wait()\n for j in range(200):\n key = str(j % 100)\n shared[key] = list(range(j % 50))\n if j % 10 == 0:\n shared.pop(str(j % 100), None)\n shared[str(j % 100)] = [j]\n except Exception:\n pass\n\n threads = [\n threading.Thread(target=dumper),\n threading.Thread(target=dumper),\n threading.Thread(target=mutator),\n ]\n for t in threads: t.start()\n for t in threads: t.join()\n```\n\nCrashes within a few hundred iterations usually. I ran it 10 times, got 9 segfaults.\n\n### Tested on\n\n**3.14.0a4 free-threading (stock install, no sanitizers):**\n```\n$ python3.14t reproducer.py\nSegmentation fault (core dumped)\n```\n\n**3.15.0a7+ free-threading (built with `--with-address-sanitizer`):**\n```\nAddressSanitizer:DEADLYSIGNAL\n==1334802==ERROR: AddressSanitizer: SEGV on unknown address 0x00000000000c\n #0 _Py_atomic_load_uint32_relaxed Include/cpython/pyatomic_gcc.h:367\n #1 Py_INCREF Include/refcount.h:267\n #2 batch_dict_exact Modules/_pickle.c:3496\n #3 save_dict Modules/_pickle.c:3563\n #4 save Modules/_pickle.c:4568\n #5 dump Modules/_pickle.c:4768\n #6 _pickle_dumps_impl Modules/_pickle.c:7992\n```\n\n### Root cause\n\n- `batch_dict_exact` calls `PyDict_Next()` which returns borrowed references to key and value\n- Between `PyDict_Next()` returning and `Py_INCREF(key)` / `Py_INCREF(value)`, another thread can mutate the dict\n- The borrowed reference points to a freed object, `Py_INCREF` dereferences it and segfaults\n- The size check at line 3512 (`PyDict_GET_SIZE(obj) != dict_size`) only catches mutations that change dict size, and only after the batch — too late to prevent the stale reference\n- Same issue exists in both the single-item path (line 3474) and the batch loop (line 3494)\n\n### Possible fix\n\n- Wrap `PyDict_Next()` + `Py_INCREF(key)` + `Py_INCREF(value)` in `Py_BEGIN_CRITICAL_SECTION(obj)` / `Py_END_CRITICAL_SECTION()` to prevent dict mutation while converting borrowed refs to owned refs\n- Keep `save()` calls outside the critical section since they can reenter Python\n- Same approach as the set iteration path at line 3644 which already uses `Py_BEGIN_CRITICAL_SECTION(obj)` with `_PySet_NextEntryRef`\n- Both `PyDict_Next` call sites in `batch_dict_exact` need this (line 3474 and line 3494)\n\n### CPython versions tested on\n\n3.14, CPython main branch\n\n### Operating systems tested on\n\nLinux\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-146470\n* gh-149940\n* gh-150025\n* gh-150039\n* gh-150062\n* gh-150261\n* gh-150262\n* gh-150263\n* gh-150292\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/overlorde","@type":"Person","name":"overlorde"},"datePublished":"2026-03-26T07:51:32Z","url":"https://github.com/python/cpython/issues/146452"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:588f30eb-79a9-add4-e859-e491a8d1d93e |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | BCD0:ADA9D:39F4DA0:4A4DE55:6B01F35C |
| html-safe-nonce | bc21773f6808e203b9c4e9c2a360df98093e18cdc4ffcf6e9f407531eeaaa4bd |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCQ0QwOkFEQTlEOjM5RjREQTA6NEE0REU1NTo2QjAxRjM1QyIsInZpc2l0b3JfaWQiOiI2NDY4MTE4NDM0ODYwMzY0NjM2IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 3109bd53cfad658d96c5905d4a89054a8f628b0d29e63f40a18b219034d0c964 |
| hovercard-subject-tag | issue:4141521889 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/146452/issue_layout |
| twitter:image | https://opengraph.githubassets.com/45c9b19e07d5e3b4822bfc1f102f5418956ce540ca32c9a2f3ec8bf3c9da17db/python/cpython/issues/146452 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/45c9b19e07d5e3b4822bfc1f102f5418956ce540ca32c9a2f3ec8bf3c9da17db/python/cpython/issues/146452 |
| og:image:alt | Bug report Bug description I've been testing the free-threaded build for thread safety issues in unaudited modules (ref #116738 — _pickle.c is unchecked). Found a segfault when pickle.dumps() runs ... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | overlorde |
| hostname | github.com |
| expected-hostname | github.com |
| None | 87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 423dbb54c5e7bfecc838eb387c1435eb3d0e760d |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width