Skip to content

The agent that grows with you

fix(environments): sandbox snapshot stores are updated under a file lock

Maciej Lisiewski85e2711c5a20
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.py
index 243fae4bbf6..fc7f0cd74a8 100644
--- a/hermes_cli/auth.py
+++ b/hermes_cli/auth.py
@@ -631,8 +631,8 @@ def _lock_holder_hint(lock_path: Path) -> str:
return ""
except OSError:
pass # exists but is not signalable (e.g. EPERM): still a live holder
- return (f"another hermes process (pid {pid}) probably still holds it "
- "(e.g. a dashboard or a slow credential refresh)")
+ # No example holder: many stores use this lock; the caller's timeout_message names which one.
+ return f"another hermes process (pid {pid}) probably still holds it"
def _stamp_lock_holder_pid(lock_file: Any) -> None:
diff --git a/tests/lock_contention.py b/tests/lock_contention.py
new file mode 100644
index 00000000000..8bdbbfd7af4
--- /dev/null
+++ b/tests/lock_contention.py
@@ -0,0 +1,56 @@
+"""Event-driven replacements for "give the other writer N seconds" in serialization tests.
+
+A lost-update test parks writer A mid-cycle and lets writer B run. Unserialized, B finishes; serialized,
+B blocks on the lock, so waiting for B with a fixed timeout always sits the timeout out on the passing
+path. These helpers signal the moment B is turned away by the lock instead, so the test waits for
+"B finished OR B is blocked" (``tests.waiting.wait_until``) and moves on immediately either way.
+"""
+
+from __future__ import annotations
+
+import threading
+
+
+def watch_file_lock_contention(monkeypatch) -> threading.Event:
+ """An event set when any thread is refused by ``hermes_cli.auth._file_lock``.
+
+ ``_file_lock`` retries a non-blocking ``_kernel_lock`` while another holder has the file, so the
+ first contention error is the proof that a second writer is waiting."""
+ from hermes_cli import auth
+
+ contended = threading.Event()
+ real_kernel_lock = auth._kernel_lock
+
+ def kernel_lock(lock_file, acquire):
+ try:
+ return real_kernel_lock(lock_file, acquire)
+ except OSError as exc:
+ if acquire and auth._is_lock_contention(exc):
+ contended.set()
+ raise
+
+ monkeypatch.setattr(auth, "_kernel_lock", kernel_lock)
+ return contended
+
+
+class ContentionObservedLock:
+ """A ``threading.Lock`` stand-in that sets ``contended`` when a caller has to wait for it."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self.contended = threading.Event()
+
+ def acquire(self, blocking: bool = True, timeout: float = -1) -> bool:
+ if self._lock.acquire(blocking=False):
+ return True
+ self.contended.set()
+ return self._lock.acquire(blocking, timeout) if blocking else False
+
+ def release(self) -> None:
+ self._lock.release()
+
+ def __enter__(self) -> bool:
+ return self.acquire()
+
+ def __exit__(self, *exc) -> None:
+ self.release()
diff --git a/tests/tools/test_modal_snapshot_isolation.py b/tests/tools/test_modal_snapshot_isolation.py
index 5cab803dccd..7952e5c46c8 100644
--- a/tests/tools/test_modal_snapshot_isolation.py
+++ b/tests/tools/test_modal_snapshot_isolation.py
@@ -111,6 +111,11 @@ def _install_modal_test_modules(
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2))
+ def _update_json_store(path, update):
+ data = _load_json_store(path)
+ update(data)
+ _save_json_store(path, data)
+
def _file_mtime_key(host_path):
try:
st = Path(host_path).stat()
@@ -123,6 +128,7 @@ def _install_modal_test_modules(
_ThreadedProcessHandle=_DummyThreadedProcessHandle,
_load_json_store=_load_json_store,
_save_json_store=_save_json_store,
+ _update_json_store=_update_json_store,
_file_mtime_key=_file_mtime_key,
)
sys.modules["tools.interrupt"] = types.SimpleNamespace(is_interrupted=lambda: False)
@@ -242,3 +248,49 @@ def test_persistent_cleanup_snapshots_without_expiry(tmp_path, monkeypatch):
assert state["snapshot_calls"] == [{"ttl": None}]
assert json.loads(state["snapshot_store"].read_text()) == {"direct:task-ttl": "im-fresh"}
+
+
+def test_concurrent_snapshot_stores_keep_both_tasks(tmp_path, monkeypatch):
+ """Two persistent sandboxes torn down at once each record their snapshot id; the
+ second store must not be overwritten by the first one's stale read of the file."""
+ import threading
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes-home"))
+ import tools.environments.base as base_module
+ import tools.environments.modal as modal_module
+ from tests.lock_contention import watch_file_lock_contention
+ from tests.waiting import wait_until
+
+ contended = watch_file_lock_contention(monkeypatch)
+ original_load = base_module._load_json_store
+ a_loaded = threading.Event()
+ release_a = threading.Event()
+
+ def load_then_block_in_a(path):
+ data = original_load(path)
+ if threading.current_thread().name == "cleanup-A" and not a_loaded.is_set():
+ a_loaded.set()
+ release_a.wait(10)
+ return data
+
+ monkeypatch.setattr(base_module, "_load_json_store", load_then_block_in_a)
+ monkeypatch.setattr(modal_module, "_load_json_store", load_then_block_in_a)
+
+ cleanup_a = threading.Thread(
+ target=modal_module._store_direct_snapshot, args=("task-A", "im-AAAA"), name="cleanup-A")
+ cleanup_a.start()
+ assert a_loaded.wait(10)
+ cleanup_b = threading.Thread(
+ target=modal_module._store_direct_snapshot, args=("task-B", "im-BBBB"), name="cleanup-B")
+ cleanup_b.start()
+ # Unlocked code lets B finish here; a locked store is seen parking B on the lock.
+ wait_until(lambda: not cleanup_b.is_alive() or contended.is_set(),
+ what="cleanup B finished or blocked on the snapshot store lock")
+ release_a.set()
+ cleanup_a.join(10)
+ cleanup_b.join(10)
+
+ assert json.loads(modal_module._snapshot_store().read_text(encoding="utf-8")) == {
+ "direct:task-A": "im-AAAA",
+ "direct:task-B": "im-BBBB",
+ }
diff --git a/tests/tui_gateway/test_user_messages.py b/tests/tui_gateway/test_user_messages.py
index cbbeaf08221..37f419ed384 100644
--- a/tests/tui_gateway/test_user_messages.py
+++ b/tests/tui_gateway/test_user_messages.py
@@ -15,8 +15,7 @@ from tui_gateway.user_messages import agent_init_failed_message
@pytest.mark.parametrize("exc_text", [
"Timed out waiting for auth store lock (/home/u/.hermes/profiles/coder/auth.lock); "
- "another hermes process (pid 4242) probably still holds it "
- "(e.g. a dashboard or a slow credential refresh)",
+ "another hermes process (pid 4242) probably still holds it",
"Timed out waiting for auth store lock (/home/u/.hermes/profiles/coder/auth.lock)",
"Timed out waiting for shared Nous auth lock (/home/u/.hermes/shared/nous.lock)",
], ids=["auth-store-with-holder", "auth-store-no-holder", "shared-nous-store"])
diff --git a/tools/environments/base.py b/tools/environments/base.py
index 6253d70ae0e..e52211817af 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, file_signature
+from utils import atomic_json_write, env_var_enabled, file_signature
logger = logging.getLogger(__name__)
@@ -203,9 +203,28 @@ def _load_json_store(path: Path) -> dict:
def _save_json_store(path: Path, data: dict) -> None:
- """Write *data* as pretty-printed JSON to *path*."""
+ """Write *data* as pretty-printed JSON to *path* atomically (readers never see a torn file)."""
path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(data, indent=2), encoding="utf-8")
+ atomic_json_write(path, data, indent=2)
+
+
+_JSON_STORE_LOCK_HOLDER = threading.local()
+
+
+def _update_json_store(path: Path, update: Callable[[dict], None]) -> None:
+ """Read-modify-write the JSON store at *path* under a cross-process lock.
+
+ Concurrent sandbox cleanups (delegate children, gateway sessions, the idle reaper) each
+ record a snapshot id; an unlocked load/mutate/save lets one cleanup drop the other's entry."""
+ from hermes_cli.auth import _file_lock
+
+ lock_path = path.with_name(f"{path.name}.lock")
+ with _file_lock(lock_path, _JSON_STORE_LOCK_HOLDER, 10.0, f"Timed out waiting for the snapshot store lock ({path})"):
+ data = _load_json_store(path)
+ before = dict(data)
+ update(data)
+ if data != before:
+ _save_json_store(path, data)
def _file_mtime_key(host_path: str) -> tuple[int, int, int, int] | None:
diff --git a/tools/environments/modal.py b/tools/environments/modal.py
index e2d1ef97d36..0b5b4d60a93 100644
--- a/tools/environments/modal.py
+++ b/tools/environments/modal.py
@@ -9,10 +9,10 @@ import shlex
import tarfile
import threading
from pathlib import Path
-from typing import Any, Optional
+from typing import Any, Callable, Optional
from hermes_constants import get_hermes_home
-from tools.environments.base import BaseEnvironment, _load_json_store, _save_json_store
+from tools.environments.base import BaseEnvironment, _load_json_store, _update_json_store
from tools.environments.base_output import _ThreadedProcessHandle
from tools.environments.file_sync import (
FileSyncManager, iter_sync_files, quoted_mkdir_command, quoted_rm_command, unique_parent_dirs)
@@ -30,8 +30,8 @@ def _load_snapshots() -> dict:
return _load_json_store(_snapshot_store())
-def _save_snapshots(data: dict) -> None:
- _save_json_store(_snapshot_store(), data)
+def _update_snapshots(update: Callable[[dict], None]) -> None:
+ _update_json_store(_snapshot_store(), update)
def _get_snapshot_restore_candidate(task_id: str) -> tuple[str | None, bool]:
@@ -45,20 +45,21 @@ def _get_snapshot_restore_candidate(task_id: str) -> tuple[str | None, bool]:
def _store_direct_snapshot(task_id: str, snapshot_id: str) -> None:
- snapshots = _load_snapshots()
- snapshots[f"direct:{task_id}"] = snapshot_id
- snapshots.pop(task_id, None)
- _save_snapshots(snapshots)
+ def update(snapshots: dict) -> None:
+ snapshots[f"direct:{task_id}"] = snapshot_id
+ snapshots.pop(task_id, None)
+
+ _update_snapshots(update)
def _delete_direct_snapshot(task_id: str, snapshot_id: str | None = None) -> None:
- snapshots = _load_snapshots()
- stale = [k for k in (f"direct:{task_id}", task_id)
- if snapshots.get(k) is not None and snapshot_id in (None, snapshots[k])]
- for key in stale:
- snapshots.pop(key)
- if stale:
- _save_snapshots(snapshots)
+ def update(snapshots: dict) -> None:
+ stale = [k for k in (f"direct:{task_id}", task_id)
+ if snapshots.get(k) is not None and snapshot_id in (None, snapshots[k])]
+ for key in stale:
+ snapshots.pop(key)
+
+ _update_snapshots(update)
def _resolve_modal_image(image_spec: Any) -> Any:
diff --git a/tools/environments/singularity.py b/tools/environments/singularity.py
index 963ccb611c4..d7bfedb10fa 100644
--- a/tools/environments/singularity.py
+++ b/tools/environments/singularity.py
@@ -11,10 +11,10 @@ import subprocess
import threading
import uuid
from pathlib import Path
-from typing import Optional
+from typing import Callable, Optional
from hermes_constants import get_hermes_home
-from tools.environments.base import BaseEnvironment, _load_json_store, _save_json_store
+from tools.environments.base import BaseEnvironment, _update_json_store
from tools.environments.base_output import _popen_bash
from tools.environments.path_utils import sanitize_task_id_for_path
from tools.environments.remote_common import bash_argv, run_capture
@@ -53,12 +53,8 @@ def _ensure_singularity_available() -> str:
return exe
-def _load_snapshots() -> dict:
- return _load_json_store(_snapshot_store())
-
-
-def _save_snapshots(data: dict) -> None:
- _save_json_store(_snapshot_store(), data)
+def _update_snapshots(update: Callable[[dict], None]) -> None:
+ _update_json_store(_snapshot_store(), update)
def _get_scratch_dir() -> Path:
@@ -215,6 +211,5 @@ class SingularityEnvironment(BaseEnvironment):
self._instance_started = False
if self._persistent and self._overlay_dir:
- snapshots = _load_snapshots()
- snapshots[self._task_id] = str(self._overlay_dir)
- _save_snapshots(snapshots)
+ overlay_dir = str(self._overlay_dir)
+ _update_snapshots(lambda snapshots: snapshots.update({self._task_id: overlay_dir}))
diff --git a/tools/environments/vercel_sandbox.py b/tools/environments/vercel_sandbox.py
index 8828c2de6f8..1009fd8dd10 100644
--- a/tools/environments/vercel_sandbox.py
+++ b/tools/environments/vercel_sandbox.py
@@ -23,7 +23,7 @@ import httpx
from hermes_cli.config_defaults import DEFAULT_VERCEL_IMAGE
from hermes_constants import get_hermes_home
-from tools.environments.base import BaseEnvironment, _load_json_store, _save_json_store
+from tools.environments.base import BaseEnvironment, _load_json_store, _update_json_store
from tools.environments.base_output import _ThreadedProcessHandle
from tools.environments.file_sync import FileSyncManager, iter_sync_files, quoted_rm_command
@@ -130,15 +130,16 @@ def _load_snapshots() -> dict:
def _store_snapshot(task_id: str, snapshot_id: str) -> None:
if task_id and snapshot_id:
- _save_json_store(_snapshot_store(), {**_load_snapshots(), task_id: snapshot_id})
+ _update_json_store(_snapshot_store(), lambda snapshots: snapshots.update({task_id: snapshot_id}))
def _delete_snapshot(task_id: str, snapshot_id: str) -> None:
"""Drop the stored id for ``task_id`` only if it still equals ``snapshot_id``."""
- snapshots = _load_snapshots()
- if task_id and snapshots.get(task_id) == snapshot_id:
- snapshots.pop(task_id)
- _save_json_store(_snapshot_store(), snapshots)
+ def update(snapshots: dict) -> None:
+ if task_id and snapshots.get(task_id) == snapshot_id:
+ snapshots.pop(task_id)
+
+ _update_json_store(_snapshot_store(), update)
def _extract_snapshot_id(snapshot: Any) -> str | None: