Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 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
108 changes: 108 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,27 @@
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

env = ModalEnvironment.__new__(ModalEnvironment)
env._sandbox = object()
env._worker = object()
env._sandbox_check_done = True
ensure_calls = []
monkeypatch.setattr(
env, "_ensure_live_sandbox", lambda: ensure_calls.append("checked")
)

env._run_bash("true")
assert ensure_calls == []
assert env._sandbox_check_done is False

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


# =========================================================================
# Test 1: Tool resolution includes terminal + file tools
# =========================================================================
Expand Down Expand Up @@ -222,6 +243,93 @@ 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._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_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