Skip to content

The agent that grows with you

fix(browser): Browser Use harness daemons die with the Hermes process that drove them (orphans_after_30s 2 -> 0)

kshitijk4poor61392231585c
diff --git a/tests/tools/test_browser_use_cli_owned_daemon.py b/tests/tools/test_browser_use_cli_owned_daemon.py
new file mode 100644
index 00000000000..3ae8ec567e0
--- /dev/null
+++ b/tests/tools/test_browser_use_cli_owned_daemon.py
@@ -0,0 +1,147 @@
+"""Browser Use harness daemons die with the Hermes process that drove them.
+
+The harness detaches its daemon on purpose (``start_new_session``) so a session persists across
+``browser_exec`` calls; that also made it outlive a SIGKILLed / OOM-killed Hermes forever (#121095).
+browser_exec now hands the daemon's process group to the per-process owner-death supervisor. These
+tests drive the real registration seam against a real detached stand-in daemon.
+"""
+
+import json
+import os
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import process_identity
+from tools import browser_use_cli
+
+pytestmark = pytest.mark.platforms("posix")
+
+# A stand-in harness daemon: the real module name on argv (the identity check reads argv), detached
+# into its own session exactly like browser_harness._ipc.spawn_kwargs() does.
+_DAEMON_PKG = "browser_harness_standin"
+
+
+def fake_daemon(tmp_path):
+ pkg = tmp_path / "pkgroot" / "browser_harness"
+ pkg.mkdir(parents=True)
+ (pkg / "__init__.py").write_text("", encoding="utf-8")
+ (pkg / "daemon.py").write_text("import time\ntime.sleep(300)\n", encoding="utf-8")
+ proc = subprocess.Popen([sys.executable, "-m", "browser_harness.daemon"], cwd=str(tmp_path / "pkgroot"),
+ stdin=subprocess.DEVNULL, start_new_session=True)
+ runtime = tmp_path / "runtime"
+ runtime.mkdir()
+ yield proc, runtime
+ if proc.poll() is None:
+ proc.kill()
+ proc.wait(timeout=10)
+
+
+def registered(monkeypatch):
+ calls = []
+ monkeypatch.setattr(browser_use_cli, "update_supervised_pgids", lambda verb, pgids: calls.append((verb, list(pgids))))
+ monkeypatch.setattr(browser_use_cli, "register_child", lambda pid, purpose: None)
+ monkeypatch.setattr(browser_use_cli, "_owned_daemon_groups", {})
+ return calls
+
+
+def _publish(runtime: Path, stem: str, pid: int, json_record: bool = True) -> None:
+ body = json.dumps({"pid": pid, "started": 1}) if json_record else str(pid)
+ (runtime / f"{stem}.pid").write_text(body, encoding="utf-8")
+
+
[email protected]("json_record", [True, False])
+def test_the_driven_daemon_is_handed_to_the_supervisor_once(fake_daemon, registered, json_record):
+ proc, runtime = fake_daemon
+ _publish(runtime, "bu", proc.pid, json_record) # BH_RUNTIME_DIR isolates one daemon: stem "bu"
+ env = {"BH_RUNTIME_DIR": str(runtime), "BU_NAME": "work"}
+
+ browser_use_cli._own_harness_daemon(env)
+ browser_use_cli._own_harness_daemon(env) # every browser_exec call re-checks; register once
+
+ assert registered == [("register", [proc.pid])]
+
+
+def test_a_pid_file_naming_something_else_is_never_registered(tmp_path, registered):
+ runtime = tmp_path / "runtime"
+ runtime.mkdir()
+ # A live process of ours that is NOT a harness daemon (and not a session leader): a stale or
+ # planted pid file must never hand its group to the supervisor.
+ stranger = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"], stdin=subprocess.DEVNULL)
+ try:
+ _publish(runtime, "bu-default", stranger.pid)
+ browser_use_cli._own_harness_daemon({"XDG_CONFIG_HOME": str(tmp_path / "x"), "BH_HOME": str(runtime.parent)})
+ browser_use_cli._own_harness_daemon({"BH_RUNTIME_DIR": str(runtime), "BH_RUNTIME_DIR_SHARED": "1"})
+ finally:
+ stranger.kill()
+ stranger.wait(timeout=10)
+ assert registered == []
+
+
+def test_stopping_the_daemons_releases_their_groups(monkeypatch, registered):
+ daemon = browser_use_cli.daemon_identity({"BU_NAME": "work"})
+ browser_use_cli._owned_daemon_groups.update({daemon: 4242})
+ monkeypatch.setattr(browser_use_cli, "_driven_daemons", {daemon: "home"})
+ monkeypatch.setattr(browser_use_cli, "_find_cli", lambda: ["browser-harness"])
+ monkeypatch.setattr(browser_use_cli, "_base_subprocess_env", dict)
+ monkeypatch.setattr(browser_use_cli, "_run_cli_killing_process_group", lambda *a: None)
+
+ browser_use_cli.stop_harness_daemons()
+
+ assert registered == [("unregister", [4242])]
+ assert browser_use_cli._owned_daemon_groups == {}
+
+
+# The daemon reparents to init once its owner dies, so cleanup leaves this test's subtree.
[email protected]_system_guard_bypass
+def test_a_sigkilled_owner_takes_its_harness_daemon_with_it(tmp_path):
+ """End to end through the real supervisor: the owner registers its detached daemon, then dies
+ by SIGKILL (no Python cleanup runs), and the daemon must go with it."""
+ pkg = tmp_path / "pkgroot" / "browser_harness"
+ pkg.mkdir(parents=True)
+ (pkg / "__init__.py").write_text("", encoding="utf-8")
+ (pkg / "daemon.py").write_text("import time\ntime.sleep(300)\n", encoding="utf-8")
+ runtime = tmp_path / "runtime"
+ runtime.mkdir()
+ owner_src = (
+ "import json, os, subprocess, sys, time\n"
+ "from tools import browser_use_cli\n"
+ f"d = subprocess.Popen([sys.executable, '-m', 'browser_harness.daemon'], cwd={str(tmp_path / 'pkgroot')!r},"
+ " stdin=subprocess.DEVNULL, start_new_session=True)\n"
+ f"open({str(runtime / 'bu.pid')!r}, 'w', encoding='utf-8').write(json.dumps({{'pid': d.pid}}))\n" # windows-footgun: ok — a write
+ f"browser_use_cli._own_harness_daemon({{'BH_RUNTIME_DIR': {str(runtime)!r}}})\n"
+ "print(d.pid, flush=True)\n"
+ "time.sleep(300)\n"
+ )
+ env = dict(os.environ, HERMES_HOME=str(tmp_path / "home"), PYTHONPATH=str(Path(__file__).resolve().parents[2]))
+ owner = subprocess.Popen([sys.executable, "-c", owner_src], env=env, stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE, text=True)
+ daemon_pid = None
+ try:
+ daemon_pid = int(owner.stdout.readline())
+ owner.kill()
+ owner.wait(timeout=10)
+ deadline = time.monotonic() + 15
+ while time.monotonic() < deadline:
+ try:
+ os.killpg(daemon_pid, 0) # windows-footgun: ok — posix-marked test
+ except ProcessLookupError:
+ break
+ time.sleep(0.05)
+ else:
+ pytest.fail("the harness daemon outlived kill -9 of the Hermes process that drove it")
+ finally:
+ if daemon_pid is not None:
+ try:
+ os.killpg(daemon_pid, 9) # windows-footgun: ok — posix-marked test
+ except ProcessLookupError:
+ pass
+ if owner.poll() is None:
+ owner.kill()
+ owner.wait(timeout=10)
+ process_identity._supervised_pgids.clear()
diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.py
index fa450229bb1..9774096db52 100644
--- a/tools/browser_use_cli.py
+++ b/tools/browser_use_cli.py
@@ -23,6 +23,7 @@ import time
from pathlib import Path
from typing import Any, Callable, Dict, List, NamedTuple, Optional
+from hermes_cli.process_identity import register_child, update_supervised_pgids
from hermes_constants import get_hermes_home, hermes_home_key
from tools.browser_harness_dirs import (daemon_env, daemon_identity, fit_default_socket_dir,
namespace_harness_dirs)
@@ -638,6 +639,62 @@ def _reload_daemons(daemons) -> None: # each ``daemon_identity`` daemon, with i
for daemon in daemons:
with contextlib.suppress(OSError, subprocess.SubprocessError):
_run_cli_killing_process_group([*cmd, "--reload"], "", daemon_env(env, daemon), 15)
+ with _owned_daemon_groups_lock:
+ pgid = _owned_daemon_groups.pop(daemon, None)
+ if pgid is not None:
+ update_supervised_pgids("unregister", [pgid])
+
+
+# Daemon identity (``daemon_identity``: its dirs + BU_NAME) -> process group of the harness daemon this
+# process owns. The harness starts its daemon with start_new_session so it outlives each CLI call (that
+# is how a session persists across browser_exec calls), which also means it outlives a SIGKILLed or
+# OOM-killed Hermes forever (#121095). Its group goes to this process's owner-death supervisor, so it
+# dies with us however we die.
+_owned_daemon_groups: dict[tuple[str, ...], int] = {}
+_owned_daemon_groups_lock = threading.Lock()
+
+
+def _own_harness_daemon(env: dict) -> None:
+ """Hand the daemon behind ``env``'s BU_NAME to the owner-death supervisor.
+
+ The harness publishes its daemon pid in ``<runtime dir>/bu-<name>.pid`` (JSON ``{"pid", "started"}``
+ or a bare pid). The daemon is accepted only while it is this user's live ``browser_harness.daemon``
+ leading its own session, so a stale or planted pid file can never hand a stranger's group to the
+ supervisor."""
+ if os.name != "posix":
+ return # Windows: the harness daemon is outside this process's job; nothing to register.
+ import psutil
+
+ # Where the daemon's pid file lives, resolved from the env the CLI ran with (a profile scope can
+ # differ from os.environ) the way browser_harness.paths / _ipc resolve it.
+ name = env.get("BU_NAME", "default")
+ isolated = env.get("BH_RUNTIME_DIR") or env.get("BH_TMP_DIR")
+ home = env.get("BH_HOME") or env.get("BROWSER_HARNESS_HOME")
+ if isolated:
+ runtime = Path(isolated).expanduser()
+ elif home:
+ runtime = Path(home).expanduser() / "runtime"
+ else:
+ runtime = Path(env.get("XDG_CONFIG_HOME") or Path.home() / ".config").expanduser() / "browser-harness" / "runtime"
+ stem = "bu" if isolated and env.get("BH_RUNTIME_DIR_SHARED") != "1" else f"bu-{name}"
+ try:
+ raw = (runtime / f"{stem}.pid").read_text(encoding="utf-8-sig").strip()
+ pid = int(json.loads(raw)["pid"]) if raw.startswith("{") else int(raw.split()[0])
+ proc = psutil.Process(pid)
+ argv = proc.cmdline()
+ if (os.getsid(pid) != pid or proc.uids().real != os.getuid() # windows-footgun: ok — posix-only, returned above
+ or argv[argv.index("-m") + 1] != "browser_harness.daemon"):
+ return
+ except (OSError, ValueError, KeyError, TypeError, IndexError, psutil.Error) as exc:
+ logger.debug("browser_exec: no harness daemon to supervise for %s: %s", name, exc)
+ return
+ daemon = daemon_identity(env)
+ with _owned_daemon_groups_lock:
+ if _owned_daemon_groups.get(daemon) == pid:
+ return
+ _owned_daemon_groups[daemon] = pid
+ update_supervised_pgids("register", [pid])
+ register_child(pid, "browser-harness-daemon")
def _route_exec(env: dict, session: str, task_id: Optional[str], local: bool, local_sidecar: bool,
@@ -769,6 +826,7 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUT
else:
dispatched = dispatch()
_reload_if_republished(env, generation)
+ _own_harness_daemon(env)
if "proc" not in dispatched:
if "error_result" in dispatched:
return dispatched["error_result"]