The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): launcher state from another PID namespace or boot is never judged dead
Teknium13fd097a0ed1
diff --git a/tests/tools/test_browser_launcher.py b/tests/tools/test_browser_launcher.pyindex 345790bfce4..7f468533540 100644--- a/tests/tools/test_browser_launcher.py+++ b/tests/tools/test_browser_launcher.py@@ -22,6 +22,7 @@ from pathlib import Pathimport pytestfrom tools import browser_launcher as launcher+from tools.browser_launcher_holders import ns_identity_FAKE_CHROMIUM = textwrap.dedent('''\#!{python}@@ -266,7 +267,7 @@ def _write_orphan_record(records: Path, pid: int, udd: str) -> Path:path = records / f"orphan-{pid}.json"path.write_text(json.dumps({"owner_pid": dead_owner.pid, "owner_start_time": None, "pid": pid,"start_time": launcher._start_time(pid), "user_data_dir": udd,- "home_key": "x", "ephemeral": False}))+ "home_key": "x", "ephemeral": False, "ns": ns_identity()}))return pathdiff --git a/tests/tools/test_browser_launcher_pidns.py b/tests/tools/test_browser_launcher_pidns.pynew file mode 100644index 00000000000..9926d447c15--- /dev/null+++ b/tests/tools/test_browser_launcher_pidns.py@@ -0,0 +1,130 @@+"""A pid in launcher state means something only inside the PID namespace and boot that wrote it.++One ``HERMES_HOME`` can be shared by a container gateway and a host CLI: a record, lease or throwaway profile dir+written in another PID namespace (or before a reboot), or one that does not say where it was written, names a+pid that may be dead HERE while its process lives THERE. It is never judged dead: never reaped, deleted,+dropped or handed over. Same-namespace state of a process that is gone is still cleaned up+(``tools/browser_launcher.py``, ``tools/browser_launcher_holders.py``).+"""++from __future__ import annotations++import json+import os+import subprocess+import sys+import textwrap+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")++_REPO = Path(__file__).resolve().parents[2]+_FOREIGN = "4026531836:00000000-0000-0000-0000-000000000000" # another pid namespace / boot+_FOREIGN_TAG = "-nffffffffffff"+++def _dead_pid() -> int:+ proc = subprocess.Popen([sys.executable, "-c", "pass"])+ proc.wait()+ return proc.pid+++def _home_state() -> tuple[Path, Path]:+ from hermes_constants import get_hermes_home+ browser = Path(get_hermes_home()) / "cache" / "browser"+ records, throwaway = browser / "chromium-records", browser / "chromium"+ for path in (records, throwaway):+ path.mkdir(mode=0o700, parents=True, exist_ok=True)+ return records, throwaway+++def _write(path: Path, data: dict, ns) -> Path:+ path.write_text(json.dumps({**data, **({"ns": ns} if ns is not None else {})}))+ return path++[email protected]("ns", [_FOREIGN, None], ids=["other-namespace", "no-identity"])+def test_state_from_another_namespace_is_never_judged_dead(ns):+ records, throwaway = _home_state()+ owner, browser, holder = _dead_pid(), _dead_pid(), _dead_pid()+ suffix = _FOREIGN_TAG if ns else ""+ profile = throwaway / f"{'a' * 16}-{browser}-1{suffix}"+ (profile / "Default").mkdir(parents=True)+ orphan_dir = throwaway / f"{'b' * 16}-{owner}-1{suffix}" # its owner died before writing a record+ orphan_dir.mkdir()+ record = _write(records / f"{'a' * 16}-{browser}{suffix}.json",+ {"owner_pid": owner, "owner_start_time": None, "pid": browser, "start_time": 1,+ "user_data_dir": str(profile), "home_key": "x", "ephemeral": True}, ns)+ lease = _write(records / f"{'c' * 16}-{browser}{suffix}@{holder}{suffix}.lease",+ {"holder_pid": holder, "holder_start_time": None, "pid": browser, "start_time": 1}, ns)++ assert launcher.reap_orphaned_browsers() == 0++ assert record.exists(), "a record from another namespace was dropped"+ assert (profile / "Default").is_dir(), "the throwaway profile named by another namespace's record was deleted"+ assert orphan_dir.is_dir(), "another namespace's throwaway profile was reclaimed"+ assert lease.exists(), "another namespace's lease was dropped"+++_HOLDER = textwrap.dedent("""\+ import os, sys+ from tools import browser_launcher as launcher+ 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}", flush=True)+ sys.stdin.readline()+""")++[email protected]_system_guard_bypass # the fake browser is ours to stop if a leg failed+def test_a_holder_in_another_namespace_keeps_the_shared_browser_up(tmp_path):+ script = write_fake_chromium(tmp_path / "chromium")+ udd, key = tmp_path / "pinned-profile", f"profile:{tmp_path / 'pinned-profile'}"+ mine, err = launcher.launch_chromium(key, executable=str(script), user_data_dir=str(udd), ephemeral=False,+ headed=False, env=dict(os.environ), timeout=30)+ assert err is None and mine.owned+ try:+ record, gone_here = launcher._record_path(mine), _dead_pid()+ foreign = _write(record.with_name(f"{record.stem}@{gone_here}{_FOREIGN_TAG}.lease"),+ {"holder_pid": gone_here, "holder_start_time": None, "pid": mine.pid,+ "start_time": mine.start_time, "user_data_dir": str(udd)}, _FOREIGN)++ launcher.stop_browser(key)+ assert launcher._pid_alive(mine.pid), "stopped a browser a holder in another namespace may still drive"+ assert launcher.reap_orphaned_browsers() == 0 and launcher._pid_alive(mine.pid)+ assert foreign.exists() and record.exists()+ finally:+ kill_fake(mine.pid, script)++[email protected]_system_guard_bypass # the fake browser is ours to stop if a leg failed+def test_a_dead_holder_in_this_namespace_is_still_dropped(tmp_path):+ """Same namespace, behaviour unchanged: the lease of a holder that crashed is dropped, so the launcher's+ stop is the last one out and stops the browser."""+ script = write_fake_chromium(tmp_path / "chromium")+ udd, key = tmp_path / "pinned-profile", f"profile:{tmp_path / 'pinned-profile'}"+ mine, err = launcher.launch_chromium(key, executable=str(script), user_data_dir=str(udd), ephemeral=False,+ headed=False, env=dict(os.environ), timeout=30)+ assert err is None and mine.owned+ holder = subprocess.Popen([sys.executable, "-c", _HOLDER, str(script), str(udd)], cwd=_REPO,+ env=dict(os.environ), stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)+ try:+ assert holder.stdout.readline().split() == [str(mine.pid), "False"]+ record = launcher._record_path(mine)+ assert list(record.parent.glob("*.lease"))+ holder.kill()+ holder.wait(timeout=10)++ launcher.stop_browser(key)+ assert wait_until(lambda: not launcher._pid_alive(mine.pid), timeout=15, what="the browser to stop")+ assert not list(record.parent.glob("*.lease")) and not record.exists()+ finally:+ holder.kill()+ kill_fake(mine.pid, script)diff --git a/tests/tools/test_browser_orphan_reaper.py b/tests/tools/test_browser_orphan_reaper.pyindex 9879189232a..71a433b16ff 100644--- a/tests/tools/test_browser_orphan_reaper.py+++ b/tests/tools/test_browser_orphan_reaper.py@@ -15,6 +15,7 @@ from unittest.mock import patchimport pytestfrom tools import browser_launcher as launcher+from tools.browser_launcher_holders import ns_identityfrom tools import browser_session as bsfrom tools import browser_session_lifecycle as lifecycle@@ -44,7 +45,7 @@ def _record(records, *, pid: int, udd: str, owner_pid: int = _DEAD_OWNER, start_path = records.dir / f"rec-{pid}.json"path.write_text(json.dumps({"owner_pid": owner_pid, "owner_start_time": None, "pid": pid,"start_time": start_time, "user_data_dir": udd, "home_key": "x",- "ephemeral": ephemeral}))+ "ephemeral": ephemeral, "ns": ns_identity()}))return path@@ -235,7 +236,8 @@ def test_browser_attached_after_its_owner_crashed_is_never_reaped_while_in_use(ruser_data_dir=udd, owned=True, ephemeral=False, home_key=hermes_home_key())record = launcher._record_path(crashed) # where the crashed owner left itrecord.write_text(json.dumps({"owner_pid": _DEAD_OWNER, "owner_start_time": None, "pid": 4242, "start_time": 777,- "user_data_dir": udd, "home_key": crashed.home_key, "ephemeral": False}))+ "user_data_dir": udd, "home_key": crashed.home_key, "ephemeral": False,+ "ns": ns_identity()}))attached, err = launcher.launch_chromium(f"profile:{udd}", executable="/opt/chrome", user_data_dir=udd,ephemeral=False)diff --git a/tools/browser_launcher.py b/tools/browser_launcher.pyindex 5985b661f25..8b916eeea67 100644--- a/tools/browser_launcher.py+++ b/tools/browser_launcher.py@@ -183,10 +183,12 @@ def _default_user_data_dir(key: str, home_key: str) -> str:named sessions), and each launch wipes its throwaway dir first. The name carries the owner's pid andstart time: a process that dies before its launch record exists leaves the dir to the reaper(:func:`_reclaim_throwaway_dirs`)."""+ from tools.browser_launcher_holders import ns_tagdigest = hashlib.sha256(f"{home_key}\0{key}".encode()).hexdigest()[:16]pid = os.getpid()started = _start_time(pid)- return str(_ephemeral_root(home_key) / (f"{digest}-{pid}-{started}" if started is not None else f"{digest}-{pid}"))+ owner = f"{pid}-{started}" if started is not None else str(pid)+ return str(_ephemeral_root(home_key) / f"{digest}-{owner}{ns_tag()}")def _launch_timeout(timeout: Optional[float]) -> float:@@ -620,9 +622,10 @@ def _last_holder_out(record: Path, browser: LaunchedBrowser) -> bool:data = _load_record(record) if record.exists() else Noneif data is not None and data.get("start_time") != browser.start_time:data = None # an earlier browser on a recycled pid- held_elsewhere = data is not None and data.get("owner_pid") != os.getpid() and _owner_alive(data)- if others and data is not None and not held_elsewhere:- holders.hand_over(record, data, others[0])+ held_elsewhere = data is not None and not holders.held_here(data, "owner_pid") and _owner_alive(data)+ heir = holders.successor(others)+ if heir is not None and data is not None and not held_elsewhere:+ holders.hand_over(record, data, heir)if others or held_elsewhere:return Falsereturn browser.owned or data is not None@@ -703,14 +706,18 @@ def _state_dir(browser: LaunchedBrowser) -> Optional[Path]:def _record_path(browser: LaunchedBrowser) -> Optional[Path]:records = _state_dir(browser)- return records / f"{_profile_digest(browser.user_data_dir)[:16]}-{browser.pid}.json" if records is not None else None+ if records is None:+ return None+ from tools.browser_launcher_holders import ns_tag+ return records / f"{_profile_digest(browser.user_data_dir)[:16]}-{browser.pid}{ns_tag()}.json"def _write_record(browser: LaunchedBrowser) -> None:+ from tools import browser_launcher_holders as holdersfrom utils import atomic_json_writerecord = {"owner_pid": os.getpid(), "owner_start_time": _start_time(os.getpid()), "pid": browser.pid,"start_time": browser.start_time, "user_data_dir": browser.user_data_dir,- "home_key": browser.home_key, "ephemeral": browser.ephemeral}+ "home_key": browser.home_key, "ephemeral": browser.ephemeral, "ns": holders.ns_identity()}try:path = _record_path(browser)if path is not None:@@ -729,6 +736,10 @@ def _remove_record(browser: LaunchedBrowser) -> None:def _owner_alive(record: dict) -> bool:+ """The record's owner is alive, or cannot be proven gone (it was written in another PID namespace)."""+ from tools.browser_launcher_holders import same_namespace+ if not same_namespace(record):+ return Trueowner = record.get("owner_pid")if not isinstance(owner, int) or not _pid_alive(owner):return False@@ -804,8 +815,9 @@ def _load_record(path: Path) -> Optional[dict]:def _reap_record(path: Path, home: Optional[str]) -> bool:"""Caller holds the records lock."""+ from tools import browser_launcher_holders as holdersrecord = _load_record(path)- if record is None:+ if record is None or not holders.same_namespace(record): # another namespace's pids name nobody herereturn Falsetracked = _tracked_browser(record)if tracked is not None: # in use here, whoever launched it@@ -813,10 +825,11 @@ def _reap_record(path: Path, home: Optional[str]) -> bool:return Falseif record.get("owner_pid") != os.getpid() and _owner_alive(record):return False- from tools import browser_launcher_holders as holdersothers = holders.other_live_holders(path, record.get("start_time"))if others: # another live Hermes process still drives it- holders.hand_over(path, record, others[0])+ heir = holders.successor(others)+ if heir is not None:+ holders.hand_over(path, record, heir)return Falsereaped = _is_recorded_browser(record, home)if reaped:@@ -871,17 +884,18 @@ def _reap_state_dir(records: Path, home: Optional[str]) -> int:return reaped-_THROWAWAY_DIR = re.compile(r"^[0-9a-f]{16}-(\d+)(?:-(\d+))?$") # _default_user_data_dir's names+_THROWAWAY_DIR = re.compile(r"^[0-9a-f]{16}-(\d+)(?:-(\d+))?(-n[0-9a-f]{12})?$") # _default_user_data_dir's namesdef _reclaim_throwaway_dirs(home: str) -> None:"""Remove ``home``'s throwaway profiles whose owning process is gone (pid and start time in the name): one- that died before writing its launch record left nothing else that would. The dir of a live owner is never- touched; a name without a start time is reclaimed only once its pid is gone."""+ that died before writing its launch record left nothing else that would. The dir of a live owner, or of an+ owner in another PID namespace or boot (its name's ``ns_tag`` differs or is missing), is never touched; a+ name without a start time is reclaimed only once its pid is gone."""root = _ephemeral_root(home)if not os.path.lexists(root) or not _is_private_dir(root):return- from tools.browser_launcher_holders import process_alive+ from tools.browser_launcher_holders import ns_tag, process_alivetry:entries = list(root.iterdir())except OSError as exc:@@ -889,8 +903,8 @@ def _reclaim_throwaway_dirs(home: str) -> None:returnfor entry in entries:match = _THROWAWAY_DIR.match(entry.name)- if match is None or int(match.group(1)) == os.getpid():- continue+ if match is None or (match.group(3) or "") != ns_tag() or int(match.group(1)) == os.getpid():+ continue # not a launcher dir, another PID namespace's (its owner cannot be checked here), or oursif process_alive(int(match.group(1)), int(match.group(2)) if match.group(2) else None):continueif _browser_running_on(str(entry)): # its record was lost or could not prove the pid: never pull the dirdiff --git a/tools/browser_launcher_holders.py b/tools/browser_launcher_holders.pyindex abb6f1da300..b0db2885ffe 100644--- a/tools/browser_launcher_holders.py+++ b/tools/browser_launcher_holders.py@@ -8,6 +8,10 @@ the record (the launcher, or whoever it was handed to) stops the browser on exitHermes process holds a lease; otherwise it hands the record to one of them, so the LAST holder stops it. Aholder that crashed is dropped once its pid and start time no longer match, never on the pid alone.+A pid means something only inside the PID namespace and boot that wrote it (a ``HERMES_HOME`` shared by a+container gateway and a host CLI): every record, lease and throwaway-dir name carries the writer's+:func:`ns_identity`, and one from another namespace or boot, or one lacking it, is never judged dead.+Every decision runs under the records dir's lock: a lease written while another process decides cannot bemissed. Siblings late-import the facade (its ``_pid_alive`` / ``_start_time`` are the patched seams)."""@@ -16,6 +20,8 @@ from __future__ import annotationsimport contextlibimport errno+import functools+import hashlibimport jsonimport loggingimport os@@ -28,6 +34,33 @@ logger = logging.getLogger(__name__)_LOCK_NAME = ".holders.lock"+def ns_identity() -> Optional[str]:+ """This process's PID namespace and boot (Linux: the pid-namespace inode + the kernel boot id); None where+ neither is readable (no ``/proc``), which then matches only another None."""+ try:+ ino = os.stat("/proc/self/ns/pid").st_ino+ boot = Path("/proc/sys/kernel/random/boot_id").read_text(encoding="ascii").strip()+ except OSError:+ return None+ return f"{ino}:{boot}"+++def ns_tag() -> str:+ """The name suffix of this namespace's records, leases and throwaway dirs (``""`` without an identity)."""+ identity = ns_identity()+ return f"-n{hashlib.sha256(identity.encode()).hexdigest()[:12]}" if identity else ""+++def same_namespace(data: dict) -> bool:+ """A record or lease written in this PID namespace and boot: only then do its pids name processes here."""+ return data.get("ns") == ns_identity()+++def held_here(data: dict, pid_field: str) -> bool:+ return data.get(pid_field) == os.getpid() and same_namespace(data)++# msvcrt.locking reports a lock another process holds as EDEADLOCK (LK_LOCK, after its own ~10 s of retries)# or EACCES (LK_NBLCK); anything else is a real error._NT_LOCK_CONTENDED = frozenset({errno.EACCES, errno.EDEADLK, getattr(errno, "EDEADLOCK", errno.EDEADLK)})@@ -90,7 +123,7 @@ def records_lock(records: Path, *, blocking: bool = True) -> Iterator[bool]:def _lease_path(record: Path, holder_pid: int) -> Path:- return record.with_name(f"{record.stem}@{holder_pid}.lease")+ return record.with_name(f"{record.stem}@{holder_pid}{ns_tag()}.lease")def _load(path: Path) -> Optional[dict]:@@ -120,23 +153,28 @@ def write_lease(record: Path, browser) -> None:me = os.getpid()atomic_json_write(_lease_path(record, me), {"holder_pid": me, "holder_start_time": launcher._start_time(me), "pid": browser.pid,- "start_time": browser.start_time, "user_data_dir": browser.user_data_dir}, indent=None)+ "start_time": browser.start_time, "user_data_dir": browser.user_data_dir, "ns": ns_identity()}, indent=None)def drop_lease(record: Path) -> None:_lease_path(record, os.getpid()).unlink(missing_ok=True)+def _holder_gone(lease: dict) -> bool:+ """Proven gone: written in this namespace and boot, and its pid + start time no longer match."""+ return same_namespace(lease) and not process_alive(lease.get("holder_pid"), lease.get("holder_start_time"))++def other_live_holders(record: Path, browser_start_time) -> list[dict]:"""Leases of OTHER live processes on the browser ``record`` names (caller holds :func:`records_lock`).- A lease of a dead holder, or one naming an earlier browser on the same pid, is removed."""+ A lease of a dead holder, or one naming an earlier browser on the same pid, is removed; one from another+ namespace counts as live (its holder cannot be checked from here)."""holders = []for path in sorted(record.parent.glob(f"{record.stem}@*.lease")):lease = _load(path)- if lease is None or lease.get("holder_pid") == os.getpid():+ if lease is None or held_here(lease, "holder_pid"):continue- if lease.get("start_time") != browser_start_time or not process_alive(- lease.get("holder_pid"), lease.get("holder_start_time")):+ if same_namespace(lease) and (lease.get("start_time") != browser_start_time or _holder_gone(lease)):path.unlink(missing_ok=True)continueholders.append(lease)@@ -148,10 +186,16 @@ def drop_dead_leases(records: Path) -> None:the browser died while its holder crashed."""for path in records.glob("*.lease"):lease = _load(path)- if lease is not None and not process_alive(lease.get("holder_pid"), lease.get("holder_start_time")):+ if lease is not None and _holder_gone(lease):path.unlink(missing_ok=True)+def successor(holders: list[dict]) -> Optional[dict]:+ """The live holder a record can be handed to: one in this namespace (a pid from another one names nobody+ here, so a record handed there could never be stopped nor reaped from here)."""+ return next((h for h in holders if same_namespace(h)), None)++def hand_over(record: Path, data: dict, holder: dict) -> None:"""Make ``holder`` the record's owner: every reaper now sees a live owner, and the holder stops thebrowser when it is the last one out."""