diff --git a/src/slic3r/plugin/PluginManager.hpp b/src/slic3r/plugin/PluginManager.hpp index 21d2bc1e5b..aa7cafef84 100644 --- a/src/slic3r/plugin/PluginManager.hpp +++ b/src/slic3r/plugin/PluginManager.hpp @@ -130,6 +130,7 @@ public: // Reject new plugin loads. Called early in app teardown, before shutdown() drains. void set_shutting_down(); + bool is_shutting_down() const { return m_shutting_down.load(std::memory_order_acquire); } void discover_plugins(bool async = false, bool clear = false); // Manually trigger a manifest-only rescan. Blocks until discovery is complete. diff --git a/src/slic3r/plugin/PythonInterpreter.cpp b/src/slic3r/plugin/PythonInterpreter.cpp index ca0dfa16f4..129407e511 100644 --- a/src/slic3r/plugin/PythonInterpreter.cpp +++ b/src/slic3r/plugin/PythonInterpreter.cpp @@ -3,7 +3,9 @@ #include "libslic3r/Utils.hpp" #include "PluginAuditManager.hpp" #include "PythonPluginBridge.hpp" +#include #include +#include #include #include #include @@ -45,7 +47,7 @@ PythonRuntimeLease::PythonRuntimeLease(PythonInterpreter& interpreter) return; } - m_lock = std::shared_lock(interpreter.m_runtime_mutex); + m_lock = std::shared_lock(interpreter.m_runtime_mutex); if (!interpreter.m_initialized.load(std::memory_order_acquire)) { m_lock.unlock(); return; @@ -477,7 +479,7 @@ std::string PythonInterpreter::bundled_uv_path() bool PythonInterpreter::initialize() { - std::unique_lock runtime_lock(m_runtime_mutex); + std::unique_lock runtime_lock(m_runtime_mutex); if (m_initialized.load(std::memory_order_acquire)) { return true; } @@ -688,7 +690,22 @@ PythonInterpreter::~PythonInterpreter() { shutdown(); } void PythonInterpreter::shutdown() { - std::unique_lock runtime_lock(m_runtime_mutex); + // Checked before waiting for the lock too, so a second call after abandon() returns at once. + if (!m_initialized.load(std::memory_order_acquire)) + return; + + // A plugin call that never returns keeps its runtime lease, and Py_Finalize joins every + // non-daemon thread, so either would keep a closing app alive. Both are waited for briefly. + constexpr auto wait = std::chrono::seconds(3); + + std::unique_lock runtime_lock(m_runtime_mutex, std::defer_lock); + if (!runtime_lock.try_lock_for(wait)) { + // The GIL is not taken back here: the stuck call may be holding it, and nothing on this + // thread runs Python after this point. + BOOST_LOG_TRIVIAL(warning) << "Python interpreter left unfinalized: a plugin call is still running"; + abandon(); + return; + } if (!m_initialized.load(std::memory_order_acquire)) return; @@ -701,6 +718,14 @@ void PythonInterpreter::shutdown() m_main_thread_state = nullptr; } + // Before the stdio tee is torn down, so tracebacks from threads still ending reach the log. + if (const int running = join_non_daemon_threads(wait); running > 0) { + // The GIL stays with this thread, so anything released during process exit still holds it. + BOOST_LOG_TRIVIAL(warning) << "Python interpreter left unfinalized: " << running << " non-daemon thread(s) still running"; + abandon(); + return; + } + log_and_restore_python_stdio(); BOOST_LOG_TRIVIAL(info) << "Finalizing Python interpreter"; @@ -714,6 +739,69 @@ void PythonInterpreter::shutdown() m_initialized.store(false, std::memory_order_release); } +void PythonInterpreter::abandon() +{ + // New leases fail from here on. Releasing the scoped_interpreter without destroying it skips + // Py_Finalize, here and in the static destructor; the process exit ends the interpreter. + m_initialized.store(false, std::memory_order_release); + static_cast(m_interpreter.release()); +} + +int PythonInterpreter::join_non_daemon_threads(std::chrono::milliseconds timeout) +{ + try { + const pybind11::module_ threading = pybind11::module_::import("threading"); + const pybind11::object main_thread = threading.attr("main_thread")(); + const auto deadline = std::chrono::steady_clock::now() + timeout; + const auto seconds_left = [deadline] { + return std::chrono::duration( + std::max(deadline - std::chrono::steady_clock::now(), std::chrono::steady_clock::duration::zero())) + .count(); + }; + + // 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 + // timeout, so one stuck in a task would block the hook, and Py_Finalize, for good. + pybind11::object hooks; + if (pybind11::hasattr(threading, "_threading_atexits")) { + hooks = threading.attr("Thread")(pybind11::arg("target") = pybind11::cpp_function([threading] { + const pybind11::list calls = threading.attr("_threading_atexits"); + for (pybind11::ssize_t i = calls.size(); i-- > 0;) + calls[i](); + }), + pybind11::arg("name") = "orca-threading-atexit", pybind11::arg("daemon") = true); + hooks.attr("start")(); + hooks.attr("join")(seconds_left()); + } + + // Enumerated again after each pass: a thread being joined may start another one. + for (;;) { + int seen = 0; + int running = 0; + for (const pybind11::handle thread : threading.attr("enumerate")()) { + // Threads Python did not start (C++ threads that entered Python) are dummy threads, + // which are daemon and cannot be joined. + if (thread.is(main_thread) || thread.attr("daemon").cast()) + continue; + ++seen; + thread.attr("join")(seconds_left()); + if (thread.attr("is_alive")().cast()) + ++running; + } + if (seen == 0 || std::chrono::steady_clock::now() >= deadline) { + // A hook still running would be run again, and waited for, by Py_Finalize. + if (hooks && hooks.attr("is_alive")().cast()) + running = std::max(running, 1); + return running; + } + } + } catch (const std::exception& ex) { + BOOST_LOG_TRIVIAL(warning) << "Could not wait for Python threads: " << ex.what(); + return 0; + } +} + bool PythonInterpreter::add_plugin_sys_path(const std::string& path, std::string& error) { if (!m_initialized.load(std::memory_order_acquire)) { diff --git a/src/slic3r/plugin/PythonInterpreter.hpp b/src/slic3r/plugin/PythonInterpreter.hpp index 8c5c5b3e40..3713dd9fab 100644 --- a/src/slic3r/plugin/PythonInterpreter.hpp +++ b/src/slic3r/plugin/PythonInterpreter.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -64,9 +65,17 @@ public: // Python ABI tag for the bundled interpreter, e.g. "cp312". static std::string python_abi_tag(); - // Finalize the Python interpreter. + // Finalize the Python interpreter. A plugin call that is still running, or a plugin thread that + // does not end, is waited for only briefly; the interpreter is then left unfinalized for the + // process exit to end, rather than keeping a closing app alive. void shutdown(); + // Runs the threading atexit hooks, which end idle worker threads, then waits for Python's + // non-daemon threads to end, up to timeout in all, and returns how many are still running. + // The caller must hold the GIL. Public so tests can reach it: shutdown() itself can + // only run once per process. + static int join_non_daemon_threads(std::chrono::milliseconds timeout); + // Add a path owned by one plugin load. The path is reference-counted across plugins and is // removed when the final plugin using it is unloaded. bool add_plugin_sys_path(const std::string& path, std::string& error); @@ -111,9 +120,10 @@ private: std::vector* plugin_modules); void remove_plugin_modules_locked(const std::vector& plugin_modules); void remove_module_tree_locked(const std::string& module_name); + void abandon(); std::atomic m_initialized{false}; - mutable std::shared_mutex m_runtime_mutex; + mutable std::shared_timed_mutex m_runtime_mutex; PyThreadState* m_main_thread_state = nullptr; // thread state saved after releasing GIL post-initialize std::unique_ptr m_interpreter; std::string m_last_error; @@ -146,7 +156,7 @@ private: static thread_local unsigned int s_depth; PythonInterpreter* m_interpreter = nullptr; - std::shared_lock m_lock; + std::shared_lock m_lock; }; inline PythonRuntimeLease PythonInterpreter::acquire_runtime_lease() diff --git a/src/slic3r/plugin/pluginTypes/printerAgent/PrinterAgentPluginCapabilityTrampoline.hpp b/src/slic3r/plugin/pluginTypes/printerAgent/PrinterAgentPluginCapabilityTrampoline.hpp index 812d69c072..18c0dbf1b2 100644 --- a/src/slic3r/plugin/pluginTypes/printerAgent/PrinterAgentPluginCapabilityTrampoline.hpp +++ b/src/slic3r/plugin/pluginTypes/printerAgent/PrinterAgentPluginCapabilityTrampoline.hpp @@ -9,13 +9,22 @@ #include "pybind11/pybind11.h" #include #include +#include #include #include #include +#include "slic3r/plugin/PluginManager.hpp" #include "slic3r/plugin/PythonInterpreter.hpp" #include +#include +#include +#include +#include +#include #include #include +#include +#include #include @@ -65,7 +74,11 @@ public: int disconnect_printer() override { - ORCA_PY_AGENT_OVERRIDE(int, disconnect_printer); + // While the app closes, the UI thread waits here; a plugin that never returns would keep it + // open, so the call gets a deadline and is left running past it. + if (!PluginManager::instance().is_shutting_down()) + return python_disconnect_printer(); + return disconnect_printer_at_shutdown(); } int send_message(std::string dev_id, std::string json_str, int qos, int flag) override @@ -305,6 +318,75 @@ public: } private: + int python_disconnect_printer() + { + ORCA_PY_AGENT_OVERRIDE(int, disconnect_printer); + } + + // One disconnect per agent at shutdown: the live agent and the agent cache both disconnect the + // same object, and a plugin need not handle two concurrent calls. Shared with the call's thread, + // which can outlive an abandoned wait. + struct ShutdownDisconnect + { + enum : int { Pending, Started, Abandoned }; + std::atomic state{Pending}; + std::promise result; + std::shared_future done{result.get_future().share()}; + std::chrono::steady_clock::time_point deadline{std::chrono::steady_clock::now() + std::chrono::seconds(3)}; + }; + + int disconnect_printer_at_shutdown() + { + std::shared_ptr call; + bool start = false; + { + std::lock_guard lock(m_shutdown_disconnect_mutex); + if (!m_shutdown_disconnect) { + m_shutdown_disconnect = std::make_shared(); + start = true; + } + call = m_shutdown_disconnect; + } + if (start) { + try { + std::thread([agent = this, call] { run_shutdown_disconnect(agent, *call); }).detach(); + } catch (const std::system_error&) { + // No thread, so no deadline either: call the plugin directly as before. + call->state.store(ShutdownDisconnect::Started); + const int result = python_disconnect_printer(); + call->result.set_value(result); + return result; + } + } + if (call->done.wait_until(call->deadline) == std::future_status::ready) + return call->done.get(); + int expected = ShutdownDisconnect::Pending; + call->state.compare_exchange_strong(expected, ShutdownDisconnect::Abandoned); + log_failure("disconnect_printer", "did not return within 3 s while the app is closing"); + return printer_agent_failure(); + } + + // Static so that nothing touches the agent, which may already be gone, before the call is claimed. + static void run_shutdown_disconnect(PyPrinterAgentPluginCapabilityTrampoline* agent, ShutdownDisconnect& call) + { + ::Slic3r::PythonGILState gil; + int expected = ShutdownDisconnect::Pending; + if (!gil || !call.state.compare_exchange_strong(expected, ShutdownDisconnect::Started)) { + // Abandoned before it started: the agent may already be gone, so it is not touched. + call.result.set_value(printer_agent_failure()); + return; + } + // The plugin may be force-unloaded while the call runs past its deadline. This reference keeps + // the Python object, and with it the agent, alive until the call has fully unwound; it is + // released before the GIL. + const pybind11::object self = pybind11::cast(static_cast(agent), + pybind11::return_value_policy::reference); + call.result.set_value(agent->python_disconnect_printer()); + } + + std::mutex m_shutdown_disconnect_mutex; + std::shared_ptr m_shutdown_disconnect; + void log_failure(const char* operation, const char* error) const { BOOST_LOG_TRIVIAL(error) << "Printer agent plugin '" << this->audit_plugin_key() << "': " << operation << " failed: " << error; diff --git a/tests/slic3rutils/test_plugin_lifecycle.cpp b/tests/slic3rutils/test_plugin_lifecycle.cpp index fc32511336..56a043d975 100644 --- a/tests/slic3rutils/test_plugin_lifecycle.cpp +++ b/tests/slic3rutils/test_plugin_lifecycle.cpp @@ -1098,6 +1098,61 @@ TEST_CASE("The bundled Python trusts the system CA certificates", "[PluginLifecy CHECK(default_context_ca_count() > 0); } +TEST_CASE("Waiting for Python threads at shutdown gives up on a thread that does not end", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + pybind11::gil_scoped_acquire gil; + + const pybind11::module_ threading = pybind11::module_::import("threading"); + const pybind11::object release = threading.attr("Event")(); + pybind11::object worker = threading.attr("Thread")(pybind11::arg("target") = release.attr("wait"), pybind11::arg("daemon") = false); + worker.attr("start")(); + + const auto start = std::chrono::steady_clock::now(); + CHECK(PythonInterpreter::join_non_daemon_threads(std::chrono::milliseconds(200)) == 1); + CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(5)); + + release.attr("set")(); + CHECK(PythonInterpreter::join_non_daemon_threads(std::chrono::seconds(5)) == 0); +} + +TEST_CASE("Waiting for Python threads at shutdown ends idle concurrent.futures workers", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + pybind11::gil_scoped_acquire gil; + + const pybind11::module_ threading = pybind11::module_::import("threading"); + const pybind11::module_ futures = pybind11::module_::import("concurrent.futures"); + const pybind11::module_ workers = pybind11::module_::import("concurrent.futures.thread"); + // The hooks that end the workers also refuse new tasks for the rest of the process; the + // interpreter outlives this test case. + const auto allow_new_tasks = [&workers] { workers.attr("_shutdown") = false; }; + + // An idle worker waits for its queue until the hooks tell it to end; the wait must not run out. + pybind11::object executor = futures.attr("ThreadPoolExecutor")(pybind11::arg("max_workers") = 1); + executor.attr("submit")(pybind11::module_::import("builtins").attr("int")).attr("result")(); + auto start = std::chrono::steady_clock::now(); + CHECK(PythonInterpreter::join_non_daemon_threads(std::chrono::seconds(5)) == 0); + CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(2)); + allow_new_tasks(); + + // A worker still in a task blocks the hooks; both are given up at the deadline. + const pybind11::object release = threading.attr("Event")(); + executor = futures.attr("ThreadPoolExecutor")(pybind11::arg("max_workers") = 1); + executor.attr("submit")(release.attr("wait")); + start = std::chrono::steady_clock::now(); + CHECK(PythonInterpreter::join_non_daemon_threads(std::chrono::milliseconds(200)) == 1); + CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(5)); + + release.attr("set")(); + CHECK(PythonInterpreter::join_non_daemon_threads(std::chrono::seconds(5)) == 0); + allow_new_tasks(); +} + #ifndef _WIN32 // Windows adds its system store whatever SSL_CERT_FILE names. TEST_CASE("SSL_CERT_FILE still overrides the bundled Python's default CA certificates", "[PluginLifecycle][Python]") { diff --git a/tests/slic3rutils/test_plugin_printer_agent.cpp b/tests/slic3rutils/test_plugin_printer_agent.cpp index 7b5c2ca9f9..717ea759b2 100644 --- a/tests/slic3rutils/test_plugin_printer_agent.cpp +++ b/tests/slic3rutils/test_plugin_printer_agent.cpp @@ -10,8 +10,10 @@ #include #include +#include #include #include +#include #include #include "plugin_test_utils.hpp" @@ -184,3 +186,68 @@ TEST_CASE("A working printer agent's answers reach the host unchanged", "[Plugin CHECK(agent->bind_detect("192.168.0.2", "secure", detect) == 0); CHECK(detect.dev_id == "192.168.0.2"); } + +TEST_CASE("A printer agent's disconnect_printer is not waited for past its deadline while the app closes", "[PluginPrinterAgent][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + py::gil_scoped_acquire gil; + + auto agent = make_agent(" release = __import__('threading').Event()\n" + " calls = 0\n" + " def disconnect_printer(self):\n" + " type(self).calls += 1\n" + " type(self).release.wait()\n" + " return 0\n"); + REQUIRE(agent.agent); + const auto capability = std::dynamic_pointer_cast(agent.agent); + REQUIRE(capability); + + PluginManager::instance().set_shutting_down(); + int first = 0; + int second = 0; + std::chrono::steady_clock::duration waited{}; + { + // As at app exit: the closing UI thread does not hold the GIL. It disconnects the agent twice, + // once as the live agent and once from the agent cache. + py::gil_scoped_release nogil; + const auto start = std::chrono::steady_clock::now(); + first = agent->disconnect_printer(); + second = agent->disconnect_printer(); + waited = std::chrono::steady_clock::now() - start; + } + CHECK(first == -1); + CHECK(second == -1); + CHECK(waited < std::chrono::seconds(5)); // one 3 s deadline, not two + // At most once: on a slow machine the call can be abandoned before its thread reaches Python. + CHECK(agent.instance.attr("calls").cast() <= 1); + + // Let the abandoned call finish before the agent is destroyed. + agent.instance.attr("release").attr("set")(); + { + py::gil_scoped_release nogil; + for (int i = 0; i < 500 && capability->ref_count() > 0; ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + CHECK(capability->ref_count() == 0); +} + +TEST_CASE("A printer agent's disconnect_printer still answers while the app closes", "[PluginPrinterAgent][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + py::gil_scoped_acquire gil; + + auto agent = make_agent(" def disconnect_printer(self): return 5\n"); + REQUIRE(agent.agent); + + PluginManager::instance().set_shutting_down(); + int result = 0; + { + py::gil_scoped_release nogil; + result = agent->disconnect_printer(); + } + CHECK(result == 5); +}