diff --git a/mempalace/__init__.py b/mempalace/__init__.py index 893a71b..c5a5465 100644 --- a/mempalace/__init__.py +++ b/mempalace/__init__.py @@ -1,6 +1,16 @@ """MemPalace — Give your AI a memory. No API key required.""" import logging +import os + + +def _strip_leaked_pythonpath() -> None: + # Venvs inherit PYTHONPATH; on multi-Python systems it can load + # compiled extensions with the wrong ABI and crash on import. + os.environ.pop("PYTHONPATH", None) + + +_strip_leaked_pythonpath() from .version import __version__ # noqa: E402 diff --git a/tests/test_init.py b/tests/test_init.py new file mode 100644 index 0000000..6abe5a0 --- /dev/null +++ b/tests/test_init.py @@ -0,0 +1,38 @@ +"""__init__-level guards that must take effect before transitive imports.""" + +import os +import subprocess +import sys + +import pytest + + +@pytest.mark.parametrize( + "pythonpath", + [ + "/tmp/some/leaked/path", + None, + ], +) +def test_init_strips_leaked_pythonpath(pythonpath): + """Package init must drop PYTHONPATH before compiled extensions load, + regardless of whether it was set in the parent environment.""" + env = os.environ.copy() + if pythonpath is None: + env.pop("PYTHONPATH", None) + else: + env["PYTHONPATH"] = pythonpath + result = subprocess.run( + [ + sys.executable, + "-c", + "import mempalace, os; print(repr(os.environ.get('PYTHONPATH')))", + ], + env=env, + capture_output=True, + text=True, + check=True, + ) + assert ( + result.stdout.strip() == "None" + ), f"PYTHONPATH not stripped (input was {pythonpath!r}): {result.stdout!r}"