René's URL Explorer Experiment


Title: Data race on frozendict reads during construction in the free-threading build · Issue #151722 · python/cpython · GitHub

Open Graph Title: Data race on frozendict reads during construction in the free-threading build · Issue #151722 · python/cpython

X Title: Data race on frozendict reads during construction in the free-threading build · Issue #151722 · python/cpython

Description: Data race on frozendict reads during construction in the free-threading build Summary In the free-threading build (--disable-gil), several frozendict (PEP 814) read paths access the object's internal state without synchronization, on the...

Open Graph Description: Data race on frozendict reads during construction in the free-threading build Summary In the free-threading build (--disable-gil), several frozendict (PEP 814) read paths access the object's intern...

X Description: Data race on frozendict reads during construction in the free-threading build Summary In the free-threading build (--disable-gil), several frozendict (PEP 814) read paths access the object's in...

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

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Data race on frozendict reads during construction in the free-threading build","articleBody":"# Data race on `frozendict` reads during construction in the free-threading build\n\n## Summary\n\nIn the free-threading build (`--disable-gil`), several `frozendict` (PEP 814)\nread paths access the object's internal state without synchronization, on the\nassumption that a `frozendict` is immutable and therefore safe to read\nlock-free. That assumption holds once the object is fully built, but **not while\nit is being constructed from a user-defined mapping**: the half-built\n`frozendict` is already observable from other threads, and its scalar fields and\nentry table are being mutated concurrently. ThreadSanitizer reports a genuine\ndata race, and a reader can observe the object's length and contents change\nunderneath it, which violates the immutability the type is supposed to\nguarantee.\n\nAffected read paths: `len(fd)` (`frozendict_length`), `repr(fd)`\n(`frozendict_repr`), `hash(fd)` (`frozendict_hash`). All three read raw\n`ma_used` and/or walk the entry table via `_PyDict_Next` with no atomic load and\nno critical section, while the corresponding mutable-`dict` paths\n(`dict_length`, `dict_repr`) use `GET_USED()` / `Py_BEGIN_CRITICAL_SECTION`.\n\n## How a half-built `frozendict` becomes observable\n\n`frozendict(mapping)` for a non-`dict` mapping takes the generic path\n`frozendict_new` → `dict_update_common` → `dict_merge`, which calls back into\nuser Python: `PyMapping_Keys(b)`, then `PyObject_GetItem(b, key)` per key\n(`Objects/dictobject.c`, the generic branch of `dict_merge`). `dict_new` already\ncalls `_PyObject_GC_TRACK(d)` *before the first item is inserted*, so from the\nvery first callback the half-built `frozendict` is discoverable via\n`gc.get_objects()`. A `__getitem__` callback can take a second reference to it\nand hand a live alias to another thread, which then reads the same object while\n`dict_merge` keeps inserting and resizing it.\n\n`can_modify_dict()` treats a `frozendict` as mutable only while it is uniquely\nreferenced (`PyUnstable_Object_IsUniquelyReferenced(mp)`), i.e. it assumes a\nhalf-built `frozendict` is private. Once user code has run during construction,\nthat assumption is false.\n\n## ThreadSanitizer evidence (main HEAD `9688d252d330b0b586760a121ee8c8f7215176e8`)\n\nBuild: `./configure --disable-gil --with-thread-sanitizer \u0026\u0026 make`.\n\n`len` read racing the construction-time size store:\n\n```\nWARNING: ThreadSanitizer: data race\n  Read of size 8 ... by thread T1:\n    #0 frozendict_length Objects/dictobject.c\n    #1 PyObject_Size / builtin_len\n  Previous atomic write of size 8 ... by main thread:\n    #0 insertdict Objects/dictobject.c            (STORE_USED, already atomic)\n    #1 setitem_take2_lock_held\n    #2 dict_merge\n    #3 frozendict_vectorcall\nSUMMARY: ThreadSanitizer: data race in frozendict_length\n```\n\n`repr` and `hash` additionally race the entry table while a concurrent\n`dictresize` reallocates it:\n\n```\nWARNING: ThreadSanitizer: data race\n  ... by main thread:\n    #0 dictresize Objects/dictobject.c\n    #1 insert_combined_dict\n    #2 insertdict\n    #3 dict_merge -\u003e frozendict_vectorcall\n  Previous read of size 8 ... by thread T1:\n    #0 _PyDict_Next          (reached from frozendict_repr / frozendict_hash)\nSUMMARY: ThreadSanitizer: data race in dictresize\n```\n\nBeyond the sanitizer report, the violation is directly observable: a reader\nwatching `len()` of the half-built object sees it grow `0 → 499 → 999 → 1899`,\nand `gc.is_tracked()` is `True` at every step.\n\nThe construction (write) side is already atomic — `insertdict`'s size update\nuses `STORE_USED` (`FT_ATOMIC_STORE_SSIZE_RELAXED`) and the inserts run under\n`Py_BEGIN_CRITICAL_SECTION(a)` on the target in `dict_merge`. The defect is on\nthe read side: the custom `frozendict` read functions deliberately dropped both\nthe atomic load and the critical section.\n\n## Reproduction\n\n```python\nimport threading, gc\n\nstop = threading.Event()\nbox = []\n\ndef reader():\n    while not stop.is_set():\n        if box:\n            try:\n                len(box[0])     # or repr(box[0]) / hash(box[0])\n            except Exception:\n                pass\n\nclass Evil:\n    def keys(self):\n        return [f\"k{i}\" for i in range(8192)]\n    def __getitem__(self, k):\n        if not box:                      # leak the half-built frozendict\n            for o in gc.get_objects():\n                if isinstance(o, frozendict) and len(o) \u003e= 1:\n                    box.append(o)\n                    break\n        return 1\n\nt = threading.Thread(target=reader, daemon=True)\nt.start()\nfor _ in range(60):\n    box.clear()\n    frozendict(Evil())\nstop.set()\nt.join(timeout=2)\n```\n\nRun under a free-threading + TSan build; the race fires for `len`, `repr` and\n`hash`.\n\n## Fix\n\n`frozendict` reads should follow the same free-threading conventions the rest of\n`dictobject.c` already uses:\n\n1. Read scalar `ma_used` through `GET_USED()`\n   (`FT_ATOMIC_LOAD_SSIZE_RELAXED`), exactly like `dict_length` and like\n   `set_len` for `frozenset`.\n2. Wrap the entry-table walk in `frozendict_repr` and `frozendict_hash` in a\n   per-object critical section, exactly like `dict_repr` already wraps\n   `anydict_repr_impl`, and like `set_repr` wraps `set_repr_lock_held` (which is\n   the `tp_repr` of both `set` and `frozenset`). The construction side already\n   holds `Py_BEGIN_CRITICAL_SECTION(a)` on the target in `dict_merge`, so the\n   reader's critical section serializes against construction and the race goes\n   away. The cached `ma_hash` short-circuit stays lock-free (atomic load),\n   matching `frozenset_hash`.\n\nWith this change, ThreadSanitizer is clean for `len`, `repr` and `hash` against\na concurrently-constructing `frozendict`, and the existing `test_dict`,\n`test_free_threading` and `test_set` suites still pass on the free-threading +\nTSan build.\n\nA PR implementing the above is ready.\n\n### One related path: lock-free `frozendict` copy (PR gh-141510 / #145920)\n\n`copy_lock_held` was deliberately made lock-free for `frozendict` sources in\n#145920 (\"A frozendict mapping is immutable so a critical section is not needed\nto ensure that a copy is consistent\"), giving a large speedup for the normal\n(finished) case. That path reads the source's `ma_used` / `ma_keys` and walks\nthe entry table, so it has the **same** latent race during construction\n(`fd.copy()` / `dict(fd)` / `fd | m` on a half-built source still trips TSan\nafter the read-side fix above). Because re-adding a critical section there would\nwalk back a deliberate, merged performance decision, I left that path as-is and\napplied only the scalar-atomic read. The clean way to also close the copy window\nwithout giving up #145920's lock-free copy is to make a half-built `frozendict`\nnon-observable in the first place — defer GC-tracking / publication until the\nconstructor returns, which would make `can_modify_dict`'s unique-reference\nassumption actually hold and keep every lock-free read correct. That is a\nbroader design decision (it would apply to `frozenset` too, which is also\nGC-tracked and observably grows during construction), so I am raising it here\nrather than bundling it into the read-path PR. Happy to follow whichever\ndirection you prefer.\n\n## Environment\n\n- CPython `main`, free-threading build\n  (`--disable-gil --with-thread-sanitizer`), reproduced on HEAD\n  `9688d252d330b0b586760a121ee8c8f7215176e8` (`3.16.0a0`).\n- Same code is present on the 3.15 branch (the `frozendict` read paths are\n  byte-for-byte the same logic).\n\n## Linked\n\n- gh-141510 (PEP 814 `frozendict`).\n- #144913 split `frozendict_length` off `dict_length` and replaced the atomic\n  read with a plain `ma_used` load.\n- #145920 made the `frozendict` copy path lock-free (`copy_lock_held`).\n\n\n\u003c!-- gh-linked-prs --\u003e\n### Linked PRs\n* gh-151724\n* gh-151740\n* gh-151954\n* gh-151967\n* gh-152021\n* gh-152067\n* gh-152225\n* gh-152230\n* gh-152271\n\u003c!-- /gh-linked-prs --\u003e\n","author":{"url":"https://github.com/tonghuaroot","@type":"Person","name":"tonghuaroot"},"datePublished":"2026-06-19T09:36:22.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":2},"url":"https://github.com/151722/cpython/issues/151722"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:ccd887b0-19da-0e24-9778-798ba60c2116
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-id90EC:16195D:2DDEEFA:3FAD34B:6A4F62B5
html-safe-nonced91cc7ef53b77e2b4e8a4aa10645d8442c3946281f5060df4eb38f14eca9374f
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5MEVDOjE2MTk1RDoyRERFRUZBOjNGQUQzNEI6NkE0RjYyQjUiLCJ2aXNpdG9yX2lkIjoiODQxOTM5MDAxNTIxNDE1MDMyNSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac643c94a8feff30d494f94589982ec1153bc4be9e03d2ef62abe9dcb2b6c09ff3
hovercard-subject-tagissue:4699629762
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/151722/issue_layout
twitter:imagehttps://opengraph.githubassets.com/b10945e931ee96267b6a3b9fa7a346d4add9fbc8165730957934d405b2c8b8d6/python/cpython/issues/151722
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/b10945e931ee96267b6a3b9fa7a346d4add9fbc8165730957934d405b2c8b8d6/python/cpython/issues/151722
og:image:altData race on frozendict reads during construction in the free-threading build Summary In the free-threading build (--disable-gil), several frozendict (PEP 814) read paths access the object's intern...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernametonghuaroot
hostnamegithub.com
expected-hostnamegithub.com
Noneb92d11c0aa4a77d54ef4af1078b6a15fb5a70a215b30c4ecf28889d5a8e656d9
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
release4b249b445842943ed31549e027f57a8ade9881ed
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/python/cpython/issues/151722#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F151722
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub Copilot appDirect agents from issue to mergehttps://github.com/features/ai/github-app
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
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
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
View all resourceshttps://github.com/resources
GitHub SponsorsFund open source developershttps://github.com/open-source/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/open-source/accelerator
GitHub Starshttps://stars.github.com
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://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
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F151722
Sign up https://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/151722
Reloadhttps://github.com/python/cpython/issues/151722
Reloadhttps://github.com/python/cpython/issues/151722
Please reload this pagehttps://github.com/python/cpython/issues/151722
python https://github.com/python
cpythonhttps://github.com/python/cpython
Please reload this pagehttps://github.com/python/cpython/issues/151722
Notifications https://github.com/login?return_to=%2Fpython%2Fcpython
Fork 34.8k https://github.com/login?return_to=%2Fpython%2Fcpython
Star 73.6k https://github.com/login?return_to=%2Fpython%2Fcpython
Code https://github.com/python/cpython
Issues 5k+ https://github.com/python/cpython/issues
Pull requests 2.3k https://github.com/python/cpython/pulls
Actions https://github.com/python/cpython/actions
Projects https://github.com/python/cpython/projects
Security and quality 0 https://github.com/python/cpython/security
Insights https://github.com/python/cpython/pulse
Code https://github.com/python/cpython
Issues https://github.com/python/cpython/issues
Pull requests https://github.com/python/cpython/pulls
Actions https://github.com/python/cpython/actions
Projects https://github.com/python/cpython/projects
Security and quality https://github.com/python/cpython/security
Insights https://github.com/python/cpython/pulse
Data race on frozendict reads during construction in the free-threading buildhttps://github.com/python/cpython/issues/151722#top
3.15pre-release feature fixes, bugs and security fixeshttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%223.15%22
3.16new features, bugs and security fixeshttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%223.16%22
interpreter-core(Objects, Python, Grammar, and Parser dirs)https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
https://github.com/tonghuaroot
tonghuaroothttps://github.com/tonghuaroot
on Jun 19, 2026https://github.com/python/cpython/issues/151722#issue-4699629762
gh-141510https://github.com/python/cpython/issues/141510
#145920https://github.com/python/cpython/pull/145920
#145920https://github.com/python/cpython/pull/145920
#145920https://github.com/python/cpython/pull/145920
PEP 814: Add built-in frozendict type #141510https://github.com/python/cpython/issues/141510
gh-141510: Update mp_length of frozendict to use non atomic operation #144913https://github.com/python/cpython/pull/144913
gh-141510: Avoid critical section on frozendict copy #145920https://github.com/python/cpython/pull/145920
gh-151722: Fix data race on frozendict reads during construction in free-threading build #151724https://github.com/python/cpython/pull/151724
gh-151722: Defer GC tracking of frozendict to end of construction #151740https://github.com/python/cpython/pull/151740
[3.15] gh-151722: Defer GC tracking of frozendict to end of construction (gh-151740) #151954https://github.com/python/cpython/pull/151954
gh-151722: Defer GC tracking of frozendict.fromkeys() result until fully built #151967https://github.com/python/cpython/pull/151967
[WIP] gh-151722: Defer GC tracking of frozendict.fromkeys() as possible #152021https://github.com/python/cpython/pull/152021
gh-151722: Do not track the dict in the GC in _PyDict_FromKeys() #152067https://github.com/python/cpython/pull/152067
[3.15] gh-151722: Do not track the frozendict in the GC in _PyDict_FromKeys() (GH-152067) #152225https://github.com/python/cpython/pull/152225
gh-151722: Defer GC tracking in frozendict.copy() #152230https://github.com/python/cpython/pull/152230
[3.15] gh-151722: Defer GC tracking in frozendict.copy() (GH-152230) #152271https://github.com/python/cpython/pull/152271
3.15pre-release feature fixes, bugs and security fixeshttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%223.15%22
3.16new features, bugs and security fixeshttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%223.16%22
interpreter-core(Objects, Python, Grammar, and Parser dirs)https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%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.