Skip to content

The agent that grows with you

fix(environments): remote file sync re-uploads same-size same-tick rewrites

Maciej Lisiewski88472b8e6e45
diff --git a/tests/tools/test_file_sync.py b/tests/tools/test_file_sync.py
index 9e1c702feef..007d92664ec 100644
--- a/tests/tools/test_file_sync.py
+++ b/tests/tools/test_file_sync.py
@@ -55,6 +55,73 @@ class TestMtimeSkip:
mgr.sync(force=True)
assert upload.call_count == 0, "unchanged files should not be re-uploaded"
+ def test_same_size_in_place_rewrite_on_a_coarse_clock_is_re_uploaded(self, tmp_path, monkeypatch):
+ """A filesystem whose timestamps did not tick between the sync and a rewrite (coarse mtime
+ AND ctime): a same-size in-place rewrite keeps every stat field, so a key recorded while its
+ mtime was that fresh must be confirmed by content before it is trusted."""
+ import pathlib
+ import time
+ from types import SimpleNamespace
+
+ token = tmp_path / "token.json"
+ token.write_text('{"access":"AAAA"}', encoding="utf-8")
+ frozen_ns = time.time_ns()
+ real_stat = pathlib.Path.stat
+
+ def frozen_clock_stat(path, *args, **kwargs):
+ st = real_stat(path, *args, **kwargs)
+ return SimpleNamespace(st_mtime_ns=frozen_ns, st_ctime_ns=frozen_ns, st_size=st.st_size,
+ st_ino=st.st_ino, st_mode=st.st_mode, st_mtime=frozen_ns / 1e9)
+
+ monkeypatch.setattr(pathlib.Path, "stat", frozen_clock_stat)
+ uploaded = []
+
+ def bulk_upload(files):
+ uploaded.extend(Path(staged).read_text(encoding="utf-8") for staged, _remote in files)
+
+ mgr = FileSyncManager(
+ get_files_fn=lambda: [(str(token), "/root/.hermes/token.json")],
+ upload_fn=MagicMock(),
+ delete_fn=MagicMock(),
+ bulk_upload_fn=bulk_upload,
+ )
+ mgr.sync(force=True)
+ mgr.sync(force=True) # unchanged bytes: confirmed by content, not uploaded again
+
+ token.write_text('{"access":"BBBB"}', encoding="utf-8")
+ mgr.sync(force=True)
+
+ assert uploaded == ['{"access":"AAAA"}', '{"access":"BBBB"}']
+
+ @pytest.mark.platforms("linux", "macos")
+ def test_same_size_same_mtime_replace_is_re_uploaded(self, tmp_path):
+ """An OAuth refresh atomically replaces a token with same-size bytes inside the mtime
+ tick of the last sync; the remote must still receive the new credential."""
+ token = tmp_path / "token.json"
+ pinned_ns = 1_800_000_000_000_000_000
+ token.write_text('{"access":"AAAA"}', encoding="utf-8")
+ os.utime(token, ns=(pinned_ns, pinned_ns))
+ uploaded = []
+
+ def bulk_upload(files):
+ uploaded.extend(Path(staged).read_text(encoding="utf-8") for staged, _remote in files)
+
+ mgr = FileSyncManager(
+ get_files_fn=lambda: [(str(token), "/root/.hermes/token.json")],
+ upload_fn=MagicMock(),
+ delete_fn=MagicMock(),
+ bulk_upload_fn=bulk_upload,
+ )
+ mgr.sync(force=True)
+
+ replacement = tmp_path / "token.json.tmp"
+ replacement.write_text('{"access":"BBBB"}', encoding="utf-8")
+ os.utime(replacement, ns=(pinned_ns, pinned_ns))
+ os.replace(replacement, token)
+ mgr.sync(force=True)
+
+ assert uploaded == ['{"access":"AAAA"}', '{"access":"BBBB"}']
+
def test_new_file_detected(self, tmp_files, tmp_path):
upload = MagicMock()
@@ -144,6 +211,29 @@ class TestTransactionalRollback:
mgr.sync(force=True)
good_delete.assert_called_once()
+ def test_a_file_vanishing_mid_plan_is_retried_not_raised(self, tmp_files, monkeypatch):
+ """sync() runs before every terminal command: a file removed between its stat and the
+ content check (a credential being rotated) must fail the cycle quietly, not the command."""
+ import tools.environments.file_sync as file_sync_mod
+
+ upload = MagicMock()
+ mgr = _make_manager(tmp_files, upload=upload)
+ mgr.sync(force=True)
+ # Re-stat as changed so the planner content-checks the already-pushed file.
+ mgr._synced_files = {remote: (-2, -2, -2, -2) for remote in mgr._synced_files}
+ real_sha = file_sync_mod._sha256_file
+
+ def vanished(path):
+ raise FileNotFoundError(path)
+
+ monkeypatch.setattr(file_sync_mod, "_sha256_file", vanished)
+ mgr.sync(force=True) # must not raise
+
+ monkeypatch.setattr(file_sync_mod, "_sha256_file", real_sha)
+ upload.reset_mock()
+ mgr.sync(force=True)
+ assert upload.call_count == 0, "the retry confirms the unchanged bytes instead of re-uploading"
+
class TestRateLimiting:
def test_sync_skipped_within_interval(self, tmp_files):
diff --git a/tools/environments/base.py b/tools/environments/base.py
index 0a3cc4c3d20..6253d70ae0e 100644
--- a/tools/environments/base.py
+++ b/tools/environments/base.py
@@ -29,7 +29,7 @@ from tools.environments.base_session_env import (
_wrap_command_script,
)
from tools.environments.base_wait import _WaitTrace
-from utils import env_var_enabled
+from utils import env_var_enabled, file_signature
logger = logging.getLogger(__name__)
@@ -208,11 +208,13 @@ def _save_json_store(path: Path, data: dict) -> None:
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
-def _file_mtime_key(host_path: str) -> tuple[float, int] | None:
- """Return ``(mtime, size)`` for cache comparison, or ``None`` if unreadable."""
+def _file_mtime_key(host_path: str) -> tuple[int, int, int, int] | None:
+ """Return the ``file_signature`` change key, or ``None`` if unreadable.
+
+ mtime + size alone miss a same-size credential refresh landing in the same mtime tick;
+ inode and ctime catch the atomic replace / rewrite."""
try:
- st = Path(host_path).stat()
- return (st.st_mtime, st.st_size)
+ return file_signature(Path(host_path).stat())
except OSError:
return None
diff --git a/tools/environments/file_sync.py b/tools/environments/file_sync.py
index 08f385d0812..4596ebf2b6a 100644
--- a/tools/environments/file_sync.py
+++ b/tools/environments/file_sync.py
@@ -28,6 +28,7 @@ import psutil
from hermes_constants import get_hermes_home
from tools.environments.base import _file_mtime_key
+from utils import mtime_is_racy
logger = logging.getLogger(__name__)
@@ -40,6 +41,8 @@ _monotonic = time.monotonic
_SYNC_INTERVAL_SECONDS = 5.0
_FORCE_SYNC_ENV = "HERMES_FORCE_FILE_SYNC"
+# Synced-state key no stat result equals (see _plan_sync): forces a content check next sync.
+_RACY_SYNC_KEY = (-1, -1, -1, -1)
# Transport callbacks provided by each backend
UploadFn = Callable[[str, str], None] # (host_path, remote_path) -> raises on failure
@@ -204,7 +207,7 @@ class FileSyncManager:
self._bulk_download_fn = bulk_download_fn
self._delete_fn = delete_fn
self._transaction_lock = threading.Lock()
- self._synced_files: dict[str, tuple[float, int]] = {} # remote_path -> (mtime, size)
+ self._synced_files: dict[str, tuple[int, int, int, int]] = {} # remote_path -> file_signature
self._pushed_hashes: dict[str, str] = {} # remote_path -> sha256 hex digest
self._upload_only_host_paths: set[str] = set()
self._last_sync_time: float = 0.0 # monotonic; 0 ensures first sync runs
@@ -228,15 +231,19 @@ class FileSyncManager:
current_files = self._get_files_fn()
self._upload_only_host_paths.update(_credential_host_paths())
- to_upload, new_files, to_delete = self._plan_sync(current_files)
-
- if not to_upload and not to_delete:
- self._last_sync_time = _monotonic()
- return
-
prev_files = dict(self._synced_files)
prev_hashes = dict(self._pushed_hashes)
try:
+ # Planning reads files too (content check against the pushed hash): a file removed
+ # or unreadable after its stat fails the cycle here like a staging read, so the
+ # caller's command still runs and the next cycle retries.
+ to_upload, new_files, to_delete = self._plan_sync(current_files)
+
+ if not to_upload and not to_delete:
+ self._synced_files = new_files # content-confirmed keys, nothing to push
+ self._last_sync_time = _monotonic()
+ return
+
# Hash and upload the same bytes: the original may be saved while
# the transport is reading it or waiting for remote acknowledgement.
with tempfile.TemporaryDirectory(prefix="hermes-sync-push-") as staging:
@@ -264,7 +271,7 @@ class FileSyncManager:
def _plan_sync(
self, current_files: list[tuple[str, str]]
- ) -> tuple[list[tuple[str, str]], dict[str, tuple[float, int]], list[str]]:
+ ) -> tuple[list[tuple[str, str]], dict[str, tuple[int, int, int, int]], list[str]]:
"""Diff *current_files* against synced state -> ``(to_upload, new_synced_state, to_delete)``."""
to_upload: list[tuple[str, str]] = []
new_files = dict(self._synced_files)
@@ -272,8 +279,15 @@ class FileSyncManager:
file_key = _file_mtime_key(host_path)
if file_key is None or self._synced_files.get(remote_path) == file_key:
continue
+ # A key whose mtime is still inside the racy window is recorded as never-matching: a
+ # same-size rewrite in the same coarse tick would keep every stat field (ctime ticks
+ # just as coarsely). The next sync then confirms the bytes against the pushed hash.
+ recorded_key = _RACY_SYNC_KEY if mtime_is_racy(file_key[0]) else file_key
+ new_files[remote_path] = recorded_key
+ pushed_hash = self._pushed_hashes.get(remote_path)
+ if pushed_hash is not None and _sha256_file(host_path) == pushed_hash:
+ continue # the remote already holds these bytes
to_upload.append((host_path, remote_path))
- new_files[remote_path] = file_key
current_remote_paths = {remote for _, remote in current_files}
to_delete = [p for p in self._synced_files if p not in current_remote_paths]
return to_upload, new_files, to_delete