From f5f9a88fdfcb38681226dc4c2a63601b8cbb79d7 Mon Sep 17 00:00:00 2001 From: Jonathan Stoff Date: Wed, 2 Dec 2026 13:26:42 -0500 Subject: [PATCH 1/2] fix(cache): key interpreter caches on absolute paths without mutating shared entries --- docs/changelog/+relative-exe-cache.bugfix.rst | 3 ++ src/python_discovery/_cached_py_info.py | 14 +++--- tests/python_discovery/test_cached_py_info.py | 43 ++++++++++++++++++- 3 files changed, 54 insertions(+), 6 deletions(-) create mode 100644 docs/changelog/+relative-exe-cache.bugfix.rst diff --git a/docs/changelog/+relative-exe-cache.bugfix.rst b/docs/changelog/+relative-exe-cache.bugfix.rst new file mode 100644 index 0000000..4578af9 --- /dev/null +++ b/docs/changelog/+relative-exe-cache.bugfix.rst @@ -0,0 +1,3 @@ +:meth:`~python_discovery.PythonInfo.from_exe` now keys its caches on the absolute executable path and copies cached +instances when ``executable`` differs, so relative paths follow working-directory changes and alternate path spellings +do not mutate previously returned :class:`~python_discovery.PythonInfo` objects. diff --git a/src/python_discovery/_cached_py_info.py b/src/python_discovery/_cached_py_info.py index d29dc43..16a31ac 100644 --- a/src/python_discovery/_cached_py_info.py +++ b/src/python_discovery/_cached_py_info.py @@ -3,6 +3,7 @@ from __future__ import annotations __lazy_modules__ = [ + "copy", "hashlib", "io", "pkgutil", @@ -17,6 +18,7 @@ f"{__spec__.parent}._windows", # ty: ignore[unresolved-attribute] # imported modules have a spec ] +import copy import hashlib import logging import os @@ -62,7 +64,7 @@ class CacheEntryMeta(TypedDict): _CACHE: Final[OrderedDict[tuple[Path, str | None], PythonInfo | Exception]] = OrderedDict() -_CACHE[Path(sys.executable), None] = PythonInfo() +_CACHE[Path(os.path.abspath(sys.executable)), None] = PythonInfo() # ruff:ignore[os-path-abspath] # keep symlink path _LOGGER: Final[logging.Logger] = logging.getLogger(__name__) _PY_INFO_SCRIPT: Final[Path] = Path(__file__).resolve().parent / "_py_info_collect.py" _MAX_QUERY_OUTPUT: Final[int] = 1 << 20 @@ -104,17 +106,19 @@ def _get_from_cache( # ruff:ignore[too-many-arguments] each argument is a separ ignore_cache: bool, executable_args: str | None, ) -> PythonInfo | Exception: - key = Path(exe), executable_args + path = Path(os.path.abspath(exe)) # ruff:ignore[os-path-abspath] # resolve() follows symlinks + key = path, executable_args if not ignore_cache and key in _CACHE: result = _CACHE[key] else: - result = _get_via_file_cache(cls, cache, key[0], exe, env, executable_args=executable_args) - if _cacheable_result(key[0], result): + result = _get_via_file_cache(cls, cache, path, exe, env, executable_args=executable_args) + if _cacheable_result(path, result): _CACHE[key] = result else: _CACHE.pop(key, None) # with launcher arguments the queried binary is not the interpreter, so keep the one the query reported - if isinstance(result, PythonInfo) and executable_args is None: + if isinstance(result, PythonInfo) and executable_args is None and result.executable != exe: + result = copy.copy(result) result.executable = exe return result diff --git a/tests/python_discovery/test_cached_py_info.py b/tests/python_discovery/test_cached_py_info.py index 31306b1..feb272c 100644 --- a/tests/python_discovery/test_cached_py_info.py +++ b/tests/python_discovery/test_cached_py_info.py @@ -8,7 +8,7 @@ from io import StringIO from os import read from pathlib import Path -from subprocess import DEVNULL, PIPE, Popen, TimeoutExpired, list2cmdline +from subprocess import DEVNULL, PIPE, Popen, TimeoutExpired, check_call, list2cmdline from threading import enumerate as active_threads from time import monotonic from typing import TYPE_CHECKING, Final @@ -773,3 +773,44 @@ def test_from_exe_timeout_with_inherited_pipes(tmp_path: Path) -> None: assert result is None assert monotonic() - started < 2.5 + + +@pytest.mark.parametrize("ignore_cache", [pytest.param(False, id="memory"), pytest.param(True, id="disk")]) +def test_from_exe_relative_path_follows_working_directory( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ignore_cache: bool +) -> None: + rel_exe = Path("venv/Scripts/python.exe" if sys.platform == "win32" else "venv/bin/python") + first, second = tmp_path / "first", tmp_path / "second" + for root in (first, second): + check_call([sys.executable, "-m", "venv", "--without-pip", str(root / "venv")]) + if sys.platform == "win32": # pragma: win32 cover + mtime = (first / rel_exe).stat().st_mtime + os.utime(second / rel_exe, (mtime, mtime)) + cache = DiskCache(tmp_path / "cache") + + monkeypatch.chdir(first) + earlier = PythonInfo.from_exe(str(rel_exe), cache, ignore_cache=ignore_cache, resolve_to_host=False) + monkeypatch.chdir(second) + later = PythonInfo.from_exe(str(rel_exe), cache, ignore_cache=ignore_cache, resolve_to_host=False) + + assert earlier is not None + assert later is not None + assert (earlier.prefix, later.prefix) == (str(first / "venv"), str(second / "venv")) + assert (earlier.executable, later.executable) == (str(rel_exe), str(rel_exe)) + + +def test_from_exe_leaves_cached_executable_untouched(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture) -> None: + monkeypatch.setattr(PythonInfo, "_current", None) + current = PythonInfo.current() + exe_path = Path(sys.executable) + dotted = f"{exe_path.parent}{os.sep}.{os.sep}{exe_path.name}" + query = mocker.patch("python_discovery._cached_py_info._get_via_file_cache", autospec=True) + + via_dot = PythonInfo.from_exe(dotted, resolve_to_host=False) + monkeypatch.chdir(exe_path.parent) + via_rel = PythonInfo.from_exe(exe_path.name, resolve_to_host=False) + + assert via_dot is not None + assert via_rel is not None + query.assert_not_called() + assert (current.executable, via_dot.executable, via_rel.executable) == (sys.executable, dotted, exe_path.name) From bf232c91d59e1eb0406b94a6e6cc612a78d73555 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Thu, 3 Dec 2026 21:11:49 -0800 Subject: [PATCH 2/2] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor(cache):=20anc?= =?UTF-8?q?hor=20relative=20paths=20with=20absolute?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Path.absolute anchors a relative executable at the working directory without the ".." collapsing of os.path.abspath, which can step out of a symlinked directory, and needs no lint suppression. The tests build both virtual environments in one venv call, compare their results in one assert, and no longer patch the private query function. --- src/python_discovery/_cached_py_info.py | 4 ++-- tests/python_discovery/test_cached_py_info.py | 15 ++++++++------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/python_discovery/_cached_py_info.py b/src/python_discovery/_cached_py_info.py index 16a31ac..44b50e9 100644 --- a/src/python_discovery/_cached_py_info.py +++ b/src/python_discovery/_cached_py_info.py @@ -64,7 +64,7 @@ class CacheEntryMeta(TypedDict): _CACHE: Final[OrderedDict[tuple[Path, str | None], PythonInfo | Exception]] = OrderedDict() -_CACHE[Path(os.path.abspath(sys.executable)), None] = PythonInfo() # ruff:ignore[os-path-abspath] # keep symlink path +_CACHE[Path(sys.executable).absolute(), None] = PythonInfo() _LOGGER: Final[logging.Logger] = logging.getLogger(__name__) _PY_INFO_SCRIPT: Final[Path] = Path(__file__).resolve().parent / "_py_info_collect.py" _MAX_QUERY_OUTPUT: Final[int] = 1 << 20 @@ -106,7 +106,7 @@ def _get_from_cache( # ruff:ignore[too-many-arguments] each argument is a separ ignore_cache: bool, executable_args: str | None, ) -> PythonInfo | Exception: - path = Path(os.path.abspath(exe)) # ruff:ignore[os-path-abspath] # resolve() follows symlinks + path = Path(exe).absolute() key = path, executable_args if not ignore_cache and key in _CACHE: result = _CACHE[key] diff --git a/tests/python_discovery/test_cached_py_info.py b/tests/python_discovery/test_cached_py_info.py index feb272c..881d0e2 100644 --- a/tests/python_discovery/test_cached_py_info.py +++ b/tests/python_discovery/test_cached_py_info.py @@ -781,8 +781,7 @@ def test_from_exe_relative_path_follows_working_directory( ) -> None: rel_exe = Path("venv/Scripts/python.exe" if sys.platform == "win32" else "venv/bin/python") first, second = tmp_path / "first", tmp_path / "second" - for root in (first, second): - check_call([sys.executable, "-m", "venv", "--without-pip", str(root / "venv")]) + check_call([sys.executable, "-m", "venv", "--without-pip", str(first / "venv"), str(second / "venv")]) if sys.platform == "win32": # pragma: win32 cover mtime = (first / rel_exe).stat().st_mtime os.utime(second / rel_exe, (mtime, mtime)) @@ -795,16 +794,19 @@ def test_from_exe_relative_path_follows_working_directory( assert earlier is not None assert later is not None - assert (earlier.prefix, later.prefix) == (str(first / "venv"), str(second / "venv")) - assert (earlier.executable, later.executable) == (str(rel_exe), str(rel_exe)) + assert (earlier.prefix, earlier.executable, later.prefix, later.executable) == ( + str(first / "venv"), + str(rel_exe), + str(second / "venv"), + str(rel_exe), + ) -def test_from_exe_leaves_cached_executable_untouched(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture) -> None: +def test_from_exe_leaves_cached_executable_untouched(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(PythonInfo, "_current", None) current = PythonInfo.current() exe_path = Path(sys.executable) dotted = f"{exe_path.parent}{os.sep}.{os.sep}{exe_path.name}" - query = mocker.patch("python_discovery._cached_py_info._get_via_file_cache", autospec=True) via_dot = PythonInfo.from_exe(dotted, resolve_to_host=False) monkeypatch.chdir(exe_path.parent) @@ -812,5 +814,4 @@ def test_from_exe_leaves_cached_executable_untouched(monkeypatch: pytest.MonkeyP assert via_dot is not None assert via_rel is not None - query.assert_not_called() assert (current.executable, via_dot.executable, via_rel.executable) == (sys.executable, dotted, exe_path.name)