Fix a Crash at Exit When an Earlier Python Thread Wait Timed Out (#17437)

join_non_daemon_threads() runs the threading exit hooks on a daemon thread and
gives up on it at the deadline. A later call started a new hook thread and
returned 0 without waiting for the old one, so shutdown() could run Py_Finalize
while the old thread was still running the hooks. Python then stops that daemon
thread when it reaches for the GIL; it unwinds through the hook lambda and
releases a Python list without the GIL while finalization's garbage collection
walks it, which crashes the process.

A call now first waits, within its deadline, for a hook thread an earlier call
left running, and counts it as still running if it does not end, so shutdown()
leaves the interpreter unfinalized instead.

This was the intermittent segfault at exit of the "ends idle
concurrent.futures workers" test, which calls the function more than once. The
app calls it once, from shutdown().
This commit is contained in:
HanifKoh authored and GitHub committed 2026-11-10 16:02:22 +08:00
1 parent 46f7b0e719
commit 9199df0811
3 files changed
+47 -1

No files matched your search

+13 -1
View File
@@ -764,6 +764,18 @@ int PythonInterpreter::join_non_daemon_threads(std::chrono::milliseconds timeout
.count();
};
// A hook thread an earlier call gave up on may still be running the hooks. Py_Finalize must
// not start under it: stopped there, it unwinds through the lambda below and releases
// Python objects without the GIL. It is waited for and counted like this call's own.
constexpr const char *hook_thread_name = "orca-threading-atexit";
for (const pybind11::handle thread : threading.attr("enumerate")()) {
if (thread.attr("name").cast<std::string>() != hook_thread_name)
continue;
thread.attr("join")(seconds_left());
if (thread.attr("is_alive")().cast<bool>())
return 1;
}
// An idle concurrent.futures worker only ends once the hooks registered with
// threading._register_atexit() tell it to, which Py_Finalize does before it joins the
// threads. They run first here, on a daemon thread: a hook joins its workers without a
@@ -775,7 +787,7 @@ int PythonInterpreter::join_non_daemon_threads(std::chrono::milliseconds timeout
for (pybind11::ssize_t i = calls.size(); i-- > 0;)
calls[i]();
}),
pybind11::arg("name") = "orca-threading-atexit", pybind11::arg("daemon") = true);
pybind11::arg("name") = hook_thread_name, pybind11::arg("daemon") = true);
hooks.attr("start")();
hooks.attr("join")(seconds_left());
}