Skip to content

The agent that grows with you

fix(scratch): run the due scratch prune in a detached child so it always finishes

Tekniumb12b2631573e
diff --git a/hermes_constants.py b/hermes_constants.py
index 35c0548ce4a..32dbd53c973 100644
--- a/hermes_constants.py
+++ b/hermes_constants.py
@@ -9,7 +9,6 @@ import re
import shutil
import stat
import sys
-import threading
from collections.abc import Callable, Mapping, MutableMapping
from contextvars import ContextVar, Token
from pathlib import Path
@@ -816,8 +815,6 @@ SCRATCH_MAX_IDLE_HOURS = 24
_SCRATCH_PRUNE_STAMP = ".last_prune"
_SCRATCH_PRUNE_INTERVAL_SECONDS = 3600
_scratch_pruned_once = False
-_scratch_prune_lock = threading.Lock()
-_scratch_prune_thread: threading.Thread | None = None
# AF_UNIX socket paths cap at 104 bytes (macOS) / 108 (Linux). Chrome appends
# ``com.google.Chrome.XXXXXX/SingletonSocket`` (~45) and the code kernel
@@ -969,9 +966,10 @@ def get_scratch_dir(home: str | Path | None = None, *, prune: bool = True) -> Pa
:func:`export_scratch_tmp_env`), so ``tempfile`` defaults land here without call sites
knowing. Entries idle for ``SCRATCH_MAX_IDLE_HOURS`` are pruned at most once per process
and once per hour across processes (stamp file), so a fan-out of children stays cheap.
- *prune* only schedules that pass on a daemon thread: the directory itself is created and
- permissioned before this returns, but no caller (the boot hook included) waits on the
- idle scan or the ``rmtree`` of a multi-GB entry.
+ The pass itself runs in a detached child process (``hermes_constants_scratch_detach``): the
+ directory is created and permissioned before this returns, no caller (the boot hook
+ included) waits on the idle scan or the ``rmtree`` of a multi-GB entry, and the pass still
+ finishes when the caller is a ``hermes`` command that exits a moment later.
Permissions follow :func:`apply_secure_dir_policy`, so an explicit ``HERMES_HOME_MODE`` or
a managed/shared home is honored instead of a blanket ``0700`` (#117347).
@@ -987,7 +985,7 @@ def get_scratch_dir(home: str | Path | None = None, *, prune: bool = True) -> Pa
except OSError:
pass
if prune:
- prune_scratch_dir_in_background(scratch)
+ _prune_scratch_dir_once(scratch)
return scratch
@@ -1018,30 +1016,9 @@ def _prune_scratch_dir_once(scratch: Path) -> None:
pass
with contextlib.suppress(Exception):
stamp.touch()
- prune_scratch_dir(scratch)
+ from hermes_constants_scratch_detach import spawn_prune
-
-def prune_scratch_dir_in_background(scratch: Path) -> None:
- """Schedule one prune of the *scratch* the caller resolved, without blocking it.
-
- The thread gets the path, never re-resolves it: threads do not inherit the profile-override
- contextvar. A process that exits mid-prune kills the daemon thread with the hourly stamp
- already touched; every deletion is re-validated right before it happens, so a cut pass only
- leaves fewer entries removed. Entries it never reached go on the next hourly pass; the one
- cut inside ``rmtree`` has fresh directory mtimes from the unlinks, so its remainder goes
- 24 h later like any other entry written to."""
- global _scratch_prune_thread
- if _scratch_pruned_once:
- return
- with _scratch_prune_lock:
- if _scratch_pruned_once or _scratch_prune_thread is not None:
- return
- # health: allow HX012 -- the caller's resolved path is passed in; nothing in the prune reads the scope
- _scratch_prune_thread = threading.Thread(
- target=_prune_scratch_dir_once, args=(scratch,), name="scratch-prune", daemon=True,
- )
- with contextlib.suppress(RuntimeError):
- _scratch_prune_thread.start()
+ spawn_prune(scratch)
def scratch_dir_usage_bytes(scratch: Path | None = None) -> int:
diff --git a/hermes_constants_scratch.py b/hermes_constants_scratch.py
index c269365bbe8..57d3ec7495b 100644
--- a/hermes_constants_scratch.py
+++ b/hermes_constants_scratch.py
@@ -160,13 +160,17 @@ def _under(path: str, root: str) -> bool:
return path == root or path.startswith(root.rstrip(os.sep) + os.sep)
-def _own_lineage() -> set[int]:
- """This process and its ancestors: never reap the shell that is running the prune."""
+# A detached pass (hermes_constants_scratch_detach) is reparented once the Hermes command that
+# launched it exits; that command's ancestors, captured when the pass starts, stay its own.
+_launcher_lineage: set[int] = set()
+
+
+def _lineage(pid: int | None = None) -> set[int]:
import psutil
pids: set[int] = set()
try:
- proc = psutil.Process()
+ proc = psutil.Process(pid)
while proc is not None and proc.pid not in pids:
pids.add(proc.pid)
proc = proc.parent()
@@ -175,6 +179,17 @@ def _own_lineage() -> set[int]:
return pids
+def adopt_launcher_lineage(pids: tuple[int, ...]) -> None:
+ for pid in pids:
+ _launcher_lineage.update(_lineage(pid))
+
+
+def _own_lineage() -> set[int]:
+ """This process and its ancestors (and its launcher's): never reap the shell that is
+ running the prune."""
+ return _lineage() | _launcher_lineage
+
+
def _registered_live_pids(home: Path) -> set[int]:
"""Live pids Hermes registered for *home*: the machine spawn ledger (every long-lived entry
point and MCP helper, ``hermes_cli.process_identity``) and the background-process checkpoint
diff --git a/hermes_constants_scratch_detach.py b/hermes_constants_scratch_detach.py
new file mode 100644
index 00000000000..f21411c51e3
--- /dev/null
+++ b/hermes_constants_scratch_detach.py
@@ -0,0 +1,57 @@
+"""The hourly scratch prune runs in a detached child process, not in the process that is due it.
+
+A pass can take seconds to minutes (the idle scan of a large tree, the ``rmtree`` of a multi-GB
+entry). Inline, it held every process start; on a daemon thread it died with every short-lived
+``hermes`` command, the hourly stamp already spent. A detached child outlives the command that
+launched it, so each due pass runs to the end, with the same rules as an inline one.
+"""
+from __future__ import annotations
+
+import logging
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+logger = logging.getLogger(__name__)
+
+# ``-I``: neither the launcher's cwd (a project ``utils/`` would shadow ours) nor PYTHON* env vars
+# decide what the child imports; it gets the launcher's own ``sys.path`` (repo root, PM/venv
+# site-packages), not ``hermes_bootstrap``, whose boot hook would schedule another prune.
+_CHILD = ("import sys; sys.path[:] = sys.argv[4:]; "
+ "import hermes_constants_scratch_detach as d; d.run(*sys.argv[1:4])")
+
+
+def spawn_prune(scratch: Path) -> None:
+ """Start one detached prune of *scratch*, the path the caller resolved (a child never
+ re-resolves the profile home). A failed spawn is logged and dropped: the stamp is already
+ spent, so the next pass is the next process past the hourly mark."""
+ argv = [sys.executable, "-I"]
+ if sys.dont_write_bytecode:
+ argv.append("-B")
+ if sys.pycache_prefix: # a sealed payload must never get __pycache__ writes
+ argv += ["-X", f"pycache_prefix={sys.pycache_prefix}"]
+ argv += ["-c", _CHILD, os.fspath(scratch), str(os.getpid()), str(os.getppid()), *sys.path]
+ from hermes_cli._subprocess_compat import windows_detach_flags_without_breakaway, windows_detach_popen_kwargs
+
+ stdio = {"stdin": subprocess.DEVNULL, "stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL}
+ try:
+ try:
+ subprocess.Popen(argv, close_fds=True, **stdio, **windows_detach_popen_kwargs())
+ except PermissionError:
+ if sys.platform != "win32":
+ raise
+ # A job object without BREAKAWAY_OK rejects CREATE_BREAKAWAY_FROM_JOB.
+ subprocess.Popen(argv, close_fds=True, **stdio, creationflags=windows_detach_flags_without_breakaway())
+ except (OSError, RuntimeError) as exc:
+ logger.debug("scratch prune: could not start the detached pass for %s: %s", scratch, exc)
+
+
+def run(scratch: str, launcher_pid: str, launcher_parent_pid: str) -> None:
+ """Child entry. The launcher's process tree stays the pass's own (never reaped; an entry it
+ works inside is kept) after the launcher exits and this child is reparented away from it."""
+ import hermes_constants_scratch
+ from hermes_constants import prune_scratch_dir
+
+ hermes_constants_scratch.adopt_launcher_lineage((int(launcher_pid), int(launcher_parent_pid)))
+ prune_scratch_dir(Path(scratch))
diff --git a/tests/conftest.py b/tests/conftest.py
index 2ad65e84413..cda6c3367fe 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -119,6 +119,12 @@ def _hermes_home_points_at_production(value: str) -> bool:
# system default so the import-time hook stays a no-op. The parallel runner
# exports its own disk-backed TMPDIR anyway.
from hermes_constants import SCRATCH_DIR_MARKER_ENV, SCRATCH_TMP_ENV_VARS
+import hermes_constants
+
+# The hourly scratch prune runs in a detached child process; a test reaching get_scratch_dir()
+# would start a real one (and hand it to any Popen mock it installed). Tests of the prune
+# reset this flag.
+hermes_constants._scratch_pruned_once = True
_HERMES_EXPORTED_TMP = os.environ.get(SCRATCH_DIR_MARKER_ENV, "")
if _HERMES_EXPORTED_TMP:
diff --git a/tests/test_scratch_dir.py b/tests/test_scratch_dir.py
index 7f969135429..dc7db6db945 100644
--- a/tests/test_scratch_dir.py
+++ b/tests/test_scratch_dir.py
@@ -7,10 +7,8 @@ import shutil
import stat
import subprocess
import sys
-import threading
import time
from pathlib import Path
-from types import SimpleNamespace
from unittest.mock import patch
from tests.waiting import wait_until
@@ -22,76 +20,73 @@ from hermes_constants import apply_scratch_tmp_env, get_scratch_dir, prune_scrat
@pytest.fixture
-def blocked_scratch_prune(tmp_path, monkeypatch):
- """A once-per-process prune that is still due and blocks until released: a caller that
- waits on it shows up as a stall, one that does not returns at once."""
+def spawned_prunes(monkeypatch):
+ """A once-per-process prune that is still due; records each process spawned for it."""
import hermes_constants as constants
- home = tmp_path / "launch"
- monkeypatch.setenv("HERMES_HOME", str(home))
monkeypatch.setattr(constants, "_scratch_pruned_once", False)
- monkeypatch.setattr(constants, "_scratch_prune_thread", None, raising=False)
- release, calls = threading.Event(), []
-
- def blocked_prune(scratch):
- calls.append(scratch)
- release.wait(timeout=3)
-
- monkeypatch.setattr(constants, "prune_scratch_dir", blocked_prune)
+ spawned = []
+ monkeypatch.setattr(subprocess, "Popen", lambda argv, **kwargs: spawned.append(argv))
token = constants.set_hermes_home_override(None)
- try:
- yield SimpleNamespace(home=home, calls=calls, release=release)
- finally:
- release.set()
- thread = getattr(constants, "_scratch_prune_thread", None)
- if thread is not None:
- thread.join(timeout=5)
- assert not thread.is_alive()
- constants.reset_hermes_home_override(token)
+ yield spawned
+ constants.reset_hermes_home_override(token)
-def _finish_prune(state):
+def test_boot_hook_and_prompt_hand_the_prune_to_one_child(spawned_prunes, tmp_path, monkeypatch):
+ """The boot hook returns with TMPDIR pointing at a scratch dir that already exists and
+ starts exactly one prune process, for that dir; the prompt build starts no other. A routed
+ caller's process prunes the routed home's dir, never the launch home's."""
import hermes_constants as constants
-
- state.release.set()
- constants._scratch_prune_thread.join(timeout=5)
-
-
-def test_boot_hook_and_prompt_never_wait_for_the_scratch_prune(blocked_scratch_prune):
- """The boot hook returns with TMPDIR pointing at a scratch dir that already exists, and the
- prune it triggered runs once, later, on that dir; the prompt build does not start another."""
from agent.prompt_builder import _local_host_hints
- state = blocked_scratch_prune
- scratch = state.home / "cache" / "scratch"
- env = {"HERMES_HOME": str(state.home)}
- start = time.monotonic()
+ home = tmp_path / "launch"
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ scratch = home / "cache" / "scratch"
+ env = {"HERMES_HOME": str(home)}
assert apply_scratch_tmp_env(env) is True
hints = _local_host_hints()
- assert time.monotonic() - start < 1.0
assert env["TMPDIR"] == str(scratch) and scratch.is_dir()
assert f"Scratch directory: {scratch} (TMPDIR points here" in hints[0]
- _finish_prune(state)
- assert state.calls == [scratch]
-
-
-def test_background_prune_targets_the_routed_home(blocked_scratch_prune, tmp_path):
- """Threads do not inherit the profile override: the prune must use the scratch dir the
- routed caller resolved, never the launch home's."""
- import hermes_constants as constants
+ assert len(spawned_prunes) == 1 and str(scratch) in spawned_prunes[0]
- state = blocked_scratch_prune
+ monkeypatch.setattr(constants, "_scratch_pruned_once", False) # the routed caller's own process
routed = tmp_path / "routed"
token = constants.set_hermes_home_override(routed)
try:
- start = time.monotonic()
- scratch = get_scratch_dir()
- assert time.monotonic() - start < 1.0
+ assert get_scratch_dir() == routed / "cache" / "scratch"
finally:
constants.reset_hermes_home_override(token)
- _finish_prune(state)
- assert scratch == routed / "cache" / "scratch"
- assert state.calls == [scratch]
+ assert len(spawned_prunes) == 2 and str(routed / "cache" / "scratch") in spawned_prunes[1]
+ assert str(scratch) not in spawned_prunes[1]
+
+
+def _idle_entry(scratch: Path, name: str) -> Path:
+ entry = scratch / name
+ (entry / "sub").mkdir(parents=True)
+ (entry / "sub" / "out.log").write_text("old output", encoding="utf-8")
+ ancient = time.time() - 30 * 3600
+ for path in (entry / "sub" / "out.log", entry / "sub", entry):
+ os.utime(path, (ancient, ancient))
+ return entry
+
+
+def test_a_short_lived_process_still_completes_its_due_prune(tmp_path):
+ """A `hermes` command that exits right after boot still gets its pass: the detached child
+ removes the idle entry of the (routed) home the command resolved, after the command is gone,
+ and leaves the launch home alone. Red on a daemon-thread prune, which dies with the command."""
+ launch, routed = tmp_path / "launch", tmp_path / "routed"
+ kept = _idle_entry(get_scratch_dir(launch, prune=False), "launch-lane")
+ doomed = _idle_entry(get_scratch_dir(routed, prune=False), "routed-lane")
+ repo = Path(__file__).resolve().parents[1]
+ launcher = ("import sys; sys.path.insert(0, sys.argv[1]); from pathlib import Path; import hermes_constants as h; "
+ "h.set_hermes_home_override(Path(sys.argv[2])); h.get_scratch_dir()")
+ env = {**os.environ, "HERMES_HOME": str(launch)}
+ subprocess.run([sys.executable, "-c", launcher, str(repo), str(routed)], env=env, cwd=tmp_path,
+ stdin=subprocess.DEVNULL, check=True, timeout=60)
+ wait_until(lambda: not doomed.exists(), timeout=60, what="the detached prune removing the idle entry")
+ assert kept.exists()
+ log = (routed / "logs" / "scratch-prune.log").read_text(encoding="utf-8-sig")
+ assert f"removed {str(doomed)!r} (" in log, log
def test_scratch_env_follows_home_and_respects_user_tmpdir(tmp_path):
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index b513947415f..137e0c77499 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -258,8 +258,9 @@ backend, cron) and every child it launches gets `TMPDIR`, `TMP` and `TEMP` point
RAM-backed system temp dir. The system prompt names this directory as the scratch
directory. Hermes only sets these when they are not already set — a `TMPDIR` exported
by you or by the OS (macOS `/var/folders`, Windows `%TEMP%`) is left alone. Entries are
-pruned in the background right after startup (at most once per hour; startup never waits for
-it) once they have been **idle for 24 hours**: an entry
+pruned by a background process started right after startup (at most once per hour; startup
+never waits for it, and the pass still finishes when the command exits at once) once they have
+been **idle for 24 hours**: an entry
stays as long as anything anywhere inside it was written in the last day, and goes a day after
the last write. Hardlinked files do not count as writes (a `git clone --local` shares pack files
with its source repo, whose activity would otherwise keep the clone forever). Before an idle entry is deleted, Hermes also stops any process still running