From af7b6dfebce4bf360fa16c9fba1b159fee633cdf Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Sun, 10 May 2026 21:05:19 +0500 Subject: [PATCH] fix: drop leaked PYTHONPATH on package init (#1423) Venvs do not strip PYTHONPATH from inheritance. On multi-Python systems where PYTHONPATH points at a different Python's site-packages, transitive imports of compiled extensions (pydantic_core, chromadb_rust_bindings) load the wrong ABI and crash with ModuleNotFoundError on pydantic_core._pydantic_core. Place the pop in mempalace/__init__.py (instead of cli.py as the reporter proposed) so all entry points are covered: the mempalace shell command, python -m mempalace, and import mempalace from a library. Tests: tests/test_init.py runs the strip in a subprocess, parametrized over set / unset PYTHONPATH. Closes #1423. --- mempalace/__init__.py | 10 ++++++++++ tests/test_init.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 tests/test_init.py 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}"