The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): the reaper never deletes a throwaway profile a Chromium still runs on
Teknium1705bb71a3e1
diff --git a/tests/tools/browser_launcher_fakes.py b/tests/tools/browser_launcher_fakes.pynew file mode 100644index 00000000000..a310a9a77eb--- /dev/null+++ b/tests/tools/browser_launcher_fakes.py@@ -0,0 +1,86 @@+"""A fake ``chromium`` for launcher tests that behaves like the real one where the launcher depends on it.++It takes Chromium's profile singleton (a ``SingletonLock`` symlink ``<host>-<pid>``; a second instance on a+held dir hands over to the running one and exits 0), answers ``/json/version`` on an ephemeral loopback port,+and writes ``DevToolsActivePort`` once ready (after ``FAKE_CHROMIUM_READY_DELAY`` seconds, default 0). Every+start appends its pid to ``<udd>/spawns``; the instance that took the singleton also to ``<udd>/launches``.+SIGTERM releases the singleton and exits, as a clean Chromium shutdown does.+"""++from __future__ import annotations++import contextlib+import os+import signal+import sys+import textwrap+from pathlib import Path++FAKE_CHROMIUM = textwrap.dedent('''\+ #!{python}+ import http.server, json, os, signal, socket, sys, threading, time+ udd = next(a.split("=", 1)[1] for a in sys.argv if a.startswith("--user-data-dir="))+ os.makedirs(udd, exist_ok=True)+ def note(name):+ with open(os.path.join(udd, name), "a") as f:+ f.write(f"{{os.getpid()}}\\n")+ note("spawns")+ lock = os.path.join(udd, "SingletonLock")+ try:+ os.symlink(f"{{socket.gethostname()}}-{{os.getpid()}}", lock)+ except FileExistsError:+ holder = int(os.readlink(lock).rpartition("-")[2])+ try:+ os.kill(holder, 0)+ sys.exit(0) # handed to the running instance, like Chromium's singleton+ except OSError:+ os.unlink(lock)+ os.symlink(f"{{socket.gethostname()}}-{{os.getpid()}}", lock)+ note("launches")+ def on_term(*_):+ with __import__("contextlib").suppress(OSError):+ os.unlink(lock)+ os._exit(0)+ signal.signal(signal.SIGTERM, on_term)+ browser_path = f"/devtools/browser/{{os.getpid()}}"+ class Version(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ body = json.dumps({{"webSocketDebuggerUrl": f"ws://127.0.0.1:{{port}}{{browser_path}}"}}).encode()+ self.send_response(200)+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)+ def log_message(self, *a):+ pass+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Version)+ port = server.server_address[1]+ threading.Thread(target=server.serve_forever, daemon=True).start()+ time.sleep(float(os.environ.get("FAKE_CHROMIUM_READY_DELAY") or 0))+ tmp = os.path.join(udd, "DevToolsActivePort.tmp")+ with open(tmp, "w") as f:+ f.write(f"{{port}}\\n{{browser_path}}\\n")+ os.replace(tmp, os.path.join(udd, "DevToolsActivePort"))+ while True:+ time.sleep(600)+''')+++def write_fake_chromium(path: Path) -> Path:+ path.write_text(FAKE_CHROMIUM.format(python=sys.executable))+ path.chmod(0o755)+ return path+++def pids(udd: Path, name: str) -> list[int]:+ """The pids the fake noted in ``<udd>/<name>`` (``spawns`` or ``launches``)."""+ try:+ return [int(line) for line in (udd / name).read_text().split()]+ except OSError:+ return []+++def kill_fake(pid: int, script: Path) -> None:+ """SIGKILL ``pid`` only while it is still our fake (its argv names the script)."""+ with contextlib.suppress(OSError):+ if str(script) in Path(f"/proc/{pid}/cmdline").read_text(errors="replace"):+ os.kill(pid, signal.SIGKILL)diff --git a/tests/tools/test_browser_launcher_reclaim.py b/tests/tools/test_browser_launcher_reclaim.pynew file mode 100644index 00000000000..43961008994--- /dev/null+++ b/tests/tools/test_browser_launcher_reclaim.py@@ -0,0 +1,89 @@+"""The reaper never deletes the throwaway profile of a Chromium that is still running on it.++A Hermes process SIGKILLed mid-launch can leave a live Chromium whose launch record is missing or cannot+prove the pid (``tools/browser_launcher.py``: ``_reclaim_throwaway_dirs``, ``_reap_record``). Deleting the dir+under it corrupts a running browser, so the dir waits until that Chromium is gone.+"""++from __future__ import annotations++import os+import signal+import subprocess+import sys+from pathlib import Path++import pytest++from tests.tools.browser_launcher_fakes import kill_fake, 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 browsers are ours to stop if a leg failed++_REPO = Path(__file__).resolve().parents[2]+++def _dir_of_a_dead_owner() -> Path:+ """A throwaway profile dir named for a Hermes process that has exited (it died mid-launch)."""+ from hermes_constants import hermes_home_key+ code = ("import sys\n"+ "from tools.browser_launcher import _default_user_data_dir, _prepare_dir\n"+ "udd = _default_user_data_dir('browser-exec-default', sys.argv[1])\n"+ "_prepare_dir(udd, True)\n"+ "print(udd, flush=True)\n")+ return Path(subprocess.run([sys.executable, "-c", code, hermes_home_key()], cwd=_REPO, env=dict(os.environ),+ capture_output=True, text=True, check=True).stdout.strip())+++def _start_browser_on(script: Path, udd: Path, log: Path) -> subprocess.Popen:+ with open(log, "wb") as out:+ proc = subprocess.Popen([str(script), f"--user-data-dir={udd}"], start_new_session=True,+ stdout=out, stderr=out)+ wait_until(lambda: (udd / "DevToolsActivePort").exists() or proc.poll() is not None, timeout=15,+ what="the fake browser to write DevToolsActivePort")+ assert proc.poll() is None, f"the fake browser exited during startup: {log.read_text()[-2000:]}"+ return proc+++def _stop(proc: subprocess.Popen) -> None:+ proc.send_signal(signal.SIGTERM)+ proc.wait(timeout=10)+++def test_an_unrecorded_live_browsers_throwaway_profile_survives_the_reclaim(tmp_path):+ """Owner SIGKILLed before its record existed, its Chromium still up: reclaim waits for that Chromium."""+ script = write_fake_chromium(tmp_path / "chromium")+ udd = _dir_of_a_dead_owner()+ proc = _start_browser_on(script, udd, tmp_path / "chromium.log")+ try:+ launcher.reap_orphaned_browsers()+ assert udd.is_dir(), "the reaper deleted the profile of a Chromium still running on it"+ assert proc.poll() is None++ _stop(proc)+ launcher.reap_orphaned_browsers()+ assert not udd.exists()+ finally:+ kill_fake(proc.pid, script)+++def test_a_live_browsers_profile_survives_when_its_record_cannot_prove_the_pid(tmp_path):+ """A record whose start time no longer proves the pid is never signalled; its dir must not go either while a+ Chromium still runs on it."""+ from hermes_constants import hermes_home_key+ script = write_fake_chromium(tmp_path / "chromium")+ udd = _dir_of_a_dead_owner()+ proc = _start_browser_on(script, udd, tmp_path / "chromium.log")+ try:+ unprovable = launcher.LaunchedBrowser(key="lost", pid=proc.pid, start_time=1, cdp_url="", http_url="",+ user_data_dir=str(udd), owned=True, ephemeral=True,+ home_key=hermes_home_key())+ launcher._write_record(unprovable) # this process's record of a browser it no longer tracks++ assert launcher.reap_orphaned_browsers() == 0+ assert proc.poll() is None, "signalled on an unproven pid"+ assert udd.is_dir(), "the reaper deleted the profile of a Chromium still running on it"+ finally:+ kill_fake(proc.pid, script)diff --git a/tools/browser_launcher.py b/tools/browser_launcher.pyindex 6b93dc17e2c..ce750246f51 100644--- a/tools/browser_launcher.py+++ b/tools/browser_launcher.py@@ -304,6 +304,11 @@ def _pid_naming_dir(user_data_dir: str) -> Optional[int]:return None+def _browser_running_on(user_data_dir: str) -> bool:+ """A live Chromium still uses ``user_data_dir`` (by argv: a ``SingletonLock`` outlives a crashed browser)."""+ return _pid_naming_dir(user_data_dir) is not None++def _devtools_endpoint_live(port: int, path: str) -> bool:"""The port answers ``/json/version`` with the browser id the DevToolsActivePort file names (the fileoutlives a crashed Chromium and its port can be recycled by another CDP server)."""@@ -760,7 +765,8 @@ def _reap_record(path: Path, home: str) -> bool:_terminate(record["pid"], record.get("start_time"), None)logger.info("browser: reaped orphaned Chromium pid %s (%s)", record["pid"], record["user_data_dir"])udd = record.get("user_data_dir")- if record.get("ephemeral") and isinstance(udd, str) and _inside_ephemeral_root(udd, home):+ if (record.get("ephemeral") and isinstance(udd, str) and _inside_ephemeral_root(udd, home)+ and (reaped or not _browser_running_on(udd))):shutil.rmtree(udd, ignore_errors=True) # its owner is gone: no launch reuses a per-process dirpath.unlink(missing_ok=True)return reaped@@ -805,9 +811,13 @@ def _reclaim_throwaway_dirs(home: str) -> None:match = _THROWAWAY_DIR.match(entry.name)if match is None or int(match.group(1)) == os.getpid():continue- if not process_alive(int(match.group(1)), int(match.group(2)) if match.group(2) else None):- shutil.rmtree(entry, ignore_errors=True) # a symlink is refused, never followed- logger.info("browser: removed the throwaway profile %s of a Hermes process that is gone", entry)+ if process_alive(int(match.group(1)), int(match.group(2)) if match.group(2) else None):+ continue+ if _browser_running_on(str(entry)): # its record was lost or could not prove the pid: never pull the dir+ logger.debug("browser: keeping the throwaway profile %s: a Chromium still runs on it", entry)+ continue+ shutil.rmtree(entry, ignore_errors=True) # a symlink is refused, never followed+ logger.info("browser: removed the throwaway profile %s of a Hermes process that is gone", entry)def _served_home_keys(homes) -> set[str]: