diff --git a/Lib/test/test_free_threading/test_func_watcher.py b/Lib/test/test_free_threading/test_func_watcher.py new file mode 100644 index 00000000000000..1effb7915fa057 --- /dev/null +++ b/Lib/test/test_free_threading/test_func_watcher.py @@ -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() diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-24-00-41-44.gh-issue-162529.GJRQ7I.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-24-00-41-44.gh-issue-162529.GJRQ7I.rst new file mode 100644 index 00000000000000..9440341ec9fc75 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-24-00-41-44.gh-issue-162529.GJRQ7I.rst @@ -0,0 +1 @@ +Function watchers are now run under the function's critical section. diff --git a/Modules/_testcapi/watchers.c b/Modules/_testcapi/watchers.c index 71cdc54009017a..588720e42315a6 100644 --- a/Modules/_testcapi/watchers.c +++ b/Modules/_testcapi/watchers.c @@ -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 @@ -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}; @@ -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}, diff --git a/Objects/funcobject.c b/Objects/funcobject.c index 2e0bcd7853b925..d5a2ba0d4e10b2 100644 --- a/Objects/funcobject.c +++ b/Objects/funcobject.c @@ -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); + 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) { @@ -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; } @@ -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; } @@ -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; } @@ -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; @@ -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; } @@ -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; }