Skip to content

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

Open
weixlu wants to merge 4 commits into
python:mainfrom
weixlu:race
Open

weixlu wants to merge 4 commits 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.

@weixlu

weixlu commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

I discussed this with @gaogaotiantian , and he'd like to see if there are approaches other than a lock to handle the data race. I've put together a few options:

  1. The current approach — use a dedicated PyMutex.

  2. Use Py_BEGIN_CRITICAL_SECTION to declare a critical section. The underlying mechanism is still a lock, and there's already similar usage in instrumentation.c, see:

  #define LOCK_CODE(code)                                             \
      assert(!_PyInterpreterState_GET()->stoptheworld.world_stopped); \
      Py_BEGIN_CRITICAL_SECTION(code)
  1. Use atomic operations (CAS, etc.), which would avoid the lock overhead and give better performance. That said, I think monitoring_tool is a fairly cold path, so the benefit of
    going lock-free isn't significant, and atomic op is more error-prone. Of course, if there's a need for it, I'm happy to implement and post it for review.

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

This PR is stale because it has been open for 90 days with no activity.

@github-actions github-actions Bot added the stale Stale PR or inactive for long period of time. label Nov 6, 2026
@johng

johng commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Do you have an implementation with critical section to review? I think we can deadlock with the plain mutex because we can technically execute arbitrary Python code on __del__ and call a function such as sys.monitoring.get_tool() which would then wait on the lock.

@weixlu

weixlu commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@johng Thanks! That makes sense. I've switched to critical section

Comment thread Python/instrumentation.c
Comment on lines +2220 to +2221
PyCriticalSection cs;
PyCriticalSection_Begin(&cs, module);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should prefere Py_BEGIN_CRITICAL_SECTION which gives added benefit of fork safety and is compiled out for the GIL build

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, Py_BEGIN_CRITICAL_SECTION is indeed better, though using it also requires restructuring the NULL check so there's a single critical section exit, which makes the diff a bit larger. My original intention was to keep the changes minimal to make the PR easier to review, though I'm not sure which approach is better here.

Comment thread Python/instrumentation.c Outdated
}
return Py_NewRef(name);
PyObject *ret = Py_NewRef(name);
PyCriticalSection_End(&cs);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can the unlock not be closer to line 2284?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've advanced the unlock, but I'm afraid it still needs to be placed within the critical section, because a concurrent free_tool_id can run Py_CLEAR in between, turning the Py_NewRef into a use-after-free.

Comment thread Python/instrumentation.c
Comment on lines +2190 to +2198
PyCriticalSection cs;
PyCriticalSection_Begin(&cs, module);
if (interp->monitoring_tool_names[tool_id] != NULL) {
PyErr_Format(PyExc_ValueError, "tool %d is already in use", tool_id);
PyCriticalSection_End(&cs);
return NULL;
}
interp->monitoring_tool_names[tool_id] = Py_NewRef(name);
PyCriticalSection_End(&cs);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this can be refactored so we just have a single critical section exit

Comment thread Python/instrumentation.c Outdated
Comment on lines +2250 to +2254
PyCriticalSection cs;
PyCriticalSection_Begin(&cs, module);
if (interp->monitoring_tool_names[tool_id] != NULL) {
if (_PyMonitoring_ClearToolId(tool_id) < 0) {
PyCriticalSection_End(&cs);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can be split across two critical sections so we're not holding it over the clear. We'd never have certainty we're holding it for the whole section anyway

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, fixed

Comment thread Python/instrumentation.c
PyInterpreterState *interp = _PyInterpreterState_GET();

PyCriticalSection cs;
PyCriticalSection_Begin(&cs, module);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe can use atomics for just a simple read?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, atomic would be enough. But if we use atomic op here, the writes in other places would also need to be atomic, otherwise TSAN will still report a data race. At that point, it feels like we might not even need critical sections. So I'm inclined to pick either critical sections or atomics rather than mixing the two.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we not need them in sections where we make a write and read to this field?

@johng

johng commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@gaogaotiantian would you kindly be able to help review too as was mentioned above you had previous discussion on this issue, thanks!

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

Labels

awaiting review stale Stale PR or inactive for long period of time.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants