Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions tests/tools/test_file_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ def _make_manager(tmp_files, remote_base="/root/.hermes", upload=None, delete=No


class TestMtimeSkip:
def test_reset_remote_state_reuploads_everything(self, tmp_files):
upload = MagicMock()
mgr = _make_manager(tmp_files, upload=upload)

mgr.sync(force=True)
upload.reset_mock()

mgr.reset_remote_state()
mgr.sync(force=True)

assert upload.call_count == 3

def test_unchanged_files_not_re_uploaded(self, tmp_files):
upload = MagicMock()
mgr = _make_manager(tmp_files, upload=upload)
Expand Down Expand Up @@ -111,6 +123,31 @@ def test_removed_file_triggers_delete(self, tmp_files):
deleted_paths = delete.call_args[0][0]
assert any("cred_b.json" in p for p in deleted_paths)

def test_reset_remote_state_replays_deletions(self, tmp_files):
delete = MagicMock()
mgr = _make_manager(tmp_files, delete=delete)

mgr.sync(force=True)
os.unlink(tmp_files["cred_b.json"])
del tmp_files["cred_b.json"]
mgr._get_files_fn = _make_get_files(tmp_files)
mgr.sync(force=True)
delete.reset_mock()

# A replacement sandbox restored from an older snapshot may contain
# the file that was already deleted from the original sandbox.
mgr.reset_remote_state()
mgr.sync(force=True)
delete.assert_called_once_with(["/root/.hermes/cred_b.json"])

# The recovery image can be reused for another cancellation, so the
# same deletion must remain queued for every subsequent reset.
delete.reset_mock()
mgr.reset_remote_state()
mgr.sync(force=True)

delete.assert_called_once_with(["/root/.hermes/cred_b.json"])

def test_no_delete_when_no_removals(self, tmp_files):
delete = MagicMock()
mgr = _make_manager(tmp_files, delete=delete)
Expand Down
223 changes: 223 additions & 0 deletions tests/tools/test_modal_sandbox_fixes.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,138 @@
pytest.skip("hermes-agent tools not importable (missing deps)", allow_module_level=True)


def test_modal_run_bash_consumes_pre_execute_liveness_check(monkeypatch):
"""Base execute's preflight must not cause a second sandbox poll."""
from tools.environments.modal import ModalEnvironment

import threading

env = ModalEnvironment.__new__(ModalEnvironment)
env._sandbox = object()
env._worker = object()
env._respawn_lock = threading.RLock()
env._respawning = False
env._sandbox_generation = 7
env._sandbox_checked_generation = 7
ensure_calls = []
monkeypatch.setattr(
env, "_ensure_live_sandbox", lambda: ensure_calls.append("checked")
)

env._run_bash("true")
assert ensure_calls == []
assert env._sandbox_checked_generation is None

env._run_bash("true")
assert ensure_calls == ["checked"]


def test_modal_delete_batches_command_arguments_under_limit():
"""Recovery tombstones must not create an oversized rm command."""
from tools.environments.file_sync import quoted_rm_command
from tools.environments.modal import _MODAL_DELETE_MAX_COMMAND_BYTES, _batch_remote_paths

paths = [f"/root/.hermes/cache/{index:05d}/" + ("x" * 80) for index in range(2000)]
batches = _batch_remote_paths(paths)

assert [path for batch in batches for path in batch] == paths
assert all(
len(quoted_rm_command(batch).encode()) <= _MODAL_DELETE_MAX_COMMAND_BYTES
for batch in batches
)
assert len(batches) > 1


class TestModalDeleteFailurePropagation:
"""`FileSyncManager.sync()` is transactional: it commits the deletion set
and stops replaying it only when the delete callback returns WITHOUT
raising. So `_modal_delete` must surface remote failures, and must not let
one aggregate deadline cover every batch.
"""

@staticmethod
def _env(exit_codes, record):
"""A ModalEnvironment stub whose exec returns the given exit codes."""
import asyncio
import threading
from types import SimpleNamespace
from tools.environments.modal import ModalEnvironment

codes = list(exit_codes)

def _make_proc(code):
async def _wait():
return code

async def _read():
return "permission denied"

return SimpleNamespace(
wait=SimpleNamespace(aio=_wait),
stderr=SimpleNamespace(read=SimpleNamespace(aio=_read)),
)

async def _exec(*args, **kwargs):
record.setdefault("commands", []).append(args[-1])
return _make_proc(codes.pop(0) if codes else 0)

class _Worker:
def run_coroutine(self, coro, timeout=None):
record.setdefault("timeouts", []).append(timeout)
return asyncio.run(coro)

env = ModalEnvironment.__new__(ModalEnvironment)
env._sandbox = SimpleNamespace(exec=SimpleNamespace(aio=_exec))
env._worker = _Worker()
env._respawn_lock = threading.RLock()
return env

def test_nonzero_batch_exit_raises_so_sync_retries(self):
"""A failed rm must NOT be silently committed as a successful delete."""
record = {}
env = self._env([1], record)

with pytest.raises(RuntimeError, match="Modal remote delete failed"):
env._modal_delete(["/root/.hermes/gh_token"])

def test_all_batches_succeed_returns_cleanly(self):
record = {}
env = self._env([0], record)
env._modal_delete(["/root/.hermes/gh_token"]) # must not raise

def test_timeout_is_applied_per_batch_not_once_for_all(self):
"""Each batch gets its own deadline, so a big tombstone set can converge."""
from tools.environments.modal import (
_DELETE_BATCH_TIMEOUT_SECONDS,
_batch_remote_paths,
)

paths = [f"/root/.hermes/cache/{i:05d}/" + ("x" * 80) for i in range(2000)]
batch_count = len(_batch_remote_paths(paths))
assert batch_count > 1, "fixture must span multiple batches"

record = {}
env = self._env([0] * batch_count, record)
env._modal_delete(paths)

# One run_coroutine call per batch, each with the full per-batch budget.
assert len(record["timeouts"]) == batch_count
assert set(record["timeouts"]) == {_DELETE_BATCH_TIMEOUT_SECONDS}

def test_later_batch_failure_still_raises(self):
"""Failure in a non-first batch must propagate, not be swallowed."""
from tools.environments.modal import _batch_remote_paths

paths = [f"/root/.hermes/cache/{i:05d}/" + ("x" * 80) for i in range(2000)]
batch_count = len(_batch_remote_paths(paths))
codes = [0] * (batch_count - 1) + [1]

record = {}
env = self._env(codes, record)
with pytest.raises(RuntimeError, match="Modal remote delete failed"):
env._modal_delete(paths)


# =========================================================================
# Test 1: Tool resolution includes terminal + file tools
# =========================================================================
Expand Down Expand Up @@ -222,6 +354,97 @@ def test_default_cwd_is_root(self):
"Tilde ~ is not expanded by subprocess.run(cwd=...)."
)

def test_cleanup_stops_worker_when_sandbox_is_already_gone(self):
"""A cancelled sandbox must not leave its async worker running."""
from tools.environments.modal import ModalEnvironment

class _Worker:
def __init__(self):
self.stop_calls = 0

def stop(self):
self.stop_calls += 1

env = ModalEnvironment.__new__(ModalEnvironment)
env._sandbox = None
env._app = object()
env._worker = _Worker()

env.cleanup()

assert env._worker.stop_calls == 1
assert env._app is None

def test_before_execute_recovers_before_file_sync(self):
"""Recovery must happen before sync and command cwd wrapping."""
from tools.environments.modal import ModalEnvironment

calls = []
env = ModalEnvironment.__new__(ModalEnvironment)
env._sandbox_generation = 0
env._sandbox_checked_generation = None
env._ensure_live_sandbox = lambda: calls.append("recover")
env._sync_manager = type("SyncManager", (), {
"sync": lambda _self: calls.append("sync"),
})()

env._before_execute()

assert calls == ["recover", "sync"]

def test_ensure_live_sandbox_reuses_recovery_image(self, monkeypatch):
"""Respawn should preserve a sandbox restored from a snapshot."""
import threading
import tools.environments.modal as modal_module
from tools.environments.modal import ModalEnvironment

resolved = []

class _Worker:
def run_coroutine(self, coro, timeout=300):
coro.close()
return "app", "replacement"

async def _create_sandbox(image):
return "unused", image

env = ModalEnvironment.__new__(ModalEnvironment)
env._respawn_lock = threading.RLock()
env._respawning = False
env._sandbox_generation = 0
env._sandbox_checked_generation = None
env._sandbox_is_live = lambda: False
env._task_id = "test"
env._recovery_image_spec = "im-persisted"
env._create_sandbox = _create_sandbox
env._worker = _Worker()
env._sync_manager = None
env._snapshot_ready = True
env.init_session = lambda: None
monkeypatch.setattr(
modal_module,
"_resolve_modal_image",
lambda spec: resolved.append(spec) or f"resolved:{spec}",
)

env._ensure_live_sandbox()

assert resolved == ["im-persisted"]
assert env._sandbox == "replacement"

def test_ensure_live_sandbox_surfaces_indeterminate_poll(self):
"""A poll error must not abandon a possibly live sandbox."""
import threading
from tools.environments.modal import ModalEnvironment

env = ModalEnvironment.__new__(ModalEnvironment)
env._respawn_lock = threading.RLock()
env._respawning = False
env._sandbox_is_live = lambda: None

with pytest.raises(RuntimeError, match="Unable to determine"):
env._ensure_live_sandbox()


# =========================================================================
# Test 7: ensurepip fix in ModalEnvironment
Expand Down
32 changes: 32 additions & 0 deletions tools/environments/file_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,26 @@ def __init__(
self._delete_fn = delete_fn
self._synced_files: dict[str, tuple[float, int]] = {} # remote_path -> (mtime, size)
self._pushed_hashes: dict[str, str] = {} # remote_path -> sha256 hex digest
self._deleted_remote_paths: set[str] = set()
self._remote_state_reset = False
self._upload_only_host_paths: set[str] = set()
self._last_sync_time: float = 0.0 # monotonic; 0 ensures first sync runs
self._sync_interval = sync_interval

def reset_remote_state(self) -> None:
"""Forget the state of a remote environment that was replaced.

A newly created sandbox has no files from the previous remote
environment, so mtime and content-hash tracking from that environment
must not suppress the first upload into its replacement. Deletion
tombstones are retained so files restored from an older snapshot are
removed again during the next forced sync.
"""
self._synced_files.clear()
self._pushed_hashes.clear()
self._remote_state_reset = True
self._last_sync_time = 0.0

def sync(self, *, force: bool = False) -> None:
"""Run a sync cycle: upload changed files, delete removed files.

Expand All @@ -179,6 +195,8 @@ def sync(self, *, force: bool = False) -> None:
current_files = self._get_files_fn()
self._upload_only_host_paths.update(_credential_host_paths())
current_remote_paths = {remote for _, remote in current_files}
new_deleted = set(self._deleted_remote_paths)
new_deleted.difference_update(current_remote_paths)

# --- Uploads: new or changed files ---
to_upload: list[tuple[str, str]] = []
Expand All @@ -194,14 +212,26 @@ def sync(self, *, force: bool = False) -> None:

# --- Deletes: synced paths no longer in current set ---
to_delete = [p for p in self._synced_files if p not in current_remote_paths]
if self._remote_state_reset:
to_delete.extend(
p for p in self._deleted_remote_paths
if p not in current_remote_paths and p not in to_delete
)

if not to_upload and not to_delete:
if self._remote_state_reset:
self._deleted_remote_paths = new_deleted
self._remote_state_reset = False
self._last_sync_time = _monotonic()
return

# Snapshot for rollback (only when there's work to do)
prev_files = dict(self._synced_files)
prev_hashes = dict(self._pushed_hashes)
new_deleted.update(to_delete)
# Preserve tombstones even if a transport operation fails. They are
# the local desired state needed to reconcile a replacement remote.
self._deleted_remote_paths.update(to_delete)

if to_upload:
logger.debug("file_sync: uploading %d file(s)", len(to_upload))
Expand Down Expand Up @@ -230,6 +260,8 @@ def sync(self, *, force: bool = False) -> None:
self._pushed_hashes.pop(p, None)

self._synced_files = new_files
self._deleted_remote_paths = new_deleted
Comment thread
exiao marked this conversation as resolved.
Resolved
self._remote_state_reset = False
self._last_sync_time = _monotonic()

except Exception as exc:
Expand Down
Loading
Loading