The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): reap leaked agent-browser daemons whose owner is still alive
andyc99a45b28eb3
diff --git a/tests/tools/test_browser_orphan_reaper.py b/tests/tools/test_browser_orphan_reaper.pyindex 59eb67a1824..33033c18a95 100644--- a/tests/tools/test_browser_orphan_reaper.py+++ b/tests/tools/test_browser_orphan_reaper.py@@ -2,6 +2,7 @@daemons whose Python parent exited without cleaning up."""import os+import timefrom unittest.mock import patchimport pytest@@ -355,3 +356,211 @@ class TestEmergencyCleanupRunsReaper:assert reaper_called, ("Reaper must run on exit even with no active sessions")+++def _age_socket_dir(d, seconds):+ """Backdate every mtime under ``d`` so it looks idle for ``seconds``."""+ old = time.time() - seconds+ for p in d.iterdir():+ os.utime(p, (old, old))+ os.utime(d, (old, old))+++class TestSocketDirIdleSeconds:+ """Unit tests for the idle-age signal backing the leak escape hatch."""++ def test_missing_dir_returns_none(self, tmp_path):+ from tools.browser_tool import _socket_dir_idle_seconds+ assert _socket_dir_idle_seconds(str(tmp_path / "nope")) is None++ def test_fresh_dir_is_near_zero(self, tmp_path):+ from tools.browser_tool import _socket_dir_idle_seconds+ d = tmp_path / "agent-browser-h_fresh"+ d.mkdir()+ assert _socket_dir_idle_seconds(str(d)) < 5++ def test_entry_mtime_beats_stale_dir_mtime(self, tmp_path):+ """Rewriting an existing file must count as activity.++ Command names repeat (``_stdout_click`` is rewritten on every click),+ and overwriting an existing file does NOT bump the *directory* mtime.+ Reading only the directory mtime would therefore report a busy session+ as idle and reap it. The reaper must scan entries too.+ """+ from tools.browser_tool import _socket_dir_idle_seconds+ d = tmp_path / "agent-browser-h_reuse"+ d.mkdir()+ f = d / "_stdout_click"+ f.write_text("x")+ _age_socket_dir(d, 7200)+ assert _socket_dir_idle_seconds(str(d)) > 7000++ f.write_text("y") # rewrite in place — dir mtime stays stale+ assert time.time() - os.path.getmtime(d) > 7000, "precondition"+ assert _socket_dir_idle_seconds(str(d)) < 5+++class TestLeakedDaemonWithLiveOwner:+ """Idle-age escape hatch for untracked daemons whose owner is still alive.++ ``owner_alive is True`` alone made a leaked daemon immortal: in-memory+ tracking is lost on any exception path between spawn and registration,+ yet the owner PID stays up, so the reaper skipped it forever. Observed in+ the wild — five agent-browser daemons accumulated over 10 days inside one+ long-lived hermes process, pinning ~5 CPU cores and driving load to 100+.++ The daemon-side ``AGENT_BROWSER_IDLE_TIMEOUT_MS`` is not a backstop here:+ it does not fire when the daemon itself is wedged (e.g. Chrome's framework+ was replaced underneath it by an auto-update).+ """++ def test_fresh_untracked_daemon_with_live_owner_is_spared(self, fake_tmpdir):+ """Within the grace window, cross-process safety still wins."""+ from tools.browser_tool import _reap_orphaned_browser_sessions++ d = _make_socket_dir(+ fake_tmpdir, "h_fresh_owner", pid=12345, owner_pid=os.getpid()+ )+ kill_calls = []++ with patch("gateway.status._pid_exists", return_value=True), \+ patch("tools.browser_tool._verify_reapable_browser_daemon", return_value=True), \+ patch("tools.process_registry.ProcessRegistry._terminate_host_pid",+ side_effect=kill_calls.append):+ _reap_orphaned_browser_sessions()++ assert 12345 not in kill_calls+ assert d.exists()++ def test_idle_untracked_daemon_with_live_owner_is_reaped(self, fake_tmpdir):+ """Past the grace window, an untracked daemon is treated as leaked."""+ from tools.browser_tool import (+ BROWSER_ORPHAN_GRACE_SECONDS,+ _reap_orphaned_browser_sessions,+ )++ d = _make_socket_dir(+ fake_tmpdir, "h_leaked_owner", pid=12345, owner_pid=os.getpid()+ )+ _age_socket_dir(d, BROWSER_ORPHAN_GRACE_SECONDS + 600)+ kill_calls = []++ with patch("gateway.status._pid_exists", return_value=True), \+ patch("tools.browser_tool._verify_reapable_browser_daemon", return_value=True), \+ patch("tools.process_registry.ProcessRegistry._terminate_host_pid",+ side_effect=kill_calls.append):+ _reap_orphaned_browser_sessions()++ assert 12345 in kill_calls+ assert not d.exists()++ def test_tracked_daemon_with_live_owner_is_spared_at_any_age(self, fake_tmpdir):+ """A session this process still tracks is never reaped, however old.++ Idle age is a fallback for *lost* bookkeeping, not an override of+ bookkeeping that is present and says the session is live.+ """+ import tools.browser_tool as bt+ from tools.browser_tool import (+ BROWSER_ORPHAN_GRACE_SECONDS,+ _reap_orphaned_browser_sessions,+ )++ d = _make_socket_dir(+ fake_tmpdir, "h_tracked_old", pid=12345, owner_pid=os.getpid()+ )+ _age_socket_dir(d, BROWSER_ORPHAN_GRACE_SECONDS * 10)+ bt._active_sessions["task-1"] = {"session_name": "h_tracked_old"}+ kill_calls = []++ with patch("gateway.status._pid_exists", return_value=True), \+ patch("tools.browser_tool._verify_reapable_browser_daemon", return_value=True), \+ patch("tools.process_registry.ProcessRegistry._terminate_host_pid",+ side_effect=kill_calls.append):+ _reap_orphaned_browser_sessions()++ assert 12345 not in kill_calls+ assert d.exists()++ def test_unknown_idle_age_fails_safe(self, fake_tmpdir):+ """Unreadable mtime => treat as too young to reap, never guess."""+ from tools.browser_tool import _reap_orphaned_browser_sessions++ d = _make_socket_dir(+ fake_tmpdir, "h_unknown_age", pid=12345, owner_pid=os.getpid()+ )+ kill_calls = []++ with patch("gateway.status._pid_exists", return_value=True), \+ patch("tools.browser_tool._socket_dir_idle_seconds", return_value=None), \+ patch("tools.browser_tool._verify_reapable_browser_daemon", return_value=True), \+ patch("tools.process_registry.ProcessRegistry._terminate_host_pid",+ side_effect=kill_calls.append):+ _reap_orphaned_browser_sessions()++ assert 12345 not in kill_calls+ assert d.exists()++ def test_identity_guard_still_gates_the_new_path(self, fake_tmpdir):+ """The escape hatch must not bypass _verify_reapable_browser_daemon.++ That guard is the anti-spoof / anti-PID-recycle defense (issue #14073);+ an idle daemon is still only reapable if it verifies.+ """+ from tools.browser_tool import (+ BROWSER_ORPHAN_GRACE_SECONDS,+ _reap_orphaned_browser_sessions,+ )++ d = _make_socket_dir(+ fake_tmpdir, "h_unverified", pid=12345, owner_pid=os.getpid()+ )+ _age_socket_dir(d, BROWSER_ORPHAN_GRACE_SECONDS + 600)+ kill_calls = []++ with patch("gateway.status._pid_exists", return_value=True), \+ patch("tools.browser_tool._verify_reapable_browser_daemon", return_value=False), \+ patch("tools.process_registry.ProcessRegistry._terminate_host_pid",+ side_effect=kill_calls.append):+ _reap_orphaned_browser_sessions()++ assert 12345 not in kill_calls+ assert d.exists()+++class TestPeriodicOrphanReap:+ """The reaper must run repeatedly, not only at cleanup-thread startup.++ A startup-only reap can never recover from a leak that appears *after*+ boot — which is exactly what happens in a hermes process that stays up+ for days.+ """++ def test_reaper_runs_on_every_interval_not_just_startup(self):+ import tools.browser_tool as bt++ cycles_to_run = 21+ reap_calls = []+ remaining = {"n": cycles_to_run}++ def fake_cleanup():+ remaining["n"] -= 1+ if remaining["n"] <= 0:+ bt._cleanup_running = False++ orig_running = bt._cleanup_running+ bt._cleanup_running = True+ try:+ with patch("tools.browser_tool._reap_orphaned_browser_sessions",+ side_effect=lambda: reap_calls.append(1)), \+ patch("tools.browser_tool._cleanup_inactive_browser_sessions",+ side_effect=fake_cleanup), \+ patch("tools.browser_tool.time.sleep"):+ bt._browser_cleanup_thread_worker()+ finally:+ bt._cleanup_running = orig_running++ every = max(1, round(bt.BROWSER_ORPHAN_REAP_INTERVAL / 30))+ expected = len([c for c in range(cycles_to_run) if c % every == 0])+ assert len(reap_calls) == expected+ assert len(reap_calls) > 1, "startup-only reap would give exactly 1"diff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex eaaff9d969e..544a06d5127 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -1642,6 +1642,22 @@ def _get_session_inactivity_timeout() -> int:BROWSER_SESSION_INACTIVITY_TIMEOUT = _get_session_inactivity_timeout()+# How often the cleanup thread re-runs the orphan reaper. The reaper used to+# run exactly once, before the cleanup loop started, which meant a hermes+# process that stays up for days could never recover from a leak that appeared+# *after* boot. Observed in the wild: five agent-browser daemons accumulated+# over 10 days in a single 18-day-uptime process, pinning ~5 CPU cores.+BROWSER_ORPHAN_REAP_INTERVAL = 300 # seconds++# Hard ceiling for a daemon whose owning hermes process is still alive but+# which has fallen out of that process's in-memory session tracking. The+# owner-alive check alone makes such a daemon immortal: in-memory tracking is+# lost on any exception path, yet the owner PID stays up, so the reaper skips+# it forever. Idle age (see ``_socket_dir_idle_seconds``) is the escape hatch.+# Deliberately a large multiple of the inactivity timeout so a legitimately+# busy session is never touched.+BROWSER_ORPHAN_GRACE_SECONDS = max(3600, BROWSER_SESSION_INACTIVITY_TIMEOUT * 20)+# Track last activity time per session_session_last_activity: Dict[str, float] = {}@@ -1872,6 +1888,40 @@ def _verify_reapable_browser_daemon(daemon_pid: int, socket_dir: str,return True+def _socket_dir_idle_seconds(socket_dir: str) -> Optional[float]:+ """Seconds since anything in ``socket_dir`` was last written.++ Every browser command writes ``_stdout_<cmd>`` / ``_stderr_<cmd>`` temp+ files into the session's socket dir, so the newest mtime under that dir is+ a last-activity marker that — unlike ``_session_last_activity`` — survives+ hermes restarts and does not depend on in-memory bookkeeping surviving an+ exception path.++ The directory's own mtime is not sufficient: command names repeat, so+ rewriting an existing ``_stdout_click`` updates that file's mtime but not+ the directory's. Scan the entries too.++ Returns ``None`` when the age cannot be determined, so callers can fail+ safe (treat unknown age as "too young to reap").+ """+ try:+ latest = os.path.getmtime(socket_dir)+ except OSError:+ return None++ try:+ with os.scandir(socket_dir) as entries:+ for entry in entries:+ try:+ latest = max(latest, entry.stat().st_mtime)+ except OSError:+ continue+ except OSError:+ pass # dir mtime alone is still a usable lower bound++ return max(0.0, time.time() - latest)++def _reap_orphaned_browser_sessions():"""Scan for orphaned agent-browser daemon processes from previous runs.@@ -1926,6 +1976,7 @@ def _reap_orphaned_browser_sessions():# Ownership check: prefer owner_pid file (cross-process safe).owner_pid_file = os.path.join(socket_dir, f"{session_name}.owner_pid")+ owner_pid: Optional[int] = Noneowner_alive: Optional[bool] = None # None = owner_pid missing/unreadableif os.path.isfile(owner_pid_file):try:@@ -1935,11 +1986,34 @@ def _reap_orphaned_browser_sessions():from gateway.status import _pid_existsowner_alive = _pid_exists(owner_pid)except (ValueError, OSError):+ owner_pid = Noneowner_alive = None # corrupt file — fall throughif owner_alive is True:- # Owner is alive — this session belongs to a live hermes process.- continue+ # Owner is alive. Normally that means the session belongs to a+ # live hermes process and must not be touched — but "owner alive"+ # alone made leaked daemons immortal: if the owner lost its+ # in-memory tracking (any exception path between spawn and+ # registration), nothing would ever reap the daemon, and the+ # daemon-side AGENT_BROWSER_IDLE_TIMEOUT_MS does not fire when the+ # daemon itself is wedged (e.g. Chrome's framework was swapped out+ # from under it by an auto-update).+ #+ # So: still trust live tracking, but fall back to idle age.+ if session_name in tracked_names:+ continue++ idle_s = _socket_dir_idle_seconds(socket_dir)+ if idle_s is None or idle_s < BROWSER_ORPHAN_GRACE_SECONDS:+ # Unknown age, or still within the grace window — fail safe.+ continue++ logger.warning(+ "Browser session %s has a live owner (PID %s) but is untracked "+ "and idle for %ds (grace %ds) — treating as leaked and reaping",+ session_name, owner_pid, int(idle_s),+ BROWSER_ORPHAN_GRACE_SECONDS)+ # fall through to the reap path belowif owner_alive is None:# No owner_pid file (legacy daemon). Fall back to in-process@@ -2003,15 +2077,26 @@ def _browser_cleanup_thread_worker():Runs every 30 seconds and checks for sessions that haven't been usedwithin the BROWSER_SESSION_INACTIVITY_TIMEOUT period.- On first run, also reaps orphaned sessions from previous process lifetimes.++ Also reaps orphaned daemons — on startup (sessions left by previous+ process lifetimes) *and* every BROWSER_ORPHAN_REAP_INTERVAL seconds+ thereafter. The periodic pass matters because a leak is not only a+ across-restart phenomenon: a daemon can fall out of in-memory tracking+ at any point in a long-lived process, and a startup-only reap can never+ recover from that."""- # One-time orphan reap on startup- try:- _reap_orphaned_browser_sessions()- except Exception as e:- logger.warning("Orphan reap error: %s", e)+ reap_every_cycles = max(1, round(BROWSER_ORPHAN_REAP_INTERVAL / 30))+ cycle = 0while _cleanup_running:+ # cycle 0 is the startup reap; then every reap_every_cycles.+ if cycle % reap_every_cycles == 0:+ try:+ _reap_orphaned_browser_sessions()+ except Exception as e:+ logger.warning("Orphan reap error: %s", e)+ cycle += 1+try:_cleanup_inactive_browser_sessions()except Exception as e: