Repository navigation
Description
Summary
When opening lammps using the python interface to the shared library, commands that invoke the interpreter from inside lammps can cause fatal errors.
LAMMPS Version and Platform
LAMMPS Versions: Probably many, but found in at least LAMMPS (24 Mar 2022), LAMMPS (29 Oct 2020) and LAMMPS (31 Aug 2021), LAMMPS (29 Aug 2021).
Operating system: MacOS, but this probably about the build of python rather than the OS per se.
Python: Various conda builds of python, including anaconda distributions as well as conda-forge distributions.
Expected Behavior
This feature should hopefully work?
Actual Behavior
The program crashes due to a failure to acquire references to the active python interpreter.
Depending on the python build, one may receive one of several error messages. I have omitted the normal output. It appears to fail when funcs.py intends to import the lammps python module.
Segfault:
<...>
LOOP ARGS 10 1.0 -4.0 <capsule object NULL at 0x10a2bb720>
Segmentation fault: 11
Fatal Python Error:
<...>
LOOP ARGS 10 1.0 -4.0 <capsule object NULL at 0x7fd8a813a780>
Fatal Python error: _PyInterpreterState_Get(): no current thread state
Python runtime state: initialized
Free without allocation error:
<...>
python(28375,0x1114f9e00) malloc: *** error for object 0x10422f080: pointer being freed was not allocated
python(28375,0x1114f9e00) malloc: *** set a breakpoint in malloc_error_break to debug
*** Process received signal ***
Signal: Abort trap: 6 (6)
Signal code: (0)
[ 0] 0 libsystem_platform.dylib 0x00007fff20994d7d _sigtramp + 29
[ 1] 0 ??? 0x00007fc7ba70d830 0x0 + 140495803177008
[ 2] 0 libsystem_c.dylib 0x00007fff208a4406 abort + 125
[ 3] 0 libsystem_malloc.dylib 0x00007fff20784165 has_default_zone0 + 0
[ 4] 0 libsystem_malloc.dylib 0x00007fff207872aa malloc_report + 151
[ 5] 0 python 0x0000000103c8ccd3 _PyObject_Free + 115
Steps to Reproduce
The easiest way to reproduce the issue is to run the following script in the /examples/python directory of lammps:
import lammps
lmp=lammps.lammps()
lmp.file('in.python')
Further Information, Files, and Links
This error seems to occur because the python executable is compiled against its static library rather than its shared library. When python is the driving code, and LAMMPS attempts to check if the python interpreter is active, Py_IsInitialized() returns 0, even though it should return 1.
As such, the error can be detected -without- lammps at all:
import sysconfig
import ctypes
library = sysconfig.get_config_vars('INSTSONAME')[0]
pylib = ctypes.CDLL(library)
if not pylib.Py_IsInitialized():
raise RuntimeError("This interpreter is not compatible with python->lammps->python controll flow..")
(On some builds INSTSONAME reports the wrong name for the python shared library, but this is a separate issue.)
I have also confirmed that from within lammps, Py_IsInitialized() returns 0,
You can likewise reproduce the segmentation fault in the interpreter by doing something nontrivial such as attempting to import a module:
>>> library.PyImport_ImportModule(b"collections")
Segmentation fault: 11
Note: within python itself, there is ctypes.pythonapi which -can- access the C-API of the running interpreter, so the above is not really a bug, just the wrong way of doing things.
My conclusion so far is that when loading the python shared library in a static build of python, the symbols in the shared library are distinct and not the ones used by the python interpreter. What we should want is for the calls in LAMMPS to call back into the active interpreter's symbol space.
-
This issue also affects the MLIAP package, and is the reason for the inclusion of the code here, but I want to be clear that this problem has nothing to do with the cython extensions used in MLIAP; the above shows that it is based on how the LAMMPS python module operates.
-
Python bindings should use
-undefined dynamic_lookupwhenPy_ENABLE_SHAREDis 0 stanford-centaur/pono#92 (comment) says that the sysconfig variable "Py_ENABLE_SHARED" can be used to detect a similar-sounding problem, however, I have a working python+LAMMPS on linux where Py_ENABLE_SHARED is zero, so I don't know if we can trust that. -
Are you switching to dynamic linking? conda-forge/python-feedstock#222 (comment) says that maybe one can load the python executable as a shared library to get around a similar-sounding problem. I attempted this and did not find it successful - I could fool ctypes into thinking that the executable was a library, but it returned 0 for Py_IsInitialized().
-
In principle scikit-build has a function called target_link_libraries_with_dynamic_lookup that is possibly supposed to handle this kind of 'lazy load'. I attempted to see if is possible to patch this into lammps cmake but I get an error that I don't know how to fix.
The test project needs language C which is not enabled.
This is also associated with some scikit-build machinery which seems to be aimed at helping to embed python or build extensions. -
I have some old conda environments laying around from late 3.6/early 3.7 that used to work and not crash, so it's not a fundamental problem with macos.
Some potential ways to address this
-
If the LAMMPS python module was built as a c-extension from python, this problem will likely not occur - in this case references to the python API in the lammps module python do not come through the python shared library. While this would most likely work, it might significantly change the build process and involve refactoring how python talks to lammps. From my limited experience, it is not too difficult to wrap the calls in liblammps using cython and compile an extension module for a given set of LAMMPS compiler settings, however, automatic integration of the various compiler flags that LAMMPS uses (serial vs parallel, BIGINT size) to the setup.py file was nontrivial to me. While such a project could have other benefits, I find it highly unclear whether this would be worth the work -- so it's probably not the right place to start.
-
Potentially, changes in how linking works: it's possible that there are some differences in the compilation flags for embedded python vs python extension modules that could be worked into our the LAMMPS build process. It could require building a separate shared compiled library to use in the lammps python module? I don't know. The scikit-build machinery or parts of it might help here.
-
Leave it alone - decide that this use case is outside of the scope of LAMMPS, at least for now.
3b) Raise an error or warning for the user ahead of crashing: One could add some state to the liblammps library which the python interpreter can set when opening lammps, when a command that requires the python interpreter runs, lammps can detect the flag is set and raise an error or warning instead of just dying - similar to the warning in lammps.mliap, but enforcing it in all scenarios where this can be a problem (through lammps/src/pythonimpl)
@rbberger Is this something you could take a look at?
@junghans Any idea if target_link_libraries_with_dynamic_lookup is something that might help?
Thanks to @jan-janssen and @athomps for helping to confirm.
Activity
rbberger commentedon Apr 6, 2022
@lubbersnick If the Python interpreter isn't compiled and linked in a way that exports its symbols as dynamic, in order for the dynamic loader to find them, there's nothing you can do. The straight forward way is having Python compiled with position independent code (PIC) and linked dynamically to libpython.
Statically linked Python interpreters, whose symbols aren't exposed, can not be used in the scenario you showcase.
If the Python interpreter exposes the symbols, then we might be able to modify how our CMake build links to Python (not libpython) as the linked discussions describe if it can be reliably detected.
rbberger commentedon Apr 6, 2022
@lubbersnick the scikit function probably just needs you to set and enable a C compiler in the parent project. The alternative is to convert the generated .c and .h file into equivalent .cpp and .h C++ files with extern C declarations if needed.
rbberger commentedon Apr 6, 2022
Overall, I'm personally trending towards 3.
lubbersnick commentedon Apr 6, 2022
So I don't quite understand -- the scikit-build thing does not aim to solve the same problem as we have here? If it does aim to solve this problem then working the cmake settings out is probably not intractable and option 2 might be feasible.
akohlmey commentedon Apr 6, 2022
No. It tries to address the problem that symbols for a plugin or shared library may be present when loading, either from another shared object or exported from the main executable, but not when linking the object. It suppresses a linker error on missing symbols when creating the plugin or shared object.
As @rbberger already stated, the problem you report is a problem of the packaging/building of the python interpreter that is launched first. If that does not export its symbols (e.g. on Linux via -Wl,--export-dynamic), then it is game over.
lubbersnick commentedon Apr 6, 2022
Ok. Here's my suggested course of action: 3b, which I volunteer for.
I will move the checks on loading the python shared library into the main section of the lammps python module rather than the MLIAP sub-section. In liblammps, I will hooks to set a global variable PYTHON_COMAMNDS_MAY_FAIL, which defaults to 0 and can be set to 1. If python-side checks fail, lammps.py will call into liblammps and set this flag. When lammps::pythonimpl starts up, it will check this flag and, if present, emit a warning that undefined behavior including fatal errors may occur.
@akohlmey @rbberger How does that sound? Is there any reason not to do this?
akohlmey commentedon Apr 6, 2022
This sounds to me like putting a band-aid on top of a band-aid.
akohlmey commentedon Apr 25, 2022
Unless there is a significant number of reports of problems, this is not really an action item, since it is ultimately a packaging problem and not a LAMMPS issue. However, we are seeing multiple other issues with "conda-style" packaging causing a variety of problems (not just for using LAMMPS), so that the best course of action in that case would be to simply recommend people not using it.
jan-janssen commentedon Apr 25, 2022
@akohlmey I am happy to recompile the conda package - I am just not sure how to do it correctly, can you provide some guidance?
akohlmey commentedon Apr 25, 2022
As far as I remember, a) the python library needs to be compiled as a shared library, and the python executable (as well as any executable embedding the corresponding python interpreter) needs to be linked with either
-Xlinker -export-dynamicor-Wl,-export-dynamicor whatever the equivalent command is for a given compiler/linker toolchain. That way all symbols are relocatable and can be added to the globally exported symbol table and thus referred back to by any (shared) library or object loaded later. Depending on the platform, it may also be possible without a) but at the very least compilation with -fpic to create relocatable objects are required. Otherwise linking of the lammps shared library will fail with when embedding the python interpreter.This seems to be what is done and how it is working on our development and automated test platforms, which include Fedora 35, CentOS 7, Ubuntu 18.04, Ubuntu 20.04, MacOS (on intel), and Windows 10 (with MSVC). We're using the "native" software distribution features for all of those to install missing packages. For Linux OS we use singularity container images, the definition files of which are part of the LAMMPS distribution.
rohskopf commentedon Apr 27, 2022
@jan-janssen, seems like conda's python is built without --enabled-shared. If you compile python from source with
./configure --enabled-shared, then you can make a virtual environment out of that. That fixed the issue for me.