René's URL Explorer Experiment


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

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@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-profiling0
react-import-mapreact,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-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:5c7c36d2-d6f7-f19b-5c0b-0280cbc87def
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idBBC2:3E4205:33BE4C8:451FDCA:6B02027A
html-safe-nonce925938d5e60632fd4adf074dfa08c9c1a6d8f9824c7e0c99abd56a6749aab512
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCQkMyOjNFNDIwNTozM0JFNEM4OjQ1MUZEQ0E6NkIwMjAyN0EiLCJ2aXNpdG9yX2lkIjoiNjU5Nzc5MTcwMDkxNDE0Mzg2NiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmacd641f661d0ead255b6800c572f04a96da270a92fa379da5a9f97e2b473f9afdc
hovercard-subject-tagissue:4922854896
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/154130/issue_layout
twitter:imagehttps://opengraph.githubassets.com/eb05c0840779e9af320e099f407d23b29d6633724ac48efc7fb6438a0ed23cbe/python/cpython/issues/154130
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/eb05c0840779e9af320e099f407d23b29d6633724ac48efc7fb6438a0ed23cbe/python/cpython/issues/154130
og:image:altCrash 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:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamedevdanzin
hostnamegithub.com
expected-hostnamegithub.com
None87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456
turbo-cache-controlno-preview
go-importgithub.com/python/cpython git https://github.com/python/cpython.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id81598961
octolytics-dimension-repository_nwopython/cpython
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id81598961
octolytics-dimension-repository_network_root_nwopython/cpython
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release423dbb54c5e7bfecc838eb387c1435eb3d0e760d
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/python/cpython/issues/154130#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F154130
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F154130
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=python%2Fcpython
Reloadhttps://github.com/python/cpython/issues/154130
Reloadhttps://github.com/python/cpython/issues/154130
Reloadhttps://github.com/python/cpython/issues/154130
pythonhttps://github.com/python
cpythonhttps://github.com/python/cpython
Codehttps://github.com/python/cpython
Issues5k+ (5k+)https://github.com/python/cpython/issues
Pull requests2.4k (2.4k)https://github.com/python/cpython/pulls
Actionshttps://github.com/python/cpython/actions
Projectshttps://github.com/python/cpython/projects
Security and qualityhttps://github.com/python/cpython/security
Insightshttps://github.com/python/cpython/insights
https://github.com/python/cpython
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/154130
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/154130
Sharing a dict iterator across threads double-DECREFs di_dict under free-threadinghttps://github.com/python/cpython/issues/154130#top
interpreter-core(Objects, Python, Grammar, and Parser dirs)https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
topic-free-threadinghttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-free-threading%22
type-crashA hard crash of the interpreter, possibly with a core dumphttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-crash%22
https://github.com/devdanzin
devdanzinhttps://github.com/devdanzin
on Jul 19, 2026https://github.com/python/cpython/issues/154130#issue-4922854896
Make dict objects thread-safe in --disable-gil builds #112075https://github.com/python/cpython/issues/112075
gh-112075: Iterating a dict shouldn't require locks #115108https://github.com/python/cpython/pull/115108
Make dict objects thread-safe in --disable-gil builds #112075https://github.com/python/cpython/issues/112075
gh-112075: Iterating a dict shouldn't require locks #115108https://github.com/python/cpython/pull/115108
Sequence iterator thread-safety #120496https://github.com/python/cpython/issues/120496
gh-120496: Add a note about iterator thread-safe #120685https://github.com/python/cpython/pull/120685
@colesburyhttps://github.com/colesbury
@eendebakpthttps://github.com/eendebakpt
@eendebakpthttps://github.com/eendebakpt
Possible data race in dictiter_iternext with with free-threading build #148873https://github.com/python/cpython/issues/148873
Sequence iterator thread-safety #120496https://github.com/python/cpython/issues/120496
Sequence iterator thread-safety #120496https://github.com/python/cpython/issues/120496
Strategy for Iterators in Free Threading #124397https://github.com/python/cpython/issues/124397
gh-154130: Fix double decref of the dict in shared dict iterators #160312https://github.com/python/cpython/pull/160312
devdanzinhttps://github.com/devdanzin
interpreter-core(Objects, Python, Grammar, and Parser dirs)https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
type-crashA hard crash of the interpreter, possibly with a core dumphttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-crash%22
topic-free-threadinghttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-free-threading%22
on Jul 19, 2026https://github.com/python/cpython/issues/154130#event-28180297538
devdanzinhttps://github.com/devdanzin
on Jul 19, 2026https://github.com/python/cpython/issues/154130#event-28180328284
TSAN-0053: FILED as python/cpython#154130 (status=reported)https://github.com/devdanzin/cpython-tsan-findings/commit/e4fb377783579363488478a317bf0ccf5cbbac1d
python/cpython#154130https://github.com/python/cpython/issues/154130
e4fb377https://github.com/devdanzin/cpython-tsan-findings/commit/e4fb377783579363488478a317bf0ccf5cbbac1d
https://github.com/BHUVANSH855
BHUVANSH855https://github.com/BHUVANSH855
on Jul 19, 2026https://github.com/python/cpython/issues/154130#issuecomment-5016909295
https://github.com/devdanzin
devdanzinhttps://github.com/devdanzin
on Jul 19, 2026https://github.com/python/cpython/issues/154130#issuecomment-5017231860
#154014https://github.com/python/cpython/issues/154014
gh-112075https://github.com/python/cpython/issues/112075
#115108https://github.com/python/cpython/pull/115108
https://github.com/devdanzin
devdanzinhttps://github.com/devdanzin
on Jul 20, 2026https://github.com/python/cpython/issues/154130#issuecomment-5018008974
https://github.com/BHUVANSH855
BHUVANSH855https://github.com/BHUVANSH855
on Jul 20, 2026https://github.com/python/cpython/issues/154130#issuecomment-5019577814
https://github.com/devdanzin
devdanzinhttps://github.com/devdanzin
on Jul 20, 2026https://github.com/python/cpython/issues/154130#issuecomment-5023529639
Sequence iterator thread-safety #120496https://github.com/python/cpython/issues/120496
@colesburyhttps://github.com/colesbury
gh-112075https://github.com/python/cpython/issues/112075
#115108https://github.com/python/cpython/pull/115108
https://github.com/devdanzin
devdanzinhttps://github.com/devdanzin
on Jul 21, 2026https://github.com/python/cpython/issues/154130#issuecomment-5035339034
#152125https://github.com/python/cpython/issues/152125
mpagehttps://github.com/mpage
on Oct 22, 2026https://github.com/python/cpython/issues/154130#event-33983477513
pythongh-154130: Fix double decref of the dict in shared dict iteratorshttps://github.com/mpage/cpython/commit/c41fa1f55364b18b3a3c71e1982f0dfde145ff90
pythongh-154130https://github.com/python/cpython/issues/154130
c41fa1fhttps://github.com/mpage/cpython/commit/c41fa1f55364b18b3a3c71e1982f0dfde145ff90
pythongh-154130: Fix double decref of the dict in shared dict iteratorshttps://github.com/mpage/cpython/commit/f29f11e266534ee228717460cf0ca9272aba532c
pythongh-154130https://github.com/python/cpython/issues/154130
f29f11ehttps://github.com/mpage/cpython/commit/f29f11e266534ee228717460cf0ca9272aba532c
pythongh-154130: Fix double decref of the dict in shared dict iteratorshttps://github.com/mpage/cpython/commit/364cc82ab2d924eeda3f5c49b69318702f73f40c
pythongh-154130https://github.com/python/cpython/issues/154130
364cc82https://github.com/mpage/cpython/commit/364cc82ab2d924eeda3f5c49b69318702f73f40c
kumaraditya303https://github.com/kumaraditya303
on Nov 20, 2026https://github.com/python/cpython/issues/154130#event-36764161106
Merge remote-tracking branch 'upstream/main' into pythongh-154130-dic…https://github.com/mpage/cpython/commit/5c501324f3f9ae788b8400685bc4087de0dda059
pythongh-154130https://github.com/python/cpython/issues/154130
5c50132https://github.com/mpage/cpython/commit/5c501324f3f9ae788b8400685bc4087de0dda059
gh-154130: Fix double decref of the dict in shared dict iterators (#1…https://github.com/python/cpython/commit/89d78fc6f9514914cec7a934af819f397b05d75e
gh-154130https://github.com/python/cpython/issues/154130
#1…https://github.com/python/cpython/pull/160312
89d78fchttps://github.com/python/cpython/commit/89d78fc6f9514914cec7a934af819f397b05d75e
kumaraditya303https://github.com/kumaraditya303
completedhttps://github.com/python/cpython/issues?q=is%3Aissue%20state%3Aclosed%20archived%3Afalse%20reason%3Acompleted
on Nov 20, 2026https://github.com/python/cpython/issues/154130#event-36768665425
Sign up for freehttps://github.com/signup?return_to=https://github.com/python/cpython/issues/154130
Sign in to commenthttps://github.com/login?return_to=https://github.com/python/cpython/issues/154130
interpreter-core(Objects, Python, Grammar, and Parser dirs)https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
topic-free-threadinghttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-free-threading%22
type-crashA hard crash of the interpreter, possibly with a core dumphttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-crash%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.