Skip to content

The agent that grows with you

fix(browser): adopting a browser through a symlinked profile keeps its launch identity

Teknium491f403a9ca1
diff --git a/tests/tools/test_browser_launcher_alias.py b/tests/tools/test_browser_launcher_alias.py
new file mode 100644
index 00000000000..75ea8bf1500
--- /dev/null
+++ b/tests/tools/test_browser_launcher_alias.py
@@ -0,0 +1,73 @@
+"""A shared profile reached through a symlink is the same browser launch: adopting it keeps its launch identity.
+
+A Hermes process attaching through another spelling of the profile (``/alias -> /profile``) after the owner
+crashed takes the launch record over. The record must still describe the browser as launched (the
+``--user-data-dir`` its argv carries), or the reaper cannot verify it once this process crashes too: it would
+leave Chromium running and delete its only record (``tools/browser_launcher.py``). Runs the real launcher against a
+fake Chromium that takes the profile singleton and serves ``/json/version`` like the real one.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+import textwrap
+from pathlib import Path
+
+import pytest
+
+from tests.tools.browser_launcher_fakes import kill_fake, pids, write_fake_chromium
+from tests.waiting import wait_until
+from tools import browser_launcher as launcher
+
+pytestmark = [pytest.mark.platforms("linux"),
+ pytest.mark.live_system_guard_bypass] # the fake browser is ours to stop if a leg failed
+
+_REPO = Path(__file__).resolve().parents[2]
+
+# A Hermes process on a persistent profile: launches (or attaches), prints "<pid> <owned>", then waits to be killed.
+_HOLDER = textwrap.dedent("""\
+ import os, sys
+ import tools.browser_session # registers the exit teardown
+ from tools import browser_launcher as launcher
+ launcher.needs_chromium_sandbox_bypass = lambda: False
+ exe, udd = sys.argv[1], sys.argv[2]
+ browser, err = launcher.launch_chromium("profile:" + udd, executable=exe, user_data_dir=udd, ephemeral=False,
+ headed=False, env=dict(os.environ), timeout=30)
+ print(f"{browser.pid} {browser.owned}" if browser else f"ERR {err!r}", flush=True)
+ sys.stdin.readline()
+""")
+
+
+def _crashing_holder(script: Path, udd: Path) -> tuple[int, str]:
+ """A holder that launches or attaches on ``udd``, then is SIGKILLed (no teardown runs)."""
+ proc = subprocess.Popen([sys.executable, "-c", _HOLDER, str(script), str(udd)], cwd=_REPO, env=dict(os.environ),
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ try:
+ line = proc.stdout.readline().split()
+ assert line and line[0] != "ERR", proc.stderr.read()[-2000:] if not line else line
+ finally:
+ proc.kill()
+ proc.wait(timeout=10)
+ return int(line[0]), line[1]
+
+
+def test_a_browser_adopted_through_a_symlink_is_still_reaped_after_its_adopter_crashes(tmp_path):
+ script = write_fake_chromium(tmp_path / "chromium")
+ udd = tmp_path / "profile"
+ alias = tmp_path / "alias"
+ alias.symlink_to(udd)
+ try:
+ pid, owned = _crashing_holder(script, udd)
+ assert owned == "True"
+ adopted, owned = _crashing_holder(script, alias)
+ assert (adopted, owned) == (pid, "False")
+
+ assert launcher.reap_orphaned_browsers() == 1
+ assert wait_until(lambda: not launcher._pid_alive(pid), timeout=15, what="the orphaned browser to stop")
+ state = launcher._shared_state_dir(str(udd))
+ assert not list(state.glob("*.json")), "a launch record outlived its reaped browser"
+ finally:
+ for spawned in pids(udd, "spawns"):
+ kill_fake(spawned, script)
diff --git a/tools/browser_launcher.py b/tools/browser_launcher.py
index b2f84ccda02..8926ed6a698 100644
--- a/tools/browser_launcher.py
+++ b/tools/browser_launcher.py
@@ -953,14 +953,14 @@ def _owner_alive(record: dict) -> bool:
def _cmdline_names_dir(pid: int, user_data_dir: str) -> bool:
- """True only when ``pid``'s argv carries exactly ``--user-data-dir=<user_data_dir>``."""
+ """True only when ``pid``'s argv carries ``--user-data-dir=`` naming ``user_data_dir`` (however either is
+ spelled: a symlink, a trailing slash)."""
try:
import psutil
argv = psutil.Process(pid).cmdline()
except Exception: # health: allow BLE001 -- unreadable identity fails closed (no kill)
return False
- want = os.path.normpath(user_data_dir)
- return any(tok.startswith("--user-data-dir=") and os.path.normpath(tok.split("=", 1)[1]) == want
+ return any(tok.startswith("--user-data-dir=") and _same_profile(tok.split("=", 1)[1], user_data_dir)
for tok in argv)
@@ -998,13 +998,16 @@ def _tracked_browser(record: dict) -> Optional[LaunchedBrowser]:
def _adopt_record(browser: LaunchedBrowser) -> None:
"""A crashed owner's record still names the browser this process now uses (attached after the crash):
- take the record over, or every reaper (this process's included) would kill it as an orphan."""
+ take the record over, or every reaper (this process's included) would kill it as an orphan. Only the owner
+ changes: the launch as recorded (its ``--user-data-dir`` spelling, DevTools id) stays what verifies it."""
+ from utils import atomic_json_write
path = _record_path(browser)
if path is None or not path.exists():
return
record = _load_record(path)
if record is not None and _record_is(record, browser) and not _owner_alive(record):
- _write_record(browser)
+ me = os.getpid()
+ atomic_json_write(path, {**record, "owner_pid": me, "owner_start_time": _start_time(me)}, indent=None)
def _load_record(path: Path) -> Optional[dict]: