René's URL Explorer Experiment


Title: gh-154535: Fix crash when a contextvars.Context iterator is shared between threads by gianghungtien · Pull Request #154586 · python/cpython · GitHub

Open Graph Title: gh-154535: Fix crash when a contextvars.Context iterator is shared between threads by gianghungtien · Pull Request #154586 · python/cpython

X Title: gh-154535: Fix crash when a contextvars.Context iterator is shared between threads by gianghungtien · Pull Request #154586 · python/cpython

Description: Fixes the SIGSEGV reported in #154535. The bug Python/hamt.c's iterator keeps its entire depth-first cursor inside the iterator object — i_level, i_pos[], and i_nodes[] (which holds borrowed node pointers) — and hamt_iterator_next() advanced it with plain reads and writes, with no locking: static hamt_iter_t hamt_iterator_next(PyHamtIteratorState *iter, PyObject **key, PyObject **val) { if (iter->i_level < 0) { /* plain read */ return I_END; } PyHamtNode *current = iter->i_nodes[iter->i_level]; if (IS_BITMAP_NODE(current)) { /* Py_TYPE(current) */ ... A single step is not a single write: descending pushes i_pos[next_level], i_nodes[next_level] and then i_level, while ascending does i_level--. Two threads advancing the same iterator interleave those updates, so i_level ends up pointing at an i_nodes[] slot that was never filled in for that level. Because i_nodes holds borrowed pointers, the very next step dereferences a stale or NULL node in IS_BITMAP_NODE(current) (Py_TYPE) or Py_SIZE(node) — a wild-pointer read, not merely a torn value. No concurrent structural change is needed; cursor desync alone is enough. This is safe under the GIL, where only one thread runs the advance at a time. That iterator backs all iteration over a contextvars.Context — iter(ctx), ctx.keys(), ctx.values(), ctx.items() — via hamt_baseiter_tp_iternext(). Per the strategy in #124397, C iterators should get the minimal changes needed so that concurrent use may return duplicate values, skip values, or raise — but must not crash. The HAMT iterator had never been brought under that hardening; it is the contextvars sibling of the already-fixed dict (#154130) and set (#144357) shared-iterator crashes. The fix Take a critical section on the iterator in hamt_baseiter_tp_iternext(), spanning the whole hamt_iterator_next() → *_bitmap_next / *_array_next / *_collision_next descent, so no other thread can observe the cursor half-updated. The HAMT itself is immutable, so nothing else needs locking, and the default (GIL-enabled) build is unaffected — Py_BEGIN_CRITICAL_SECTION compiles away there. The borrowed key/value are strengthened inside the critical section and the yield function is called after releasing it, so no allocation happens under the lock — matching the setiter_iternext() idiom in Objects/setobject.c. _PyHamt_Eq() also drives hamt_iterator_next(), but over a stack-local PyHamtIteratorState that is private to the call, so it needs no locking. The header comment on PyHamtIteratorState now records which of the two cases requires the lock. Concurrent iteration over a shared Context iterator may still skip or repeat items. That is the documented expectation for free-threaded C iterators, and the added test asserts only that no item is invented — the same contract used by the existing tuple/list/range tests in the file. Verification Free-threaded build of main on Windows x64 (PCbuild\build.bat -p x64 -c Release --disable-gil), PYTHON_GIL=0. The reproducer from the issue, before the fix — 5/5 runs die with 0xC0000005 (access violation): run 1 exit=-1073741819 run 2 exit=-1073741819 run 3 exit=-1073741819 run 4 exit=-1073741819 run 5 exit=-1073741819 After the fix, 5/5 runs complete cleanly. The new regression test, ContendedContextIterationTest, reproduces it the same way: 5/5 crashes before the fix ("Windows fatal exception: access violation"), 8/8 passes after. A single pass over a shared iterator turned out to be over too quickly to reliably desync the cursor, so test_restarted_shared_iterator keeps replacing the iterator as it is exhausted to hold the threads on top of each other — that is the variant that reproduces. The class also inherits the existing test_iteration / test_shared_iterator cases. Also run green: test_free_threading (full package), test_context, test_contextlib, test_asyncio.test_context on the free-threaded build test_context, test_contextlib, test_asyncio, test_capi on the default x64 build python_d -m test -R 3:3 test_context test_contextlib — no refleaks Tools/patchcheck/patchcheck.py — clean Issue: gh-154535

Open Graph Description: Fixes the SIGSEGV reported in #154535. The bug Python/hamt.c's iterator keeps its entire depth-first cursor inside the iterator object — i_level, i_pos[], and i_nodes[] (which holds borrowed no...

X Description: Fixes the SIGSEGV reported in #154535. The bug Python/hamt.c&#39;s iterator keeps its entire depth-first cursor inside the iterator object — i_level, i_pos[], and i_nodes[] (which holds borrowe...

Opengraph URL: https://github.com/python/cpython/pull/154586

X: @github

direct link

Domain: github.com

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/:user_id/:repository/pull/:id/files(.:format)
route-controllerpull_requests
route-actionfiles
fetch-noncev2:8519266f-a69f-0220-648d-1617e59a1f69
current-catalog-service-hashae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b
request-id8988:2270F4:3919083:4BAC905:6B0214CC
html-safe-nonceca3aabbfa053c8cad13ee08bbd5ee0ad1834a1149fa879074f8d69d576e8dfac
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4OTg4OjIyNzBGNDozOTE5MDgzOjRCQUM5MDU6NkIwMjE0Q0MiLCJ2aXNpdG9yX2lkIjoiODg3MDk3OTk1NzgxMjIzNzUxNiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac3b235cab5ac41e220ee23dc4d53694ea310630e1a9287f5e8ba1f3bfdc8089c3
hovercard-subject-tagpull_request:4123524449
github-keyboard-shortcutsrepository,pull-request-list,pull-request-conversation,pull-request-files-changed,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///pull_requests/show/files
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/python/cpython/pull/154586/files
twitter:imagehttps://avatars.githubusercontent.com/u/41053218?s=400&v=4
twitter:cardsummary_large_image
og:imagehttps://avatars.githubusercontent.com/u/41053218?s=400&v=4
og:image:altFixes the SIGSEGV reported in #154535. The bug Python/hamt.c's iterator keeps its entire depth-first cursor inside the iterator object — i_level, i_pos[], and i_nodes[] (which holds borrowed no...
og:site_nameGitHub
og:typeobject
hostnamegithub.com
expected-hostnamegithub.com
None87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456
turbo-cache-controlno-preview
diff-viewunified
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 full-width
disable-turbotrue
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

Links:

Skip to contenthttps://github.com/python/cpython/pull/154586/files#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fpull%2F154586%2Ffiles
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%2Fpull%2F154586%2Ffiles
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fpull_requests%2Fshow%2Ffiles&source=header-repo&source_repo=python%2Fcpython
Reloadhttps://github.com/python/cpython/pull/154586/files
Reloadhttps://github.com/python/cpython/pull/154586/files
Reloadhttps://github.com/python/cpython/pull/154586/files
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
Sign up for GitHub https://github.com/signup?return_to=%2Fpython%2Fcpython%2Fissues%2Fnew%2Fchoose
terms of servicehttps://docs.github.com/terms
privacy statementhttps://docs.github.com/privacy
Sign inhttps://github.com/login?return_to=%2Fpython%2Fcpython%2Fissues%2Fnew%2Fchoose
gianghungtienhttps://github.com/gianghungtien
python:mainhttps://github.com/python/cpython/tree/main
gianghungtien:gh-154535-hamt-iterator-thread-safetyhttps://github.com/gianghungtien/cpython/tree/gh-154535-hamt-iterator-thread-safety
Conversation 4 https://github.com/python/cpython/pull/154586
Commits 4 https://github.com/python/cpython/pull/154586/commits
Checks 50 https://github.com/python/cpython/pull/154586/checks
Files changed 4 https://github.com/python/cpython/pull/154586/files
gh-154535: Fix crash when a contextvars.Context iterator is shared between threads https://github.com/python/cpython/pull/154586/files#top
Show all changes 4 commits https://github.com/python/cpython/pull/154586/files
a3ea63c gh-154535: Fix crash when a contextvars.Context iterator is shared be… gianghungtien Jul 24, 2026 https://github.com/python/cpython/pull/154586/commits/a3ea63c15f5c5fc88f3556ce11e7ab9cb0524f56
073b086 Merge branch 'main' into gh-154535-hamt-iterator-thread-safety gianghungtien Aug 10, 2026 https://github.com/python/cpython/pull/154586/commits/073b086c33b4bc469ec5701c5db28a397797d4a8
b290e8a gh-154535: Drop redundant INCREF/DECREF in hamt_baseiter_tp_iternext() gianghungtien Sep 8, 2026 https://github.com/python/cpython/pull/154586/commits/b290e8a531629826c2a571bdf1fe1b96c07a9805
54603d4 Merge branch 'main' of https://github.com/python/cpython into gh-1545… gianghungtien Sep 8, 2026 https://github.com/python/cpython/pull/154586/commits/54603d4c3484bb2e28d77bc4a0b0f74b0372847f
Clear filters https://github.com/python/cpython/pull/154586/files
Please reload this pagehttps://github.com/python/cpython/pull/154586/files
Please reload this pagehttps://github.com/python/cpython/pull/154586/files
pycore_hamt.h https://github.com/python/cpython/pull/154586/files#diff-189652fbff592ca4ed852013ef1f16cb21597898b7df4e718f1d1a420f48d479
test_iteration.py https://github.com/python/cpython/pull/154586/files#diff-2e51e17906bce15fef8803cdb5f9a05036e37b6540f8a06cef4e8f5014ac3d2f
2026-07-24-09-05-11.gh-issue-154535.Kq7vXm.rst https://github.com/python/cpython/pull/154586/files#diff-d2d123ee1eb1581633d4fa62ce3f93d1d181ffc090b7262195daf1a0510ac9f9
hamt.c https://github.com/python/cpython/pull/154586/files#diff-57efcedae5cd47def53e512cf0bae5554f794563c3c6269b3a9ac3fa24055001
https://github.com/python/cpython/blob/main/.github/CODEOWNERS#L236
Include/internal/pycore_hamt.hhttps://github.com/python/cpython/pull/154586/files#diff-189652fbff592ca4ed852013ef1f16cb21597898b7df4e718f1d1a420f48d479
View file https://github.com/python/cpython/blob/54603d4c3484bb2e28d77bc4a0b0f74b0372847f/Include/internal/pycore_hamt.h
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/python/cpython/pull/154586/{{ revealButtonHref }}
https://github.com/python/cpython/pull/154586/files#diff-189652fbff592ca4ed852013ef1f16cb21597898b7df4e718f1d1a420f48d479
https://github.com/python/cpython/pull/154586/files#diff-189652fbff592ca4ed852013ef1f16cb21597898b7df4e718f1d1a420f48d479
Lib/test/test_free_threading/test_iteration.pyhttps://github.com/python/cpython/pull/154586/files#diff-2e51e17906bce15fef8803cdb5f9a05036e37b6540f8a06cef4e8f5014ac3d2f
View file https://github.com/python/cpython/blob/54603d4c3484bb2e28d77bc4a0b0f74b0372847f/Lib/test/test_free_threading/test_iteration.py
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/python/cpython/pull/154586/{{ revealButtonHref }}
https://github.com/python/cpython/pull/154586/files#diff-2e51e17906bce15fef8803cdb5f9a05036e37b6540f8a06cef4e8f5014ac3d2f
https://github.com/python/cpython/pull/154586/files#diff-2e51e17906bce15fef8803cdb5f9a05036e37b6540f8a06cef4e8f5014ac3d2f
https://github.com/python/cpython/pull/154586/files#diff-2e51e17906bce15fef8803cdb5f9a05036e37b6540f8a06cef4e8f5014ac3d2f
Misc/NEWS.d/next/Core_and_Builtins/2026-07-24-09-05-11.gh-issue-154535.Kq7vXm.rsthttps://github.com/python/cpython/pull/154586/files#diff-d2d123ee1eb1581633d4fa62ce3f93d1d181ffc090b7262195daf1a0510ac9f9
View file https://github.com/python/cpython/blob/54603d4c3484bb2e28d77bc4a0b0f74b0372847f/Misc/NEWS.d/next/Core_and_Builtins/2026-07-24-09-05-11.gh-issue-154535.Kq7vXm.rst
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/python/cpython/pull/154586/{{ revealButtonHref }}
https://github.com/python/cpython/blob/main/.github/CODEOWNERS#L236
Python/hamt.chttps://github.com/python/cpython/pull/154586/files#diff-57efcedae5cd47def53e512cf0bae5554f794563c3c6269b3a9ac3fa24055001
View file https://github.com/python/cpython/blob/54603d4c3484bb2e28d77bc4a0b0f74b0372847f/Python/hamt.c
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/python/cpython/pull/154586/{{ revealButtonHref }}
https://github.com/python/cpython/pull/154586/files#diff-57efcedae5cd47def53e512cf0bae5554f794563c3c6269b3a9ac3fa24055001
https://github.com/python/cpython/pull/154586/files#diff-57efcedae5cd47def53e512cf0bae5554f794563c3c6269b3a9ac3fa24055001
https://github.com/python/cpython/pull/154586/files#diff-57efcedae5cd47def53e512cf0bae5554f794563c3c6269b3a9ac3fa24055001
Please reload this pagehttps://github.com/python/cpython/pull/154586/files
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.