René's URL Explorer Experiment


Title: Sharing a `contextvars.Context` iterator across threads crashes (HAMT iterator cursor corruption) under free-threading · Issue #154535 · python/cpython · GitHub

Open Graph Title: Sharing a `contextvars.Context` iterator across threads crashes (HAMT iterator cursor corruption) under free-threading · Issue #154535 · python/cpython

X Title: Sharing a `contextvars.Context` iterator across threads crashes (HAMT iterator cursor corruption) under free-threading · Issue #154535 · python/cpython

Description: Crash report What happened? On the free-threaded build, advancing a single shared iterator over a contextvars.Context from multiple threads corrupts the iterator's traversal cursor and dereferences a garbage node pointer → SIGSEGV. The H...

Open Graph Description: Crash report What happened? On the free-threaded build, advancing a single shared iterator over a contextvars.Context from multiple threads corrupts the iterator's traversal cursor and dereferences...

X Description: Crash report What happened? On the free-threaded build, advancing a single shared iterator over a contextvars.Context from multiple threads corrupts the iterator's traversal cursor and derefere...

Opengraph URL: https://github.com/python/cpython/issues/154535

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Sharing a `contextvars.Context` iterator across threads crashes (HAMT iterator cursor corruption) under free-threading","articleBody":"# Crash report\n\n### What happened?\n\nOn the free-threaded build, advancing a single shared iterator over a `contextvars.Context` from multiple threads corrupts the iterator's traversal cursor and dereferences a garbage node pointer → **SIGSEGV**.\n\nThe HAMT iterator keeps its whole cursor — `i_nodes[]` (borrowed node pointers), `i_pos[]`, `i_level` — inside the iterator object and advances it with plain reads/writes and **no critical section** (`Python/hamt.c`, main@`a1d580430c8`):\n\n```c\nstatic hamt_iter_t\nhamt_iterator_next(PyHamtIteratorState *iter, PyObject **key, PyObject **val) {\n    if (iter->i_level \u003c 0)                       /* :2188  plain read of the cursor level */\n        return I_END;\n    PyHamtNode *current = iter->i_nodes[iter->i_level];   /* :2194  read node at current level */\n    if (IS_BITMAP_NODE(current)) {               /* :2196  Py_TYPE(current) -> SEGV on a wild node */\n        return hamt_iterator_bitmap_next(iter, key, val);\n    }\n    ...\n}\n\nstatic hamt_iter_t\nhamt_iterator_bitmap_next(PyHamtIteratorState *iter, ...) {\n    int8_t level = iter->i_level;\n    PyHamtNode_Bitmap *node = (PyHamtNode_Bitmap *)(iter->i_nodes[level]);\n    if (pos + 1 >= Py_SIZE(node)) {              /* :2092  Py_SIZE(node) -> SEGV on a wild node */\n        iter->i_level--;                         /* :2097  plain write of the cursor level */\n        return hamt_iterator_next(iter, key, val);\n    }\n    ...\n}\n```\n\nTwo threads calling `next()` on the same iterator desync `i_level` against `i_nodes[]`, so a thread reads `current = iter->i_nodes[iter->i_level]` as a stale / `NULL` / wild pointer and immediately evaluates `IS_BITMAP_NODE(current)` = `Py_TYPE(current)` (or `Py_SIZE(node)` in `hamt_iterator_bitmap_next`) — dereferencing garbage. Because the nodes in `i_nodes` are held **borrowed** (`hamt_iterator_init`: \"we don't incref/decref nodes in i_nodes\"), a concurrent structural change is not even required — cursor desync alone produces the wild dereference. This is safe under the GIL (one thread runs the advance at a time).\n\nThe HAMT iterator backs `contextvars.Context` iteration — `iter(ctx)`, `ctx.keys()`, `ctx.values()`, `ctx.items()` — via `hamt_baseiter_tp_iternext` (`hamt.c:2479`).\n\n### Reproducer\n\nFree-threaded build, `PYTHON_GIL=0`:\n\n```python\nimport contextvars, threading\nNT = 8; ITERS = 40000\nvs = [contextvars.ContextVar(f\"v{i}\") for i in range(16)]\nctx = contextvars.copy_context()\ndef populate():\n    for i, v in enumerate(vs):\n        v.set(i)\nctx.run(populate)\ncell = [iter(ctx)]\ndef worker():\n    for _ in range(ITERS):\n        it = cell[0]\n        try: next(it)\n        except StopIteration: cell[0] = iter(ctx)\n        except Exception: pass\nts = [threading.Thread(target=worker) for _ in range(NT)]\nfor t in ts: t.start()\nfor t in ts: t.join()\n```\n\n- **6/6 SIGSEGV** on a plain free-threaded debug build (no sanitizer).\n- On a free-threaded ASan build:\n\n```\nAddressSanitizer: SEGV in _Py_TYPE_impl  Include/object.h:234\n  hamt_iterator_bitmap_next  Python/hamt.c:2092\n  hamt_iterator_next         Python/hamt.c:2196\n  hamt_baseiter_tp_iternext  Python/hamt.c:2479\n  context_run                Python/context.c:731\n```\n\n- Under TSan: `WARNING: ThreadSanitizer: data race … Python/hamt.c:2188 in hamt_iterator_next`.\n\nThe crash is not `Py_DEBUG`-only — it reproduces as a raw SIGSEGV from the wild-pointer dereference on the plain free-threaded build.\n\n### Relationship to gh-124397\n\nPer gh-124397 (\"Strategy for Iterators in Free Threading\") point 3, C iterators should get \"the minimal changes necessary to cause them to **not crash** … Concurrent access is allowed to return duplicate values, skip values, or raise an exception.\" The HAMT / `Context` iterator was never brought under that hardening, so it crashes rather than returning dup/skip. It is the `contextvars.Context` sibling of the already-tracked shared-iterator crashes: dict (#154130), set (#144357), and memoryview.\n\n### Suggested fix\n\nBring the HAMT iterator advance under a per-iterator critical section (or make the `i_level`/`i_pos`/`i_nodes` cursor accesses atomic with a NULL/bounds check on the borrowed `i_nodes[i_level]` before dereferencing), matching the `dictiter`/`setiter` hardening. The guard must span the whole `hamt_iterator_next` → `*_bitmap_next` / `*_array_next` descent because `i_nodes` holds borrowed pointers.\n\n*Found with [fusil](https://github.com/devdanzin/fusil)'s `--tsan` mode; reproducer reduced and this report drafted with AI assistance (Claude Code), then verified by hand on free-threaded debug / ASan / TSan builds of `main`.*\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-154586\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/devdanzin","@type":"Person","name":"devdanzin"},"datePublished":"2026-07-23T11:12:54Z","url":"https://github.com/python/cpython/issues/154535"}

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:ae64d7cc-32e3-a94f-bed2-326ad8f31203
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idEBEA:1087D4:34CCA1F:4688103:6B020978
html-safe-nonce2a0ee99531d0c8faa0dcaf4ad71bb5fdb872764498ac5d406a108bbecd531758
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFQkVBOjEwODdENDozNENDQTFGOjQ2ODgxMDM6NkIwMjA5NzgiLCJ2aXNpdG9yX2lkIjoiMjc4MDIzODIxNjMyNDg0Mzg5NiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmacde578d9966be570470c6b8f26c9c18e188da9925c081ba3ac6625bf1c8bc881c
hovercard-subject-tagissue:4958244703
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/154535/issue_layout
twitter:imagehttps://opengraph.githubassets.com/50b70786673b17314ef539746acdb04c0e99f37e07e21900789763ab38b5c78a/python/cpython/issues/154535
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/50b70786673b17314ef539746acdb04c0e99f37e07e21900789763ab38b5c78a/python/cpython/issues/154535
og:image:altCrash report What happened? On the free-threaded build, advancing a single shared iterator over a contextvars.Context from multiple threads corrupts the iterator's traversal cursor and dereferences...
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/154535#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F154535
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%2F154535
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/154535
Reloadhttps://github.com/python/cpython/issues/154535
Reloadhttps://github.com/python/cpython/issues/154535
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/154535
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/154535
Sharing a contextvars.Context iterator across threads crashes (HAMT iterator cursor corruption) under free-threadinghttps://github.com/python/cpython/issues/154535#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 23, 2026https://github.com/python/cpython/issues/154535#issue-4958244703
gh-124397https://github.com/python/cpython/issues/124397
gh-124397https://github.com/python/cpython/issues/124397
#154130https://github.com/python/cpython/issues/154130
#144357https://github.com/python/cpython/pull/144357
fusilhttps://github.com/devdanzin/fusil
gh-154535: Fix crash when a contextvars.Context iterator is shared between threads #154586https://github.com/python/cpython/pull/154586
devdanzinhttps://github.com/devdanzin
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
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
on Jul 23, 2026https://github.com/python/cpython/issues/154535#event-28378297597
gianghungtienhttps://github.com/gianghungtien
on Aug 10, 2026https://github.com/python/cpython/issues/154535#event-29244216604
Merge branch 'main' into pythongh-154535-hamt-iterator-thread-safetyhttps://github.com/gianghungtien/cpython/commit/073b086c33b4bc469ec5701c5db28a397797d4a8
pythongh-154535https://github.com/python/cpython/issues/154535
073b086https://github.com/gianghungtien/cpython/commit/073b086c33b4bc469ec5701c5db28a397797d4a8
gianghungtienhttps://github.com/gianghungtien
on Sep 8, 2026https://github.com/python/cpython/issues/154535#event-30789122444
pythongh-154535: Drop redundant INCREF/DECREF in hamt_baseiter_tp_ite…https://github.com/gianghungtien/cpython/commit/b290e8a531629826c2a571bdf1fe1b96c07a9805
pythongh-154535https://github.com/python/cpython/issues/154535
b290e8ahttps://github.com/gianghungtien/cpython/commit/b290e8a531629826c2a571bdf1fe1b96c07a9805
Merge branch 'main' of https://github.com/python/cpython into pythong…https://github.com/gianghungtien/cpython/commit/54603d4c3484bb2e28d77bc4a0b0f74b0372847f
https://github.com/python/cpythonhttps://github.com/python/cpython
pythong…https://github.com/python/cpython/issues/154535
54603d4https://github.com/gianghungtien/cpython/commit/54603d4c3484bb2e28d77bc4a0b0f74b0372847f
Sign up for freehttps://github.com/signup?return_to=https://github.com/python/cpython/issues/154535
Sign in to commenthttps://github.com/login?return_to=https://github.com/python/cpython/issues/154535
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.