Skip to content

The agent that grows with you

fix(agent): a managed worker dies with its owner, descendants included

Teknium9434884ca3f6
diff --git a/agent/managed_worker.py b/agent/managed_worker.py
index f67bd2bfce7..2a4ca05702f 100644
--- a/agent/managed_worker.py
+++ b/agent/managed_worker.py
@@ -133,6 +133,22 @@ class WorkerChannel:
_INTERRUPTED = object()
+# The owner's control pipe closing under a live worker means the owner died (a closing owner
+# signals the worker itself). The agent is interrupted at once; cooperative tools get this long.
+ORPHAN_GRACE_SECONDS = 10
+
+
+def _die_with_owner():
+ """Then end this worker and, on POSIX, every descendant still in its process group: the owner
+ spawns it as a group leader (``start_new_session``). Tools that open their own session (the
+ terminal tool, background processes meant to outlive the turn) are not in it. Never a group
+ this process does not lead."""
+ def kill():
+ if os.name != 'nt' and os.getpgrp() == os.getpid():
+ import signal
+ os.killpg(os.getpid(), signal.SIGKILL) # windows-footgun: ok — POSIX only
+ os._exit(1)
+ threading.Timer(ORPHAN_GRACE_SECONDS, kill).start()
class WorkerControls:
@@ -180,9 +196,11 @@ class WorkerControls:
if state is not None:
state['answer'] = frame['value']
state['event'].set()
- except (EOFError, OSError, ValueError):
+ except (EOFError, OSError, ValueError) as exc:
self.stop()
self.finish.set()
+ if not isinstance(exc, ValueError):
+ _die_with_owner()
def approval(self, data):
from tools.approval import ack_gateway_approval
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.py
index a57de933db8..e34a837f257 100644
--- a/gateway/session_managed_worker.py
+++ b/gateway/session_managed_worker.py
@@ -23,6 +23,9 @@ HELLO_SECONDS = 60
# After Stop the child interrupts its agent and emits its result; the owner terminates a
# child that has not acknowledged within this window instead of waiting on the pipe forever.
STOP_ACK_SECONDS = 30
+# Own session (POSIX): a worker whose owner died kills its whole group (managed_worker
+# _die_with_owner); on Windows it exits itself.
+WORKER_POPEN = {'start_new_session': True, 'close_fds': True}
class ManagedExecutionUnknown(RuntimeError):
@@ -439,7 +442,7 @@ async def execute_managed(authority, ref, row, policy):
log_path = worker_log_path(authority.profile_id)
process = await acquire_process(subprocess.Popen, [sys.executable, '-m', 'agent.managed_worker'],
cwd=cwd, stdin=subprocess.PIPE, env=env, stdout=subprocess.PIPE,
- stderr=subprocess.DEVNULL if log_path is None else subprocess.PIPE, close_fds=True)
+ stderr=subprocess.DEVNULL if log_path is None else subprocess.PIPE, **WORKER_POPEN)
except asyncio.CancelledError:
# acquire_process owns late-child cleanup; no bootstrap or reservation was sent.
return _interrupted_before_bootstrap(authority, row)
diff --git a/tests/gateway/test_managed_worker_parent_death.py b/tests/gateway/test_managed_worker_parent_death.py
new file mode 100644
index 00000000000..9ad2aaf686f
--- /dev/null
+++ b/tests/gateway/test_managed_worker_parent_death.py
@@ -0,0 +1,77 @@
+"""A managed worker dies with its owner, descendants included, even when its turn ignores the
+interrupt (andrexibiza 29 / P3.g). The owner spawns it in its own session; the owner's death
+closes the control pipe, and the worker hard-kills its process group after a short grace."""
+import contextlib
+import os
+from pathlib import Path
+import signal
+import subprocess
+import sys
+import textwrap
+import time
+
+import psutil
+import pytest
+
+ROOT = Path(__file__).resolve().parents[2]
+
+# A worker past bootstrap whose agent ignores interrupt and whose turn blocks forever in a tool
+# that has started a descendant (the real WorkerControls reads the owner's pipe).
+WORKER = textwrap.dedent('''
+ import subprocess, sys, threading, time
+ import agent.managed_worker as mw
+ mw.ORPHAN_GRACE_SECONDS = 1
+ grandchild = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)'])
+ print(grandchild.pid, flush=True)
+ controls = mw.WorkerControls(channel=None, route='r')
+ controls.agent = type('Stubborn', (), {'interrupt': lambda self, *a, **k: None})()
+ while True:
+ time.sleep(1)
+''')
+
+# The owner side: the real spawn options, then it is killed without any cleanup.
+OWNER = textwrap.dedent('''
+ import subprocess, sys
+ from gateway.session_managed_worker import WORKER_POPEN
+ worker = subprocess.Popen([sys.executable, '-c', sys.argv[1]], stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, **WORKER_POPEN)
+ print(worker.pid, worker.stdout.readline().decode().strip(), flush=True)
+ worker.wait()
+''')
+
+
+def _gone(pid, timeout):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ try:
+ if psutil.Process(pid).status() == psutil.STATUS_ZOMBIE:
+ return True
+ except psutil.NoSuchProcess:
+ return True
+ time.sleep(.1)
+ return False
+
+
[email protected]("linux", "macos")
[email protected]_system_guard_bypass # cleanup may signal our own descendants after init adopted them
+def test_worker_and_its_descendants_die_when_the_owner_is_killed():
+ env = {**os.environ, 'PYTHONPATH': str(ROOT)}
+ owner = subprocess.Popen([sys.executable, '-c', OWNER, WORKER], cwd=ROOT, env=env,
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
+ worker_pid = grandchild_pid = None
+ try:
+ worker_pid, grandchild_pid = map(int, owner.stdout.readline().split())
+ assert os.getpgid(worker_pid) == worker_pid # its own session, not the owner's group
+ owner.kill()
+ owner.wait(timeout=5)
+ assert _gone(worker_pid, 15), 'the orphaned worker outlived its owner'
+ assert _gone(grandchild_pid, 5), "the worker's descendant outlived it"
+ finally:
+ owner.stdout.close()
+ if owner.poll() is None:
+ owner.kill()
+ owner.wait(timeout=5)
+ for pid in (worker_pid, grandchild_pid):
+ if pid is not None and not _gone(pid, 0):
+ with contextlib.suppress(ProcessLookupError):
+ os.kill(pid, signal.SIGKILL) # windows-footgun: ok — POSIX-only test