Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions Lib/test/test_free_threading/test_func_watcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import gc
import unittest

from test.support import import_helper, threading_helper

_testcapi = import_helper.import_module("_testcapi")

NTHREADS = 8
ITERS = 200


def template(x=1, *, y=2):
return x


@threading_helper.requires_working_threading()
class TestFuncWatcherThreadSafety(unittest.TestCase):
"""MODIFY events and stores to function fields must not interleave.

When a function watcher receives a MODIFY event, the function must still
hold the value announced by the previous event for the same attribute.
Otherwise watchers that track a function's state (e.g. a JIT) can end up
believing it holds a different value than it does.
"""

def setUp(self):
# Stopping the world for a garbage collection can suspend the
# function's critical section between an event and its store. Keep
# the GC out of the way so this checks what the setters guarantee.
if gc.isenabled():
gc.disable()
self.addCleanup(gc.enable)

def check_events_match_stores(self, event, getter, setter, make_value):
def target(x=1, *, y=2):
return x

def writer():
for _ in range(ITERS):
setter(target, make_value())

_testcapi.start_func_order_watcher(target, event)
try:
threading_helper.run_concurrently(writer, NTHREADS)
finally:
history, mismatches = _testcapi.stop_func_order_watcher()

self.assertEqual(mismatches, 0,
f"{mismatches} of {len(history) - 1} events were "
f"delivered before the previous event's store")
self.assertEqual(len(history), NTHREADS * ITERS + 1)
self.assertIs(getter(target), history[-1])

def check_attr(self, attr, event, make_value):
self.check_events_match_stores(
event,
lambda f: getattr(f, attr),
lambda f, v: setattr(f, attr, v),
make_value)

def test_code(self):
# Every store gets a distinct code object so that identity checks
# can't pass by coincidence.
code = template.__code__
self.check_attr(
"__code__", _testcapi.PYFUNC_EVENT_MODIFY_CODE,
lambda: code.replace(co_name=f"template_{id(object())}"))

def test_defaults(self):
self.check_attr(
"__defaults__", _testcapi.PYFUNC_EVENT_MODIFY_DEFAULTS,
lambda: (object(),))

def test_kwdefaults(self):
self.check_attr(
"__kwdefaults__", _testcapi.PYFUNC_EVENT_MODIFY_KWDEFAULTS,
lambda: {"y": object()})

def test_qualname(self):
self.check_attr(
"__qualname__", _testcapi.PYFUNC_EVENT_MODIFY_QUALNAME,
lambda: str(object()))

def test_defaults_via_capi(self):
self.check_events_match_stores(
_testcapi.PYFUNC_EVENT_MODIFY_DEFAULTS,
lambda f: f.__defaults__,
_testcapi.set_func_defaults_via_capi,
lambda: (object(),))

def test_kwdefaults_via_capi(self):
self.check_events_match_stores(
_testcapi.PYFUNC_EVENT_MODIFY_KWDEFAULTS,
lambda f: f.__kwdefaults__,
_testcapi.set_func_kwdefaults_via_capi,
lambda: {"y": object()})


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Function watchers are now run under the function's critical section.
114 changes: 114 additions & 0 deletions Modules/_testcapi/watchers.c
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "pycore_interp_structs.h" // CODE_MAX_WATCHERS
#include "pycore_context.h" // CONTEXT_MAX_WATCHERS
#include "pycore_lock.h" // _PyOnceFlag
#include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_LOAD_PTR_RELAXED()

/*[clinic input]
module _testcapi
Expand Down Expand Up @@ -648,6 +649,117 @@ allocate_too_many_func_watchers(PyObject *self, PyObject *args)
Py_RETURN_NONE;
}

// A function watcher that checks MODIFY events for one function will arrive in
// the same order as their corresponding stores. When an event is delivered,
// the watched field must still hold the value announced by the previous event.
// Written in C so that it doesn't run any bytecode or drop references to
// objects owned by other threads, either of which can block and suspend the
// function's critical section.
static int order_watcher_id = -1;
static PyObject *order_target;
static PyFunction_WatchEvent order_event;
static PyObject *order_history; // announced values, in event order
static Py_ssize_t order_mismatches;

static PyObject *
get_watched_func_field(PyFunctionObject *func, PyFunction_WatchEvent event)
{
PyObject *value;
switch (event) {
case PyFunction_EVENT_MODIFY_CODE:
value = FT_ATOMIC_LOAD_PTR_RELAXED(func->func_code);
break;
case PyFunction_EVENT_MODIFY_DEFAULTS:
value = FT_ATOMIC_LOAD_PTR_RELAXED(func->func_defaults);
break;
case PyFunction_EVENT_MODIFY_KWDEFAULTS:
value = FT_ATOMIC_LOAD_PTR_RELAXED(func->func_kwdefaults);
break;
case PyFunction_EVENT_MODIFY_QUALNAME:
value = FT_ATOMIC_LOAD_PTR_RELAXED(func->func_qualname);
break;
default:
Py_UNREACHABLE();
}
return value == NULL ? Py_None : value;
}

static int
order_func_watcher_callback(PyFunction_WatchEvent event,
PyFunctionObject *func, PyObject *new_value)
{
if ((PyObject *)func != order_target || event != order_event) {
return 0;
}
PyObject *current = get_watched_func_field(func, event);
int res;
Py_BEGIN_CRITICAL_SECTION(order_history);
Py_ssize_t n = PyList_GET_SIZE(order_history);
if (PyList_GET_ITEM(order_history, n - 1) != current) {
_Py_atomic_add_ssize(&order_mismatches, 1);
}
res = PyList_Append(order_history, new_value ? new_value : Py_None);
Py_END_CRITICAL_SECTION();
return res;
}

static PyObject *
start_func_order_watcher(PyObject *self, PyObject *args)
{
PyObject *func;
int event;
if (!PyArg_ParseTuple(args, "O!i", &PyFunction_Type, &func, &event)) {
return NULL;
}
if (event != PyFunction_EVENT_MODIFY_CODE &&
event != PyFunction_EVENT_MODIFY_DEFAULTS &&
event != PyFunction_EVENT_MODIFY_KWDEFAULTS &&
event != PyFunction_EVENT_MODIFY_QUALNAME)
{
PyErr_SetString(PyExc_ValueError, "expected a MODIFY event");
return NULL;
}
if (order_watcher_id != -1) {
PyErr_SetString(PyExc_RuntimeError, "order watcher already active");
return NULL;
}
PyObject *current = get_watched_func_field((PyFunctionObject *)func,
(PyFunction_WatchEvent)event);
PyObject *history = PyList_New(1);
if (history == NULL) {
return NULL;
}
PyList_SET_ITEM(history, 0, Py_NewRef(current));
int wid = PyFunction_AddWatcher(order_func_watcher_callback);
if (wid < 0) {
Py_DECREF(history);
return NULL;
}
order_watcher_id = wid;
order_target = Py_NewRef(func);
order_event = (PyFunction_WatchEvent)event;
order_history = history;
order_mismatches = 0;
Py_RETURN_NONE;
}

static PyObject *
stop_func_order_watcher(PyObject *self, PyObject *Py_UNUSED(args))
{
if (order_watcher_id == -1) {
PyErr_SetString(PyExc_RuntimeError, "order watcher not active");
return NULL;
}
if (PyFunction_ClearWatcher(order_watcher_id) < 0) {
return NULL;
}
order_watcher_id = -1;
PyObject *result = Py_BuildValue("(Nn)", order_history, order_mismatches);
order_history = NULL;
Py_CLEAR(order_target);
return result;
}

// Test contexct object watchers
#define NUM_CONTEXT_WATCHERS 2
static int context_watcher_ids[NUM_CONTEXT_WATCHERS] = {-1, -1};
Expand Down Expand Up @@ -861,6 +973,8 @@ static PyMethodDef test_methods[] = {
_TESTCAPI_SET_FUNC_KWDEFAULTS_VIA_CAPI_METHODDEF
{"allocate_too_many_func_watchers", allocate_too_many_func_watchers,
METH_NOARGS, NULL},
{"start_func_order_watcher", start_func_order_watcher, METH_VARARGS, NULL},
{"stop_func_order_watcher", stop_func_order_watcher, METH_NOARGS, NULL},

// Code object watchers.
{"add_context_watcher", add_context_watcher, METH_O, NULL},
Expand Down
78 changes: 37 additions & 41 deletions Objects/funcobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,32 @@ func_clear_version(PyInterpreterState *interp, PyFunctionObject *func)
func->func_version = FUNC_VERSION_CLEARED;
}

/* Notify watchers that *field is about to change, then store new_value (a new
reference) into it.

The function's critical section is held across both steps so that concurrent
modifications of the same function deliver their events in the same order as
their stores. The watchers must not be called while the world is stopped as
they can run arbitrary code and can deadlock by stopping the world again
(e.g. by triggering a garbage collection) or by waiting on a lock held by a
parked thread. */
static void
func_set_watched_field(PyFunctionObject *func, PyFunction_WatchEvent event,
PyObject **field, PyObject *new_value)
{
PyInterpreterState *interp = _PyInterpreterState_GET();
PyObject *old_value;
Py_BEGIN_CRITICAL_SECTION(func);
handle_func_event(event, func, new_value);
_PyEval_StopTheWorld(interp);

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 opens up the opportunity for us to release the critical section, have the function be further modified before we stop the world, and then when we resume w/ the world stopped the function is modified from before we do the update.

I think in that case watchers should be in a sane state - we've fired the events in order, but here we're going to update to the 1st value which is going to lead to an inconsistent state.

I think we probably need to capture (and inc ref) the value and then validate that it's the same. I think it's similar to https://github.com/python/cpython/pull/161586/changes - @nascheme may have this paged into his head enough where he has a good idea if this is the same pattern.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Yeah, I think this design has problems. It can't promise the ordering if the STW request is contended (stw->mutex, or a global STW like GC). The CS can be suspended and other threads run holding that CS before you enter STW. Also, if the callback suspends (by allocating and triggering GC, taking another critical section, or running bytecode), another setter can get in.

Two possible ideas: document that MODIFY events can arrive in different order from the stores, when threads race. I'm guessing you don't want that, seems the point of this PR to avoid it.

Another idea, record something (per-func modification count) under the CS before firing the event, in STW check and if changed the restart and retry. I think you could still get "strange" events, e.g. if T1 sets A and T2 sets B, watcher could see A B A. That approach seems similar to the counter based approach I was trying to use to fix the typeobject STW deadlock issue. Tricky to get right.

@alexmalyshev alexmalyshev Dec 4, 2026 •

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.

Two possible ideas: document that MODIFY events can arrive in different order from the stores, when threads race. I'm guessing you don't want that, seems the point of this PR to avoid it.

Yeah I'd prefer not to further cement this behavior if possible.

Another idea, record something (per-func modification count) under the CS before firing the event, in STW check and if changed the restart and retry. I think you could still get "strange" events, e.g. if T1 sets A and T2 sets B, watcher could see A B A.

Also would like to avoid this.

Suggesting a much larger change, but could we stop the world on just the first time we clear the function's version? IIUC, once cleared, it can never change value again. It would require hunting down all the places where these fields are loaded without holding the critical section or using atomics though. But the upside would be that we could then just use the function's critical section for all future function modifications.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think that could work. There are quite a lot of readers to change. It would require atomic loads for the hot paths but should have negligible performance impact. Perhaps that should happen in a different PR and then this one would be just moving the event into the CS?

func_clear_version(interp, func);
old_value = *field;
*field = new_value;
_PyEval_StartTheWorld(interp);
Py_END_CRITICAL_SECTION();
Py_XDECREF(old_value);
}

void
_PyFunction_ClearCodeByVersion(uint32_t version)
{
Expand Down Expand Up @@ -436,14 +462,8 @@ PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
return -1;
}
PyFunctionObject *func = (PyFunctionObject *)op;
handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, func, defaults);
PyInterpreterState *interp = _PyInterpreterState_GET();
_PyEval_StopTheWorld(interp);
func_clear_version(interp, func);
PyObject *old_defaults = func->func_defaults;
func->func_defaults = defaults;
_PyEval_StartTheWorld(interp);
Py_XDECREF(old_defaults);
func_set_watched_field(func, PyFunction_EVENT_MODIFY_DEFAULTS,
&func->func_defaults, defaults);
return 0;
}

Expand Down Expand Up @@ -486,14 +506,8 @@ PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
return -1;
}
PyFunctionObject *func = (PyFunctionObject *)op;
handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, func, defaults);
PyInterpreterState *interp = _PyInterpreterState_GET();
_PyEval_StopTheWorld(interp);
func_clear_version(interp, func);
PyObject *old_kwdefaults = func->func_kwdefaults;
func->func_kwdefaults = defaults;
_PyEval_StartTheWorld(interp);
Py_XDECREF(old_kwdefaults);
func_set_watched_field(func, PyFunction_EVENT_MODIFY_KWDEFAULTS,
&func->func_kwdefaults, defaults);
return 0;
}

Expand Down Expand Up @@ -731,14 +745,8 @@ func_set_code(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
}
}

handle_func_event(PyFunction_EVENT_MODIFY_CODE, op, value);
PyInterpreterState *interp = _PyInterpreterState_GET();
_PyEval_StopTheWorld(interp);
func_clear_version(interp, op);
PyObject *old_code = op->func_code;
op->func_code = Py_NewRef(value);
_PyEval_StartTheWorld(interp);
Py_XDECREF(old_code);
func_set_watched_field(op, PyFunction_EVENT_MODIFY_CODE,
&op->func_code, Py_NewRef(value));
return 0;
}

Expand Down Expand Up @@ -786,8 +794,8 @@ func_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
"__qualname__ must be set to a string object");
return -1;
}
handle_func_event(PyFunction_EVENT_MODIFY_QUALNAME, (PyFunctionObject *) op, value);
Py_BEGIN_CRITICAL_SECTION(op);
handle_func_event(PyFunction_EVENT_MODIFY_QUALNAME, op, value);
_PyObject_XSetRefDelayed(&op->func_qualname, Py_NewRef(value));
Py_END_CRITICAL_SECTION();
return 0;
Expand Down Expand Up @@ -873,14 +881,8 @@ func_set_defaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
return -1;
}

handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, op, value);
PyInterpreterState *interp = _PyInterpreterState_GET();
_PyEval_StopTheWorld(interp);
func_clear_version(interp, op);
PyObject *old_defaults = op->func_defaults;
op->func_defaults = Py_XNewRef(value);
_PyEval_StartTheWorld(interp);
Py_XDECREF(old_defaults);
func_set_watched_field(op, PyFunction_EVENT_MODIFY_DEFAULTS,
&op->func_defaults, Py_XNewRef(value));
return 0;
}

Expand Down Expand Up @@ -921,14 +923,8 @@ func_set_kwdefaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
return -1;
}

handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, op, value);
PyInterpreterState *interp = _PyInterpreterState_GET();
_PyEval_StopTheWorld(interp);
func_clear_version(interp, op);
PyObject *old_kwdefaults = op->func_kwdefaults;
op->func_kwdefaults = Py_XNewRef(value);
_PyEval_StartTheWorld(interp);
Py_XDECREF(old_kwdefaults);
func_set_watched_field(op, PyFunction_EVENT_MODIFY_KWDEFAULTS,
&op->func_kwdefaults, Py_XNewRef(value));
return 0;
}

Expand Down
Loading