Skip to content

The agent that grows with you

fix(bot-screen): hold the display-allocation and a per-profile start lock across spawn

teknium1ed5d2dc4f171
diff --git a/tests/tools/test_bot_desktop_runtime.py b/tests/tools/test_bot_desktop_runtime.py
index caa544f006e..fd89a14d6de 100644
--- a/tests/tools/test_bot_desktop_runtime.py
+++ b/tests/tools/test_bot_desktop_runtime.py
@@ -2,7 +2,9 @@
from __future__ import annotations
+import contextlib
import sys
+from pathlib import Path
import pytest
@@ -57,3 +59,88 @@ def test_recorded_display_held_by_a_live_server_is_not_reused(tmp_path, monkeypa
assert runtime._allocate_display() != 37
live.clear()
assert runtime._allocate_display() == 37, "a free recorded number is reclaimed"
+
+
+
+_FAKE_LAUNCHER = """#!/usr/bin/env bash
+# Stands in for launcher.sh + Xvnc: the X lock appears only after a delay (the TOCTOU window), then the
+# env file + socket are published; stays alive until killed like the real supervisor.
+: > "$HERMES_BD_XLOCK_DIR/spawned.$$"
+sleep 0.4
+echo $$ > "$HERMES_BD_XLOCK_DIR/.X${HERMES_BD_DISPLAY_NUM}-lock"
+: > "$HERMES_BD_SOCKET"
+printf 'DISPLAY=:%s\\n' "$HERMES_BD_DISPLAY_NUM" > "$HERMES_BD_ENV_FILE"
+sleep 30
+"""
+
+# One start() per process: state_dir() is HERMES_HOME-scoped and process-global, so two profiles need two
+# interpreters — which is also how two gateway profiles race on a real host.
+_DRIVER = """
+import json, os, sys
+from pathlib import Path
+sys.path.insert(0, {repo!r})
+from tools.bot_desktop import runtime
+scratch = Path({scratch!r})
+runtime._LAUNCHER = scratch / "launcher.sh"
+runtime._X_LOCK_DIR = scratch / "xlocks"
+runtime._ALLOC_LOCK = scratch / "alloc.lock"
+runtime.missing_binaries = lambda: []
+runtime.geometry = lambda: "800x600"
+os.environ["HERMES_BD_XLOCK_DIR"] = str(scratch / "xlocks")
+try:
+ st = runtime.start(wait_seconds=10)
+ print(json.dumps({{"display": st.display, "pid": st.pid}}), flush=True)
+except Exception as exc:
+ print(json.dumps({{"error": str(exc)}}), flush=True)
+sys.stdin.readline() # the test releases us once every driver has reported; we own the launcher, we stop it
+runtime.stop()
+"""
+
+
+def start_in_fresh_process(tmp_path):
+ import os
+ import subprocess
+
+ (tmp_path / "launcher.sh").write_text(_FAKE_LAUNCHER, encoding="utf-8")
+ (tmp_path / "xlocks").mkdir()
+ repo = str(Path(__file__).resolve().parents[2])
+ procs: list[subprocess.Popen] = []
+
+ def launch(home: Path) -> subprocess.Popen:
+ env = {**os.environ, "HERMES_HOME": str(home)}
+ proc = subprocess.Popen([sys.executable, "-c", _DRIVER.format(repo=repo, scratch=str(tmp_path))],
+ env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
+ procs.append(proc)
+ return proc
+
+ yield launch
+ for proc in procs:
+ with contextlib.suppress(OSError):
+ proc.communicate("go\n", timeout=20)
+ proc.kill()
+
+
+def _collect(procs):
+ import json
+ out = [json.loads(p.stdout.readline()) for p in procs] # every driver holds its launcher until released
+ assert all("error" not in o for o in out), out
+ return out
+
+
+def test_concurrent_cold_starts_of_two_profiles_get_distinct_displays(tmp_path, start_in_fresh_process):
+ """The allocation lock must outlive the pick: Xvnc writes /tmp/.X<n>-lock well after start() chose n, so
+ a second profile starting in that window used to pick the same n (and its launcher's stale-lock cleanup
+ could then unlink the winner's socket)."""
+ out = _collect([start_in_fresh_process(tmp_path / "a"), start_in_fresh_process(tmp_path / "b")])
+ assert len({o["display"] for o in out}) == 2, out
+
+
+def test_concurrent_starts_of_one_profile_spawn_one_launcher(tmp_path, start_in_fresh_process):
+ """Two start() calls for one profile spawn ONE launcher; the second used to spawn its own, overwrite
+ launcher.pid and orphan the first (both callers then reported the last-written pid)."""
+ out = _collect([start_in_fresh_process(tmp_path / "a"), start_in_fresh_process(tmp_path / "a")])
+ assert len({o["pid"] for o in out}) == 1, out
+ assert len(list((tmp_path / "xlocks").glob("spawned.*"))) == 1
diff --git a/tools/bot_desktop/runtime.py b/tools/bot_desktop/runtime.py
index 9f18a3637cc..7547eafd741 100644
--- a/tools/bot_desktop/runtime.py
+++ b/tools/bot_desktop/runtime.py
@@ -14,6 +14,7 @@ Chromium spawns merge in so the agent acts on this profile's screen and nowhere
from __future__ import annotations
+import contextlib
import logging
import os
import shutil
@@ -152,10 +153,13 @@ def _launcher_pid() -> Optional[int]:
return pid if actual is not None and abs(actual - born) < 0.01 else None
+_X_LOCK_DIR = Path("/tmp") # where X servers write .X<n>-lock (tests point it at a scratch dir)
+
+
def _display_in_use(num: int) -> bool:
"""A live X server owns ``:num``: its lock file names a running pid. A lock left by a crashed
server (dead pid) does not count, so the number can be reclaimed."""
- lock = Path(f"/tmp/.X{num}-lock")
+ lock = _X_LOCK_DIR / f".X{num}-lock"
try:
pid = int(lock.read_text(encoding="utf-8").strip())
except (OSError, ValueError):
@@ -166,22 +170,34 @@ def _display_in_use(num: int) -> bool:
_ALLOC_LOCK = Path("/tmp/.hermes-bot-desktop-alloc.lock") # host-wide: profiles allocate from one band
-def _allocate_display() -> int:
- """Pick this profile's display number under a host-wide lock. The recorded number is only reused
- when no OTHER server holds it now: after profile A stops, B may have taken A's old number, and
- A's launcher must never unlink B's socket and lock."""
- import fcntl
- with open(_ALLOC_LOCK, "a+", encoding="utf-8") as fh: # windows-footgun: ok — Linux-only runtime
+def _flocked(path: Path):
+ import fcntl # windows-footgun: ok — Linux-only runtime (is_supported_host gates start)
+ with open(path, "a+", encoding="utf-8") as fh: # windows-footgun: ok — Linux-only runtime
fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
- recorded = _read(state_dir() / "display")
- if recorded and recorded.isdigit() and not _display_in_use(int(recorded)):
- return int(recorded)
- for num in range(_DISPLAY_MIN, _DISPLAY_MAX + 1):
- if not _display_in_use(num):
- return num
+ try:
+ yield fh
+ finally:
+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
+
+
+def _pick_display() -> int:
+ """Caller holds ``_ALLOC_LOCK``. The recorded number is only reused when no OTHER server holds it now:
+ after profile A stops, B may have taken A's number, and A's launcher must never unlink B's socket."""
+ recorded = _read(state_dir() / "display")
+ if recorded and recorded.isdigit() and not _display_in_use(int(recorded)):
+ return int(recorded)
+ for num in range(_DISPLAY_MIN, _DISPLAY_MAX + 1):
+ if not _display_in_use(num):
+ return num
raise RuntimeError("no free X display number in the Bot Desktop band")
+def _allocate_display() -> int:
+ with _flocked(_ALLOC_LOCK):
+ return _pick_display()
+
+
def desktop_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str, str]:
"""``base_env`` (default ``os.environ``) with this profile's DISPLAY/XAUTHORITY/DBUS_SESSION_BUS_ADDRESS
merged in when its desktop is running. Unchanged otherwise, so hosts with a real seat keep it.
@@ -273,20 +289,29 @@ def _profile_name() -> str:
def start(*, wait_seconds: float = 15.0) -> DesktopStatus:
"""Start this profile's desktop (idempotent). Blocks until the launcher publishes its env file or
- ``wait_seconds`` pass; raises ``RuntimeError`` naming the blocker."""
+ ``wait_seconds`` pass; raises ``RuntimeError`` naming the blocker.
+
+ Two locks, both held from the running-check to the launcher's publish: the per-profile ``start.lock``
+ so two start() calls for one profile spawn one launcher (the loser sees it running), and the host-wide
+ display-allocation lock so a second profile cannot pick the same number before this Xvnc has written
+ ``/tmp/.X<n>-lock`` (it would then fail and its launcher's stale-lock cleanup could remove our socket)."""
if not is_supported_host():
raise RuntimeError("Bot Desktop runs on Linux gateway hosts only")
missing = missing_binaries()
if missing:
hint = install_command() or "install TigerVNC (Xvnc) and the Xfce core components"
raise RuntimeError(f"Bot Desktop needs {', '.join(missing)} on the gateway host. Install: {hint}")
- if _launcher_pid() is not None and published_env().get("DISPLAY"):
- return status()
-
sd = state_dir()
sd.mkdir(parents=True, exist_ok=True)
os.chmod(sd, 0o700)
- num = _allocate_display()
+ with _flocked(sd / "start.lock"):
+ if _launcher_pid() is not None and published_env().get("DISPLAY"):
+ return status()
+ with _flocked(_ALLOC_LOCK):
+ return _spawn_and_wait(sd, _pick_display(), wait_seconds)
+
+
+def _spawn_and_wait(sd: Path, num: int, wait_seconds: float) -> DesktopStatus:
(sd / "display").write_text(str(num), encoding="utf-8")
env_file = sd / "env"
env_file.unlink(missing_ok=True)
@@ -328,8 +353,16 @@ def start(*, wait_seconds: float = 15.0) -> DesktopStatus:
def stop() -> bool:
"""Stop this profile's desktop; True when a running launcher was signalled."""
- pid = _launcher_pid()
+ if not is_supported_host():
+ return False
sd = state_dir()
+ sd.mkdir(parents=True, exist_ok=True)
+ with _flocked(sd / "start.lock"):
+ return _stop_locked(sd)
+
+
+def _stop_locked(sd: Path) -> bool:
+ pid = _launcher_pid()
if pid is None:
(sd / "env").unlink(missing_ok=True)
return False