Files
hermes-agent/tools/process_registry_checkpoint.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

163 lines
8.7 KiB
Python

"""Running-process checkpoint persistence and PID-safe recovery."""
import json
import logging
import time
from typing import Any, Dict, List, Optional
from agent.redact import redact_sensitive_text
logger = logging.getLogger("tools.process_registry")
class ProcessCheckpointMixin:
def _detached_host_fate(self, pid: Optional[int], expected_start: Optional[int]) -> str:
"""Subclass supplies the live PID decision. See ProcessRegistry."""
raise NotImplementedError
# ----- Checkpoint (crash recovery) -----
def _write_checkpoint(self, extra_entries: Optional[list[dict[str, Any]]] = None):
"""Write running process metadata to the checkpoint file atomically."""
from tools.process_registry import _checkpoint_path, _CHECKPOINT_FIELDS
try:
with self._lock:
entries = []
for s in self._running.values():
if s.exited:
continue
# Backfill the start time so recovery can detect PID recycling
# even for sessions spawned before this field existed.
if s.host_start_time is None and s.pid_scope == "host" and s.pid:
s.host_start_time = self._safe_host_start_time(s.pid)
entry = {"session_id": s.id, **{f: getattr(s, f) for f in _CHECKPOINT_FIELDS}}
# Redact inline credentials before persisting (~/.hermes/processes.json).
# Recovery uses command only for display (adoption re-validates the
# PID, never re-runs it), so masking is lossless.
# See #77484.
entry["command"] = redact_sensitive_text(s.command, code_file=True)
entry["owner_task_id"] = s.owner_task_id or s.task_id
entries.append(entry)
if extra_entries:
tracked_ids = {item.get("session_id") for item in entries}
entries.extend(item for item in extra_entries if item.get("session_id") not in tracked_ids)
known = {*self._running, *self._finished}
from hermes_cli.active_sessions import _FileLock
from utils import atomic_json_write
path = _checkpoint_path()
# Every interpreter of the profile (owner, each managed worker) rewrites this file from
# its own table; a worker's output-log handoff is its only path to the next one, so a
# writer keeps the handoffs it does not track (read-merge-write under one file lock).
with _FileLock(path.with_name(path.name + ".lock")):
entries.extend(self._foreign_handoffs(path, known))
atomic_json_write(path, entries)
except Exception as e:
logger.debug("Failed to write checkpoint file: %s", e, exc_info=True)
def _foreign_handoffs(self, path, known) -> list[dict[str, Any]]:
"""On-disk worker handoffs this registry never tracked whose log still decides an outcome:
the process is alive (same start time) or its recorded exit is waiting to be read."""
from pathlib import Path
from tools.process_registry_output_log import _exit_path, adoptable_log
try:
on_disk = json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
return []
return [entry for entry in on_disk if isinstance(entry, dict) and entry.get("session_id") not in known
and (log := adoptable_log(entry.get("output_log"))) and Path(log).exists()
and (_exit_path(log).exists() or self._detached_host_fate(
entry.get("pid"), entry.get("host_start_time")) == "running")]
def recover_from_checkpoint(self) -> int:
"""On gateway startup, probe PIDs from the checkpoint file; returns how many
were recovered as detached sessions."""
from tools.process_registry import (
ProcessSession, _CHECKPOINT_FIELDS, _checkpoint_path,
_CHECKPOINT_DEFAULTS, _WATCHER_ROUTE_KEYS, _stop_systemd_unit,
)
from tools.process_registry_output_log import adoptable_log
# This host adopts what a crashed predecessor left running, so the jobs it starts must
# survive its own crash for the next one: they stay out of the owner-death supervisor.
self._jobs_outlive_host = True
checkpoint_path = _checkpoint_path()
if not checkpoint_path.exists():
return 0
try:
entries = json.loads(checkpoint_path.read_text(encoding="utf-8-sig"))
except Exception:
return 0
recovered = 0
unresolved_scope_entries: list[dict[str, Any]] = []
for entry in entries:
pid, pid_scope = entry.get("pid"), entry.get("pid_scope", "host")
if not pid:
continue
# The registry is process-global, so every profile's checkpoint carries every live
# process; a multiplexer recovering several homes must adopt each session once.
with self._lock:
already_tracked = entry.get("session_id") in self._running
if already_tracked:
continue
if pid_scope != "host": # in-sandbox PIDs mean nothing once the env handle is gone
logger.info(
"Skipping recovery for non-host process: %s (pid=%s, scope=%s)",
entry.get("command", "unknown")[:60], pid, pid_scope)
continue
# Alive and still ours: re-attach. A start-time probe that cannot
# be read is not proof the PID was reused — dropping it would leave
# a live child unsupervised, and marking it exited would invent a
# completion. A positive mismatch means the number was recycled:
# do not adopt it and do not signal it.
fate = self._detached_host_fate(pid, entry.get("host_start_time"))
# A worker spawn's output log and recorded exit outlive both the spawner and the PID,
# so its reader decides the outcome (a recycled PID is never signalled: fate != running).
log = adoptable_log(entry.get("output_log"))
if log:
fate = "running"
if fate == "reused":
logger.info(
"Not recovering session %s: pid %d is alive but its "
"start time no longer matches — PID was recycled onto "
"an unrelated process; refusing to adopt or signal it.",
entry.get("session_id", "?"), pid)
continue
if fate != "running":
systemd_unit = entry.get("systemd_unit", "")
if systemd_unit and not _stop_systemd_unit(systemd_unit):
logger.warning(
"Could not reap persisted scope %s for dead wrapper pid %s; "
"retaining checkpoint entry for the next startup",
systemd_unit, pid)
unresolved_scope_entries.append(entry)
continue
fields = {f: entry.get(f, _CHECKPOINT_DEFAULTS[f]) for f in _CHECKPOINT_FIELDS}
fields.update(
command=entry.get("command", "unknown"),
owner_task_id=entry.get("owner_task_id", "") or entry.get("task_id", ""),
started_at=entry.get("started_at", time.time()))
# detached: no Popen handle, but can report status + kill; a worker spawn's output log
# (and recorded exit) outlives its spawner, so tail it from the start.
fields["output_log"] = log
session = ProcessSession(id=entry["session_id"], detached=True, **fields)
if session.output_log:
self._track_started(session, self._log_reader_loop, f"proc-log-reader-{session.id}")
else:
with self._lock:
self._running[session.id] = session
recovered += 1
logger.info("Recovered detached process: %s (pid=%d)", session.command[:60], pid)
# Re-enqueue watcher so gateway can resume notifications
if session.watcher_interval > 0:
self.pending_watchers.append({
"session_id": session.id,
"check_interval": session.watcher_interval,
"session_key": session.session_key,
**{key: getattr(session, f"watcher_{key}") for key in _WATCHER_ROUTE_KEYS},
"notify_on_complete": session.notify_on_complete,
"parent_session_id": session.parent_session_id,
})
self._write_checkpoint(extra_entries=unresolved_scope_entries)
return recovered