The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(file-sync): clean stale sync-back archives
KoNit-K6a03d5a94cc6
diff --git a/tests/tools/test_file_sync_back.py b/tests/tools/test_file_sync_back.pyindex 5075dd3aeaf..210bdebeae2 100644--- a/tests/tools/test_file_sync_back.py+++ b/tests/tools/test_file_sync_back.py@@ -14,9 +14,11 @@ fcntl = pytest.importorskip("fcntl")from tools.environments.file_sync import (FileSyncManager,+ _cleanup_stale_sync_back_tars,_sha256_file,_SYNC_BACK_BACKOFF,_SYNC_BACK_MAX_RETRIES,+ _SYNC_BACK_STALE_TAR_SECONDS,)@@ -89,6 +91,49 @@ def _make_manager(return mgr+class TestStaleSyncBackTarCleanup:+ """Hard-killed sync-back archives are cleaned up conservatively."""++ def test_removes_only_stale_hermes_sync_back_tars(self, tmp_path, monkeypatch):+ stale = tmp_path / "hermes-sync-back-stale.tar"+ recent = tmp_path / "hermes-sync-back-recent.tar"+ unrelated = tmp_path / "other-process.tar"+ for path in (stale, recent, unrelated):+ path.write_bytes(b"tar")+ now = 10_000.0+ os.utime(stale, (now - _SYNC_BACK_STALE_TAR_SECONDS - 1,) * 2)+ os.utime(recent, (now - _SYNC_BACK_STALE_TAR_SECONDS + 1,) * 2)+ monkeypatch.setattr("tools.environments.file_sync.time.time", lambda: now)++ _cleanup_stale_sync_back_tars(tmp_path)++ assert not stale.exists()+ assert recent.exists()+ assert unrelated.exists()++ def test_preserves_active_tar_when_stat_or_unlink_fails(self, tmp_path, monkeypatch):+ active = tmp_path / "hermes-sync-back-active.tar"+ stale = tmp_path / "hermes-sync-back-stale.tar"+ active.write_bytes(b"tar")+ stale.write_bytes(b"tar")+ now = 10_000.0+ os.utime(stale, (now - _SYNC_BACK_STALE_TAR_SECONDS - 1,) * 2)+ monkeypatch.setattr("tools.environments.file_sync.time.time", lambda: now)+ original_unlink = Path.unlink++ def fail_for_stale(path, *args, **kwargs):+ if path == stale:+ raise OSError("busy")+ return original_unlink(path, *args, **kwargs)++ monkeypatch.setattr(Path, "unlink", fail_for_stale)++ _cleanup_stale_sync_back_tars(tmp_path)++ assert active.exists()+ assert stale.exists()++# ---------------------------------------------------------------------------# Tests# ---------------------------------------------------------------------------diff --git a/tools/environments/file_sync.py b/tools/environments/file_sync.pyindex 272fd29ea62..fcd7b1c6456 100644--- a/tools/environments/file_sync.py+++ b/tools/environments/file_sync.py@@ -48,6 +48,32 @@ 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+_SYNC_BACK_TEMP_TAR_PREFIX = "hermes-sync-back-"+_SYNC_BACK_STALE_TAR_SECONDS = 24 * 60 * 60+++def _cleanup_stale_sync_back_tars(temp_dir: Path | None = None) -> None:+ """Remove old sync-back archives left behind when a process is hard-killed.++ Only archives created with this module's dedicated prefix are considered. A+ cleanup race or permission error must not prevent the current sync-back.+ """+ directory = temp_dir or Path(tempfile.gettempdir())+ cutoff = time.time() - _SYNC_BACK_STALE_TAR_SECONDS+ try:+ candidates = directory.glob(f"{_SYNC_BACK_TEMP_TAR_PREFIX}*.tar")+ for candidate in candidates:+ try:+ if candidate.is_symlink() or not candidate.is_file():+ continue+ if candidate.stat().st_mtime >= cutoff:+ continue+ candidate.unlink()+ logger.debug("sync_back: removed stale temporary archive %s", candidate)+ except OSError:+ logger.debug("sync_back: could not remove stale temporary archive %s", candidate)+ except OSError:+ logger.debug("sync_back: could not scan temporary directory %s", directory)def iter_sync_files(container_base: str = "/root/.hermes") -> list[tuple[str, str]]:@@ -311,9 +337,13 @@ class FileSyncManager:except Exception:file_mapping = []+ # A hard kill bypasses the finally below. Reclaim only old archives using+ # our dedicated prefix before allocating another full-tree download.+ _cleanup_stale_sync_back_tars()+# 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(suffix=".tar")+ fd, tar_path = tempfile.mkstemp(prefix=_SYNC_BACK_TEMP_TAR_PREFIX, suffix=".tar")os.close(fd)try:self._bulk_download_fn(Path(tar_path))