Skip to content

The agent that grows with you

fix(tests): subprocess-surviving isolation marker closes the #82770 fixture escape

Teknium62d3ef683c52
diff --git a/hermes_state.py b/hermes_state.py
index 8ad73354d41..38e0f4e556b 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -461,11 +461,24 @@ def _real_platform_state_root() -> Optional[Path]:
return None
+#: Env marker exported by the hermetic test conftest at the same moment it
+#: redirects ``HERMES_HOME`` to the per-session tmp isolation root. Its
+#: value is that isolation root. Unlike ``PYTEST_*`` (owned by pytest, and
+#: routinely scrubbed by tests that rebuild a child environment), this marker
+#: is OURS: it declares "this process tree is running under Hermes test
+#: isolation", and it inherits into subprocess children by default — so a
+#: child that received the patched ``HERMES_HOME`` also received the marker,
+#: and a child that resolves a production DB while carrying it is, by
+#: definition, an isolation escape (#82770).
+_TEST_ISOLATION_MARKER_ENV = "HERMES_TEST_ISOLATION"
+
+
def _running_under_pytest() -> bool:
"""True when this process (or a parent test process) is a pytest run."""
return bool(
os.environ.get("PYTEST_CURRENT_TEST")
or os.environ.get("PYTEST_VERSION")
+ or os.environ.get(_TEST_ISOLATION_MARKER_ENV)
)
diff --git a/tests/conftest.py b/tests/conftest.py
index 9c1140db9fe..431d2542021 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -91,6 +91,20 @@ if _hermes_home_points_at_production(os.environ.get("HERMES_HOME", "")):
os.environ["HERMES_HOME"] = _SESSION_HERMES_HOME
atexit.register(shutil.rmtree, _SESSION_HERMES_HOME, True)
+# Subprocess-surviving isolation marker (#82770). PYTEST_CURRENT_TEST /
+# PYTEST_VERSION are pytest's own vars, and tests that spawn children
+# routinely rebuild the child env and strip them ("the subprocess must look
+# like a real CLI") — which used to disarm hermes_state's live-DB guard in
+# the child at the same moment the child lost the HERMES_HOME redirect.
+# HERMES_TEST_ISOLATION is OUR marker: exported here (before any test module
+# imports), inherited by every child by default, and honored by
+# hermes_state._running_under_pytest() as a test-context signal. A child
+# that carries it and still resolves the production state.db fails hard.
+# Tests that legitimately need a child to look like a non-test process AND
+# open a real DB must export HERMES_STATE_DB_GUARD_BYPASS=1 in that child's
+# env instead of stripping markers.
+os.environ["HERMES_TEST_ISOLATION"] = os.environ.get("HERMES_HOME", "") or "1"
+
#: HERMES_HOME as it stood when conftest was imported - i.e. before any test
#: module could import code that configures logging. Recorded so the guard in
#: tests/test_log_isolation.py can assert the sandbox existed AT THAT MOMENT.
@@ -467,6 +481,14 @@ def _hermetic_environment(tmp_path, monkeypatch):
(fake_hermes_home / "memories").mkdir()
(fake_hermes_home / "skills").mkdir()
monkeypatch.setenv("HERMES_HOME", str(fake_hermes_home))
+ # Keep the subprocess-surviving isolation marker pointed at THIS test's
+ # home (#82770): children spawned by the test inherit it by default, so
+ # hermes_state's live-DB guard stays armed in them even when the test
+ # strips pytest's own PYTEST_* vars from the child env.
+ monkeypatch.setenv("HERMES_TEST_ISOLATION", str(fake_hermes_home))
+ # And never let a developer-shell (or leaked child) bypass disarm the
+ # guard for in-process code under test.
+ monkeypatch.delenv("HERMES_STATE_DB_GUARD_BYPASS", raising=False)
# 3b. hermes_state computes ``DEFAULT_DB_PATH = get_hermes_home() / "state.db"``
# at import time. When the module is first imported at collection (any
diff --git a/tests/hermes_state/test_isolation_marker_env.py b/tests/hermes_state/test_isolation_marker_env.py
new file mode 100644
index 00000000000..3c5e7751cf7
--- /dev/null
+++ b/tests/hermes_state/test_isolation_marker_env.py
@@ -0,0 +1,121 @@
+"""Subprocess-surviving isolation marker (#82770).
+
+``PYTEST_CURRENT_TEST`` / ``PYTEST_VERSION`` are pytest's vars: tests that
+spawn children and rebuild the child environment routinely strip them so the
+child "looks like a real CLI" — which used to disarm the live-DB guard in the
+child at the same moment the child lost the ``HERMES_HOME`` redirect. That
+pairing is exactly how fixture rows (dm:123 / chat-1 / wx-chat) landed in a
+developer's production state.db.
+
+``HERMES_TEST_ISOLATION`` is Hermes's own marker: the hermetic conftest
+exports it (value = the isolation root) before any test module imports, it
+inherits into children by default, and ``hermes_state`` honors it as a
+test-context signal. These tests pin all three properties.
+"""
+
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import hermes_state
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+_CHILD_PROBE = r"""
+import json, os, sys
+sys.path.insert(0, {repo!r})
+import hermes_state as hs
+fired = False
+try:
+ hs._ensure_test_isolation(hs._real_platform_state_root() / "state.db")
+except RuntimeError:
+ fired = True
+print(json.dumps({{
+ "armed": hs._running_under_pytest(),
+ "fired": fired,
+}}))
+"""
+
+
+def _spawn_probe(env: dict) -> dict:
+ """Run the guard probe in a real child process with exactly *env*."""
+ proc = subprocess.run(
+ [sys.executable, "-c", _CHILD_PROBE.format(repo=str(REPO_ROOT))],
+ capture_output=True,
+ text=True,
+ env=env,
+ timeout=60,
+ )
+ assert proc.returncode == 0, proc.stderr
+ return json.loads(proc.stdout.strip().splitlines()[-1])
+
+
+def _minimal_env(**extra) -> dict:
+ """A rebuilt-from-scratch child env — the residual-bypass pattern."""
+ env = {
+ "PATH": os.environ.get("PATH", ""),
+ "HOME": os.environ.get("HOME", ""),
+ "SYSTEMROOT": os.environ.get("SYSTEMROOT", ""), # Windows needs it
+ "LOCALAPPDATA": os.environ.get("LOCALAPPDATA", ""),
+ }
+ env = {k: v for k, v in env.items() if v}
+ env.update(extra)
+ return env
+
+
+def test_conftest_exports_the_marker():
+ """The hermetic conftest must export the marker before tests run."""
+ assert os.environ.get("HERMES_TEST_ISOLATION"), (
+ "HERMES_TEST_ISOLATION must be exported by tests/conftest.py so "
+ "subprocess children inherit a test-context signal that survives "
+ "PYTEST_* scrubbing"
+ )
+
+
+def test_marker_alone_reports_test_context(monkeypatch):
+ monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False)
+ monkeypatch.delenv("PYTEST_VERSION", raising=False)
+ monkeypatch.setenv("HERMES_TEST_ISOLATION", "/tmp/some-isolation-root")
+ assert hermes_state._running_under_pytest() is True
+
+
+def test_no_signals_reports_production(monkeypatch):
+ """Marker absent + PYTEST_* absent = a real user run; guard must not arm
+ off the env (ancestry may still arm it in a real child — not this seam)."""
+ monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False)
+ monkeypatch.delenv("PYTEST_VERSION", raising=False)
+ monkeypatch.delenv("HERMES_TEST_ISOLATION", raising=False)
+ assert hermes_state._running_under_pytest() is False
+
+
+def test_child_with_rebuilt_env_keeping_marker_refuses_production_db():
+ """THE regression: a child whose env was rebuilt from scratch (PYTEST_*
+ stripped, HERMES_HOME lost) but which keeps the marker must still refuse
+ to open the production state.db."""
+ env = _minimal_env(HERMES_TEST_ISOLATION="/tmp/pytest-isolation-root")
+ result = _spawn_probe(env)
+ assert result["armed"] is True
+ assert result["fired"] is True, (
+ "guard did not fire in a marker-carrying child aimed at the "
+ "production state.db — the #82770 escape is open again"
+ )
+
+
+def test_child_bypass_env_disarms_guard_even_with_marker():
+ """The sanctioned escape hatch for children that genuinely need a real
+ DB: HERMES_STATE_DB_GUARD_BYPASS=1, not marker-stripping."""
+ env = _minimal_env(
+ HERMES_TEST_ISOLATION="/tmp/pytest-isolation-root",
+ HERMES_STATE_DB_GUARD_BYPASS="1",
+ )
+ result = _spawn_probe(env)
+ assert result["fired"] is False
+
+
+def test_child_inheriting_full_test_env_refuses_production_db():
+ """Default inheritance (env=None equivalent): everything rides along."""
+ result = _spawn_probe(dict(os.environ))
+ assert result["armed"] is True
+ assert result["fired"] is True
diff --git a/tests/hermes_state/test_live_db_guard_ancestry.py b/tests/hermes_state/test_live_db_guard_ancestry.py
index 713a7ca1fcc..b6c853eb430 100644
--- a/tests/hermes_state/test_live_db_guard_ancestry.py
+++ b/tests/hermes_state/test_live_db_guard_ancestry.py
@@ -54,11 +54,17 @@ else:
def _scrubbed_env(**overrides):
- """The environment a rebuilt-from-scratch child spawn ends up with."""
+ """The environment a rebuilt-from-scratch child spawn ends up with.
+
+ Also strips ``HERMES_TEST_ISOLATION`` — the conftest-exported marker
+ layer would otherwise arm the guard first and these tests would no
+ longer prove anything about the ancestry fallback they exist to pin.
+ """
env = {
k: v
for k, v in os.environ.items()
- if not k.startswith("PYTEST_") and k != "HERMES_HOME"
+ if not k.startswith("PYTEST_")
+ and k not in ("HERMES_HOME", "HERMES_TEST_ISOLATION")
}
env.update(overrides)
return env