Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 137 additions & 1 deletion tests/tools/test_browser_cleanup.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Regression tests for browser session cleanup and screenshot recovery."""

from unittest.mock import patch
from unittest.mock import MagicMock, patch


class TestScreenshotPathRecovery:
Expand Down Expand Up @@ -138,3 +138,139 @@ def test_emergency_cleanup_clears_all_tracking_state(self):
assert browser_tool._session_last_activity == {}
assert browser_tool._recording_sessions == set()
assert browser_tool._cleanup_done is True


def _fake_chrome_proc(pid, cmdline, parent_name=None):
"""Build a psutil.Process stand-in for the orphan-chrome scanner.

``parent_name=None`` models a browser whose daemon died (psutil returns
``None`` once the parent is gone / reparented past a subreaper); a string
models a live parent with that process name.
"""
proc = MagicMock()
proc.pid = pid
proc.info = {"pid": pid, "cmdline": cmdline}
if parent_name is None:
proc.parent.return_value = None
else:
parent = MagicMock()
parent.name.return_value = parent_name
proc.parent.return_value = parent
return proc


class TestOrphanedChromeReaper:
"""Regression for Chromium orphaned by an abnormal daemon death.

When the agent-browser daemon dies without shutting Chromium down (OOM
kill / crash / SIGKILL — the common failure mode on memory-starved
hosts), the browser tree is reparented to init and every existing
cleanup path goes blind:

* ``_cleanup_single_browser_session`` kills via the *daemon* PID's
child tree — ``_terminate_host_pid`` returns silently when that PID
is already dead — then removes the socket dir, destroying the only
pid breadcrumb;
* ``_reap_orphaned_browser_sessions`` only globs daemon socket dirs
(``agent-browser-h_*``/``cdp_*``/``hermes_*``), never the browser's
``agent-browser-chrome-*`` user-data dir.

Verified live: SIGKILL the daemon after a successful navigate and the
full Chromium tree (12+ processes) survives session cleanup
indefinitely. The contract: the periodic sweep must tree-kill any main
Chromium process carrying an ``agent-browser-chrome-*`` user-data dir
whose parent is no longer a live agent-browser daemon, and must leave
daemon-owned browsers and unrelated Chrome installs alone.
"""

ORPHAN_CMDLINE = [
"/opt/chromium/chrome",
"--headless=new",
"--user-data-dir=/tmp/agent-browser-chrome-abc123",
"--no-sandbox",
]

def test_orphaned_main_chrome_is_reaped(self):
from tools import browser_tool

orphan = _fake_chrome_proc(4242, self.ORPHAN_CMDLINE, parent_name=None)

with (
patch("psutil.process_iter", return_value=[orphan]),
patch(
"tools.process_registry.ProcessRegistry._terminate_host_pid"
) as mock_kill,
patch("tools.browser_tool.shutil.rmtree") as mock_rmtree,
):
reaped = browser_tool._reap_orphaned_chrome_processes()

assert reaped == 1
mock_kill.assert_called_once_with(4242)
mock_rmtree.assert_called_once_with(
"/tmp/agent-browser-chrome-abc123", ignore_errors=True
)

def test_daemon_owned_chrome_is_left_alone(self):
"""A browser whose parent is a live agent-browser daemon is in use."""
from tools import browser_tool

owned = _fake_chrome_proc(
4243, self.ORPHAN_CMDLINE, parent_name="agent-browser-l"
)

with (
patch("psutil.process_iter", return_value=[owned]),
patch(
"tools.process_registry.ProcessRegistry._terminate_host_pid"
) as mock_kill,
):
reaped = browser_tool._reap_orphaned_chrome_processes()

assert reaped == 0
mock_kill.assert_not_called()

def test_helper_and_unrelated_processes_are_skipped(self):
"""--type= helpers die with the main tree; foreign Chromes are not ours."""
from tools import browser_tool

helper = _fake_chrome_proc(
4244,
self.ORPHAN_CMDLINE + ["--type=renderer"],
parent_name=None,
)
foreign = _fake_chrome_proc(
4245,
["/usr/bin/google-chrome", "--user-data-dir=/home/u/.config/chrome"],
parent_name=None,
)
no_cmdline = _fake_chrome_proc(4246, [], parent_name=None)

with (
patch("psutil.process_iter", return_value=[helper, foreign, no_cmdline]),
patch(
"tools.process_registry.ProcessRegistry._terminate_host_pid"
) as mock_kill,
):
reaped = browser_tool._reap_orphaned_chrome_processes()

assert reaped == 0
mock_kill.assert_not_called()

def test_orphan_reap_runs_chrome_sweep_even_without_socket_dirs(self):
"""The sweep must not be short-circuited by the empty-socket-dir return.

An orphaned browser leaves NO socket dir behind (the daemon's dir is
removed by session cleanup), so the sweep has to run precisely when
the socket-dir scan finds nothing.
"""
from tools import browser_tool

with (
patch("glob.glob", return_value=[]),
patch(
"tools.browser_tool._reap_orphaned_chrome_processes"
) as mock_sweep,
):
browser_tool._reap_orphaned_browser_sessions()

mock_sweep.assert_called_once_with()
109 changes: 109 additions & 0 deletions tools/browser_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -1703,6 +1703,9 @@ def _reap_orphaned_browser_sessions():
socket_dirs += glob.glob(os.path.join(tmpdir, "agent-browser-hermes_*"))

if not socket_dirs:
# No daemon socket dirs — but Chromium orphaned by an abnormal
# daemon death leaves no socket dir behind, so sweep for it anyway.
_reap_orphaned_chrome_processes()
return

# Build set of session_names currently tracked by this process (fallback path)
Expand Down Expand Up @@ -1793,6 +1796,106 @@ def _reap_orphaned_browser_sessions():
if reaped:
logger.info("Reaped %d orphaned browser session(s) from previous run(s)", reaped)

# Daemons reaped above take their Chromium children with them (live
# PPID tree walk). Chromium whose daemon died on its own has no
# surviving pid breadcrumb — sweep for it by cmdline signature.
_reap_orphaned_chrome_processes()


def _find_orphaned_chrome_processes() -> List[tuple]:
"""Find Chromium main processes whose agent-browser daemon is gone.

agent-browser launches Chromium with
``--user-data-dir=<tmp>/agent-browser-chrome-<uuid>``. When the daemon
dies without shutting the browser down (OOM kill, crash, SIGKILL —
common on memory-starved hosts), the browser is cut loose and keeps
running: on POSIX it reparents to init (or a subreaper), on Windows its
PPID is invalidated. Nothing else can find it after that:

* the socket-dir reaper above only globs ``agent-browser-h_*`` /
``cdp_*`` / ``hermes_*`` dirs, and the daemon's pid file dies with
the socket dir;
* ``_cleanup_single_browser_session`` kills by walking the *daemon*
PID's child tree — ``_terminate_host_pid`` returns silently when
that PID is already dead, so the browser tree is never touched.

This is the same class of leak as the Windows-only reaper proposed in
#43577, but it is *not* Windows-specific: the "POSIX SIGTERM cascade
handles it" assumption only holds while a live process walks the tree,
which is exactly what an abnormally-killed daemon cannot do (reproduced
on Linux — a SIGKILLed daemon leaves its whole Chromium tree behind).
Detection is therefore done cross-platform via ``psutil`` (already a
hard dependency) rather than a per-OS process query.

The ``--user-data-dir`` basename is the one durable signature that
survives the daemon: only agent-browser-spawned Chromium carries it.
A Chromium whose parent is a live agent-browser daemon is in use and
is skipped; one whose parent is dead or foreign is unreachable garbage.

Returns ``(psutil.Process, user_data_dir)`` tuples for main browser
processes only — the ``--type=renderer/gpu/...`` helpers are children
of the main process and die with its tree kill.
"""
import psutil

orphans = []
for proc in psutil.process_iter(attrs=["pid", "cmdline"]):
try:
cmdline = proc.info.get("cmdline") or []
user_data_dir = None
is_helper = False
for arg in cmdline:
if arg.startswith("--user-data-dir="):
path = arg[len("--user-data-dir="):]
if os.path.basename(path).startswith("agent-browser-chrome-"):
user_data_dir = path
elif arg.startswith("--type="):
is_helper = True
if user_data_dir is None or is_helper:
continue
parent = proc.parent()
if parent is not None and "agent-browser" in (parent.name() or ""):
continue # daemon alive and owning this browser — not an orphan
orphans.append((proc, user_data_dir))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This appends any process with the matching argument unless its immediate parent name contains agent-browser. Current main requires both process identity and binding to a specific session before a tree kill (_verify_reapable_browser_daemon), because predictable temporary-path state otherwise permits same-user arbitrary-process DoS. Please require durable evidence that this profile/process belongs to a known dead Hermes daemon, and add a negative test for a matching command line without that association.

except (psutil.NoSuchProcess, psutil.AccessDenied, OSError):
continue
return orphans


def _reap_orphaned_chrome_processes() -> int:
"""Tree-kill Chromium instances left behind by dead agent-browser daemons.

Runs on every cleanup-thread tick (and from the startup/atexit orphan
reap) so an abnormal daemon death is repaired within one
``BROWSER_SESSION_INACTIVITY_TIMEOUT`` window instead of leaking
browser processes until reboot. Safe to call from any context; never
raises.
"""
try:
orphans = _find_orphaned_chrome_processes()
except Exception as e:
logger.debug("Orphaned-Chromium scan failed: %s", e)
return 0

reaped = 0
for proc, user_data_dir in orphans:
try:
from tools.process_registry import ProcessRegistry
ProcessRegistry._terminate_host_pid(proc.pid)
logger.info(
"Reaped orphaned Chromium PID %d (agent-browser daemon gone, "
"user-data-dir %s)", proc.pid, user_data_dir,
)
reaped += 1
except Exception as e:
logger.warning("Could not reap orphaned Chromium PID %d: %s",
proc.pid, e)
continue
# The profile dir is garbage once its browser is dead; removing it
# also keeps this sweep idempotent on hosts where rmtree races.
shutil.rmtree(user_data_dir, ignore_errors=True)
return reaped


def _browser_cleanup_thread_worker():
"""
Expand All @@ -1814,6 +1917,12 @@ def _browser_cleanup_thread_worker():
except Exception as e:
logger.warning("Cleanup thread error: %s", e)

# Sweep Chromium orphaned by an abnormal daemon death (OOM kill,
# crash). Session-level cleanup above can't reach these: with the
# daemon PID dead, its kill path is a silent no-op and the socket
# dir (with the only pid breadcrumb) gets removed.
_reap_orphaned_chrome_processes()

# Sleep in 1-second intervals so we can stop quickly if needed
for _ in range(30):
if not _cleanup_running:
Expand Down