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.
This commit is contained in:
mvalentsev
2026-05-13 22:53:36 +05:00
parent 475810ed43
commit af7b6dfebc
2 changed files with 48 additions and 0 deletions
+10
View File
@@ -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
+38
View File
@@ -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}"