Files
hermes-agent/tools/process_registry_ownership.py
kshitijk4poor 755a280ff0 fix(processes): a background job dies with the Hermes process that started it (orphans_after_10s 3 -> 0); persist_on_release jobs still outlive it
Symptom: ProcessRegistry.spawn_local starts every terminal(background=true) job in its own session, and
the agent-lifecycle sweeps that stop jobs (kill_all on release, agent_close, a turn timeout) only run
while the owner is alive. A CLI, TUI or worker that is SIGKILLed / OOM-killed / crashes left every job
running on init. Measured on Linux (tbg_probe, kill -9 the owner, check at +10 s, 2/2 runs): pipe job
1/1 alive, pipe job with a child 2/2 alive. A PTY job's hangup stops only jobs that keep the default
SIGHUP action: a HUP-ignoring PTY job (`nohup`'d server, trap '' HUP) and its child 2/2 alive.

Change (tools/process_registry_ownership.py, a new ProcessRegistry mixin; process_registry.py is at its
size cap and shrinks by 10 lines): a local background job's process group goes to the owner-death
supervisor (process_identity layer 4) for as long as the job's own process runs: pipe jobs start through spawn_owned
(purpose="terminal-background", recorded in the spawn ledger), PTY jobs hand their pty.fork group to
own_process_groups. The group is released when the job leaves _running (exit, kill, reconcile) and by
_reap_untracked after a failed setup, so a job's deliberate `server &` survivors keep today's
behaviour once the job ends. A foreground command that yields to background (adopt_local) hands its
supervised group to the job instead of releasing it.

Deliberately NOT owned (they must outlive the owner):
- persist_on_release jobs (#41225, ec5c9c738a): the user asked for them to outlive the agent.
- every job of a gateway (a host that ran recover_from_checkpoint, or a supervised gateway): it
  re-adopts the jobs a crashed predecessor left running, so its own jobs must survive its crash the
  same way. Its clean shutdown still kills them (kill_all(source="gateway_shutdown")).
- Windows: the layer-3 job object covers ownership; the spawn path there is unchanged.
The systemd-scope, TERM->KILL tree kill, start-time PID-reuse guards and post-kill survivor checks stay:
they cover a live owner.

Result: same probe, 3/3 runs: pipe 0/1, pipe+child 0/2, HUP-ignoring PTY job + child 0/2 alive; the
persist_on_release job 1/1 alive (as intended). tests/tools/test_terminal_owned_jobs.py now also covers
jobs: kill -9 owner vs live control owner (jobs + PTY job + command die, persist_on_release job lives,
control untouched), a recovering host's jobs outlive its kill -9, finished job releases, yielded
command keeps its group until the job ends, unowned jobs never reach the supervisor. 5/5 green x3, 5/5
red on the pre-change code, each red on its own mutation (8 mutations). Two existing tests build
sessions by hand or fake Popen + os.killpg; they now carry the new field / stub the supervisor.
_reap_untracked moves into the mixin unchanged apart from the release.
2026-10-29 16:58:09 +05:30

83 lines
4.6 KiB
Python

"""Which local background jobs die with their owner, for ProcessRegistry (process_identity layer 4)."""
import subprocess
import threading
from contextlib import suppress
from typing import Any
from hermes_cli.process_identity import own_process_groups, release_process_groups, spawn_owned
class ProcessOwnershipMixin:
"""A local job's process group goes to the owner-death supervisor while the job's own process runs,
so it dies with this process however this process dies (SIGKILL, OOM, crash): the agent-lifecycle
sweeps only run while we are alive, and a killed CLI/TUI/worker left every job running on init.
``ProcessSession._owned_pgid`` is that group, cleared by the one release so a recycled pgid is
never unregistered on someone else's behalf. The subclass supplies ``_terminate_host_pid``."""
# Set by recover_from_checkpoint: this host re-adopts the jobs a crashed predecessor left
# running, so its own jobs must outlive its crash the same way (see _owns_job).
_jobs_outlive_host = False
_owned_pgid_lock = threading.Lock()
def _owns_job(self, persist_on_release: bool) -> bool:
"""Not owned, on purpose: ``persist_on_release`` jobs, which must outlive the agent (#41225);
every job of a gateway, which re-adopts its jobs from the checkpoint after a crash (flagged by
recover_from_checkpoint; a supervised gateway also before it gets there); and Windows, where
the layer-3 job object covers ownership."""
from tools.process_registry import _IS_WINDOWS, _is_supervised_gateway_process
return not (_IS_WINDOWS or persist_on_release or self._jobs_outlive_host
or _is_supervised_gateway_process())
def _spawn_job(self, session: Any, argv: list[str], persist_on_release: bool, **popen_kwargs) -> subprocess.Popen:
"""Start a pipe job in its own session, owned unless ``_owns_job`` says it must outlive us."""
if self._owns_job(persist_on_release):
proc = spawn_owned(argv, purpose="terminal-background", **popen_kwargs)
session._owned_pgid = proc.pid
return proc
# noqa: subprocess-stdin — a forwarder: spawn_local passes stdin=DEVNULL in popen_kwargs
return subprocess.Popen(argv, start_new_session=True, **popen_kwargs) # detached-spawn: ok — see _owns_job
def _own_pty_job(self, session: Any, pty_proc: Any) -> None:
"""The PTY child leads its own session and group (pty.fork). Its hangup reaches only jobs that
keep the default SIGHUP action; `nohup`/trap-HUP servers outlived a killed owner."""
if self._owns_job(session.persist_on_release):
own_process_groups([pty_proc.pid])
session._owned_pgid = pty_proc.pid
def _take_handoff_group(self, session: Any, proc: subprocess.Popen) -> None:
"""A foreground command that yields to background hands its supervised group over with the
pipe (LocalEnvironment._run_bash): the job keeps it, unless jobs here must outlive us."""
owned_pgid, proc._hermes_owned_pgid = getattr(proc, "_hermes_owned_pgid", None), None
if owned_pgid is not None and self._owns_job(False):
session._owned_pgid = owned_pgid
elif owned_pgid is not None:
release_process_groups([owned_pgid])
def _release_job_group(self, session: Any) -> None:
"""The job's own process exited or was killed: stop covering its group. What it left behind on
purpose (`server &`) is no longer this job's, exactly as before."""
with self._owned_pgid_lock:
owned_pgid, session._owned_pgid = session._owned_pgid, None
if owned_pgid is not None:
release_process_groups([owned_pgid])
def _reap_untracked(self, session: Any, proc: subprocess.Popen) -> None:
"""Post-Popen setup failed: kill the orphaned subprocess (and any setsid
descendants) so nothing leaks untracked."""
from tools.process_registry import _stop_systemd_unit
with suppress(Exception):
if session.systemd_unit:
# Scope teardown is the authoritative cleanup for the worker cgroup;
# the systemd-run wrapper PID is terminated below as fallback.
_stop_systemd_unit(session.systemd_unit)
# _terminate_host_pid revalidates the kernel start time captured at
# spawn before signalling: pgid == pid would only prove the pid leads a
# group, and a reaped child can be recycled onto an unrelated leader.
self._terminate_host_pid(proc.pid, session.host_start_time)
with suppress(Exception):
proc.wait(timeout=5)
self._release_job_group(session)