The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(metrics): hermes.process.exit from per-process markers and turn watchdogs
teknium1040dc77490e9
diff --git a/agent/turn_facade_lease.py b/agent/turn_facade_lease.pyindex 3a2432f384a..b0f13e308cb 100644--- a/agent/turn_facade_lease.py+++ b/agent/turn_facade_lease.py@@ -75,6 +75,8 @@ class DurableTurnLease:# Stamp the activity clock at turn entry: `_last_activity_ts` persists across turns, so# without this the watchdog would measure idle from the PREVIOUS turn and abort a fresh one.self.agent._touch_activity("starting new turn")+ from hermes_cli.observability.shared_metrics_process import arm_turn+ arm_turn(self.agent)from agent.periodic_scheduler import scheduleself.timer_handles.append(schedule(self.refresh_tick, self.refresh_interval))diff --git a/agent/turn_liveness.py b/agent/turn_liveness.pyindex 7b0562815dd..db5da80f429 100644--- a/agent/turn_liveness.py+++ b/agent/turn_liveness.py@@ -139,6 +139,8 @@ class TurnLivenessWatchdog:# Stop renewing the lease so a wedge the interrupt cannot unwind expires via TTL.self._deactivate_turn()self._surface_committed_abort(snapshot)+ from hermes_cli.observability.shared_metrics_process import record_watchdog_turn_abort+ record_watchdog_turn_abort(self._agent)return Falsedef _sample(self) -> Optional[ActivitySnapshot]:diff --git a/gateway/run.py b/gateway/run.pyindex b7f5b1c58f5..1fc53559a3b 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -2728,6 +2728,8 @@ def _abandon_timed_out_gateway_turn(request_hard_interrupt(agent, _INTERRUPT_REASON_TIMEOUT, tool_reason=_INTERRUPT_TOOL_REASON_TIMEOUT)except Exception:logger.debug("Timed-out agent interrupt failed", exc_info=True)+ from hermes_cli.observability.shared_metrics_process import record_watchdog_turn_abort+ record_watchdog_turn_abort(agent)try:_reap_gateway_turn_processes(diff --git a/gateway/shutdown_watchdog.py b/gateway/shutdown_watchdog.pyindex db156237428..1aa1379f49b 100644--- a/gateway/shutdown_watchdog.py+++ b/gateway/shutdown_watchdog.py@@ -163,6 +163,9 @@ def _mark_exited_quietly(exit_code: int, reason: str) -> None:with contextlib.suppress(Exception):from gateway.lifecycle_ledger import mark_exitedmark_exited(exit_code, reason=reason)+ with contextlib.suppress(Exception): # os._exit skips atexit: stamp the exit-metrics marker now+ from hermes_cli.observability.shared_metrics_process import stamp_exit+ stamp_exit("watchdog")with contextlib.suppress(Exception):from gateway.status import write_runtime_status# Only the supervisor-restart code asserts a restart; other codes leave the recordeddiff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex 6dbf6b7e884..4b86caa0c4b 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -300,6 +300,9 @@ def _job_warnings(job: Dict[str, Any]) -> List[str]:def cron_tick():"""Run due jobs once and exit."""from cron.scheduler import CronTickYielded, tick+ from hermes_cli.observability.shared_metrics_process import begin_process++ begin_process("cron")try:tick(verbose=True)except CronTickYielded as exc:diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 98da16e74ef..342eb138eb3 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -4592,6 +4592,7 @@ def run_gateway(verbose: int = 0, quiet: bool = False, replace: bool = False, fo_guard_existing_gateway_process_conflict(replace=replace)sys.path.insert(0, str(PROJECT_ROOT))_apply_startup_watchdog_config()+ from hermes_cli.observability.shared_metrics_process import begin_process; begin_process("gateway")# Detached Windows runs (HERMES_GATEWAY_DETACHED=1, or non-TTY for older wrappers) ignore# console-control broadcasts from sibling CLIs; foreground runs keep Ctrl+C-to-stop.diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 8b8bd3ab8a7..1af9ca467b1 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -1884,7 +1884,9 @@ def cmd_chat(args):try:from cli import main as cli_main+ from hermes_cli.observability.shared_metrics_process import begin_process+ begin_process("cli")cli_main(**kwargs)except ValueError as e:print(f"Error: {e}")@@ -2796,6 +2798,8 @@ def cmd_dashboard(args):# (Docker/s6, CI, --no-open pipelines) fall through to start_server's# fail-closed SystemExit unchanged._maybe_setup_dashboard_auth_interactively(args)+ if _headless_backend:+ from hermes_cli.observability.shared_metrics_process import begin_process; begin_process("serve")# The in-browser Chat tab (embedded TUI over PTY/WebSocket) is always# available — desktop and dashboard both rely on `/api/ws` + `/api/pty`.diff --git a/hermes_cli/observability/shared_metrics_process.py b/hermes_cli/observability/shared_metrics_process.pynew file mode 100644index 00000000000..c0fcd27fc9c--- /dev/null+++ b/hermes_cli/observability/shared_metrics_process.py@@ -0,0 +1,220 @@+"""hermes.process.exit: how Hermes processes (and watchdog-killed turns) end.++A crash or SIGKILL cannot record itself. Each long-lived entrypoint drops a small marker under its+profile's store dir at start and restamps it on the way out (``clean``, ``crash`` + class from the+excepthook, ``watchdog`` from a hard-exit watchdog). The NEXT Hermes start in that profile reports+every marker whose owner is gone; one still ``running`` whose pid fails the canonical start-time+liveness check was killed. Reporting runs on a daemon thread so startup never waits on the Relay+runtime; a claimed-but-unreported marker (the reporter died mid-way) is reclaimed later.+"""++from __future__ import annotations++import atexit+import json+import logging+import os+import sys+import threading+from pathlib import Path+from typing import Any++logger = logging.getLogger(__name__)++MARKER_DIRNAME = "process_markers"+_REPORTING = ".reporting"+# Most specific first: ModuleNotFoundError is an ImportError, RecursionError a RuntimeError.+_CRASH_CLASSES = (+ (MemoryError, "memory_error"), (ImportError, "import_error"), (OSError, "os_error"),+ (RuntimeError, "runtime_error"),+)+_STATE: dict[str, Any] = {}+_STATE_LOCK = threading.Lock()+++def crash_class(exc: BaseException | None) -> str:+ return next((label for kind, label in _CRASH_CLASSES if isinstance(exc, kind)), "other")+++def markers_dir(home: Path) -> Path:+ return home / "telemetry" / "shared_metrics" / MARKER_DIRNAME+++def _write_marker(path: Path, record: dict[str, Any]) -> None:+ tmp = path.with_name(f".{path.name}.tmp")+ tmp.write_text(json.dumps(record), encoding="utf-8")+ os.replace(tmp, path)+++def stamp_exit(exit_kind: str, crash: str = "none") -> None:+ """Restamp this process's marker with how it is ending. Never raises; no-op when unmarked."""+ try:+ with _STATE_LOCK:+ record = _STATE.get("record")+ path = _STATE.get("path")+ if record is None or path is None or record.get("state") != "running":+ return+ record = {**record, "state": exit_kind, "crash_class": crash}+ _STATE["record"] = record+ _write_marker(path, record)+ except Exception:+ logger.debug("Process exit marker not stamped", exc_info=True)+++def _excepthook(previous: Any) -> Any:+ def hook(exc_type: type[BaseException], exc: BaseException, tb: Any) -> None:+ if not issubclass(exc_type, (KeyboardInterrupt, SystemExit)):+ stamp_exit("crash", crash_class(exc))+ previous(exc_type, exc, tb)++ return hook+++def begin_process(kind: str) -> None:+ """Mark this process as a running ``kind`` and report dead predecessors. Once per process."""+ try:+ from hermes_constants import get_hermes_home++ from .shared_metrics_update import _collection_on++ if _STATE:+ return+ _STATE["kind"] = kind # watchdog turn rows name the surface even when this home is off+ if not _collection_on():+ return+ from gateway.status import get_process_start_time++ home = get_hermes_home()+ directory = markers_dir(home)+ directory.mkdir(parents=True, exist_ok=True)+ pid = os.getpid()+ path = directory / f"{kind}-{pid}.json"+ record = {"kind": kind, "pid": pid, "start_time": get_process_start_time(pid), "state": "running"}+ with _STATE_LOCK:+ _write_marker(path, record)+ _STATE.update(path=path, record=record)+ sys.excepthook = _excepthook(sys.excepthook)+ atexit.register(stamp_exit, "clean")+ threading.Thread(+ target=_report_dead_markers, args=(home, path), name="hermes-exit-metrics", daemon=True,+ ).start()+ except Exception:+ logger.debug("Process exit marker not started", exc_info=True)+++def current_process_kind() -> str:+ return _STATE.get("kind") or "other"+++def _claimer_alive(path: Path) -> bool:+ from gateway.status import runtime_status_pid_is_live++ try:+ claimer = int(path.name.rsplit(".", 2)[-2])+ except (IndexError, ValueError):+ return False+ return runtime_status_pid_is_live({"pid": claimer})+++def _claim(path: Path) -> Path | None:+ """Rename a reportable marker so exactly one reporter owns it; None when not reportable."""+ from gateway.status import runtime_status_pid_is_live++ if path.name.endswith(_REPORTING):+ if _claimer_alive(path):+ return None+ record_path = path+ else:+ record_path = None+ try:+ record = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None+ if record_path is None and record.get("state") == "running" and runtime_status_pid_is_live(record):+ return None+ claimed = path.with_name(f"{path.name.split('.json')[0]}.json.{os.getpid()}{_REPORTING}")+ try:+ os.replace(path, claimed)+ except OSError: # a concurrent reporter won+ return None+ return claimed+++def process_exit_fields(record: dict[str, Any]) -> dict[str, str]:+ from .shared_metrics_contract import CRASH_CLASSES, PROCESS_EXIT_KINDS, PROCESS_KINDS++ state = record.get("state")+ exit_kind = "killed" if state == "running" or state not in PROCESS_EXIT_KINDS else state+ crash = record.get("crash_class") if exit_kind == "crash" else "none"+ kind = record.get("kind")+ return {+ "crash_class": crash if crash in CRASH_CLASSES else "other",+ "exit_kind": exit_kind,+ "process_kind": kind if kind in PROCESS_KINDS else "other",+ }+++def _report_dead_markers(home: Path, own: Path) -> None:+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ from . import shared_metrics_contract as contract+ from .shared_metrics_events import _emit++ token = set_hermes_home_override(home) # a thread does not inherit the profile binding+ try:+ for path in sorted(markers_dir(home).iterdir()):+ if path == own or path.name.startswith(".") or ".json" not in path.name:+ continue+ claimed = _claim(path)+ if claimed is None:+ continue+ try:+ record = json.loads(claimed.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ record = None+ if isinstance(record, dict):+ _emit(contract.PROCESS_EXIT_MARK, process_exit_fields, record=record)+ claimed.unlink(missing_ok=True)+ from .shared_metrics_update import report_pending_updates++ report_pending_updates()+ except Exception:+ logger.debug("Dead process markers not reported", exc_info=True)+ finally:+ reset_hermes_home_override(token)+++def arm_turn(agent: Any) -> None:+ """At turn entry (profile scope bound): the owning home for an off-thread watchdog abort, and+ a fresh once-per-turn latch shared by both turn watchdogs."""+ try:+ from hermes_constants import get_hermes_home++ agent._metrics_turn_home = str(get_hermes_home())+ agent._metrics_watchdog_abort_counted = False+ except Exception:+ logger.debug("Turn exit metrics not armed", exc_info=True)+++def record_watchdog_turn_abort(agent: Any) -> None:+ """One exit_kind=watchdog row per turn a watchdog killed, in the turn's own profile. Never raises."""+ try:+ home = getattr(agent, "_metrics_turn_home", None)+ # No armed turn means no known owning profile: never guess the scope.+ if not home or getattr(agent, "_metrics_watchdog_abort_counted", True):+ return+ agent._metrics_watchdog_abort_counted = True+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ from . import shared_metrics_contract as contract+ from .shared_metrics_events import _emit++ token = set_hermes_home_override(home)+ try:+ _emit(contract.PROCESS_EXIT_MARK, lambda: {+ "crash_class": "none", "exit_kind": "watchdog", "process_kind": current_process_kind(),+ })+ finally:+ reset_hermes_home_override(token)+ except Exception:+ logger.debug("Watchdog turn abort not recorded", exc_info=True)diff --git a/tests/hermes_cli/test_shared_metrics_reliability.py b/tests/hermes_cli/test_shared_metrics_reliability.pynew file mode 100644index 00000000000..dc9e1602fd9--- /dev/null+++ b/tests/hermes_cli/test_shared_metrics_reliability.py@@ -0,0 +1,173 @@+"""v4 reliability metrics: hermes.update.run / hermes.update.stage from the final update receipt,+hermes.process.exit from per-process markers and turn watchdogs."""++from __future__ import annotations++import json+import os+import subprocess+import sys+from datetime import datetime, timedelta, timezone+from types import SimpleNamespace++import pytest++from hermes_cli import update_receipt+from hermes_cli.observability import relay_shared_metrics+from hermes_cli.observability import shared_metrics_contract as contract+from hermes_cli.observability import shared_metrics_process as process_metrics+from hermes_cli.observability import shared_metrics_update as update_metrics+++def marks(tmp_path, monkeypatch):+ """Capture decision marks at the runtime boundary; collection on unless a test turns it off."""+ captured: list[tuple[str, dict]] = []+ policy = {"on": True}+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.setattr(+ "hermes_cli.config.read_raw_config_readonly",+ lambda: {"telemetry": {"shared_metrics": {"enabled": policy["on"]}}},+ )+ monkeypatch.setattr(relay_shared_metrics, "enabled", lambda: policy["on"])+ monkeypatch.setattr(relay_shared_metrics, "record_process_mark", lambda mark, data: captured.append((mark, data)))+ yield SimpleNamespace(rows=captured, policy=policy, home=tmp_path / "home")+++def _identity(monkeypatch, *shas: str) -> None:+ committed = int((datetime.now(timezone.utc) - timedelta(days=10)).timestamp())+ sequence = iter(shas)+ last = {"sha": shas[0]}++ def identity(refresh: bool = False) -> dict:+ last["sha"] = next(sequence, last["sha"])+ return {"sha": last["sha"], "short_sha": last["sha"][:8], "version": "0.1.0", "source": "git",+ "commit_date": committed}++ monkeypatch.setattr(update_receipt, "_code_identity", identity)+++def _assert_valid(rows: list[tuple[str, dict]]) -> None:+ for mark, data in rows:+ assert contract.counter_dimensions_are_valid(contract._DECISION_MARK_METRICS[mark], data), (mark, data)+++def test_failed_update_reports_the_stage_it_never_reached(marks, monkeypatch):+ _identity(monkeypatch, "a" * 40)+ update_receipt.begin_update_receipt()+ update_receipt.record_stage("plan", "success")+ update_receipt.record_stage("snapshot", "skipped")+ update_receipt.record_stage("apply", "success", mode="git")+ # The PM preparation child died: the parent finalizes with no deps mark.+ update_receipt.finalize_pending_update_receipt(1, "completion exited 1")++ runs = [data for mark, data in marks.rows if mark == contract.UPDATE_RUN_MARK]+ stages = [data for mark, data in marks.rows if mark == contract.UPDATE_STAGE_MARK]+ assert runs == [{+ "apply_mode": "git", "duration_bucket": "lt_30s", "failed_stage": "deps",+ "from_version_age_bucket": "7d_to_30d", "kind": "cli", "outcome": "failed",+ }]+ assert [(s["stage"], s["outcome"]) for s in stages] == [+ ("plan", "success"), ("snapshot", "skipped"), ("apply", "success")]+ _assert_valid(marks.rows)+++def test_pre_pull_interpreter_parks_the_receipt_and_the_next_start_reports_it_once(marks, monkeypatch):+ (marks.home / "telemetry" / "shared_metrics").mkdir(parents=True)+ _identity(monkeypatch, "a" * 40, "b" * 40) # the checkout moved under this interpreter+ update_receipt.begin_update_receipt()+ update_receipt.record_stage("plan", "success")+ update_receipt.finalize_update_receipt("failed")++ assert marks.rows == [] # nothing recorded (or imported) by the pre-pull interpreter+ parked = list(update_metrics.pending_updates_dir(marks.home).glob("*.json"))+ assert len(parked) == 1++ update_metrics.report_pending_updates()+ update_metrics.report_pending_updates()+ assert [mark for mark, _ in marks.rows].count(contract.UPDATE_RUN_MARK) == 1+ assert not parked[0].exists()+ _assert_valid(marks.rows)+++def test_disabled_collection_records_no_update_rows(marks, monkeypatch):+ marks.policy["on"] = False+ _identity(monkeypatch, "a" * 40)+ update_receipt.begin_update_receipt()+ update_receipt.record_stage("plan", "success")+ update_receipt.finalize_update_receipt("success")+ update_metrics.record_desktop_update(outcome="success", failed_stage=None, duration_ms=1, mechanism="app-installer")+ assert marks.rows == []+++def _dead_pid() -> int:+ child = subprocess.Popen([sys.executable, "-c", "pass"])+ child.wait()+ return child.pid+++def test_dead_markers_report_killed_or_crash_and_live_ones_wait(marks):+ from gateway.status import get_process_start_time++ directory = process_metrics.markers_dir(marks.home)+ directory.mkdir(parents=True)+ dead = _dead_pid()+ killed = directory / f"cli-{dead}.json"+ killed.write_text(json.dumps({"kind": "cli", "pid": dead, "start_time": None, "state": "running"}))+ crashed = directory / "tui-2.json"+ crashed.write_text(json.dumps({+ "kind": "tui", "pid": _dead_pid(), "start_time": None, "state": "crash", "crash_class": "import_error"}))+ parent = os.getppid()+ live = directory / f"gateway-{parent}.json"+ live.write_text(json.dumps({+ "kind": "gateway", "pid": parent, "start_time": get_process_start_time(parent), "state": "running"}))++ process_metrics._report_dead_markers(marks.home, directory / "self.json")+ process_metrics._report_dead_markers(marks.home, directory / "self.json")++ rows = sorted(data["exit_kind"] + ":" + data["crash_class"] + ":" + data["process_kind"] for _, data in marks.rows)+ assert rows == ["crash:import_error:tui", "killed:none:cli"]+ assert live.exists() and not killed.exists() and not crashed.exists()+ _assert_valid(marks.rows)+++def test_turn_watchdog_abort_counts_once_per_turn_in_the_turn_profile(marks, tmp_path, monkeypatch):+ agent = SimpleNamespace()+ process_metrics.record_watchdog_turn_abort(agent) # never armed: no owning profile, no row+ process_metrics.arm_turn(agent)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "other")) # the watchdog thread's ambient home+ seen: list[str] = []+ monkeypatch.setattr(relay_shared_metrics, "record_process_mark", lambda mark, data: (+ marks.rows.append((mark, data)), seen.append(str(__import__("hermes_constants").get_hermes_home()))))+ process_metrics.record_watchdog_turn_abort(agent)+ process_metrics.record_watchdog_turn_abort(agent) # the second watchdog on the same turn+ assert [data["exit_kind"] for _, data in marks.rows] == ["watchdog"]+ assert seen == [str(marks.home)]+ _assert_valid(marks.rows)+++def test_begin_process_marks_then_stamps_clean_and_crash(marks, monkeypatch):+ monkeypatch.setattr(process_metrics, "_STATE", {})+ monkeypatch.setattr(sys, "excepthook", lambda *a: None)+ monkeypatch.setattr(process_metrics.atexit, "register", lambda *a, **k: None)+ monkeypatch.setattr(process_metrics.threading, "Thread", lambda **k: SimpleNamespace(start=lambda: None))+ process_metrics.begin_process("cli")+ marker = process_metrics.markers_dir(marks.home) / f"cli-{os.getpid()}.json"+ assert json.loads(marker.read_text())["state"] == "running"+ sys.excepthook(ModuleNotFoundError, ModuleNotFoundError("x"), None)+ process_metrics.stamp_exit("clean") # atexit after a crash must not hide it+ record = json.loads(marker.read_text())+ assert (record["state"], record["crash_class"]) == ("crash", "import_error")+++def test_v3_schema_accepts_exactly_the_contract_values():+ from pathlib import Path++ import hermes_cli.observability as observability++ schema = json.loads((Path(observability.__file__).parent / "schemas/hermes.shared_metrics.v3.schema.json").read_text())+ by_name = {d["properties"]["name"]["const"]: d for d in schema["$defs"].values() if "properties" in d}+ for metric in (contract.UPDATE_RUN_METRIC, contract.UPDATE_STAGE_METRIC, contract.PROCESS_EXIT_METRIC):+ dims = by_name[metric]["properties"]["dimensions"]["properties"]+ assert {field: set(spec["enum"]) for field, spec in dims.items()} == {+ field: set(values) for field, values in contract._COUNTER_DIMENSION_VALUES[metric].items()}diff --git a/tui_gateway/entry.py b/tui_gateway/entry.pyindex 017c5bdb3da..d81f6fa7a98 100644--- a/tui_gateway/entry.py+++ b/tui_gateway/entry.py@@ -276,6 +276,9 @@ def main():logger.warning("TUI message injector did not install", exc_info=True)_close_rpc_stdin_on_exec()_install_sidecar_publisher()+ from hermes_cli.observability.shared_metrics_process import begin_process++ begin_process("tui")# One TLS authority: trust the OS store process-wide before any# outbound call resolves a CA bundle (see agent/ssl_verify.py).