Skip to content

The agent that grows with you

fix(browser): a Chromium whose launcher dies mid-launch is left a record for the reaper

Tekniumfc50f3db832e
diff --git a/tests/tools/test_browser_launcher.py b/tests/tools/test_browser_launcher.py
index 1ff21f8ebc4..ce7cdf25f7b 100644
--- a/tests/tools/test_browser_launcher.py
+++ b/tests/tools/test_browser_launcher.py
@@ -421,6 +421,80 @@ def test_a_throwaway_profile_left_by_a_process_that_died_mid_launch_is_reclaimed
alive.communicate("\n", timeout=30)
+# A Chromium that never becomes ready: records its pid, never writes DevToolsActivePort.
+_NEVER_READY_CHROMIUM = textwrap.dedent('''\
+ #!{python}
+ import os, sys, time
+ udd = next(a.split("=", 1)[1] for a in sys.argv if a.startswith("--user-data-dir="))
+ with open(os.path.join(udd, "pid.tmp"), "w") as f:
+ f.write(str(os.getpid()))
+ os.replace(os.path.join(udd, "pid.tmp"), os.path.join(udd, "pid"))
+ time.sleep(600)
+''')
+
+# A Hermes process waiting for that Chromium's readiness: prints its throwaway dir, then launches.
+_WAITING_LAUNCHER = textwrap.dedent("""\
+ import os, sys
+ from hermes_constants import hermes_home_key
+ from tools import browser_launcher as launcher
+ launcher.needs_chromium_sandbox_bypass = lambda: False
+ print(launcher._default_user_data_dir("slow", hermes_home_key()), flush=True)
+ launcher.launch_chromium("slow", executable=sys.argv[1], headed=False, env=dict(os.environ), timeout=300)
+""")
+
+
[email protected]_system_guard_bypass # the never-ready fake browser is ours to stop if a leg failed
+def test_a_launcher_killed_during_the_readiness_wait_leaves_its_chromium_to_the_reaper(fake_chromium, tmp_path):
+ """Hermes dies (SIGKILL, a crash) while its new Chromium is still starting (a first launch may wait
+ 120 s): that browser must already carry a launch record, so the next reap stops it."""
+ from tests.waiting import wait_until
+ slow = tmp_path / "never-ready-chromium"
+ slow.write_text(_NEVER_READY_CHROMIUM.format(python=sys.executable))
+ slow.chmod(0o755)
+ hermes = subprocess.Popen([sys.executable, "-c", _WAITING_LAUNCHER, str(slow)], text=True,
+ cwd=Path(__file__).resolve().parents[2], env=dict(os.environ),
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ pid = None
+ try:
+ udd = Path(hermes.stdout.readline().strip())
+ pid = int(wait_until(lambda: (udd / "pid").exists() and (udd / "pid").read_text(), timeout=30,
+ what="the launched Chromium to start"))
+ hermes.kill()
+ hermes.wait(timeout=10)
+ assert launcher._pid_alive(pid)
+
+ assert launcher.reap_orphaned_browsers() == 1, "a Chromium whose launcher died mid-launch has no record"
+ assert _gone(pid)
+ finally:
+ hermes.kill()
+ if pid is not None:
+ _kill_fake(pid, slow)
+
+
[email protected]_system_guard_bypass # the never-ready fake browser is ours to stop if a leg failed
+def test_a_reap_during_this_processs_own_readiness_wait_leaves_the_starting_chromium(fake_chromium, tmp_path):
+ from tests.waiting import wait_until
+ slow = tmp_path / "never-ready-chromium"
+ slow.write_text(_NEVER_READY_CHROMIUM.format(python=sys.executable))
+ slow.chmod(0o755)
+ result = {}
+ launch = threading.Thread(target=lambda: result.update(out=launcher.launch_chromium(
+ "slow", executable=str(slow), headed=False, env=dict(os.environ), timeout=4)))
+ launch.start()
+ try:
+ wait_until(lambda: launcher._launching and list(_records().glob("*.json")), timeout=30,
+ what="the starting Chromium's launch record")
+ pid = next(iter(launcher._launching))
+ assert launcher.reap_orphaned_browsers() == 0
+ assert launcher._pid_alive(pid), "the janitor killed this process's own starting browser"
+ finally:
+ launch.join(timeout=60)
+ assert result["out"][0] is None and "in time" in result["out"][1]
+ assert not launcher._launching and not list(_records().glob("*.json"))
+
+
@pytest.mark.parametrize("headed,display,expect_headless", [
(False, ":1", True),
(True, ":1", False),
diff --git a/tools/browser_launcher.py b/tools/browser_launcher.py
index c08ae4dfc49..6b93dc17e2c 100644
--- a/tools/browser_launcher.py
+++ b/tools/browser_launcher.py
@@ -78,6 +78,7 @@ class LaunchedBrowser:
_browsers: dict[str, LaunchedBrowser] = {}
_procs: dict[str, subprocess.Popen] = {}
+_launching: dict[int, LaunchedBrowser] = {} # pid -> a spawned Chromium still in its readiness wait
_key_locks: dict[str, threading.Lock] = {}
_lock = threading.RLock()
_autoinstall_attempted = False
@@ -444,23 +445,42 @@ def _launch_owned(key: str, executable: str, udd: str, *, ephemeral: bool, packa
except (OSError, subprocess.SubprocessError) as exc:
return None, f"Failed to launch Chromium ({executable}): {exc}"
start_time = _start_time(proc.pid)
- found, err = _wait_for_devtools(proc, udd, time.monotonic() + _launch_timeout(timeout))
+ starting = _make_browser(key, 0, "", pid=proc.pid, start_time=start_time, user_data_dir=udd, owned=True,
+ ephemeral=ephemeral, home_key=home_key)
+ # Recorded before the readiness wait (a first launch may take 120 s): if this process dies in it, the
+ # record is what lets the next reaper stop this Chromium. Tracked as launching so this process's own
+ # reaper leaves it alone meanwhile.
+ with _lock:
+ _launching[proc.pid] = starting
+ _write_record(starting)
+ try:
+ found, err = _wait_for_devtools(proc, udd, time.monotonic() + _launch_timeout(timeout))
+ except BaseException: # interrupted (Ctrl-C, shutdown): nobody else knows this browser exists
+ _abandon_launch(proc, starting)
+ raise
if found is None:
- if proc.poll() is None: # one that already exited is reaped by poll(); its pid is no longer ours
- _terminate(proc.pid, start_time, proc)
- if ephemeral:
- shutil.rmtree(udd, ignore_errors=True)
+ _abandon_launch(proc, starting)
return None, err
browser = _make_browser(key, found[0], found[1], pid=proc.pid, start_time=start_time, user_data_dir=udd,
owned=True, ephemeral=ephemeral, home_key=home_key)
with _lock:
+ _launching.pop(proc.pid, None)
_browsers[key] = browser
_procs[key] = proc
- _write_record(browser)
logger.info("browser: launched Chromium pid %s for %s (port %s)", proc.pid, key, found[0])
return browser, None
+def _abandon_launch(proc: subprocess.Popen, starting: LaunchedBrowser) -> None:
+ with _lock:
+ _launching.pop(proc.pid, None)
+ if proc.poll() is None: # one that already exited is reaped by poll(); its pid is no longer ours
+ _terminate(proc.pid, starting.start_time, proc)
+ _remove_record(starting)
+ if starting.ephemeral:
+ shutil.rmtree(starting.user_data_dir, ignore_errors=True)
+
+
# ── Lookup / stop ────────────────────────────────────────────────────────────────────────────────────
def _alive(browser: LaunchedBrowser) -> bool:
@@ -693,7 +713,7 @@ def _is_recorded_browser(record: dict, home: str) -> bool:
def _tracked_browser(record: dict) -> Optional[LaunchedBrowser]:
with _lock:
- return next((b for b in _browsers.values() if b.pid == record.get("pid")), None)
+ return next((b for b in (*_browsers.values(), *_launching.values()) if b.pid == record.get("pid")), None)
def _adopt_record(browser: LaunchedBrowser) -> None: