fix(service): restore MEMPALACE_PALACE_PATH after the call that stamped it

Each run_* entrypoint sets MEMPALACE_PALACE_PATH so downstream config
resolution sees that call's palace, and none of them put it back. In the
daemon that costs nothing — one call, one process. In any process making
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 since 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 run_mine, run_sync and run_diary_write the same
discipline through a small decorator.

Tests cover both directions — a caller whose variable was already set
gets it back unchanged, and a caller who had none keeps none. All four
fail with the decorators removed.
This commit is contained in:
Joshua Fontany
2026-08-08 13:15:12 -07:00
parent c7a026bbd0
commit accb4e3245
2 changed files with 88 additions and 0 deletions
+34
View File
@@ -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:
+54
View File
@@ -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