diff --git a/doc/source/changelog.rst b/doc/source/changelog.rst index fd3cfef2f..617c3daac 100644 --- a/doc/source/changelog.rst +++ b/doc/source/changelog.rst @@ -211,6 +211,10 @@ organisation on `GitHub `__. * Fixed ``System.set_time`` rejecting a zero time returned by ``System.time``, since a zero ``GeneralUnit`` has no units. +* Fixed converting a molecule to RDKit hanging, or aborting on Python 3.13 and later, when the + conversion emitted a warning, e.g. when bond orders couldn't be inferred. The console didn't + release the GIL after importing its Python implementation. + `2026.2.0 `__ - September 2026 ---------------------------------------------------------------------------------------------- diff --git a/tests/convert/test_rdkit.py b/tests/convert/test_rdkit.py index 845116f4c..5b83bd8e5 100644 --- a/tests/convert/test_rdkit.py +++ b/tests/convert/test_rdkit.py @@ -273,3 +273,37 @@ def test_rdkit_sdf_tags(tagged_sdf): # check that the data is the same on the rdkit molecule for prop in rdmol.GetPropNames(): assert rdmol.GetProp(prop) == rdmol2.GetProp(prop) + + +@pytest.mark.skipif( + "rdkit" not in sr.convert.supported_formats(), + reason="rdkit support is not available", +) +def test_rdkit_console_warning_without_gil(): + """ + Make sure that a console warning raised during conversion, which runs + without the GIL, doesn't hang or abort the interpreter. The conversion + runs in a separate process, since the failure is a deadlock. + """ + import subprocess + import sys + import textwrap + + # Hiding MDAnalysis makes bond-order inference of a molecule with dummy + # atoms fail, so the converter emits a warning. + script = textwrap.dedent( + """ + import sys + sys.modules["MDAnalysis"] = None + + import sire as sr + + mols = sr.morph.link_to_perturbed(sr.load_test_files("merged_molecule.s3")) + sr.convert.to_rdkit(mols.molecules("property is_perturbable")[0]) + """ + ) + + result = subprocess.run( + [sys.executable, "-c", script], capture_output=True, text=True, timeout=300 + ) + assert result.returncode == 0, result.stderr diff --git a/wrapper/Base/releasegil_impl.cpp b/wrapper/Base/releasegil_impl.cpp index 76a87077f..8c34c121f 100644 --- a/wrapper/Base/releasegil_impl.cpp +++ b/wrapper/Base/releasegil_impl.cpp @@ -4,6 +4,8 @@ #include "SireBase/console.h" #include "SireBase/releasegil.h" +#include "Helpers/scoped_gil_acquire.hpp" + #include static bool _is_ipython = false; @@ -282,65 +284,23 @@ class ConsoleImpl : public SireBase::ConsoleBase { if (pyconsole) { - PyGILState_STATE gilstate = PyGILState_Ensure(); + SireHelpers::ScopedGILAcquire gil; Py_DECREF(pyconsole); - delete pyconsole; pyconsole = 0; - PyGILState_Release(gilstate); } } void debug(const QString &message) const { - const_cast(this)->get_pyconsole(); - - if (pyconsole) - { - PyGILState_STATE gilstate = PyGILState_Ensure(); - - PyObject *result = PyObject_CallMethod(pyconsole, "debug", "s", message.toUtf8().constData()); - - if (result == 0) - { - qDebug() << "UNABLE TO CALL DEBUG"; - qDebug() << message; - } - else - { - Py_DECREF(result); - } - - PyGILState_Release(gilstate); - } - else + if (not this->call("debug", message)) { - qDebug() << "NO PYCONSOLE"; qDebug() << message; } } void warning(const QString &message) const { - const_cast(this)->get_pyconsole(); - - if (pyconsole) - { - PyGILState_STATE gilstate = PyGILState_Ensure(); - - PyObject *result = PyObject_CallMethod(pyconsole, "warning", "s", message.toUtf8().constData()); - - if (result == 0) - { - qWarning() << message; - } - else - { - Py_DECREF(result); - } - - PyGILState_Release(gilstate); - } - else + if (not this->call("warning", message)) { qWarning() << message; } @@ -348,26 +308,7 @@ class ConsoleImpl : public SireBase::ConsoleBase void error(const QString &message) const { - const_cast(this)->get_pyconsole(); - - if (pyconsole) - { - PyGILState_STATE gilstate = PyGILState_Ensure(); - - PyObject *result = PyObject_CallMethod(pyconsole, "error", "s", message.toUtf8().constData()); - - if (result == 0) - { - qCritical() << message; - } - else - { - Py_DECREF(result); - } - - PyGILState_Release(gilstate); - } - else + if (not this->call("error", message)) { qCritical() << message; } @@ -375,47 +316,48 @@ class ConsoleImpl : public SireBase::ConsoleBase void info(const QString &message) const { - const_cast(this)->get_pyconsole(); - - if (pyconsole) + if (not this->call("info", message)) { - PyGILState_STATE gilstate = PyGILState_Ensure(); + qInfo() << message; + } + } - PyObject *result = PyObject_CallMethod(pyconsole, "info", "s", message.toUtf8().constData()); +private: + /** Call the named method of the Python console with the message, + * returning whether it succeeded. */ + bool call(const char *method, const QString &message) const + { + SireHelpers::ScopedGILAcquire gil; - if (result == 0) - { - qInfo() << "UNABLE TO CALL INFO"; - qInfo() << message; - } - else - { - Py_DECREF(result); - } + const_cast(this)->get_pyconsole(); - PyGILState_Release(gilstate); - } - else + if (not pyconsole) + return false; + + PyObject *result = PyObject_CallMethod(pyconsole, method, "s", message.toUtf8().constData()); + + if (result == 0) { - qInfo() << "NO PYCONSOLE"; - qInfo() << message; + PyErr_Clear(); + return false; } + + Py_DECREF(result); + return true; } -private: + /** Import the Python console. This must be called with the GIL held. */ void get_pyconsole() { if (pyconsole) return; - PyGILState_STATE gilstate = PyGILState_Ensure(); - PyObject *sire_utils = PyImport_ImportModule("sire.utils"); if (sire_utils == 0) { + PyErr_Clear(); qWarning() << "COULD NOT IMPORT SIRE.UTILS"; - PyGILState_Release(gilstate); return; } @@ -425,9 +367,8 @@ class ConsoleImpl : public SireBase::ConsoleBase if (pyconsole == 0) { + PyErr_Clear(); qWarning() << "Could not import Console from sire.utils"; - PyGILState_Release(gilstate); - return; } } diff --git a/wrapper/Convert/SireOpenMM/pyqm.cpp b/wrapper/Convert/SireOpenMM/pyqm.cpp index 1370fb65e..068177e89 100644 --- a/wrapper/Convert/SireOpenMM/pyqm.cpp +++ b/wrapper/Convert/SireOpenMM/pyqm.cpp @@ -34,7 +34,9 @@ #include "openmm/serialization/SerializationNode.h" #include "openmm/serialization/SerializationProxy.h" +#include "Helpers/scoped_gil_acquire.hpp" #include "SireError/errors.h" + #include "SireMaths/vector.h" #include "SireStream/datastream.h" #include "SireStream/shareddatastream.h" @@ -51,16 +53,6 @@ using namespace SireVol; // atoms, in Angstrom. static const double VIRTUAL_PC_DELTA = 0.01; -class GILLock -{ -public: - GILLock() { state_ = PyGILState_Ensure(); } - ~GILLock() { PyGILState_Release(state_); } - -private: - PyGILState_STATE state_; -}; - ///////// ///////// Implementation of PyQMCallback ///////// @@ -159,7 +151,7 @@ PyQMCallback::call( { // Acquire GIL before calling Python code. - GILLock lock; + SireHelpers::ScopedGILAcquire gil; if (this->is_method) { @@ -216,7 +208,7 @@ PyQMCallback::call4( QVector idx_mm) const { // Acquire GIL before calling Python code. - GILLock lock; + SireHelpers::ScopedGILAcquire gil; bp::object result; try diff --git a/wrapper/Convert/SireRDKit/sire_rdkit.cpp b/wrapper/Convert/SireRDKit/sire_rdkit.cpp index 693a913d8..bbcfc9784 100644 --- a/wrapper/Convert/SireRDKit/sire_rdkit.cpp +++ b/wrapper/Convert/SireRDKit/sire_rdkit.cpp @@ -15,6 +15,8 @@ #include "boost/python.hpp" +#include "Helpers/scoped_gil_acquire.hpp" + #include "SireStream/datastream.h" #include "SireStream/shareddatastream.h" @@ -63,19 +65,6 @@ using SireMol::SelectorMol; namespace bp = boost::python; -// RAII wrapper to acquire/release the Python GIL before calling back into -// Python from arbitrary C++ contexts (including non-Python-created threads). -// Same pattern as wrapper/Convert/SireOpenMM/pyqm.cpp's GILLock. -class GILLock -{ -public: - GILLock() { state_ = PyGILState_Ensure(); } - ~GILLock() { PyGILState_Release(state_); } - -private: - PyGILState_STATE state_; -}; - namespace SireRDKit { // Optional Python callback used as a fallback for RDKit bond-order/ @@ -105,7 +94,7 @@ namespace SireRDKit if (bond_order_inference_callback == nullptr or bond_order_inference_callback->is_none()) return false; - GILLock lock; + SireHelpers::ScopedGILAcquire gil; try { diff --git a/wrapper/Helpers/CMakeLists.txt b/wrapper/Helpers/CMakeLists.txt index d3f34abce..401a2c96d 100644 --- a/wrapper/Helpers/CMakeLists.txt +++ b/wrapper/Helpers/CMakeLists.txt @@ -23,6 +23,7 @@ set ( WRAPHELPERS_SOURCES release_gil_policy.hpp release_gil_policy.cpp + scoped_gil_acquire.hpp scoped_gil_release.hpp ) diff --git a/wrapper/Helpers/scoped_gil_acquire.hpp b/wrapper/Helpers/scoped_gil_acquire.hpp new file mode 100644 index 000000000..dea994155 --- /dev/null +++ b/wrapper/Helpers/scoped_gil_acquire.hpp @@ -0,0 +1,34 @@ +#ifndef _HELPERS_SCOPED_GIL_ACQUIRE_HPP_ +#define _HELPERS_SCOPED_GIL_ACQUIRE_HPP_ + +#include "boost/python.hpp" + +namespace SireHelpers +{ + /** Acquire the GIL for the lifetime of this object. + * + * Use this before calling into Python from C++ that may run without the + * GIL, e.g. within a ScopedGILRelease or on a worker thread. The GIL is + * released on every return path, including during stack unwinding. + */ + class ScopedGILAcquire + { + public: + ScopedGILAcquire() : state(PyGILState_Ensure()) + { + } + + ~ScopedGILAcquire() + { + PyGILState_Release(state); + } + + private: + ScopedGILAcquire(const ScopedGILAcquire &); + ScopedGILAcquire &operator=(const ScopedGILAcquire &); + + PyGILState_STATE state; + }; +} + +#endif