Title: PyContext watcher registry has data races in free-threaded builds · Issue #155619 · python/cpython · GitHub
Open Graph Title: PyContext watcher registry has data races in free-threaded builds · Issue #155619 · python/cpython
X Title: PyContext watcher registry has data races in free-threaded builds · Issue #155619 · python/cpython
Description: Bug description PyContext_AddWatcher() and PyContext_ClearWatcher() are public in Python 3.14's and above free-threaded builds, but CPython's context-watcher registry is accessed without synchronization. The public declarations are avail...
Open Graph Description: Bug description PyContext_AddWatcher() and PyContext_ClearWatcher() are public in Python 3.14's and above free-threaded builds, but CPython's context-watcher registry is accessed without synchroniz...
X Description: Bug description PyContext_AddWatcher() and PyContext_ClearWatcher() are public in Python 3.14's and above free-threaded builds, but CPython's context-watcher registry is accessed without sy...
Opengraph URL: https://github.com/python/cpython/issues/155619
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"PyContext watcher registry has data races in free-threaded builds","articleBody":"### Bug description\n\n`PyContext_AddWatcher()` and `PyContext_ClearWatcher()` are public in Python 3.14's and above free-threaded builds, but CPython's context-watcher registry is accessed without synchronization.\n\nThe public declarations are available unconditionally for CPython 3.14+ builds:\n\n- [`PyContext_WatchCallback`, `PyContext_AddWatcher()`, and `PyContext_ClearWatcher()`](https://github.com/python/cpython/blob/dbac03b411549c0f40fbb66127ae6f445027fcc8/Include/cpython/context.h#L30-L62)\n\nThe per-interpreter registry consists of two ordinary, non-atomic fields:\n\n- [`PyInterpreterState.context_watchers[CONTEXT_MAX_WATCHERS]`](https://github.com/python/cpython/blob/dbac03b411549c0f40fbb66127ae6f445027fcc8/Include/internal/pycore_interp_structs.h#L979-L985), an array of callback function pointers\n- [`PyInterpreterState.active_context_watchers`](https://github.com/python/cpython/blob/dbac03b411549c0f40fbb66127ae6f445027fcc8/Include/internal/pycore_interp_structs.h#L982-L985), a `uint8_t` bitmask indicating which slots are active\n\nAll three operations access this shared state without a lock or atomic operations:\n\n1. [`notify_context_watchers()`](https://github.com/python/cpython/blob/dbac03b411549c0f40fbb66127ae6f445027fcc8/Python/context.c#L113-L142) reads the bitmask and callback pointers.\n2. [`PyContext_AddWatcher()`](https://github.com/python/cpython/blob/dbac03b411549c0f40fbb66127ae6f445027fcc8/Python/context.c#L145-L161) scans and writes the callback array, then performs a read-modify-write on the bitmask.\n3. [`PyContext_ClearWatcher()`](https://github.com/python/cpython/blob/dbac03b411549c0f40fbb66127ae6f445027fcc8/Python/context.c#L164-L180) reads and clears the callback slot, then performs another read-modify-write on the bitmask.\n\nNotification is performed directly by the thread whose current context changes: [`context_switched()` calls `notify_context_watchers()`](https://github.com/python/cpython/blob/dbac03b411549c0f40fbb66127ae6f445027fcc8/Python/context.c#L183-L190), including from `PyContext_Enter()` and `PyContext_Exit()`. On a free-threaded interpreter, multiple attached threads in the same interpreter can therefore dispatch callbacks concurrently while another thread calls AddWatcher or ClearWatcher.\n\nThis creates CPython-internal data races, independently of whether the callback protects its own state:\n\n| Concurrent operations | Shared objects | Possible result |\n|---|---|---|\n| AddWatcher / AddWatcher | Callback slots and active bitmask | Both callers can select the same empty slot, one callback can overwrite the other, and both can return the same watcher ID. Concurrent bitmask read-modify-writes can also lose an update. |\n| AddWatcher / notification | Callback slots and active bitmask | Notification can observe an active bit without a safely published callback pointer, or otherwise observe inconsistent/stale registry state. |\n| ClearWatcher / notification | Callback slots and active bitmask | Notification can snapshot an active bit and then load a callback slot which has become NULL. In a debug build this reaches `assert(cb != NULL)`; in a release build it may attempt to call a NULL or stale function pointer. |\n| ClearWatcher / ClearWatcher | Callback slot and active bitmask | Both callers can observe the slot as registered, and their unsynchronized reads/writes constitute a data race. |\n| AddWatcher / ClearWatcher | Callback slots and active bitmask | A slot may be reused while another operation is clearing it, producing a mismatched callback/active-bit state. |\n\nThe same implementation is present on the current [Python 3.14 branch](https://github.com/python/cpython/blob/e2ec020314487c3fea9807894172becb6c5f4577/Python/context.c#L113-L180).\n\nThere is also an API-lifetime question: `PyContext_ClearWatcher()` does not specify whether a callback already selected by another thread may begin or continue after ClearWatcher returns. Without that guarantee, an extension cannot know when it is safe to tear down state used by its callback. Separately, because notifications run on the switching threads, the documentation should say explicitly that a single `PyContext_WatchCallback` may be invoked concurrently by multiple threads in a free-threaded interpreter.\n\nThe [context watcher documentation](https://github.com/python/cpython/blob/dbac03b411549c0f40fbb66127ae6f445027fcc8/Doc/c-api/contextvars.rst#L104-L148) currently specifies registration, clearing, and exception handling, but does not describe any free-threading restrictions or concurrency guarantees.\n\nFor comparison:\n\n- [Dictionary watcher documentation](https://github.com/python/cpython/blob/dbac03b411549c0f40fbb66127ae6f445027fcc8/Doc/c-api/dict.rst#L443-L470) explicitly says AddWatcher and ClearWatcher are not internally synchronized and require external synchronization on free-threaded builds.\n- [Type watcher documentation](https://github.com/python/cpython/blob/dbac03b411549c0f40fbb66127ae6f445027fcc8/Doc/c-api/type.rst#L78-L99) explicitly requires `PyType_AddWatcher()` to run at startup before spawning the first thread.\n\nA startup-only rule would avoid concurrent AddWatcher calls, but it would not by itself make ClearWatcher safe against notifications from active threads. Context switches are normal runtime operations, so external synchronization against internal notification is not generally available to an extension.\n\n### Expected behavior\n\nAccess to CPython's per-interpreter context-watcher registry should be data-race-free in free-threaded builds.\n\nThe API should also define:\n\n- whether the same callback can execute concurrently on multiple threads;\n- whether `PyContext_ClearWatcher()` waits for, cancels, or permits already-selected/in-flight callbacks;\n- when callback-owned state may safely be destroyed after clearing a watcher.\n\nThe implementation likely needs synchronization or an atomic publication/snapshot scheme for AddWatcher, ClearWatcher, and notification. Any solution should account for callback reentrancy and avoid holding a registry lock while calling extension callbacks.\n\nAt minimum, if concurrent registration or clearing cannot be supported, the documentation should state enforceable startup/shutdown restrictions. Documentation alone does not appear sufficient for ClearWatcher racing with notification unless the API also provides a usable lifetime rule.\n\n### CPython versions\n\n- Python 3.14 branch at `e2ec020314487c3fea9807894172becb6c5f4577`\n- CPython main at `dbac03b411549c0f40fbb66127ae6f445027fcc8`\n\nThis report is based on source inspection. The races are platform-independent C data races in the free-threaded build; I have not included a probabilistic crash reproducer.\n\n### Operating systems\n\nAll platforms using a free-threaded CPython build.\n\n### Related issues\n\n- [gh-127124: Pass opaque state to PyContext_AddWatcher callback](https://github.com/python/cpython/issues/127124) is related to callback state management, but does not appear to cover synchronization of the watcher registry.\n\n\n### CPython versions tested on:\n\n3.14\n\n### Operating systems tested on:\n\nmacOS\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-155943\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/florentinl","@type":"Person","name":"florentinl"},"datePublished":"2026-08-12T11:45:34Z","url":"https://github.com/python/cpython/issues/155619"}
| react-profiling | 0 |
| react-import-map | react,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-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:f2e4cafc-c14d-bd76-88fc-1e4034f865dc |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 9D0E:1FAE:14FBA65:1BF27E6:6B022F6A |
| html-safe-nonce | 57e2136acf59305e706e577da05c026525cad86f6484c7906a406d32acdc013f |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5RDBFOjFGQUU6MTRGQkE2NToxQkYyN0U2OjZCMDIyRjZBIiwidmlzaXRvcl9pZCI6IjQwNzI0ODAwNzYyMzc3Nzg3OTQiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 08d9528a31837c11bab2ff07d814e059d4ec27c229de6ca39b71b73d1d0a4901 |
| hovercard-subject-tag | issue:5130502966 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/155619/issue_layout |
| twitter:image | https://opengraph.githubassets.com/64bd416edee51f3a9228215f5c80df3d62504e0a8d95c6c0437ee4a1193ee8f3/python/cpython/issues/155619 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/64bd416edee51f3a9228215f5c80df3d62504e0a8d95c6c0437ee4a1193ee8f3/python/cpython/issues/155619 |
| og:image:alt | Bug description PyContext_AddWatcher() and PyContext_ClearWatcher() are public in Python 3.14's and above free-threaded builds, but CPython's context-watcher registry is accessed without synchroniz... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | florentinl |
| hostname | github.com |
| expected-hostname | github.com |
| None | 87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 423dbb54c5e7bfecc838eb387c1435eb3d0e760d |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width