diff --git a/mempalace/service.py b/mempalace/service.py index b4ec76b..44e92b8 100644 --- a/mempalace/service.py +++ b/mempalace/service.py @@ -10,6 +10,7 @@ from __future__ import annotations import contextlib import io +import functools import os import sys from typing import Any @@ -18,6 +19,36 @@ from .config import MempalaceConfig _EXPLICIT_BACKEND_ENV = "MEMPALACE_BACKEND_EXPLICIT" _PALACE_PATH_ENV = "MEMPALACE_PALACE_PATH" + + +def _restores_palace_env(fn): + """Restore ``MEMPALACE_PALACE_PATH`` after the call that stamped it. + + Each ``run_*`` entrypoint sets the variable so downstream config resolution sees THIS + call's palace. In the daemon that costs nothing — one call, one process. In any process + that makes two calls it leaks: ``config.py`` reads this variable with priority OVER the + config file, so the first call's palace silently becomes the second caller's, and a + tmpdir palace that has since been removed reads back as ``PalaceNotFoundError`` from an + unrelated code path. + + ``daemon.py`` already saves and restores exactly these keys around its own dispatch. + This gives the service entrypoints the same discipline. + """ + + @functools.wraps(fn) + def _wrapped(*args, **kwargs): + previous = os.environ.get(_PALACE_PATH_ENV) + try: + return fn(*args, **kwargs) + finally: + if previous is None: + os.environ.pop(_PALACE_PATH_ENV, None) + else: + os.environ[_PALACE_PATH_ENV] = previous + + return _wrapped + + _BACKEND_ENV = "MEMPALACE_BACKEND" # Env vars a job may mutate via _apply_backend / palace_path injection. They are # snapshotted per job and restored afterward so a job that switches the backend @@ -140,6 +171,7 @@ def execute_job(kind: str, payload: dict[str, Any]) -> dict[str, Any]: return result +@_restores_palace_env def run_mine(payload: dict[str, Any]) -> dict[str, Any]: """Run the same mine operation as the CLI, without daemon transport concerns.""" palace_path = os.path.abspath( @@ -232,6 +264,7 @@ def run_mine(payload: dict[str, Any]) -> dict[str, Any]: return {"success": True, "kind": "mine", "mode": mode, "dry_run": dry_run, "exit_code": 0} +@_restores_palace_env def run_sync(payload: dict[str, Any]) -> dict[str, Any]: """Run sync and render the same operator-facing summary shape as the CLI.""" palace_path = os.path.abspath( @@ -337,6 +370,7 @@ def run_sync(payload: dict[str, Any]) -> dict[str, Any]: return {"success": True, "report": report, "exit_code": 0} +@_restores_palace_env def run_diary_write(payload: dict[str, Any]) -> dict[str, Any]: palace_path = payload.get("palace_path") if palace_path: diff --git a/tests/test_service_palace_env.py b/tests/test_service_palace_env.py new file mode 100644 index 0000000..c8e4899 --- /dev/null +++ b/tests/test_service_palace_env.py @@ -0,0 +1,54 @@ +"""A service entrypoint leaves MEMPALACE_PALACE_PATH as it found it.""" + +from __future__ import annotations + +import os + +import pytest + +from mempalace import service + +_ENV = "MEMPALACE_PALACE_PATH" + + +@pytest.fixture(autouse=True) +def _restore_env(): + before = os.environ.get(_ENV) + yield + if before is None: + os.environ.pop(_ENV, None) + else: + os.environ[_ENV] = before + + +@pytest.mark.parametrize("entrypoint", ["run_mine", "run_sync", "run_diary_write"]) +def test_entrypoint_restores_the_palace_path_it_stamped(entrypoint, tmp_path, monkeypatch): + """`config.py` reads this variable with priority OVER the config file, so a stamp left + standing makes the first call's palace the second caller's. One call per process never + notices; any process making two does. + + The entrypoint is expected to fail on the throwaway path — the assertion covers what the + environment looks like AFTER it returns or raises, which is the property at issue. + """ + monkeypatch.setenv(_ENV, "/palace/the-caller-already-had") + fn = getattr(service, entrypoint) + + try: + fn({"palace_path": str(tmp_path / "throwaway"), "source": str(tmp_path)}) + except Exception: # noqa: BLE001 - the call's outcome is not what this asserts + pass + + assert os.environ.get(_ENV) == "/palace/the-caller-already-had" + + +def test_an_entrypoint_that_found_no_variable_leaves_none_behind(tmp_path, monkeypatch): + """The unset case matters as much: a stamp left where nothing stood makes every later + resolution in the process read a palace the caller never named.""" + monkeypatch.delenv(_ENV, raising=False) + + try: + service.run_mine({"palace_path": str(tmp_path / "throwaway"), "source": str(tmp_path)}) + except Exception: # noqa: BLE001 + pass + + assert _ENV not in os.environ