The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): reclaim sync-back temps by owner PID and harden socket tolerance
liuhao1024e928655b8578
diff --git a/tests/tools/test_file_sync_back.py b/tests/tools/test_file_sync_back.pyindex 25a3d04b52a..e513ce625a4 100644--- a/tests/tools/test_file_sync_back.py+++ b/tests/tools/test_file_sync_back.py@@ -141,6 +141,46 @@ class TestStaleSyncBackTempCleanup:assert not leaked.exists()assert list(tmp_root.iterdir()) == []+ def test_dead_owner_entry_reclaimed_regardless_of_age(self, tmp_path, monkeypatch):+ """#114437: an entry whose owner PID is gone is reclaimed immediately — age (and the+ staging-dir mtime freeze during extraction) must not keep a leaked multi-GB tar around."""+ entry = tmp_path / f"hermes-sync-back-{os.getpid()}-xyz.tar"+ entry.write_bytes(b"x")+ fresh = time.time()+ os.utime(entry, (fresh, fresh))+ monkeypatch.setattr("tools.environments.file_sync._pid_alive", lambda pid: False)++ assert _cleanup_stale_sync_back_temp(tmp_path) == 1+ assert not entry.exists()++ def test_live_owner_entry_survives_any_age(self, tmp_path, monkeypatch):+ """An entry owned by a live process (this one, or a concurrent gateway under a+ different HERMES_HOME) is never reclaimed, however old its mtime looks."""+ entry = tmp_path / f"hermes-sync-back-{os.getpid()}-xyz.tar"+ entry.write_bytes(b"x")+ os.utime(entry, (0, 0))+ monkeypatch.setattr("tools.environments.file_sync._pid_alive", lambda pid: True)++ assert _cleanup_stale_sync_back_temp(tmp_path) == 0+ assert entry.exists()++ def test_new_temp_entries_embed_the_owner_pid(self, tmp_path):+ """Fresh temp entries carry the owning PID so the sweep can judge ownership (#114437)."""+ seen = {}++ def download(dest: Path):+ seen["tar"] = dest+ _make_tar({"root/.hermes/x.txt": b"hi"}, dest)++ mgr = _make_manager(tmp_path, bulk_download_fn=download)+ mgr.sync_back()++ name = seen["tar"].name+ assert name.startswith(f"{_SYNC_BACK_TEMP_PREFIX}{os.getpid()}-")+ from tools.environments.file_sync import _temp_entry_owner_pid+ assert _temp_entry_owner_pid(name) == os.getpid()+ assert _temp_entry_owner_pid("hermes-sync-back-legacy.tar") is None+# ---------------------------------------------------------------------------# Tests@@ -511,20 +551,13 @@ class TestSyncBackSizeCap:mgr.sync_back(hermes_home=tmp_path / ".hermes")assert Path(host_file).read_bytes() == b"remote_version"- def test_sync_back_cap_reads_env_override_at_import(self, monkeypatch):- """HERMES_SYNC_BACK_MAX_BYTES overrides the 2 GiB default at import time (#114437)."""- import importlib- from tools.environments import file_sync as file_sync_mod- monkeypatch.setenv("HERMES_SYNC_BACK_MAX_BYTES", "1024")- try:- reloaded = importlib.reload(file_sync_mod)- assert reloaded._SYNC_BACK_MAX_BYTES == 1024- finally:- monkeypatch.delenv("HERMES_SYNC_BACK_MAX_BYTES", raising=False)- importlib.reload(file_sync_mod)-def test_stale_sweep_window_is_bounded_to_half_an_hour(self):- """A hard-kill crash loop must not accumulate tars for hours before reclaim (#114437)."""+ """A hard-kill crash loop must not accumulate tars for hours before reclaim (#114437).++ The cutoff only governs legacy (pre-PID) names and Windows hosts — owned entries+ are reclaimed by owner liveness instead — but it still bounds a crash loop's+ leftovers from an older build.+ """assert _SYNC_BACK_STALE_SECONDS <= 30 * 60diff --git a/tests/tools/test_sync_back_backends.py b/tests/tools/test_sync_back_backends.pyindex 8d43c2a692c..61d54ab2f7e 100644--- a/tests/tools/test_sync_back_backends.py+++ b/tests/tools/test_sync_back_backends.py@@ -173,12 +173,24 @@ class TestSSHBulkDownload:failures = (subprocess.CompletedProcess([], 1, stderr=b"ssh: connect to host refused"),subprocess.CompletedProcess([], 2, stderr=b""),+ subprocess.CompletedProcess([], 2, stderr=b"\n"), # whitespace-only is bare too)for completed in failures:with patch.object(subprocess, "run", return_value=completed):with pytest.raises(EnvironmentConnectionError):ssh_mock_env._ssh_bulk_download(dest)+ def test_ssh_bulk_download_anchor_rejects_midline_marker(self, ssh_mock_env, tmp_path):+ """A diagnostic merely containing 'socket ignored' mid-line is not tolerated."""+ from tools.environments.base import EnvironmentConnectionError+ dest = tmp_path / "backup.tar"+ stderr = b"tar: socket ignored dir/state.db: Cannot open: Permission denied\n"+ completed = subprocess.CompletedProcess([], 2, stderr=stderr)++ with patch.object(subprocess, "run", return_value=completed):+ with pytest.raises(EnvironmentConnectionError):+ ssh_mock_env._ssh_bulk_download(dest)+class TestSSHCleanup:"""Verify SSH cleanup() calls sync_back() before closing ControlMaster."""@@ -276,6 +288,8 @@ class TestModalBulkDownload:assert args[1] == "-c"assert "tar cf -" in args[2]assert "-C / root/.hermes" in args[2]+ # Live sockets cannot be archived; exclude them like the SSH backend (#114437).+ assert "--exclude='*.sock'" in args[2]def test_modal_bulk_download_uses_120s_timeout(self, tmp_path):@@ -347,6 +361,8 @@ class TestDaytonaBulkDownload:assert env._sandbox.process.exec.call_count == 2tar_cmd = env._sandbox.process.exec.call_args_list[0][0][0]assert "tar cf" in tar_cmd+ # Live sockets cannot be archived; exclude them like the SSH backend (#114437).+ assert "--exclude='*.sock'" in tar_cmd# PID-suffixed temp path avoids collisions on sync_back retryassert "/tmp/.hermes_sync." in tar_cmdassert ".tar" in tar_cmddiff --git a/tools/environments/daytona.py b/tools/environments/daytona.pyindex 04237afc62d..3d839acb742 100644--- a/tools/environments/daytona.py+++ b/tools/environments/daytona.py@@ -111,7 +111,10 @@ class DaytonaEnvironment(BaseEnvironment):rel_base = f"{self._remote_home}/.hermes".lstrip("/")# PID-suffixed remote temp path avoids collisions if sync_back runs concurrently.remote_tar = f"/tmp/.hermes_sync.{os.getpid()}.tar"- self._sandbox.process.exec(f"tar cf {shlex.quote(remote_tar)} -C / {shlex.quote(rel_base)}")+ # --exclude: live sockets cannot be archived ("socket ignored"), and on tar builds+ # that make the skipped socket fatal would fail the download (#114437).+ self._sandbox.process.exec(+ f"tar cf {shlex.quote(remote_tar)} --exclude='*.sock' -C / {shlex.quote(rel_base)}")self._sandbox.fs.download_file(remote_tar, str(dest))with contextlib.suppress(Exception): # best-effort cleanupself._sandbox.process.exec(f"rm -f {shlex.quote(remote_tar)}")diff --git a/tools/environments/file_sync.py b/tools/environments/file_sync.pyindex 97822a247cf..547b73d03cd 100644--- a/tools/environments/file_sync.py+++ b/tools/environments/file_sync.py@@ -47,24 +47,59 @@ GetFilesFn = Callable[[], list[tuple[str, str]]] # () -> [(host_path, remote_pa_SYNC_BACK_MAX_RETRIES = 3_SYNC_BACK_BACKOFF = (2, 4, 8) # seconds between retries-# 2 GiB by default — refuse to extract larger tars. Overridable for hosts whose synced tree-# legitimately exceeds the cap (a skip means sync-back silently does nothing at full cost).-_SYNC_BACK_MAX_BYTES = int(os.environ.get("HERMES_SYNC_BACK_MAX_BYTES", 2 * 1024 * 1024 * 1024))+_SYNC_BACK_MAX_BYTES = 2 * 1024 * 1024 * 1024 # 2 GiB — refuse to extract larger tars_SYNC_BACK_TEMP_PREFIX = "hermes-sync-back-"# A sync-back temp entry (the downloaded tar or the extraction staging dir) is only leaked by-# a hard kill (SIGKILL/OOM/power loss — the ``finally`` never runs), so anything older than-# this is safe to reclaim. The download itself is bounded by a 120 s subprocess timeout, so a-# live transfer is minutes old at most; the cutoff only has to sit above that. The old 6 h-# window let a crash loop accumulate tens of GB before anything was reclaimed (#114437).+# a hard kill (SIGKILL/OOM/power loss — the ``finally`` never runs). Entries embed the owning+# PID and an entry whose owner is dead is reclaimed immediately, whatever its age, so this+# cutoff only governs names without an embedded PID (leftovers from before the ownership+# scheme — no live process still creates them, so a short window suffices) and Windows hosts,+# where an arbitrary PID cannot be probed. The old 6 h window let a crash loop accumulate+# tens of GB before anything was reclaimed (#114437)._SYNC_BACK_STALE_SECONDS = 30 * 60+def _sync_back_temp_prefix() -> str:+ """Temp prefix embedding the owning PID, mirroring daytona's PID-suffixed remote temp.++ Ownership lets the stale sweep reclaim an entry the moment its owner process is gone+ (age-independent, and safe between concurrent gateway processes, which hold distinct+ PIDs) instead of guessing liveness from mtime — a staging dir's mtime does not move+ while content streams into its subdirectories.+ """+ return f"{_SYNC_BACK_TEMP_PREFIX}{os.getpid()}-"+++def _temp_entry_owner_pid(name: str) -> int | None:+ """Return the PID embedded in a sync-back temp entry name, or None for legacy names."""+ if not name.startswith(_SYNC_BACK_TEMP_PREFIX):+ return None+ pid_part = name[len(_SYNC_BACK_TEMP_PREFIX):].split("-", 1)[0]+ return int(pid_part) if pid_part.isdigit() else None+++def _pid_alive(pid: int) -> bool:+ """Whether *pid* names a live process (POSIX signal-0 probe; callers guard for Windows)."""+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError: # exists but is owned by another user+ return True+ except OSError:+ return True+ return True++def _cleanup_stale_sync_back_temp(temp_dir: Path | None = None) -> int:"""Remove sync-back tars and staging dirs left behind by a hard-killed process.- Only entries carrying this module's prefix and older than ``_SYNC_BACK_STALE_SECONDS``- are touched. Returns the number of entries removed; a permission error or a race with- another sync-back must not prevent the current one.+ An entry whose embedded owner PID is no longer alive is reclaimed immediately —+ age-independent, and never touching another live process's transfer even though the+ file lock is per ``HERMES_HOME`` while the temp directory is shared. Entries without+ an embedded PID (pre-ownership leftovers) and Windows hosts fall back to the+ ``_SYNC_BACK_STALE_SECONDS`` cutoff. Returns the number of entries removed; a+ permission error or a race with another sync-back must not prevent the current one."""directory = temp_dir or Path(tempfile.gettempdir())cutoff = time.time() - _SYNC_BACK_STALE_SECONDS@@ -76,7 +111,13 @@ def _cleanup_stale_sync_back_temp(temp_dir: Path | None = None) -> int:return 0for candidate in candidates:try:- if candidate.is_symlink() or candidate.lstat().st_mtime >= cutoff:+ owner = _temp_entry_owner_pid(candidate.name)+ if owner is not None and os.name != "nt":+ if _pid_alive(owner):+ continue # a live process owns this entry — leave it alone+ elif candidate.is_symlink() or candidate.lstat().st_mtime >= cutoff:+ continue+ if candidate.is_symlink():continueif candidate.is_dir():shutil.rmtree(candidate)@@ -356,7 +397,7 @@ class FileSyncManager:# mkstemp + close: NamedTemporaryFile keeps an exclusive handle on Windows, so the# backend's open(dest, "wb") / write_bytes on the same path raised PermissionError.- fd, tar_path = tempfile.mkstemp(prefix=_SYNC_BACK_TEMP_PREFIX, suffix=".tar")+ fd, tar_path = tempfile.mkstemp(prefix=_sync_back_temp_prefix(), suffix=".tar")os.close(fd)try:self._bulk_download_fn(Path(tar_path))@@ -372,7 +413,7 @@ class FileSyncManager:tar_size, _SYNC_BACK_MAX_BYTES)return- with tempfile.TemporaryDirectory(prefix=_SYNC_BACK_TEMP_PREFIX) as staging:+ with tempfile.TemporaryDirectory(prefix=_sync_back_temp_prefix()) as staging:with tarfile.open(tar_path) as tar:tar.extractall(staging, filter="data")diff --git a/tools/environments/modal.py b/tools/environments/modal.pyindex 5229699572d..cec7f8524f1 100644--- a/tools/environments/modal.py+++ b/tools/environments/modal.py@@ -234,7 +234,9 @@ class ModalEnvironment(BaseEnvironment):def _modal_bulk_download(self, dest: Path) -> None:"""Download remote .hermes/ as a tar archive (sandboxes run as root, so /root/.hermes)."""- data = self._exec("tar cf - -C / root/.hermes", timeout=120, fail_label="bulk download", capture=True)+ # --exclude: live sockets cannot be archived ("socket ignored"), and a tar build that+ # makes the skipped socket fatal would fail the download (#114437).+ data = self._exec("tar cf - --exclude='*.sock' -C / root/.hermes", timeout=120, fail_label="bulk download", capture=True)dest.write_bytes(data.encode() if isinstance(data, str) else data)def _modal_delete(self, remote_paths: list[str]) -> None:diff --git a/tools/environments/ssh.py b/tools/environments/ssh.pyindex 93263defa22..0e831137602 100644--- a/tools/environments/ssh.py+++ b/tools/environments/ssh.py@@ -255,10 +255,12 @@ class SSHEnvironment(BaseEnvironment):stderr = result.stderr.decode(errors="replace").strip()# tar exits 2 for non-fatal conditions; a socket that slipped past the exclude# pattern (or a tar without --exclude support) is the only one we knowingly accept,- # and only when nothing else was reported. Every other non-zero status still fails- # the transfer.- tolerated = result.returncode == 2 and bool(stderr) and all(- "socket ignored" in line for line in stderr.splitlines() if line.strip())+ # and only when nothing else was reported — anchored to the diagnostic suffix so a+ # filename merely containing "socket ignored" cannot sneak through. Every other+ # non-zero status still fails the transfer.+ diagnostic_lines = [line for line in stderr.splitlines() if line.strip()]+ tolerated = result.returncode == 2 and bool(diagnostic_lines) and all(+ line.endswith(": socket ignored") for line in diagnostic_lines)if not tolerated:raise _sync_error(f"SSH bulk download failed: {stderr}",f"File sync from {self.host}")