Title: Sharing a dict iterator across threads double-DECREFs di_dict under free-threading · Issue #154130 · python/cpython · GitHub
Open Graph Title: Sharing a dict iterator across threads double-DECREFs di_dict under free-threading · Issue #154130 · python/cpython
X Title: Sharing a dict iterator across threads double-DECREFs di_dict under free-threading · Issue #154130 · python/cpython
Description: Crash report What happened? On a free-threaded build, advancing a single, shared dict iterator (iter({...})) from multiple threads double-frees the underlying dict and crashes. All three dict iterators (dict_keyiterator / dict_valueitera...
Open Graph Description: Crash report What happened? On a free-threaded build, advancing a single, shared dict iterator (iter({...})) from multiple threads double-frees the underlying dict and crashes. All three dict itera...
X Description: Crash report What happened? On a free-threaded build, advancing a single, shared dict iterator (iter({...})) from multiple threads double-frees the underlying dict and crashes. All three dict itera...
Opengraph URL: https://github.com/python/cpython/issues/154130
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Sharing a dict iterator across threads double-DECREFs di_dict under free-threading","articleBody":"# Crash report\n\n### What happened?\n\nOn a free-threaded build, advancing a single, shared `dict` iterator (`iter({...})`) from multiple threads double-frees the underlying dict and crashes.\n\nAll three dict iterators (`dict_keyiterator` / `dict_valueiterator` / `dict_itemiterator`) route `next()` through `dictiter_iternext_threadsafe` (`Objects/dictobject.c`). Its exhaustion path drops the iterator's owning reference to the dict:\n\n```c\nfail:\n di->di_dict = NULL; /* non-atomic clear */\n Py_DECREF(d); /* drop the iterator's ONE owning ref to the dict */\n return -1;\n```\n\nand the caller reads that reference with no lock:\n\n```c\nstatic PyObject*\ndictiter_iternextkey(PyObject *self)\n{\n dictiterobject *di = (dictiterobject *)self;\n PyDictObject *d = di->di_dict; /* plain read */\n if (d == NULL)\n return NULL;\n PyObject *value;\n if (dictiter_iternext_threadsafe(d, self, &value, NULL) \u003c 0) {\n value = NULL;\n }\n return value;\n}\n```\n\nThe iterator holds exactly one reference to the dict (`di_dict`). Two threads calling `next()` on the same near-exhausted iterator interleave as: both read `d = di->di_dict` (non-NULL), both reach `fail:`, and both run `Py_DECREF(d)`. The second `Py_DECREF` has no matching reference — the dict's refcount underflows / it is freed one owner too early, and a sibling thread still walking `d` (and the dict freelist / keys object) then touches freed memory.\n\nThis `fail: di->di_dict = NULL; Py_DECREF(d)` pattern predates free-threading (it is correct under the GIL, where only one thread runs the iterator); the lock-free `dictiter_iternext_threadsafe` wrapper carried it over unguarded.\n\n### Reproducer\n\n```python\nimport threading\n\nNT = 8\nITERS = 200_000\n\ndef newit():\n return iter({k: k for k in range(32)})\n\ncell = [newit()]\n\ndef worker():\n for _ in range(ITERS):\n it = cell[0]\n try:\n next(it) # dictiter_iternextkey -> dictiter_iternext_threadsafe\n except StopIteration:\n cell[0] = newit() # refill so the fail: (exhaustion) path is hit repeatedly\n except Exception:\n pass\n\nthreads = [threading.Thread(target=worker) for _ in range(NT)]\nfor t in threads: t.start()\nfor t in threads: t.join()\nprint(\"done, no crash\")\n```\n\n`PYTHON_GIL=0 ./python repro.py` on a free-threaded build:\n\n- **Debug build → SIGABRT within seconds, ~8/8 runs**, with `_Py_NegativeRefcount` on the dict (`Objects/dictobject.c:6159`), plus downstream corruption faces as the freed dict/keys object is reused (`dictkeys_incref` immortal-refcount assert `:484`; `new_dict` type assert `:978`; `clear_freelist` `Objects/object.c:909`; `validate_refcounts` in `gc_free_threading.c`).\n- **Release build (`-O0`, no sanitizer) → SIGSEGV** (use-after-free), or occasionally `Fatal Python error: PyMutex_Unlock: unlocking mutex that is not locked` from the corrupted dict mutex.\n\nSo it is neither debug-only nor sanitizer-only. Debug backtrace (the negative-refcount object **is** the dict `d`):\n\n```\n#8 _PyObject_AssertFailed (obj=0x...dict...) at Objects/object.c:3278\n#9 _Py_NegativeRefcount at Objects/object.c:275\n#12 Py_DECREF at ./Include/refcount.h:363\n#13 dictiter_iternext_threadsafe (d=0x...dict...) at Objects/dictobject.c:6159 \u003c-- fail: Py_DECREF(d)\n#14 dictiter_iternextkey at Objects/dictobject.c:5791\n#15 builtin_next at Python/bltinmodule.c:1776\n```\n\n### Suggested fix\n\nConsume the reference atomically so exactly one thread performs the DECREF:\n\n```c\nfail:\n PyDictObject *old = _Py_atomic_exchange_ptr(&di->di_dict, NULL);\n if (old != NULL) {\n Py_DECREF(old);\n }\n return -1;\n```\n\nand keep the dict alive for the duration of the lock-free walk (the caller uses `d` and its keys/values across the whole `dictiter_iternext_threadsafe` body) so a sibling that wins the exchange cannot free it mid-iteration — take a strong reference or the dict's critical section for the walk. One fix covers keys/values/items, since all three route through `dictiter_iternext_threadsafe`.\n\n### Why this is not the documented value-benign iterator race\n\nThis function was written to be shared across threads, and a crash is explicitly out of contract:\n\n- The lock-free dict iterator `dictiter_iternext_threadsafe` was added by **gh-112075 / PR #115108** (\"Iterating a dict shouldn't require locks\"), under the umbrella **gh-112075** (\"Make `dict` objects thread-safe in `--disable-gil` builds\"). PR #115108 states it \"[handles] races against the dict as well as **allowing the iterator to be used from multiple threads simultaneously**.\" It made the *value read* safe (`_Py_TryIncrefCompare` / `acquire_key_value`) but carried the old `fail: di->di_dict = NULL; Py_DECREF(d)` exhaustion path in unchanged — hence this double-free.\n- **gh-120496** (\"Sequence iterator thread-safety\") decided *not* to fix the fact that concurrent iteration can return duplicate/skipped values, and documented it instead (only the `Doc/glossary.rst` note, PR #120685, merged; the code-fix PRs were closed). But the contract agreed on that issue is explicit — @colesbury and @eendebakpt: iterating from multiple threads \"**will not crash the interpreter**\" (that's the acceptable line; wrong values are OK, crashes are not), and @eendebakpt flagged \"the risks of **overflows inside the C code**.\"\n- **gh-148873** reported this iterator's data-race face and was **closed as a duplicate of gh-120496** — folding a double-free into the value-benign class. That is the gap this issue closes: the same unsynchronized clear-and-DECREF is not benign — it double-frees the dict and crashes (negative refcount / UAF / SIGSEGV) on plain free-threaded builds, which gh-120496 / gh-124397 put squarely on the not-acceptable side.\n\n*(Found by `fusil --tsan`, a ThreadSanitizer fuzzer; crash confirmed by re-running the reproducer without a sanitizer on a plain free-threaded build. Draft and reproducer by Claude Code, minimized and reviewed by hand.)*\n\n\n### CPython versions tested on:\n\nCPython main branch\n\n### Operating systems tested on:\n\nLinux\n\n### Output from running 'python -VV' on the command line:\n\nPython 3.16.0a0 free-threading build (heads/main:a1d580430c8, Jul 18 2026, 20:23:36) [Clang 21.1.8 (6ubuntu1)]\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-160312\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/devdanzin","@type":"Person","name":"devdanzin"},"datePublished":"2026-07-19T13:29:24Z","url":"https://github.com/python/cpython/issues/154130"}
| 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:5c7c36d2-d6f7-f19b-5c0b-0280cbc87def |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | BBC2:3E4205:33BE4C8:451FDCA:6B02027A |
| html-safe-nonce | 925938d5e60632fd4adf074dfa08c9c1a6d8f9824c7e0c99abd56a6749aab512 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCQkMyOjNFNDIwNTozM0JFNEM4OjQ1MUZEQ0E6NkIwMjAyN0EiLCJ2aXNpdG9yX2lkIjoiNjU5Nzc5MTcwMDkxNDE0Mzg2NiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | d641f661d0ead255b6800c572f04a96da270a92fa379da5a9f97e2b473f9afdc |
| hovercard-subject-tag | issue:4922854896 |
| 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/154130/issue_layout |
| twitter:image | https://opengraph.githubassets.com/eb05c0840779e9af320e099f407d23b29d6633724ac48efc7fb6438a0ed23cbe/python/cpython/issues/154130 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/eb05c0840779e9af320e099f407d23b29d6633724ac48efc7fb6438a0ed23cbe/python/cpython/issues/154130 |
| og:image:alt | Crash report What happened? On a free-threaded build, advancing a single, shared dict iterator (iter({...})) from multiple threads double-frees the underlying dict and crashes. All three dict itera... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | devdanzin |
| 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