diff --git a/hermes_cli/home_data_layout.py b/hermes_cli/home_data_layout.py index f2492489fd..8b912b19bc 100644 --- a/hermes_cli/home_data_layout.py +++ b/hermes_cli/home_data_layout.py @@ -1,19 +1,19 @@ """Machine-specific state excluded from portable home transfers.""" from __future__ import annotations +from collections.abc import Iterable +from pathlib import Path # Dependency generations, downloaded tools, and partial transfers belong to this machine. PM_RUNTIME_ROOT_DIRS = frozenset({"installs", "tools", "cache"}) -# Frozen copies of provider plugins that running processes import from (``providers.plugin_reload``), as path -# parts relative to a home. Each belongs to one live process and is rebuilt from ``plugins/`` by the next one. +# Frozen copies of provider plugins that Hermes processes import from (``providers.plugin_reload``), as path parts +# relative to the Hermes root: one directory per process, live or left by a crash, rebuilt from ``plugins/``. PROVIDER_PLUGIN_SNAPSHOT_PARTS = ("runtime", "provider-plugins") -def provider_plugin_snapshot_dir(directory: str, names, home) -> set[str]: - """For a copytree ignore walking the home *home*: the snapshot dir when *directory* is ``/runtime``.""" - from pathlib import Path - +def provider_plugin_snapshot_dir(directory: str, names: Iterable[str], home: Path) -> set[str]: + """For a copytree ignore walking *home*: the snapshot dir when *directory* is ``/runtime``.""" parent, leaf = PROVIDER_PLUGIN_SNAPSHOT_PARTS if leaf not in names: return set() diff --git a/providers/plugin_reload.py b/providers/plugin_reload.py index e82774f8d7..04ec0ebc35 100644 --- a/providers/plugin_reload.py +++ b/providers/plugin_reload.py @@ -10,11 +10,12 @@ registrations stay live until then, and stay live if the new tree fails to impor in ``sys.modules`` with its ``__path__`` on its own copy, so anything built from it (a cached agent's client) imports even its not-yet-loaded files from that version: every object runs one version end to end, never a mix. -The copies are read for the whole life of the process, so they live under ``/runtime/provider-plugins`` -and not in a temp dir that is cleaned by age (#156493). Each process holds an OS lock on ``owner.lock`` in its -own root while it runs; the next process to create a root removes the roots whose lock nobody holds (their -process is gone, killed or crashed included). Creating a root and that sweep run under one setup lock, so a -sweep never sees a root its owner has made but not locked yet. +The copies are read for the whole life of the process, so they live under ``/runtime/provider-plugins`` (the +Hermes root, which deleting a profile never removes) and not in a temp dir that is cleaned by age (#156493). Each +process holds an OS lock on ``owner.lock`` in its own root while it runs, and the next process to create a root +reclaims the roots whose lock nobody holds: their process is gone, killed or crashed included. Creating a root and +that sweep run under one setup lock, so a sweep never sees a root its owner has made but not locked yet. A process +that cannot take the setup lock still gets a root, under a name no sweep ever matches. """ from __future__ import annotations @@ -28,27 +29,33 @@ import shutil import sys import tempfile import threading +import uuid from pathlib import Path -from hermes_constants import get_process_hermes_home, mkdir_under_hermes_home +from hermes_cli.home_data_layout import PROVIDER_PLUGIN_SNAPSHOT_PARTS +from hermes_constants import get_default_hermes_root, mkdir_under_hermes_home logger = logging.getLogger(__name__) # Directories inside a plugin tree that never hold code the provider imports. _SKIP_DIRS = frozenset({"__pycache__", ".git", "node_modules", "tests", "evals", ".venv"}) _SNAPSHOT_IGNORE = shutil.ignore_patterns("__pycache__", ".git", "node_modules", ".venv") -_ROOT_PREFIX = "hermes-provider-plugins-" +# Roots made under the setup lock, with an owner lock: the only ones a sweep reclaims. Anything else in the +# directory (another release's roots, a root made without the setup lock, files a user put there) is never touched. +_OWNED_PREFIX = "owned-" +_UNSWEPT_PREFIX = "unswept-" +_REAPING_PREFIX = f".reaping-{_OWNED_PREFIX}" _OWNER_LOCK = "owner.lock" _SETUP_LOCK = ".setup.lock" -_REAPING_PREFIX = ".reaping-" -# One directory per process for the frozen copies; removed when the process exits. +_SETUP_WAIT_SECONDS = 30 +# One directory per process for the frozen copies; removed on a normal exit, reclaimed later otherwise. _snapshot_root: Path | None = None _snapshot_lock = threading.Lock() def _owner_alive(root: Path) -> bool: - """Whether a process holds *root*'s owner lock. Asked under the setup lock, so a root without a lock file - is never mid-setup: its owner died before taking it (or predates owner locks).""" + """Whether a process holds *root*'s owner lock. Asked under the setup lock, so an owned root without a lock + file is never mid-setup: its owner died before taking it.""" from pm.filesystem import lock_fd, unlock_fd try: @@ -65,32 +72,31 @@ def _owner_alive(root: Path) -> bool: def _claim_dead_roots(parent: Path) -> list[Path]: - """Rename every root this loader created whose owner is gone out of the way; the caller deletes them after - releasing the setup lock, so a large dead root never holds up other processes starting. Anything else in - *parent* is left alone.""" + """Rename the owned roots whose owner is gone, and the claims a sweeper killed mid-delete left behind, to + names unique to this sweep. The caller deletes them after releasing the setup lock, so a large dead root never + holds up other processes starting, and two sweepers never delete the same claim.""" claimed = [] with contextlib.suppress(OSError): for entry in parent.iterdir(): - if not entry.name.startswith(_ROOT_PREFIX) or entry.is_symlink() or not entry.is_dir(): + if entry.is_symlink() or not entry.is_dir(): continue with contextlib.suppress(OSError): # unreadable, or another user's: not ours to judge - if not _owner_alive(entry): - claim = parent / f"{_REAPING_PREFIX}{entry.name}" + leftover = entry.name.startswith(_REAPING_PREFIX) + if leftover or (entry.name.startswith(_OWNED_PREFIX) and not _owner_alive(entry)): + claim = parent / f"{_REAPING_PREFIX}{uuid.uuid4().hex}" os.rename(entry, claim) claimed.append(claim) - # A sweeper that died mid-delete left its claims behind; nothing else uses the name. - with contextlib.suppress(OSError): - claimed.extend(e for e in parent.iterdir() if e.name.startswith(_REAPING_PREFIX) and e not in claimed) return claimed -def _release_root(root: Path, owner_fd: int, creator_pid: int) -> None: +def _release_root(root: Path, owner_fd: int | None, creator_pid: int) -> None: # A forked child inherits this hook and shares the flock (it belongs to the open file): its exit must # neither delete the parent's live copy nor drop the parent's lock. if os.getpid() != creator_pid: return - with contextlib.suppress(OSError): - os.close(owner_fd) + if owner_fd is not None: + with contextlib.suppress(OSError): + os.close(owner_fd) shutil.rmtree(root, ignore_errors=True) @@ -98,20 +104,23 @@ def _new_root() -> Path: """This process's root, with its owner lock held until the process exits.""" from pm.filesystem import lock_path - parent = mkdir_under_hermes_home(get_process_hermes_home() / "runtime" / "provider-plugins") + parent = mkdir_under_hermes_home(get_default_hermes_root().joinpath(*PROVIDER_PLUGIN_SNAPSHOT_PARTS)) try: - setup_fd = lock_path(parent / _SETUP_LOCK, timeout=30) - except PermissionError: - # Another user's lock file (a home shared across UIDs): this process can still own a root of its - # own; it only skips reclaiming the others'. + setup_fd = lock_path(parent / _SETUP_LOCK, timeout=_SETUP_WAIT_SECONDS) + except PermissionError: # another user's lock file: a home shared across UIDs setup_fd = None - logger.warning("Cannot open %s; not reclaiming provider plugin snapshots of exited processes", - parent / _SETUP_LOCK) + if setup_fd is None: + # Without the setup lock a sweep could see this root before its owner lock is taken, so make it under a + # name no sweep matches. It is still removed on a normal exit; after a crash it stays. + logger.warning("Could not take %s; this process's provider plugin snapshots will not be reclaimed if it " + "crashes, and it reclaims no others", parent / _SETUP_LOCK) + root = Path(tempfile.mkdtemp(prefix=_UNSWEPT_PREFIX, dir=parent)) + atexit.register(_release_root, root, None, os.getpid()) + return root claimed: list[Path] = [] try: - if setup_fd is not None: - claimed = _claim_dead_roots(parent) - root = Path(tempfile.mkdtemp(prefix=_ROOT_PREFIX, dir=parent)) + claimed = _claim_dead_roots(parent) + root = Path(tempfile.mkdtemp(prefix=_OWNED_PREFIX, dir=parent)) try: owner_fd = lock_path(root / _OWNER_LOCK, timeout=0) except BaseException: @@ -121,8 +130,7 @@ def _new_root() -> Path: shutil.rmtree(root, ignore_errors=True) raise OSError(f"{root / _OWNER_LOCK} is held by another process") finally: - if setup_fd is not None: - os.close(setup_fd) + os.close(setup_fd) for claim in claimed: shutil.rmtree(claim, ignore_errors=True) atexit.register(_release_root, root, owner_fd, os.getpid()) diff --git a/tests/providers/test_provider_snapshot_reclaim.py b/tests/providers/test_provider_snapshot_reclaim.py index ba137f84fd..6d86434edb 100644 --- a/tests/providers/test_provider_snapshot_reclaim.py +++ b/tests/providers/test_provider_snapshot_reclaim.py @@ -1,15 +1,17 @@ -"""Frozen provider-plugin copies of exited processes are reclaimed, and live ones never are (#156493). +"""Frozen provider-plugin copies of exited processes are reclaimed, and nothing else ever is (#156493). -Copies live under ``/runtime/provider-plugins`` for the life of their process, so a crashed or killed +Copies live under ``/runtime/provider-plugins`` for the life of their process, so a crashed or killed process would leave its copy forever. Each process holds a lock on ``owner.lock`` in its root; the next process -to create a root reclaims those nobody holds. +to create a root reclaims the owned roots nobody holds. """ from __future__ import annotations import os +import shutil import sys import types +from pathlib import Path import pytest @@ -29,29 +31,35 @@ def loader(tmp_path, monkeypatch): fn(*args) -def _parent(): - from hermes_constants import get_process_hermes_home +def _parent() -> Path: + from hermes_constants import get_default_hermes_root - return get_process_hermes_home() / "runtime" / "provider-plugins" + return get_default_hermes_root() / "runtime" / "provider-plugins" -def test_roots_of_exited_processes_are_reclaimed_and_everything_else_is_kept(loader): - reload, _hooks = loader +def _seed(*roots: Path) -> None: + for root in roots: + (root / "pkg").mkdir(parents=True) + + +def test_dead_owned_roots_are_reclaimed_and_everything_else_is_kept(loader): from pm.filesystem import lock_path + reload, _hooks = loader parent = _parent() - dead, never_locked, live = (parent / f"{reload._ROOT_PREFIX}{n}" for n in ("dead", "never-locked", "live")) - unrelated = parent / "not-a-snapshot" - for root in (dead, never_locked, live, unrelated): - (root / "pkg").mkdir(parents=True) + owned = reload._OWNED_PREFIX + dead, never_locked, live = (parent / f"{owned}{n}" for n in ("dead", "never-locked", "live")) + # A root from a release without owner locks (its process may still be running), a root made without the setup + # lock, a killed sweeper's claim lookalike that is not one, and plain user data: never ours to delete. + kept = [parent / n for n in ("hermes-provider-plugins-older", f"{reload._UNSWEPT_PREFIX}x", ".reaping-mine", "notes")] + _seed(dead, never_locked, live, *kept) (dead / reload._OWNER_LOCK).write_text("") - (unrelated / reload._OWNER_LOCK).write_text("") holder = lock_path(live / reload._OWNER_LOCK, timeout=0) assert holder is not None try: mine = reload._new_root() - assert mine.parent == parent - assert live.is_dir() and unrelated.is_dir() + assert mine.parent == parent and mine.name.startswith(owned) + assert live.is_dir() and all(k.is_dir() for k in kept) assert not dead.exists() and not never_locked.exists() assert not [e for e in parent.iterdir() if e.name.startswith(reload._REAPING_PREFIX)] # The next process to start leaves this one's root alone. @@ -64,19 +72,48 @@ def test_roots_of_exited_processes_are_reclaimed_and_everything_else_is_kept(loa def test_a_sweeper_that_died_mid_delete_has_its_claims_finished(loader): reload, _hooks = loader - parent = _parent() - leftover = parent / f"{reload._REAPING_PREFIX}{reload._ROOT_PREFIX}gone" - (leftover / "pkg").mkdir(parents=True) + leftover = _parent() / f"{reload._REAPING_PREFIX}gone" + _seed(leftover) reload._new_root() assert not leftover.exists() -def test_a_lock_failure_keeps_its_cause_and_leaves_no_root(loader, monkeypatch): - reload, _hooks = loader +@pytest.mark.parametrize("failure", ["timeout", "foreign lock file"]) +def test_without_the_setup_lock_the_root_is_one_no_sweep_matches(loader, monkeypatch, failure): import pm.filesystem + reload, hooks = loader + real = pm.filesystem.lock_path + stray = _parent() / f"{reload._OWNED_PREFIX}dead" + _seed(stray) + + def setup_unavailable(path, **kw): + if path.name == reload._SETUP_LOCK: + if failure == "timeout": + return None + raise PermissionError(13, "denied", str(path)) + return real(path, **kw) + + monkeypatch.setattr(pm.filesystem, "lock_path", setup_unavailable) + root = reload._new_root() + monkeypatch.setattr(pm.filesystem, "lock_path", real) + + assert root.name.startswith(reload._UNSWEPT_PREFIX) + assert stray.is_dir() # it reclaimed nothing without the lock + reload._snapshot_root = None + reload._new_root() # a later sweep, holding the setup lock: never touches the unswept root + assert root.is_dir() and not stray.exists() + (release, args) = hooks[0] + release(*args) # a normal exit still removes it + assert not root.exists() + + +def test_a_lock_failure_keeps_its_cause_and_leaves_no_root(loader, monkeypatch): + import pm.filesystem + + reload, _hooks = loader real = pm.filesystem.lock_path def refuse_owner(path, **kw): @@ -87,7 +124,7 @@ def test_a_lock_failure_keeps_its_cause_and_leaves_no_root(loader, monkeypatch): monkeypatch.setattr(pm.filesystem, "lock_path", refuse_owner) with pytest.raises(PermissionError): reload._new_root() - assert not [e for e in _parent().iterdir() if e.name.startswith(reload._ROOT_PREFIX)] + assert not [e for e in _parent().iterdir() if e.name.startswith(reload._OWNED_PREFIX)] @pytest.mark.skipif(sys.platform == "win32", reason="needs os.fork") @@ -107,18 +144,37 @@ def test_a_forked_child_exiting_keeps_its_parents_copy(loader): assert root.is_dir() -def test_backups_and_profile_clones_leave_the_snapshots_out(tmp_path): - from pathlib import Path +def test_snapshots_live_under_the_root_even_for_a_named_profile(loader, tmp_path, monkeypatch): + # Deleting a named profile removes its whole home while a multiplexed gateway launched in it may keep serving + # other profiles; the copies that gateway imports from must not be inside that home. + reload, _hooks = loader + root_home = tmp_path / "home" + named = root_home / "profiles" / "work" + named.mkdir(parents=True) + (named / "config.yaml").write_text("") + monkeypatch.setenv("HERMES_HOME", str(named)) + root = reload._new_root() + + assert root.parent == root_home / "runtime" / "provider-plugins" + + +def test_backups_and_profile_clones_leave_the_snapshots_out(tmp_path): from hermes_cli.backup import _should_exclude - from hermes_cli.home_data_layout import provider_plugin_snapshot_dir + from hermes_cli.profiles import _clone_all_copytree_ignore for rel in ("runtime/provider-plugins/x/owner.lock", "profiles/work/runtime/provider-plugins/x/a.py"): assert _should_exclude(Path(rel)) assert not _should_exclude(Path("runtime/active_sessions.json")) - home = tmp_path / "home" - (home / "runtime" / "provider-plugins").mkdir(parents=True) - names = ["provider-plugins", "active_sessions.json"] - assert provider_plugin_snapshot_dir(str(home / "runtime"), names, home) == {"provider-plugins"} - assert provider_plugin_snapshot_dir(str(home / "skills" / "runtime"), names, home) == set() + source = tmp_path / "source" + (source / "runtime" / "provider-plugins" / "owned-x").mkdir(parents=True) + (source / "runtime" / "provider-plugins" / "owned-x" / "a.py").write_text("") + (source / "runtime" / "active_sessions.json").write_text("{}") + (source / "skills" / "runtime" / "provider-plugins").mkdir(parents=True) # a skill's own data: copied + clone = tmp_path / "clone" + shutil.copytree(source, clone, ignore=_clone_all_copytree_ignore(source)) + + assert not (clone / "runtime" / "provider-plugins").exists() + assert (clone / "runtime" / "active_sessions.json").is_file() + assert (clone / "skills" / "runtime" / "provider-plugins").is_dir()