Skip to content

The agent that grows with you

fix(tools): stop socket-ignoring tars from failing sync-back and leaking GBs

liuhao10242f62b1f4de04
diff --git a/tests/tools/test_file_sync_back.py b/tests/tools/test_file_sync_back.py
index 9933b1cd4c8..25a3d04b52a 100644
--- a/tests/tools/test_file_sync_back.py
+++ b/tests/tools/test_file_sync_back.py
@@ -511,6 +511,22 @@ 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)."""
+ assert _SYNC_BACK_STALE_SECONDS <= 30 * 60
+
class TestSyncBackWindowsHost:
"""#76267: sync_back on a Windows host. The staging tar must be reopenable for writing by
diff --git a/tests/tools/test_sync_back_backends.py b/tests/tools/test_sync_back_backends.py
index 8f32f6c25d2..8d43c2a692c 100644
--- a/tests/tools/test_sync_back_backends.py
+++ b/tests/tools/test_sync_back_backends.py
@@ -131,6 +131,54 @@ class TestSSHBulkDownload:
call_kwargs = mock_run.call_args
assert call_kwargs.kwargs.get("timeout") == 120 or call_kwargs[1].get("timeout") == 120
+ def test_ssh_bulk_download_excludes_sockets(self, ssh_mock_env, tmp_path):
+ """The remote tar must skip live sockets — gateway.sock cannot be archived (#114437)."""
+ dest = tmp_path / "backup.tar"
+
+ with patch.object(subprocess, "run", return_value=subprocess.CompletedProcess([], 0)) as mock_run:
+ ssh_mock_env._ssh_bulk_download(dest)
+
+ cmd_str = " ".join(mock_run.call_args[0][0])
+ assert "--exclude='*.sock'" in cmd_str
+
+ def test_ssh_bulk_download_tolerates_socket_ignored_exit_2(
+ self, ssh_mock_env, tmp_path
+ ):
+ """rc=2 whose stderr is only 'socket ignored' lines must not fail the transfer (#114437)."""
+ dest = tmp_path / "backup.tar"
+ stderr = b"tar: home/testuser/.hermes/gateway.sock: socket ignored\n"
+ completed = subprocess.CompletedProcess([], 2, stderr=stderr)
+
+ with patch.object(subprocess, "run", return_value=completed):
+ ssh_mock_env._ssh_bulk_download(dest) # must not raise
+
+ def test_ssh_bulk_download_fails_on_other_exit_2_errors(self, ssh_mock_env, tmp_path):
+ """rc=2 reporting anything besides an ignored socket still fails the transfer."""
+ from tools.environments.base import EnvironmentConnectionError
+ dest = tmp_path / "backup.tar"
+ stderr = (b"tar: home/testuser/.hermes/gateway.sock: socket ignored\n"
+ b"tar: home/testuser/.hermes/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)
+
+ def test_ssh_bulk_download_fails_on_exit_1_and_bare_exit_2(
+ self, ssh_mock_env, tmp_path
+ ):
+ """rc=1, and rc=2 with no diagnostic at all, still fail the transfer."""
+ from tools.environments.base import EnvironmentConnectionError
+ dest = tmp_path / "backup.tar"
+ failures = (
+ subprocess.CompletedProcess([], 1, stderr=b"ssh: connect to host refused"),
+ subprocess.CompletedProcess([], 2, stderr=b""),
+ )
+ for completed in failures:
+ 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."""
diff --git a/tools/environments/file_sync.py b/tools/environments/file_sync.py
index 35f4afd6cf9..97822a247cf 100644
--- a/tools/environments/file_sync.py
+++ b/tools/environments/file_sync.py
@@ -47,12 +47,16 @@ GetFilesFn = Callable[[], list[tuple[str, str]]] # () -> [(host_path, remote_pa
_SYNC_BACK_MAX_RETRIES = 3
_SYNC_BACK_BACKOFF = (2, 4, 8) # seconds between retries
-_SYNC_BACK_MAX_BYTES = 2 * 1024 * 1024 * 1024 # 2 GiB — refuse to extract larger tars
+# 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_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; a live transfer is hours younger than the cutoff.
-_SYNC_BACK_STALE_SECONDS = 6 * 60 * 60
+# 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).
+_SYNC_BACK_STALE_SECONDS = 30 * 60
def _cleanup_stale_sync_back_temp(temp_dir: Path | None = None) -> int:
diff --git a/tools/environments/ssh.py b/tools/environments/ssh.py
index 0b6a50afad8..93263defa22 100644
--- a/tools/environments/ssh.py
+++ b/tools/environments/ssh.py
@@ -244,12 +244,24 @@ class SSHEnvironment(BaseEnvironment):
# Tar from / with the full path so archive entries keep absolute paths
# (home/user/.hermes/skills/f.py), matching _pushed_hashes keys.
rel_base = f"{self._remote_home}/.hermes".lstrip("/")
- ssh_cmd = self._build_ssh_command() + [f"tar cf - -C / {shlex.quote(rel_base)}"]
+ # Live sockets inside .hermes (gateway.sock and friends) cannot be archived: tar prints
+ # "socket ignored" and exits 2, which used to fail every sync-back and leave a multi-GB
+ # temp tar behind on each retry (#114437). Exclude them up front.
+ ssh_cmd = self._build_ssh_command() + [
+ f"tar cf - --exclude='*.sock' -C / {shlex.quote(rel_base)}"]
with open(dest, "wb") as f:
result = subprocess.run(ssh_cmd, stdin=subprocess.DEVNULL, stdout=f, stderr=subprocess.PIPE, timeout=120)
if result.returncode != 0:
- raise _sync_error(f"SSH bulk download failed: {result.stderr.decode(errors='replace').strip()}",
- f"File sync from {self.host}")
+ 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())
+ if not tolerated:
+ raise _sync_error(f"SSH bulk download failed: {stderr}",
+ f"File sync from {self.host}")
def _ssh_delete(self, remote_paths: list[str]) -> None:
self._run_ssh_checked(quoted_rm_command(remote_paths), 10, "remote rm failed",