René's URL Explorer Experiment


Title: _decimal: `mpd_context_t::status`/`traps` mutated non-atomically leading to data race · Issue #149142 · python/cpython · GitHub

Open Graph Title: _decimal: `mpd_context_t::status`/`traps` mutated non-atomically leading to data race · Issue #149142 · python/cpython

X Title: _decimal: `mpd_context_t::status`/`traps` mutated non-atomically leading to data race · Issue #149142 · python/cpython

Description: Bug report Bug description: Summary Modules/_decimal/_decimal.c performs unsynchronized read-modify-write and plain stores on the status and traps fields of mpd_context_t embedded in a Python decimal.Context. Whenever a Context instance ...

Open Graph Description: Bug report Bug description: Summary Modules/_decimal/_decimal.c performs unsynchronized read-modify-write and plain stores on the status and traps fields of mpd_context_t embedded in a Python decim...

X Description: Bug report Bug description: Summary Modules/_decimal/_decimal.c performs unsynchronized read-modify-write and plain stores on the status and traps fields of mpd_context_t embedded in a Python decim...

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

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"_decimal: `mpd_context_t::status`/`traps` mutated non-atomically leading to data race","articleBody":"# Bug report\n\n### Bug description:\n\n## Summary\n\n`Modules/_decimal/_decimal.c` performs unsynchronized read-modify-write and plain stores on the `status` and `traps` fields of `mpd_context_t` embedded in a Python `decimal.Context`. Whenever a `Context` instance is reachable from more than one free-threaded thread — explicitly via `context=` arguments, `Context.\u003cmethod\u003e(…)`, `ctx.flags[…] = …`, etc. — those accesses race.\n\n#141148 + #146482 fix the *implicit* sharing case (inherited context via `contextvars`). This issue is for the underlying primitive, which is independent of how the `Context` ended up shared and is still racy after #146482.\n\n## Affected sites\n\nAll in `Modules/_decimal/_decimal.c`:\n\n| Line | Code | Reached from Python by |\n|------|------|------------------------|\n| 616  | `ctx-\u003estatus \\|= status;` (in `dec_addstatus`) | any arithmetic on the context |\n| 617, 625, 629 | reads of `ctx-\u003etraps` (in `dec_addstatus` trap path) | same |\n| 715  | `SdFlags(self) \u0026 flag` (in `signaldict_getitem`) | `ctx.flags[X]`, `ctx.traps[X]` |\n| 744  | `SdFlags(self) \\|= flag;` (in `signaldict_setitem`) | `ctx.flags[X] = True`, `ctx.traps[X] = True` |\n| 747  | `SdFlags(self) \u0026= ~flag;` (in `signaldict_setitem`) | `ctx.flags[X] = False`, `ctx.traps[X] = False` |\n| 1407 | `CTX(self)-\u003etraps = 0;` (in `_decimal_Context_clear_traps_impl`) | `ctx.clear_traps()` |\n| 1421 | `CTX(self)-\u003estatus = 0;` (in `_decimal_Context_clear_flags_impl`) | `ctx.clear_flags()` |\n\n`SdFlags(v)` is `*v-\u003eflags` where `v-\u003eflags` is bound to either `\u0026CTX(ctx)-\u003estatus` or `\u0026CTX(ctx)-\u003etraps` (`_decimal.c:1474–1475`), so the signaldict paths are the same memory as the context-level paths via a different surface.\n\n## Triggering pattern\n\nAny pure-Python code that shares one `Context` instance across free-threaded threads. Five minimal reproducers, one per site, are below. They use a barrier so the racing windows align on the first iteration; under TSan on a free-threaded debug build (`./configure --disable-gil --with-thread-sanitizer`) each one should reliably produce a data race report attributable to the matching site.\n\n```python\n# common.py\nimport threading\nN_THREADS = 8\nITERATIONS = 100_000\ndef run_concurrently(workers):\n    barrier = threading.Barrier(len(workers))\n    threads = [threading.Thread(target=w, args=(barrier,)) for w in workers]\n    for t in threads: t.start()\n    for t in threads: t.join()\n```\n\n### 1. `dec_addstatus` (`:616`)\n\n```python\n# repro_status_or.py\nimport decimal\nfrom common import N_THREADS, ITERATIONS, run_concurrently\nSHARED = decimal.Context(prec=4)  # prec=4 makes \"1.23456\" Inexact|Rounded\ndef worker(barrier):\n    barrier.wait()\n    for _ in range(ITERATIONS):\n        SHARED.create_decimal(\"1.23456\")  # -\u003e dec_addstatus(SHARED, ...)\nrun_concurrently([worker] * N_THREADS)\n```\n\n### 2. `clear_flags` race vs. `dec_addstatus` (`:1421` ↔ `:616`)\n\n```python\n# repro_clear_flags.py\nimport decimal\nfrom common import ITERATIONS, run_concurrently\nSHARED = decimal.Context(prec=4)\ndef producer(barrier):\n    barrier.wait()\n    for _ in range(ITERATIONS):\n        SHARED.create_decimal(\"1.23456\")\ndef clearer(barrier):\n    barrier.wait()\n    for _ in range(ITERATIONS):\n        SHARED.clear_flags()             # ctx-\u003estatus = 0;\nrun_concurrently([producer]*4 + [clearer]*4)\n```\n\n### 3. `clear_traps` race vs. trap-detection read (`:1407` ↔ `:617`)\n\n```python\n# repro_clear_traps.py\nimport decimal\nfrom common import ITERATIONS, run_concurrently\nSHARED = decimal.Context(prec=4, traps=[decimal.Inexact])\ndef producer(barrier):\n    barrier.wait()\n    for _ in range(ITERATIONS):\n        try:\n            SHARED.create_decimal(\"1.23456\")  # reads ctx-\u003etraps\n        except decimal.Inexact:\n            pass\ndef clearer(barrier):\n    barrier.wait()\n    for _ in range(ITERATIONS):\n        SHARED.clear_traps()             # ctx-\u003etraps = 0;\nrun_concurrently([producer]*4 + [clearer]*4)\n```\n\n### 4. `signaldict_setitem` self-race (`:744` / `:747`)\n\n```python\n# repro_signaldict_set.py\nimport decimal\nfrom common import ITERATIONS, run_concurrently\nSHARED = decimal.Context(prec=28)\nA, B = decimal.Inexact, decimal.Rounded  # different bits, same word\ndef setter_a(barrier):\n    barrier.wait()\n    for _ in range(ITERATIONS):\n        SHARED.flags[A] = True     # |= bit_a\n        SHARED.flags[A] = False    # \u0026= ~bit_a\ndef setter_b(barrier):\n    barrier.wait()\n    for _ in range(ITERATIONS):\n        SHARED.flags[B] = True\n        SHARED.flags[B] = False\nrun_concurrently([setter_a]*4 + [setter_b]*4)\nprint(\"final flags:\", dict(SHARED.flags))   # observable lost-update on FT\n```\n\n(Substituting `SHARED.traps` for `SHARED.flags` produces the same race on `ctx-\u003etraps`.)\n\n### 5. `signaldict_getitem` read vs. `dec_addstatus` write (`:715` ↔ `:616`)\n\n```python\n# repro_signaldict_get.py\nimport decimal\nfrom common import ITERATIONS, run_concurrently\nSHARED = decimal.Context(prec=4)\nINEXACT = decimal.Inexact\ndef producer(barrier):\n    barrier.wait()\n    for _ in range(ITERATIONS):\n        SHARED.create_decimal(\"1.23456\")\ndef reader(barrier):\n    barrier.wait()\n    for _ in range(ITERATIONS):\n        _ = SHARED.flags[INEXACT]   # reads ctx-\u003estatus non-atomically\nrun_concurrently([producer]*4 + [reader]*4)\n```\n\n## Suggested fix\n\nThe cleanest free-threading-safe option is a per-`Context` `PyMutex` covering all reads and writes of `status` and `traps`. The fields are tiny (one `uint32_t` each) and accessed at very high frequency, so an alternative is to switch to `_Py_atomic_or_uint32` / `_Py_atomic_and_uint32` / `_Py_atomic_load_uint32` / `_Py_atomic_store_uint32` directly on the fields. Given that the trap-detection path needs to read `traps` and `status` together, atomics-only is a little awkward (the OR-then-test sequence wants both observations to be from the same logical state), so `PyMutex` is probably the better fit; the lock-free path can be reserved for the hot read in `signaldict_getitem` if profiling shows the mutex matters.\n\nEither way, the fix should also cover the four `CTX(...)-\u003estatus = 0;` resets at `:1825`, `:1901`, `:1924`, `:1985` (in `current_context_from_dict`, `PyDec_SetCurrentContext`, `init_current_context`, and `PyDec_SetCurrentContext` for the contextvar variant) — those are stores into a `Context` that has just been created or just been swapped in, so they're not strictly racy in the current code, but if any future change exposes them earlier the same atomicity argument applies.\n\n## Related\n\n- #141148 / #146482 — fixes the implicit `getcontext()`/`current_context()` inheritance path. After that PR lands, the primitive sites above are still racy whenever a `Context` is shared explicitly (e.g. `Decimal(value, context=shared_ctx)` or `shared_ctx.create_decimal(s)`); see the issue's own MRE for an explicit-share case that #146482 doesn't cover.\n\n_Drafted by Claude Code, reviewed by a human._\n\n### CPython versions tested on:\n\nCPython main branch, 3.15\n\n### Operating systems tested on:\n\nLinux\n\n\u003c!-- gh-linked-prs --\u003e\n### Linked PRs\n* gh-150598\n\u003c!-- /gh-linked-prs --\u003e\n","author":{"url":"https://github.com/devdanzin","@type":"Person","name":"devdanzin"},"datePublished":"2026-04-29T09:21:55.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":4},"url":"https://github.com/149142/cpython/issues/149142"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:e3931e2e-eb1f-8452-0cba-7e85eb6aee9a
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-id8964:3BE023:60E0:78E6:6A53F3EA
html-safe-nonce023392089ffa05eba9dd81f884ab6b47d0938d654ecef5609dccb083bcb89f62
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4OTY0OjNCRTAyMzo2MEUwOjc4RTY6NkE1M0YzRUEiLCJ2aXNpdG9yX2lkIjoiMTg0NDc3Mjc1NzAzMzk3MjcxNCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac8f86b2c8d0bbf2e8a9f8a9842c10293dad3ef10577b2f372673cb090cb79be16
hovercard-subject-tagissue:4349303323
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/149142/issue_layout
twitter:imagehttps://opengraph.githubassets.com/7522964c0b35316ad96bc00e335b8f305b9b7d72fd421dec5ef875fbef34e9b5/python/cpython/issues/149142
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/7522964c0b35316ad96bc00e335b8f305b9b7d72fd421dec5ef875fbef34e9b5/python/cpython/issues/149142
og:image:altBug report Bug description: Summary Modules/_decimal/_decimal.c performs unsynchronized read-modify-write and plain stores on the status and traps fields of mpd_context_t embedded in a Python decim...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamedevdanzin
hostnamegithub.com
expected-hostnamegithub.com
Noneb9a586c06a05a7a86fc7e3f4dbd03e42f6869085879aa184aa6369456dbd50fb
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
release07a982c1d40157c619b364352b704c3ce66bb332
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/python/cpython/issues/149142#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F149142
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%2F149142
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/149142
Reloadhttps://github.com/python/cpython/issues/149142
Reloadhttps://github.com/python/cpython/issues/149142
Please reload this pagehttps://github.com/python/cpython/issues/149142
python https://github.com/python
cpythonhttps://github.com/python/cpython
Please reload this pagehttps://github.com/python/cpython/issues/149142
Notifications https://github.com/login?return_to=%2Fpython%2Fcpython
Fork 35k https://github.com/login?return_to=%2Fpython%2Fcpython
Star 73.8k 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
_decimal: mpd_context_t::status/traps mutated non-atomically leading to data racehttps://github.com/python/cpython/issues/149142#top
docsDocumentation in the Doc dirhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22docs%22
extension-modulesC modules in the Modules dirhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22extension-modules%22
topic-free-threadinghttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-free-threading%22
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
https://github.com/devdanzin
devdanzinhttps://github.com/devdanzin
on Apr 29, 2026https://github.com/python/cpython/issues/149142#issue-4349303323
#141148https://github.com/python/cpython/issues/141148
#146482https://github.com/python/cpython/pull/146482
#146482https://github.com/python/cpython/pull/146482
data races in decimal module with global context #141148https://github.com/python/cpython/issues/141148
GH-141148: ensure tasks/threads get fresh copy of decimal.Context #146482https://github.com/python/cpython/pull/146482
GH-141148: ensure tasks/threads get fresh copy of decimal.Context #146482https://github.com/python/cpython/pull/146482
GH-149142: Fix decimal mpd_context_t.status race in free-threading #150598https://github.com/python/cpython/pull/150598
docsDocumentation in the Doc dirhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22docs%22
extension-modulesC modules in the Modules dirhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22extension-modules%22
topic-free-threadinghttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-free-threading%22
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
docs issueshttps://github.com/orgs/python/projects/52
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.