AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(mcp): preserve cancellation and clean up descendant groups (#1166)
Ilia Alshanetsky137186e51738
diff --git a/changelog.d/+cr-012-mcp-timeout-pipes.fixed.md b/changelog.d/+cr-012-mcp-timeout-pipes.fixed.mdnew file mode 100644index 00000000..c336f8ae--- /dev/null+++ b/changelog.d/+cr-012-mcp-timeout-pipes.fixed.md@@ -0,0 +1 @@+Bound MCP output-pipe draining after engine shutdown so detached helpers cannot delay timeout responses indefinitely. Canceled and timed-out requests now report their context error even when the engine's signal handler exits successfully, and requests canceled before startup do not launch the engine.diff --git a/changelog.d/+mcp-orphan-cleanup.fixed.md b/changelog.d/+mcp-orphan-cleanup.fixed.mdnew file mode 100644index 00000000..5906a0b8--- /dev/null+++ b/changelog.d/+mcp-orphan-cleanup.fixed.md@@ -0,0 +1 @@+On POSIX systems, MCP timeouts now terminate descendant processes (X search, YouTube/transcript, Digg helpers) instead of leaving them orphaned and running after the engine is killed. Per-source timeouts also stop helpers whose parent exits before them.diff --git a/mcp/internal/engine/proc_group_unix.go b/mcp/internal/engine/proc_group_unix.gonew file mode 100644index 00000000..9a614825--- /dev/null+++ b/mcp/internal/engine/proc_group_unix.go@@ -0,0 +1,39 @@+//go:build !windows++package engine++import (+ "os/exec"+ "syscall"+)++// setProcessGroup puts the engine child in its own process group so a+// timeout kill reaches same-group grandchildren (grok CLI). Descendants+// spawned via lib/subproc.py run in their own pgids (os.setsid) and are+// unreachable by kill(-pid); they die via the engine's SIGTERM handler,+// which killpg()s each registered child group. Mirrors lib/subproc.py's+// os.setsid discipline.+func setProcessGroup(cmd *exec.Cmd) {+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}+}++// termProcessGroup SIGTERMs the whole engine process group (negative pid =+// group). This runs the python SIGTERM handler, which cleans the setsid'd+// descendant groups before the SIGKILL backstop. Errors are ignored: the+// group may already be gone when the deadline fires.+func termProcessGroup(cmd *exec.Cmd) {+ if cmd.Process == nil {+ return+ }+ _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)+}++// killProcessGroup SIGKILLs the whole engine process group (negative pid =+// group). ESRCH and other errors are intentionally ignored: the group may+// already be gone when the deadline fires.+func killProcessGroup(cmd *exec.Cmd) {+ if cmd.Process == nil {+ return+ }+ _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)+}diff --git a/mcp/internal/engine/proc_group_unix_test.go b/mcp/internal/engine/proc_group_unix_test.gonew file mode 100644index 00000000..66504f8e--- /dev/null+++ b/mcp/internal/engine/proc_group_unix_test.go@@ -0,0 +1,296 @@+//go:build !windows++package engine++import (+ "context"+ "errors"+ "os"+ "os/exec"+ "os/signal"+ "path/filepath"+ "strconv"+ "strings"+ "syscall"+ "testing"+ "time"+)++func TestRunParentCancellationIsNotSuccess(t *testing.T) {+ dir := t.TempDir()+ ready := filepath.Join(dir, "ready")+ stub := filepath.Join(dir, "python3-cancel-stub.sh")+ script := `#!/bin/sh+trap 'printf "canceled cleanly\n" >&2; exit 0' TERM+printf 'partial research\n'+: > "$RUN_CANCEL_READY"+while :; do sleep 1; done+`+ if err := os.WriteFile(stub, []byte(script), 0o755); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ readyCh := make(chan error, 1)+ go func() {+ deadline := time.NewTimer(3 * time.Second)+ defer deadline.Stop()+ tick := time.NewTicker(10 * time.Millisecond)+ defer tick.Stop()+ for {+ select {+ case <-tick.C:+ if _, err := os.Stat(ready); err == nil {+ readyCh <- nil+ cancel()+ return+ }+ case <-deadline.C:+ readyCh <- errors.New("child did not install its SIGTERM handler")+ cancel()+ return+ }+ }+ }()++ started := time.Now()+ res, err := Run(ctx, RunOptions{+ PythonPath: stub,+ CacheDir: stageCache(t),+ Timeout: 10 * time.Second,+ ExtraEnv: []string{"RUN_CANCEL_READY=" + ready},+ })+ if readyErr := <-readyCh; readyErr != nil {+ t.Fatal(readyErr)+ }+ if time.Since(started) > 4*time.Second {+ t.Error("parent cancellation exceeded the bounded shutdown grace")+ }+ if !errors.Is(err, context.Canceled) {+ t.Errorf("Run error = %v, want context.Canceled after clean child exit", err)+ }+ if res == nil {+ t.Fatal("Run result is nil; want partial output alongside cancellation")+ }+ if res.ExitCode != 0 || res.TimedOut {+ t.Errorf("Run result = %+v, want clean exit without timeout", res)+ }+ if string(res.Stdout) != "partial research\n" || !strings.Contains(string(res.Stderr), "canceled cleanly") {+ t.Errorf("partial output lost: stdout=%q stderr=%q", res.Stdout, res.Stderr)+ }+}++func TestRunTimeoutBoundsInheritedPipes(t *testing.T) {+ executable, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ for _, mode := range []string{"signal-exit", "clean-exit", "clean-exit-without-child", "term-ignoring-in-group"} {+ t.Run(mode, func(t *testing.T) {+ dir := t.TempDir()+ pidFile := filepath.Join(dir, "detached.pid")+ stub := filepath.Join(dir, "python3-detached-stub.sh")+ if err := os.WriteFile(stub, []byte("#!/bin/sh\nexec \"$CR012_TEST_BINARY\" -test.run='^TestRunDetachedPipeHelper$'\n"), 0o755); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ if raw, err := os.ReadFile(pidFile); err == nil {+ if pid, err := strconv.Atoi(string(raw)); err == nil && pid > 0 {+ _ = syscall.Kill(pid, syscall.SIGKILL)+ }+ }+ })++ started := time.Now()+ res, err := Run(context.Background(), RunOptions{+ PythonPath: stub,+ CacheDir: stageCache(t),+ Timeout: 200 * time.Millisecond,+ ExtraEnv: []string{+ "CR012_TEST_BINARY=" + executable,+ "CR012_HELPER_MODE=" + mode,+ "CR012_PID_FILE=" + pidFile,+ },+ })+ elapsed := time.Since(started)+ if elapsed > 4*time.Second {+ t.Errorf("Run took %s for a 200ms timeout; detached pipes must not outlive the bounded shutdown grace", elapsed)+ }+ if err == nil || !strings.Contains(err.Error(), "timeout") {+ t.Errorf("Run error = %v, want timeout", err)+ }+ if res == nil || !res.TimedOut {+ t.Fatalf("Run result = %+v, want TimedOut", res)+ }+ if mode != "clean-exit-without-child" && (!strings.Contains(string(res.Stdout), "detached stdout") || !strings.Contains(string(res.Stderr), "detached stderr")) {+ t.Fatalf("detached process did not inherit both pipes: stdout=%q stderr=%q", res.Stdout, res.Stderr)+ }+ if mode == "term-ignoring-in-group" {+ assertPidDead(t, pidFile, "TERM-ignoring in-group grandchild")+ }+ })+ }+}++func TestRunDetachedPipeHelper(t *testing.T) {+ mode := os.Getenv("CR012_HELPER_MODE")+ if mode == "" {+ t.Skip("subprocess fixture")+ }+ if mode == "pipe-holder" || mode == "pipe-holder-ignore-term" {+ if mode == "pipe-holder-ignore-term" {+ signal.Ignore(syscall.SIGTERM)+ }+ _, _ = os.Stdout.WriteString("detached stdout\n")+ _, _ = os.Stderr.WriteString("detached stderr\n")+ time.Sleep(8 * time.Second)+ os.Exit(0)+ }+ if mode == "clean-exit" || mode == "clean-exit-without-child" {+ terminated := make(chan os.Signal, 1)+ signal.Notify(terminated, syscall.SIGTERM)+ go func() {+ <-terminated+ os.Exit(0)+ }()+ }+ if mode == "clean-exit-without-child" {+ time.Sleep(8 * time.Second)+ os.Exit(0)+ }+ child := exec.Command(os.Args[0], "-test.run=^TestRunDetachedPipeHelper$")+ if mode == "term-ignoring-in-group" {+ child.Env = append(os.Environ(), "CR012_HELPER_MODE=pipe-holder-ignore-term")+ } else {+ child.Env = append(os.Environ(), "CR012_HELPER_MODE=pipe-holder")+ child.SysProcAttr = &syscall.SysProcAttr{Setsid: true}+ }+ child.Stdout = os.Stdout+ child.Stderr = os.Stderr+ if err := child.Start(); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(os.Getenv("CR012_PID_FILE"), []byte(strconv.Itoa(child.Process.Pid)), 0o600); err != nil {+ _ = child.Process.Kill()+ t.Fatal(err)+ }+ time.Sleep(8 * time.Second)+ os.Exit(0)+}++// TestSetProcessGroupSetsSetpgid guards the CR-013 fix: the engine child+// must lead its own process group so a timeout kill reaches grandchildren+// (node bird-search, yt-dlp, grok CLI) instead of SIGKILLing only the+// direct python child while its atexit SIGTERM cleanup never runs.+func TestSetProcessGroupSetsSetpgid(t *testing.T) {+ cmd := exec.Command("true")+ setProcessGroup(cmd)+ if cmd.SysProcAttr == nil {+ t.Fatal("SysProcAttr is nil; want Setpgid process-group attribute")+ }+ if !cmd.SysProcAttr.Setpgid {+ t.Fatal("SysProcAttr.Setpgid = false, want true")+ }+}++// TestRunTimeoutKillsGrandchild exercises the group-kill path end to end:+// a stub interpreter spawns a background sleep grandchild, Run hits its+// deadline, and the grandchild must be dead afterwards. With the old+// exec.CommandContext behavior only the direct child died and the+// grandchild kept running.+func TestRunTimeoutKillsGrandchild(t *testing.T) {+ dir := t.TempDir()+ stub := filepath.Join(dir, "python3-group-stub.sh")+ inGroupPid := filepath.Join(dir, "grandchild.pid")+ setsidPid := filepath.Join(dir, "setsid-grandchild.pid")+ script := `#!/usr/bin/env bash+# Grandchildren redirect their fds away from the stub's stdout/stderr:+# otherwise a surviving orphan holds Go's exec pipe open and cmd.Wait()+# blocks until the orphan exits, masking the leak as a slow pass.+sleep 30 >/dev/null 2>&1 &+echo -n "$!" > "` + inGroupPid + `"+# True shape of the engine's descendants: lib/subproc.py spawns every+# child with os.setsid, so node bird-search / yt-dlp / digg each lead+# their own pgid that kill(-enginepid) can never reach. Only the+# engine's SIGTERM handler (killpg per registered child) kills them —+# modeled here by the trap, mirroring last30days._on_sigterm.+setsid sleep 30 >/dev/null 2>&1 &+SIDPID=$!+echo -n "$SIDPID" > "` + setsidPid + `"+trap 'kill -TERM "$SIDPID" 2>/dev/null; exit 143' TERM+sleep 30+`+ if err := os.WriteFile(stub, []byte(script), 0o755); err != nil {+ t.Fatalf("write stub: %v", err)+ }+ cache := stageCache(t)++ res, err := Run(context.Background(), RunOptions{+ PythonPath: stub,+ CacheDir: cache,+ Timeout: 500 * time.Millisecond,+ })+ if err == nil {+ t.Fatal("expected timeout error")+ }+ if !res.TimedOut {+ t.Fatal("TimedOut = false, want true")+ }++ assertPidDead(t, inGroupPid, "in-group grandchild")+ assertPidDead(t, setsidPid, "setsid grandchild")+}++// TestTermProcessGroupSendsSigterm checks the first phase of the deadline+// path directly: a process in its own group must exit promptly after+// termProcessGroup (no SIGKILL backstop involved).+func TestTermProcessGroupSendsSigterm(t *testing.T) {+ cmd := exec.Command("sleep", "30")+ setProcessGroup(cmd)+ if err := cmd.Start(); err != nil {+ t.Fatalf("start sleep: %v", err)+ }+ termProcessGroup(cmd)+ done := make(chan error, 1)+ go func() { done <- cmd.Wait() }()+ select {+ case <-done:+ case <-time.After(5 * time.Second):+ killProcessGroup(cmd)+ <-done+ t.Fatal("process survived SIGTERM group kill; SIGKILL backstop fired")+ }+}++// assertPidDead reads a pid from pidFile and polls until no process with+// that pid exists. A SIGKILL-only deadline path leaves the setsid+// grandchild alive (its pgid differs), so this fails without the+// SIGTERM-first discipline.+func assertPidDead(t *testing.T, pidFile, what string) {+ t.Helper()+ raw, readErr := os.ReadFile(pidFile)+ if readErr != nil {+ t.Fatalf("%s pid file missing: %v", what, readErr)+ }+ pid, convErr := strconv.Atoi(strings.TrimSpace(string(raw)))+ if convErr != nil || pid <= 0 {+ t.Fatalf("bad %s pid %q: %v", what, raw, convErr)+ }++ // Signal delivery is async; poll for the process to disappear.+ deadline := time.Now().Add(5 * time.Second)+ for {+ if kerr := syscall.Kill(pid, 0); kerr != nil {+ if !errors.Is(kerr, syscall.ESRCH) {+ t.Logf("kill(pid, 0) = %v; treating as dead", kerr)+ }+ return+ }+ if time.Now().After(deadline) {+ // Best-effort cleanup so a regression does not leak sleeps.+ _ = syscall.Kill(pid, syscall.SIGKILL)+ t.Fatalf("%s pid %d still alive 5s after timeout; group kill failed", what, pid)+ }+ time.Sleep(20 * time.Millisecond)+ }+}diff --git a/mcp/internal/engine/proc_group_windows.go b/mcp/internal/engine/proc_group_windows.gonew file mode 100644index 00000000..7c9ce332--- /dev/null+++ b/mcp/internal/engine/proc_group_windows.go@@ -0,0 +1,33 @@+//go:build windows++package engine++import (+ "os/exec"+)++// setProcessGroup is a no-op on Windows: syscall.SysProcAttr has no Setpgid+// field and process groups are a POSIX concept. The timeout path falls back+// to killing the direct child.+func setProcessGroup(cmd *exec.Cmd) {+}++// killProcessGroup kills only the direct child on Windows. TerminateProcess+// does not run Python signal or atexit handlers, so descendant cleanup is+// not guaranteed on this platform.+func killProcessGroup(cmd *exec.Cmd) {+ if cmd.Process == nil {+ return+ }+ _ = cmd.Process.Kill()+}++// termProcessGroup kills the direct child on Windows: there is no+// SIGTERM equivalent, so the TERM and KILL phases collapse into the same+// action and the grace wait in Run is skipped on prompt exit.+func termProcessGroup(cmd *exec.Cmd) {+ if cmd.Process == nil {+ return+ }+ _ = cmd.Process.Kill()+}diff --git a/mcp/internal/engine/run.go b/mcp/internal/engine/run.goindex 2b7b865f..5f635c70 100644--- a/mcp/internal/engine/run.go+++ b/mcp/internal/engine/run.go@@ -36,6 +36,15 @@ const DefaultTimeout = 5 * time.Minute// (seconds, integer). Honored by Run when RunOptions.Timeout is zero.const TimeoutEnvOverride = "LAST30DAYS_MCP_TIMEOUT"+// termGracePeriod bounds the SIGTERM phase of the deadline path: the+// python SIGTERM handler needs a moment to killpg() the setsid'd+// descendant groups before the SIGKILL backstop fires.+const termGracePeriod = 2 * time.Second++// pipeGracePeriod bounds output draining after the engine exits even if+// an unregistered detached descendant still holds its output pipes.+const pipeGracePeriod = time.Second+// PythonEnvOverride lets operators select the Python 3.12+ executable used// by the MCP server. When unset, Run preserves the python3 PATH lookup.const PythonEnvOverride = "LAST30DAYS_PYTHON"@@ -88,19 +97,71 @@ func Run(ctx context.Context, opts RunOptions) (*RunResult, error) {defer cancel()args := append([]string{scriptPath}, opts.Args...)- cmd := exec.CommandContext(subCtx, pythonPath, args...)+ cmd := exec.Command(pythonPath, args...)cmd.Env = buildEnv(opts.CacheDir, opts.ExtraEnv)+ cmd.WaitDelay = pipeGracePeriod+ // Own process group so a timeout SIGTERM reaches same-group+ // grandchildren (grok CLI). exec.CommandContext would SIGKILL only the+ // direct python child while its SIGTERM-handler/atexit cleanup never+ // runs on SIGKILL, orphaning the setsid'd descendant groups.+ // Mirrors lib/subproc.py.+ setProcessGroup(cmd)var stdout, stderr bytes.Buffercmd.Stdout = &stdoutcmd.Stderr = &stderr- err = cmd.Run()+ if err := subCtx.Err(); err != nil {+ return &RunResult{+ ExitCode: -1,+ TimedOut: errors.Is(err, context.DeadlineExceeded),+ }, fmt.Errorf("engine: subprocess not started: %w", err)+ }+ if err := cmd.Start(); err != nil {+ res := &RunResult{+ Stdout: stdout.Bytes(),+ Stderr: stderr.Bytes(),+ ExitCode: 0,+ TimedOut: errors.Is(subCtx.Err(), context.DeadlineExceeded),+ }+ return res, fmt.Errorf("engine: subprocess failed to start: %w", err)+ }+ waitCh := make(chan error, 1)+ go func() { waitCh <- cmd.Wait() }()++ select {+ case <-subCtx.Done():+ // Deadline or parent cancel: SIGTERM the group first so the+ // python SIGTERM handler killpg()s the setsid'd descendant+ // groups (node, yt-dlp, digg) that kill(-pid) cannot reach,+ // then SIGKILL stragglers that ignore TERM. Then reap.+ termProcessGroup(cmd)+ select {+ case err = <-waitCh:+ killProcessGroup(cmd)+ case <-time.After(termGracePeriod):+ killProcessGroup(cmd)+ err = <-waitCh+ }+ case werr := <-waitCh:+ err = werr+ }++ ctxErr := subCtx.Err()res := &RunResult{Stdout: stdout.Bytes(),Stderr: stderr.Bytes(),ExitCode: 0,- TimedOut: errors.Is(subCtx.Err(), context.DeadlineExceeded),+ TimedOut: errors.Is(ctxErr, context.DeadlineExceeded),+ }+ if cmd.ProcessState != nil {+ res.ExitCode = cmd.ProcessState.ExitCode()+ }+ if res.TimedOut {+ return res, fmt.Errorf("engine: subprocess exceeded %s timeout: %w", timeout, ctxErr)+ }+ if ctxErr != nil {+ return res, fmt.Errorf("engine: subprocess canceled: %w", ctxErr)}if err == nil {return res, nil@@ -108,13 +169,9 @@ func Run(ctx context.Context, opts RunOptions) (*RunResult, error) {var exitErr *exec.ExitErrorif errors.As(err, &exitErr) {- res.ExitCode = exitErr.ExitCode()- if res.TimedOut {- return res, fmt.Errorf("engine: subprocess exceeded %s timeout", timeout)- }return res, fmt.Errorf("engine: subprocess exited with code %d", res.ExitCode)}- return res, fmt.Errorf("engine: subprocess failed to start: %w", err)+ return res, fmt.Errorf("engine: subprocess failed: %w", err)}// resolvePython returns a resolved interpreter path or a clear error. Adiff --git a/mcp/internal/engine/run_test.go b/mcp/internal/engine/run_test.goindex af3771b9..d9b08484 100644--- a/mcp/internal/engine/run_test.go+++ b/mcp/internal/engine/run_test.go@@ -247,6 +247,39 @@ func TestRunTimesOut(t *testing.T) {if !strings.Contains(err.Error(), "timeout") {t.Fatalf("error %q lacks 'timeout' marker", err)}+ if !errors.Is(err, context.DeadlineExceeded) {+ t.Fatalf("Run error = %v, want context.DeadlineExceeded", err)+ }+}++func TestRunCanceledBeforeStart(t *testing.T) {+ for _, wantErr := range []error{context.Canceled, context.DeadlineExceeded} {+ t.Run(wantErr.Error(), func(t *testing.T) {+ expired := wantErr == context.DeadlineExceeded+ ctx, cancel := context.WithCancel(context.Background())+ if expired {+ cancel()+ ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(-time.Second))+ }+ cancel()+ cache := stageCache(t)+ // A missing executable exposes an attempted start even when a+ // valid child would be killed before it could write output.+ res, err := Run(ctx, RunOptions{+ PythonPath: filepath.Join(cache, "must-not-start"),+ CacheDir: cache,+ })+ if !errors.Is(err, wantErr) {+ t.Errorf("Run error = %v, want %v", err, wantErr)+ }+ if res == nil {+ t.Fatal("Run result is nil; want a canceled result")+ }+ if res.TimedOut != expired || res.ExitCode != -1 || len(res.Stdout) != 0 {+ t.Errorf("Run result = %+v, want no started subprocess and TimedOut=%v", res, expired)+ }+ })+ }}func TestResolvePythonHonorsEnvOverride(t *testing.T) {diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex fbf80edd..73391e44 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -15,7 +15,6 @@ import reimport signalimport sqlite3import sys-import threadingfrom collections.abc import Callablefrom pathlib import Path@@ -51,36 +50,33 @@ if os.name == "nt":SCRIPT_DIR = Path(__file__).parent.resolve()sys.path.insert(0, str(SCRIPT_DIR))-from lib import competitors as competitors_mod, corpus, dates, discovery_handoff, env, freshness, html_render, http, permission_preflight, pipeline, reddit, registers, render, schema, ui, x_envelope+from lib import competitors as competitors_mod, corpus, dates, discovery_handoff, env, freshness, html_render, http, permission_preflight, pipeline, reddit, registers, render, schema, subproc, ui, x_envelope-_child_pids: set[int] = set()-_child_pids_lock = threading.Lock()+atexit.register(subproc.cleanup_children)-def register_child_pid(pid: int) -> None:- with _child_pids_lock:- _child_pids.add(pid)+def _on_sigterm(signum, frame) -> None:+ """SIGTERM handler: clean descendant groups, then die as SIGTERM.--def unregister_child_pid(pid: int) -> None:- with _child_pids_lock:- _child_pids.discard(pid)---def _cleanup_children() -> None:- with _child_pids_lock:- pids = list(_child_pids)- for pid in pids:- try:- if hasattr(os, "killpg"):- os.killpg(os.getpgid(pid), signal.SIGTERM)- else:- os.kill(pid, signal.SIGTERM)- except (ProcessLookupError, PermissionError, OSError):- continue+ Every run_with_timeout child runs in its own pgid (lib/subproc.py via+ os.setsid), so a group kill aimed at the engine can never reach them;+ only the lib.subproc registry can. atexit never runs on a signal death,+ so without this handler an MCP timeout would orphan node bird-search,+ yt-dlp, and the digg CLI. The MCP server SIGTERMs the engine group+ first, giving this handler room to killpg() each registered child+ group before the SIGKILL backstop. Restoring the default disposition+ and re-raising preserves killed-by-SIGTERM semantics for the parent.+ """+ subproc.cleanup_children()+ signal.signal(signal.SIGTERM, signal.SIG_DFL)+ os.kill(os.getpid(), signal.SIGTERM)-atexit.register(_cleanup_children)+def _install_sigterm_handler() -> None:+ try:+ signal.signal(signal.SIGTERM, _on_sigterm)+ except (ValueError, OSError, RuntimeError):+ passdef parse_meta_ads_page(raw: str) -> str:@@ -4343,4 +4339,5 @@ def _main(if __name__ == "__main__":+ _install_sigterm_handler()raise SystemExit(main())diff --git a/skills/last30days/scripts/lib/bird_x.py b/skills/last30days/scripts/lib/bird_x.pyindex ca0361b9..67ce8102 100644--- a/skills/last30days/scripts/lib/bird_x.py+++ b/skills/last30days/scripts/lib/bird_x.py@@ -345,34 +345,16 @@ def _invoke_bird_subprocess(query: str, count: int, timeout: int):"--json",]- pid_holder: list[int] = []-- def _register(pid: int) -> None:- pid_holder.append(pid)- try:- from last30days import register_child_pid- register_child_pid(pid)- except ImportError:- pass-try:result = subproc.run_with_timeout(cmd,timeout=timeout,env=_subprocess_env(),- on_pid=_register,)except subproc.SubprocTimeout:return None, {"error": f"Search timed out after {timeout}s", "items": []}except Exception as e:return None, {"error": str(e), "items": []}- finally:- if pid_holder:- try:- from last30days import unregister_child_pid- unregister_child_pid(pid_holder[0])- except Exception:- passreturn result, Nonediff --git a/skills/last30days/scripts/lib/subproc.py b/skills/last30days/scripts/lib/subproc.pyindex c2971cdb..0716f1f4 100644--- a/skills/last30days/scripts/lib/subproc.py+++ b/skills/last30days/scripts/lib/subproc.py@@ -10,6 +10,8 @@ from __future__ import annotationsimport osimport signalimport subprocess+import threading+import timefrom dataclasses import dataclassfrom typing import Optional, Sequence@@ -18,6 +20,96 @@ class SubprocTimeout(Exception):"""Raised when a subprocess exceeds its timeout and is killed."""+# Live run_with_timeout children, process-wide. Each child is a session+# leader (os.setsid), so a group kill aimed at the engine never reaches it;+# the engine's SIGTERM handler and atexit hook drain this set instead. It+# lives here, not in last30days.py, because the entrypoint runs as+# __main__: importing it by name from lib/ executes a second module copy+# with its own empty registry, and on a worker thread that copy cannot+# install its signal handler either. RLock because cleanup_children runs+# inside a signal handler on the main thread, which may already hold the+# lock in register_child_pid.+_child_pids: set[int] = set()+_child_pids_lock = threading.RLock()+# Set once cleanup_children starts. Worker threads keep running while the+# handler sleeps through the grace, so a source can spawn a child after the+# snapshot; register_child_pid kills such late children itself.+_shutting_down = False+++def register_child_pid(pid: int) -> None:+ with _child_pids_lock:+ _child_pids.add(pid)+ late = _shutting_down+ if late:+ _kill_child_group(pid, getattr(signal, "SIGKILL", signal.SIGTERM))+++def unregister_child_pid(pid: int) -> None:+ with _child_pids_lock:+ _child_pids.discard(pid)+++# Upper bound on how long cleanup_children waits for SIGTERMed groups before+# SIGKILLing them. It runs inside the engine's SIGTERM handler, so it must+# finish well inside the MCP server's termGracePeriod+# (mcp/internal/engine/run.go), after which the engine group is SIGKILLed and+# the handler never reaches the escalation. Pinned by tests/test_subproc.py.+CLEANUP_TERM_GRACE_SECONDS = 0.8+_CLEANUP_POLL_SECONDS = 0.05+++def _signal_group(pgid: int, sig: int) -> bool:+ """Signal a child's process group; False once the group has no members."""+ try:+ os.killpg(pgid, sig)+ except (ProcessLookupError, PermissionError, OSError):+ return False+ return True+++def _kill_child_group(pid: int, sig: int) -> None:+ if hasattr(os, "setsid") and hasattr(os, "killpg"):+ _signal_group(pid, sig)+ return+ try:+ os.kill(pid, sig)+ except (ProcessLookupError, PermissionError, OSError):+ pass+++def cleanup_children(grace: float = CLEANUP_TERM_GRACE_SECONDS) -> None:+ """Terminate the process group of every registered child.++ SIGTERM every group, wait up to ``grace`` seconds for the groups to+ empty, then SIGKILL the survivors. run_with_timeout starts each child+ with os.setsid, so the child's pid is its pgid; signalling the pgid+ directly still reaches grandchildren after the leader has been reaped,+ and the kernel does not reuse a pid while a group of that id has+ members. A group whose only member is an unreaped zombie still reads as+ live, which at worst costs the full grace and a harmless SIGKILL.+ Children registered after this call starts are SIGKILLed as they+ register, since the caller is about to exit.+ """+ global _shutting_down+ with _child_pids_lock:+ _shutting_down = True+ pids = list(_child_pids)+ if not pids:+ return+ if not (hasattr(os, "setsid") and hasattr(os, "killpg")):+ for pid in pids:+ _kill_child_group(pid, signal.SIGTERM)+ return+ live = [pgid for pgid in pids if _signal_group(pgid, signal.SIGTERM)]+ deadline = time.monotonic() + grace+ while live and time.monotonic() < deadline:+ time.sleep(_CLEANUP_POLL_SECONDS)+ live = [pgid for pgid in live if _signal_group(pgid, 0)]+ for pgid in live:+ _signal_group(pgid, signal.SIGKILL)++@dataclassclass SubprocResult:"""Result of a subprocess run that captured stdout and stderr."""@@ -47,8 +139,8 @@ def run_with_timeout(timeout: Timeout in seconds passed to ``communicate()``.env: Optional environment dict. If None, inherits parent env.on_pid: Optional callable invoked with the child PID right after- spawn. Used by bird_x.py to register child PIDs for cleanup- tracking. Exceptions raised by the callback are suppressed.+ spawn. Exceptions raised by the callback are suppressed. The+ child is registered for cleanup_children() regardless.Returns:SubprocResult with returncode, stdout, and stderr as strings.@@ -77,37 +169,50 @@ def run_with_timeout(except Exception:pass+ register_child_pid(proc.pid)try:- stdout, stderr = proc.communicate(timeout=timeout)- except subprocess.TimeoutExpired:try:- if hasattr(os, "killpg") and hasattr(os, "getpgid"):- os.killpg(os.getpgid(proc.pid), signal.SIGTERM)- else:- proc.kill()- except (ProcessLookupError, PermissionError, OSError, AttributeError):- proc.kill()- try:- proc.wait(timeout=5)+ stdout, stderr = proc.communicate(timeout=timeout)except subprocess.TimeoutExpired:- # Child ignored SIGTERM (or our killpg lost the race); escalate.- # Guard killpg/getpgid the same way the SIGTERM path above does:- # they are POSIX-only and raise AttributeError on Windows. The- # primary path was hardened in #552; this mirrors that guard on the- # escalation path (added later in #433) so the same crash can't- # re-surface here (#588).+ term_deadline = time.monotonic() + 5+ pgid = Nonetry:- if hasattr(os, "killpg") and hasattr(os, "getpgid"):- os.killpg(os.getpgid(proc.pid), signal.SIGKILL)+ if preexec is not None and hasattr(os, "killpg"):+ pgid = proc.pid+ os.killpg(pgid, signal.SIGTERM)else:proc.kill()except (ProcessLookupError, PermissionError, OSError, AttributeError):+ pgid = Noneproc.kill()try:proc.wait(timeout=5)except subprocess.TimeoutExpired:- pass # process unkillable (e.g. D-state); leave as zombie- raise SubprocTimeout(f"Command {cmd[0]} timed out after {timeout}s")+ # Child ignored SIGTERM (or our killpg lost the race); escalate.+ try:+ if pgid is not None:+ os.killpg(pgid, signal.SIGKILL)+ else:+ proc.kill()+ except (ProcessLookupError, PermissionError, OSError, AttributeError):+ proc.kill()+ try:+ proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ pass # process unkillable (e.g. D-state); leave as zombie+ else:+ if pgid is not None:+ # Reaping the leader does not end its process group. Keep+ # the remaining members inside the original TERM grace.+ while _signal_group(pgid, 0):+ remaining = term_deadline - time.monotonic()+ if remaining <= 0:+ _signal_group(pgid, signal.SIGKILL)+ break+ time.sleep(min(_CLEANUP_POLL_SECONDS, remaining))+ raise SubprocTimeout(f"Command {cmd[0]} timed out after {timeout}s")+ finally:+ unregister_child_pid(proc.pid)return SubprocResult(returncode=proc.returncode,diff --git a/tests/test_subproc.py b/tests/test_subproc.pyindex 16f372bc..9f2d603a 100644--- a/tests/test_subproc.py+++ b/tests/test_subproc.py@@ -36,6 +36,9 @@ def get_shell_cmd(cmd_str: str) -> list[str]:class TestRunWithTimeout(unittest.TestCase):+ def setUp(self):+ self.addCleanup(setattr, subproc, "_shutting_down", False)+def test_success_returns_stdout(self):result = subproc.run_with_timeout(get_shell_cmd("echo hello"),@@ -76,6 +79,74 @@ class TestRunWithTimeout(unittest.TestCase):timeout=1,)+ @unittest.skipIf(IS_WINDOWS, "process groups are POSIX-only")+ def test_timeout_kills_grandchild_after_leader_exits(self):+ import pathlib+ import signal+ import sys+ import tempfile+ import time++ child = """+import os, pathlib, signal, sys, time+if sys.argv[2] == "ignore":+ signal.signal(signal.SIGTERM, signal.SIG_IGN)+pathlib.Path(sys.argv[1]).write_text(str(os.getpid()))+time.sleep(15)+"""+ leader = """+import signal, subprocess, sys, time+signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))+subprocess.Popen([sys.executable, "-c", *sys.argv[1:]],+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+time.sleep(15)+"""++ def running(pid):+ try:+ real_os.kill(pid, 0)+ if sys.platform.startswith("linux"):+ state = pathlib.Path(f"/proc/{pid}/stat").read_text().rpartition(") ")[2].split()[0]+ return state != "Z"+ return True+ except (ProcessLookupError, FileNotFoundError):+ return False++ for mode in ("default", "ignore"):+ with self.subTest(term_handler=mode), tempfile.TemporaryDirectory() as tmp:+ pidfile = pathlib.Path(tmp, "grandchild.pid")++ def wait_ready(pid):+ deadline = time.monotonic() + 3+ while time.monotonic() < deadline:+ if pidfile.exists() and pidfile.stat().st_size:+ return+ time.sleep(0.01)++ try:+ started = time.monotonic()+ with self.assertRaises(subproc.SubprocTimeout):+ subproc.run_with_timeout(+ [sys.executable, "-c", leader, child, str(pidfile), mode],+ timeout=0.1,+ on_pid=wait_ready,+ )+ self.assertLess(time.monotonic() - started, 9)+ pid = int(pidfile.read_text())+ deadline = time.monotonic() + 1+ while running(pid) and time.monotonic() < deadline:+ time.sleep(0.01)+ self.assertFalse(running(pid), "grandchild survived the leader's clean TERM exit")+ self.assertEqual(subproc._child_pids, set())+ finally:+ if pidfile.exists() and pidfile.stat().st_size:+ pid = int(pidfile.read_text())+ if running(pid):+ try:+ real_os.kill(pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+def test_missing_command_raises_oserror(self):"""Missing executables raise FileNotFoundError (or PermissionError onsome filesystems if a same-named junk file exists)."""@@ -112,6 +183,170 @@ class TestRunWithTimeout(unittest.TestCase):self.assertIsInstance(seen_pids[0], int)self.assertGreater(seen_pids[0], 0)+ def test_child_pid_registered_during_run_and_cleared_after(self):+ """Every run_with_timeout child is in the cleanup registry while alive."""+ seen = []+ with patch.object(+ subproc, "register_child_pid", wraps=subproc.register_child_pid+ ) as reg, patch.object(+ subproc, "unregister_child_pid", wraps=subproc.unregister_child_pid+ ) as unreg:+ result = subproc.run_with_timeout(+ get_shell_cmd("echo ok"),+ timeout=5,+ on_pid=seen.append,+ )+ self.assertEqual(result.stdout.strip(), "ok")+ reg.assert_called_once_with(seen[0])+ unreg.assert_called_once_with(seen[0])+ self.assertEqual(subproc._child_pids, set())++ def test_timed_out_child_is_unregistered(self):+ with self.assertRaises(subproc.SubprocTimeout):+ subproc.run_with_timeout(get_shell_cmd("sleep 10"), timeout=1)+ self.assertEqual(subproc._child_pids, set())++ @unittest.skipIf(IS_WINDOWS, "process groups are POSIX-only")+ def test_cleanup_children_kills_group_spawned_on_worker_thread(self):+ """Pipeline sources spawn on ThreadPoolExecutor workers; the main-thread+ SIGTERM handler must see those children in the same registry and kill+ the whole setsid group, grandchildren included."""+ import tempfile+ import threading+ import time++ outcome = {}+ with tempfile.TemporaryDirectory() as tmp:+ pidfile = real_os.path.join(tmp, "grandchild.pid")++ def worker():+ try:+ subproc.run_with_timeout(+ ["sh", "-c", f"sleep 30 & echo $! > {pidfile}; wait"],+ timeout=20,+ on_pid=lambda pid: outcome.update(pid=pid),+ )+ outcome["error"] = None+ except Exception as exc:+ outcome["error"] = exc++ thread = threading.Thread(target=worker)+ start = time.monotonic()+ thread.start()+ deadline = start + 5+ while time.monotonic() < deadline and not (+ real_os.path.exists(pidfile) and real_os.path.getsize(pidfile)+ ):+ time.sleep(0.01)+ self.assertTrue(real_os.path.getsize(pidfile))+ self.assertIn(outcome["pid"], subproc._child_pids)++ subproc.cleanup_children()+ thread.join(10)++ # The backgrounded sleep inherits the stdout pipe, so communicate()+ # returns well before the 20s timeout only if the grandchild died too.+ self.assertFalse(thread.is_alive())+ self.assertLess(time.monotonic() - start, 10)+ self.assertIsNone(outcome["error"])+ self.assertEqual(subproc._child_pids, set())++ @unittest.skipIf(IS_WINDOWS, "process groups are POSIX-only")+ def test_cleanup_children_sigkills_term_ignoring_group(self):+ """Engine SIGTERM cannot fall through to run_with_timeout's own SIGKILL+ escalation, so cleanup_children must escalate a group whose leader and+ grandchild both ignore SIGTERM."""+ import tempfile+ import threading+ import time++ outcome = {}+ with tempfile.TemporaryDirectory() as tmp:+ pidfile = real_os.path.join(tmp, "grandchild.pid")++ def worker():+ try:+ outcome["result"] = subproc.run_with_timeout(+ ["sh", "-c", f"trap '' TERM; sleep 30 & echo $! > {pidfile}; wait"],+ timeout=20,+ )+ except Exception as exc:+ outcome["error"] = exc++ thread = threading.Thread(target=worker)+ thread.start()+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline and not (+ real_os.path.exists(pidfile) and real_os.path.getsize(pidfile)+ ):+ time.sleep(0.01)+ self.assertTrue(real_os.path.getsize(pidfile))++ start = time.monotonic()+ subproc.cleanup_children(grace=0.3)+ elapsed = time.monotonic() - start+ thread.join(5)++ self.assertGreaterEqual(elapsed, 0.3)+ self.assertLess(elapsed, 1.0)+ self.assertFalse(thread.is_alive())+ self.assertNotIn("error", outcome)+ self.assertEqual(outcome["result"].returncode, -9)+ self.assertEqual(subproc._child_pids, set())++ @unittest.skipIf(IS_WINDOWS, "process groups are POSIX-only")+ def test_child_registered_after_cleanup_started_is_killed(self):+ """Workers keep running while the handler waits out the grace; a child+ spawned after the snapshot must not outlive the engine."""+ import time++ subproc._shutting_down = True+ start = time.monotonic()+ result = subproc.run_with_timeout(get_shell_cmd("sleep 10"), timeout=5)+ self.assertEqual(result.returncode, -9)+ self.assertLess(time.monotonic() - start, 2)+ self.assertEqual(subproc._child_pids, set())++ def test_cleanup_children_returns_immediately_when_registry_empty(self):+ import time++ self.assertEqual(subproc._child_pids, set())+ start = time.monotonic()+ subproc.cleanup_children()+ self.assertLess(time.monotonic() - start, 0.05)++ def test_cleanup_grace_fits_inside_mcp_term_grace(self):+ """The engine's SIGTERM handler runs cleanup_children; the MCP server+ SIGKILLs the engine termGracePeriod after its SIGTERM. Keep at least+ half of that window as margin for the SIGKILL pass and handler exit."""+ import pathlib+ import re++ run_go = pathlib.Path(__file__).resolve().parents[1] / "mcp" / "internal" / "engine" / "run.go"+ match = re.search(+ r"^const termGracePeriod = (\d+) \* time\.Second$",+ run_go.read_text(encoding="utf-8"),+ re.M,+ )+ self.assertIsNotNone(match, "termGracePeriod declaration not found in run.go")+ self.assertLessEqual(subproc.CLEANUP_TERM_GRACE_SECONDS * 2, int(match.group(1)))++ def test_lib_never_imports_engine_entrypoint(self):+ """last30days.py runs as __main__; importing it by name from lib/+ executes a second copy whose state (child registry, signal handler)+ the running engine never sees."""+ import pathlib+ import re++ lib_dir = pathlib.Path(subproc.__file__).parent+ pattern = re.compile(r"^\s*(from\s+last30days\s+import|import\s+last30days\b)", re.M)+ offenders = [+ str(path.relative_to(lib_dir))+ for path in lib_dir.rglob("*.py")+ if pattern.search(path.read_text(encoding="utf-8", errors="replace"))+ ]+ self.assertEqual(offenders, [])+def test_timeout_falls_back_to_kill_when_killpg_unavailable(self):"""Simulate Windows (no killpg/getpgid) — should fall back to proc.kill()."""real_hasattr = builtins.hasattr