From 0ca0fed9f74989b63e25286fbfa192dabd1b5a34 Mon Sep 17 00:00:00 2001 From: sausheong Date: Fri, 8 May 2026 22:08:58 +0800 Subject: [PATCH] fix(browser): reap orphaned Chromes when parent dies hard chromedp launches Chrome as detached subprocesses; on SIGKILL, OOM, or any path that bypasses our cleanup chain they reparent to PID 1 and survive indefinitely. Each launch now allocates a known harness-browser-* user-data-dir and registers it with a single detached /bin/sh watchdog spawned via Setsid. When the parent dies the watchdog detects stdin EOF and pkills + rm -rfs every still-tracked path. Clean teardown untracks the path so a later hard exit can't kill the next session sharing the process. --- tools/browser/browser.go | 18 +++++ tools/browser/reaper_other.go | 10 +++ tools/browser/reaper_unix.go | 119 ++++++++++++++++++++++++++++++++++ 3 files changed, 147 insertions(+) create mode 100644 tools/browser/reaper_other.go create mode 100644 tools/browser/reaper_unix.go diff --git a/tools/browser/browser.go b/tools/browser/browser.go index 82462c9..7db7101 100644 --- a/tools/browser/browser.go +++ b/tools/browser/browser.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "os" "strings" "sync" "time" @@ -453,7 +454,19 @@ func (t *BrowserTool) reapIdleSessions() { // launchBrowser starts a fresh Chrome and returns its task context plus a // teardown function that closes both the task and the underlying allocator. +// +// Each launch gets its own user-data-dir created up-front so the path is +// known to both Chrome (it appears in argv as --user-data-dir=…) and the +// reaper watchdog. If the parent dies hard before cleanup runs, the +// watchdog SIGKILLs any process whose argv contains that path and rm -rfs +// the dir. func launchBrowser(parent context.Context) (context.Context, context.CancelFunc, error) { + udd, err := os.MkdirTemp("", "harness-browser-") + if err != nil { + return nil, nil, fmt.Errorf("create user-data-dir: %w", err) + } + trackDirForReaping(udd) + allocCtx, allocCancel := chromedp.NewExecAllocator(parent, append(chromedp.DefaultExecAllocatorOptions[:], chromedp.NoSandbox, @@ -461,6 +474,7 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc, chromedp.UserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"), chromedp.Flag("disable-blink-features", "AutomationControlled"), chromedp.Flag("lang", "en-US"), + chromedp.UserDataDir(udd), )..., ) taskCtx, taskCancel := chromedp.NewContext(allocCtx) @@ -474,11 +488,15 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc, ); err != nil { taskCancel() allocCancel() + untrackDirForReaping(udd) + _ = os.RemoveAll(udd) return nil, nil, err } cleanup := func() { taskCancel() allocCancel() + untrackDirForReaping(udd) + _ = os.RemoveAll(udd) } return taskCtx, cleanup, nil } diff --git a/tools/browser/reaper_other.go b/tools/browser/reaper_other.go new file mode 100644 index 0000000..9d7c155 --- /dev/null +++ b/tools/browser/reaper_other.go @@ -0,0 +1,10 @@ +//go:build !unix + +package browser + +// Stubs for platforms without POSIX pkill/sh. Windows callers fall back +// to chromedp's own teardown; hard-kill orphans are a known limitation +// there until we add a native implementation (e.g. Job Objects). + +func trackDirForReaping(dir string) {} +func untrackDirForReaping(dir string) {} diff --git a/tools/browser/reaper_unix.go b/tools/browser/reaper_unix.go new file mode 100644 index 0000000..d2c9276 --- /dev/null +++ b/tools/browser/reaper_unix.go @@ -0,0 +1,119 @@ +//go:build unix + +package browser + +import ( + "fmt" + "io" + "os/exec" + "sync" + "syscall" +) + +// Why a watchdog subprocess? +// +// chromedp launches Chrome through os/exec; the resulting processes do +// not share a process group with us. On clean shutdown the alloc +// context cancel kills them. On SIGKILL / OOM / force-quit / panic that +// bypasses our cleanup chain, they reparent to PID 1 and survive +// indefinitely — each holding ~150 MB and a temp profile dir. +// +// startReaper spawns a single /bin/sh subprocess detached from our +// process group (Setsid). It accumulates user-data-dir paths from its +// stdin and, when the parent dies (stdin EOF), runs `pkill -9 -f` on +// each path and `rm -rf` the dirs. The watchdog cannot be reaped from +// outside because we never Wait on it; it exits on stdin EOF and the +// kernel cleans up. + +var ( + reaperOnce sync.Once + reaperMu sync.Mutex + reaperPipe io.WriteCloser +) + +// reaperScript reads lines from stdin. A bare path is "tracked"; a line +// of the form "REMOVE " is "untracked" (cleanly closed by us, so +// don't kill it on parent death). On EOF, kill -9 every still-tracked +// process whose argv contains the path, then rm -rf the path. +// +// Pure POSIX sh — no bash-isms. Tested on macOS /bin/sh (dash on Linux +// behaves the same). +const reaperScript = ` +paths="" +while IFS= read -r line; do + case "$line" in + "REMOVE "*) + removed="${line#REMOVE }" + new="" + for x in $paths; do + [ "$x" = "$removed" ] && continue + new="$new $x" + done + paths="$new" + ;; + *) + paths="$paths $line" + ;; + esac +done +for p in $paths; do + [ -z "$p" ] && continue + pkill -9 -f "$p" 2>/dev/null + rm -rf "$p" 2>/dev/null +done +` + +func startReaper() { + reaperOnce.Do(func() { + cmd := exec.Command("/bin/sh", "-c", reaperScript) + // Setsid detaches from our controlling terminal and process + // group, so signals to us don't propagate to the watchdog. + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} + // Discard stdout/stderr so a closed terminal can't EPIPE the + // watchdog before it runs cleanup. + cmd.Stdout = nil + cmd.Stderr = nil + stdin, err := cmd.StdinPipe() + if err != nil { + return + } + if err := cmd.Start(); err != nil { + _ = stdin.Close() + return + } + // Deliberately do not Wait — the watchdog must outlive us. + reaperPipe = stdin + }) +} + +// trackDirForReaping registers a Chrome user-data-dir with the +// watchdog. If the parent dies hard before untrackDirForReaping is +// called, the watchdog will SIGKILL any process whose argv contains +// dir and rm -rf the dir. +func trackDirForReaping(dir string) { + if dir == "" { + return + } + startReaper() + reaperMu.Lock() + defer reaperMu.Unlock() + if reaperPipe == nil { + return + } + _, _ = fmt.Fprintf(reaperPipe, "%s\n", dir) +} + +// untrackDirForReaping tells the watchdog this dir was torn down +// cleanly. Best-effort; failure is harmless (worst case the watchdog +// rm -rfs an already-empty dir on parent death). +func untrackDirForReaping(dir string) { + if dir == "" { + return + } + reaperMu.Lock() + defer reaperMu.Unlock() + if reaperPipe == nil { + return + } + _, _ = fmt.Fprintf(reaperPipe, "REMOVE %s\n", dir) +}