From b70cca5bfc47a6b6a996125eba97572438114136 Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Wed, 21 Oct 2026 12:53:15 -0700 Subject: [PATCH] gh-159739: Skip context watchers cleared during notification A context watcher callback can clear a later watcher while a context-switch notification is being dispatched. The dispatcher still uses its earlier snapshot of active watchers, so it calls a NULL callback and crashes; check that each callback is still registered before invoking it. Backport to 3.15 and 3.14. --- .../next/C_API/2026-10-21-19-55-00.gh-issue-159739.ctxt01.rst | 2 ++ Python/context.c | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/C_API/2026-10-21-19-55-00.gh-issue-159739.ctxt01.rst diff --git a/Misc/NEWS.d/next/C_API/2026-10-21-19-55-00.gh-issue-159739.ctxt01.rst b/Misc/NEWS.d/next/C_API/2026-10-21-19-55-00.gh-issue-159739.ctxt01.rst new file mode 100644 index 000000000000000..10c268e1043c9ed --- /dev/null +++ b/Misc/NEWS.d/next/C_API/2026-10-21-19-55-00.gh-issue-159739.ctxt01.rst @@ -0,0 +1,2 @@ +Avoid a crash if a context watcher is cleared while other context watchers +are being notified. diff --git a/Python/context.c b/Python/context.c index d48543c9e023a61..87f967063a27b20 100644 --- a/Python/context.c +++ b/Python/context.c @@ -169,8 +169,8 @@ notify_context_watchers(PyThreadState *ts, PyContextEvent event, PyObject *ctx) assert(i < CONTEXT_MAX_WATCHERS); if (bits & 1) { PyContext_WatchCallback cb = interp->context_watchers[i]; - assert(cb != NULL); - if (cb(event, ctx) < 0) { + // A previous callback may have cleared this watcher. + if (cb != NULL && cb(event, ctx) < 0) { PyErr_FormatUnraisable( "Exception ignored in %s watcher callback for %R", context_event_name(event), ctx);