Skip to content

gh-154348: fix data race on nogil build about sys.monitoring.use_tool_id()#154459

Open
weixlu wants to merge 1 commit into
python:mainfrom
weixlu:race
Open

gh-154348: fix data race on nogil build about sys.monitoring.use_tool_id()#154459
weixlu wants to merge 1 commit into
python:mainfrom
weixlu:race

Conversation

@weixlu

@weixlu weixlu commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

As reported in #154348 (found by devdanzin's fusil), interp->monitoring_tool_names[tool_id] for sys.monitoring is accessed without any synchronization, which is a data race on free-threaded build.

The fix is straightforward, just add a dedicated PyMutex and serialize all access on monitoring_tool_names

Testing

  • The reproducer (8 threads × 6000 rounds) now runs clean under a TSAN build.
  • This PR only adds a mutex, so basic functional behavior is unchanged.

Notes for reviewer:

  • Of course the writer need a lock, but why reader (i.e. monitoring.get_tool) needs one as well? Because it reads the pointer and then increfs it. A concurrent free_tool_id can run Py_CLEAR (drop the last reference and free the object) in between, turning the Py_NewRef into a use-after-free.
  • The clear/free paths calls _PyMonitoring_ClearToolId, which internally does a stop-the-world. Is it safe to hold a PyMutex across STW? This is safe, because a thread blocked on PyMutex_Lock detaches its thread state, so it is seen as stopped.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant