Skip to content

The agent that grows with you

fix(telemetry): update runs counted once, parked only while opted in, recovered files kept until saved

teknium1287564fedd52
diff --git a/hermes_cli/observability/relay_shared_metrics.py b/hermes_cli/observability/relay_shared_metrics.py
index 6b2abd9b38d..3880eef80fd 100644
--- a/hermes_cli/observability/relay_shared_metrics.py
+++ b/hermes_cli/observability/relay_shared_metrics.py
@@ -7,6 +7,7 @@ import contextlib
import contextvars
import logging
import threading
+import uuid
from collections import deque
from dataclasses import dataclass, field
from time import monotonic_ns
@@ -934,6 +935,15 @@ class _Runtime:
# No flush here: the next task close or the atexit shutdown drains the subscriber.
self._with_scope_stack(self.relay.scope.event, mark, data=data, metadata=self._event_metadata())
+ def record_process_marks_saved(self, marks: list[tuple[str, dict[str, Any]]]) -> int:
+ """Emit ``marks`` and wait for the store; how many settled without a store error."""
+ ticket = uuid.uuid4().hex
+ metadata = {**self._event_metadata(), contract.COMMIT_TICKET_KEY: ticket}
+ for mark, data in marks:
+ self._with_scope_stack(self.relay.scope.event, mark, data=data, metadata=metadata)
+ self.relay.subscribers.flush()
+ return self.subscriber.take_saved(ticket)
+
def record_auxiliary_tokens(self, event: dict[str, Any]) -> None:
tokens = fields_.model_token_fields(
event.get("usage"), call_role="auxiliary", aux_task=event.get("aux_task"),
@@ -1191,6 +1201,16 @@ def record_process_mark(mark: str, data: dict[str, Any]) -> None:
runtime._safe(runtime.record_process_mark, mark, data)
+def record_process_marks_saved(marks: list[tuple[str, dict[str, Any]]]) -> int:
+ """``record_process_mark`` for facts recovered from a file the caller deletes only once they are
+ saved (a busy store would otherwise lose them for good). How many rows are settled: saved, rejected
+ by the contract, or nothing to record because collection is off."""
+ if not enabled() or not relay_runtime.relay_instrumentation_enabled():
+ return len(marks)
+ runtime = _get_runtime(retry_failed=True)
+ return (runtime._safe(runtime.record_process_marks_saved, marks) or 0) if runtime is not None else 0
+
+
def record_session_friction(signal: str, session_id: str, fallback_route: dict[str, str]) -> None:
"""Record one friction signal in the active profile's runtime (callers already checked enabled())."""
if not relay_runtime.relay_instrumentation_enabled():
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index 13f80b08ace..5e89cdff244 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -16,6 +16,9 @@ from hermes_cli.platforms import PLATFORMS
from toolsets import BUILTIN_TOOL_NAMES
SCHEMA_KEY = "hermes.metrics.schema_version"
+# A random per-emit token (no payload) on rows whose producer waits to learn they were SAVED: facts
+# recovered from a file that is deleted only then. Events persist on the Relay thread.
+COMMIT_TICKET_KEY = "hermes.shared_metrics.commit_ticket"
SCHEMA_VERSION = "hermes.metrics.event.v3"
MODEL_CALL_SCOPE = "hermes.model_call"
MODEL_CALL_PROFILE_MODEL = "unknown"
@@ -599,7 +602,7 @@ def _relay_metadata(
metadata = getattr(event, "metadata", None)
if not isinstance(metadata, dict) or metadata.get(schema_key) != schema_version:
return None
- allowed = {schema_key, RUNTIME_INSTANCE_KEY, "otel.status_code", *extra_keys}
+ allowed = {schema_key, RUNTIME_INSTANCE_KEY, COMMIT_TICKET_KEY, "otel.status_code", *extra_keys}
if set(metadata) - allowed or metadata.get("otel.status_code", "OK") not in {"OK", "ERROR"}:
return None
return metadata
diff --git a/hermes_cli/observability/shared_metrics_events.py b/hermes_cli/observability/shared_metrics_events.py
index 2b1760a1bf7..672eed613cc 100644
--- a/hermes_cli/observability/shared_metrics_events.py
+++ b/hermes_cli/observability/shared_metrics_events.py
@@ -31,6 +31,18 @@ def _emit(mark: str, build: Callable[..., dict[str, str] | None], **raw: Any) ->
logger.debug("Shared-metrics %s not recorded", mark, exc_info=True)
+def emit_saved(marks: list[tuple[str, dict[str, str]]]) -> int:
+ """``_emit`` for facts recovered from a file: how many rows are settled (saved, rejected, or
+ collection off), so the caller deletes the file only then. Blocks on the store: no hot paths."""
+ try:
+ from .relay_shared_metrics import record_process_marks_saved
+
+ return record_process_marks_saved(marks) if marks else 0
+ except Exception:
+ logger.debug("Shared-metrics recovered rows not recorded", exc_info=True)
+ return 0
+
+
def record_setup_completed(*, surface: str, provider: str | None) -> None:
_emit(contract.SETUP_COMPLETED_MARK, fields_.setup_completed_fields, surface=surface, provider=provider)
diff --git a/hermes_cli/observability/shared_metrics_process.py b/hermes_cli/observability/shared_metrics_process.py
index c8cee799f71..11ed6c566cf 100644
--- a/hermes_cli/observability/shared_metrics_process.py
+++ b/hermes_cli/observability/shared_metrics_process.py
@@ -75,12 +75,13 @@ def begin_process(kind: str) -> None:
try:
from hermes_constants import get_hermes_home
- from .shared_metrics_update import _collection_on
+ from .shared_metrics_update import _collection_on, purge_pending_updates
if _STATE:
return
_STATE["kind"] = kind # watchdog turn rows name the surface even when this home is off
if not _collection_on():
+ purge_pending_updates(get_hermes_home()) # parked while on, never to be counted once off
return
from gateway.status import get_process_start_time
@@ -130,6 +131,8 @@ def _claim(path: Path) -> Path | None:
record = json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
return None
+ if not isinstance(record, dict):
+ 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}")
@@ -154,11 +157,22 @@ def process_exit_fields(record: dict[str, Any]) -> dict[str, str]:
}
+def settle_claim(claimed: Path, original: Path, saved: bool) -> None:
+ """Delete a claimed file once its row is saved; otherwise hand it back for the next start."""
+ try:
+ if saved:
+ claimed.unlink(missing_ok=True)
+ else:
+ os.replace(claimed, original)
+ except OSError: # a leftover claim is reclaimed once this reporter is gone
+ logger.debug("Claimed shared-metrics file not settled", exc_info=True)
+
+
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
+ from .shared_metrics_events import emit_saved
token = set_hermes_home_override(home) # a thread does not inherit the profile binding
try:
@@ -172,9 +186,8 @@ def _report_dead_markers(home: Path, own: Path) -> None:
record = json.loads(claimed.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
record = None
- if isinstance(record, dict):
- _emit(contract.PROCESS_EXIT_MARK, process_exit_fields, record=record)
- claimed.unlink(missing_ok=True)
+ rows = [(contract.PROCESS_EXIT_MARK, process_exit_fields(record))] if isinstance(record, dict) else []
+ settle_claim(claimed, path, emit_saved(rows) == len(rows))
from .shared_metrics_update import report_pending_updates
report_pending_updates()
diff --git a/hermes_cli/observability/shared_metrics_subscriber.py b/hermes_cli/observability/shared_metrics_subscriber.py
index 52c754c2485..c4a6a06ba8d 100644
--- a/hermes_cli/observability/shared_metrics_subscriber.py
+++ b/hermes_cli/observability/shared_metrics_subscriber.py
@@ -15,6 +15,7 @@ from .shared_metrics import SharedMetricsStore
from .shared_metrics_fields import milestones_for
from .shared_metrics_contract import (
CLIENT_ACTIVE_METRIC,
+ COMMIT_TICKET_KEY,
INSTALL_SNAPSHOT_METRIC,
MODEL_ROUTE_METRIC,
TOOL_CALL_METRIC,
@@ -74,6 +75,7 @@ class SharedMetricsSubscriber:
self._active = True
self._lock = threading.RLock()
self._milestones_done: set[str] = set(store.recorded_milestones())
+ self._saved_tickets: dict[str, int] = {}
# Events arrive on the Relay thread, which carries no profile binding.
self._hermes_home = get_hermes_home()
@@ -100,14 +102,21 @@ class SharedMetricsSubscriber:
self.store.record_milestone(milestone, age, self._client_resource)
self._milestones_done.add(milestone)
+ def take_saved(self, ticket: str) -> int:
+ """How many events carrying ``ticket`` settled without a store error (and forget the ticket)."""
+ with self._lock:
+ return self._saved_tickets.pop(ticket, 0)
+
def __call__(self, event: Any) -> None:
+ metadata = getattr(event, "metadata", None)
if self._runtime_id is not None:
- metadata = getattr(event, "metadata", None)
if (
not isinstance(metadata, dict)
or metadata.get(RUNTIME_INSTANCE_KEY) != self._runtime_id
):
return
+ ticket = metadata.get(COMMIT_TICKET_KEY) if isinstance(metadata, dict) else None
+ saved = True # a row the contract rejects is settled too: no retry can change that
for metric_name, dimensions, amount in self._classify(event):
with self._lock:
if not self._active:
@@ -121,6 +130,11 @@ class SharedMetricsSubscriber:
self.store.record_counter(metric_name, dimensions, self._client_resource, amount)
self._record_milestones(metric_name, dimensions)
except Exception:
+ saved = False
logger.warning(
"Unable to persist the Hermes shared metric: %s", metric_name, exc_info=True
)
+ if ticket and saved:
+ with self._lock:
+ if self._active:
+ self._saved_tickets[ticket] = self._saved_tickets.get(ticket, 0) + 1
diff --git a/hermes_cli/observability/shared_metrics_update.py b/hermes_cli/observability/shared_metrics_update.py
index d29e9856b90..e226a2d8dfc 100644
--- a/hermes_cli/observability/shared_metrics_update.py
+++ b/hermes_cli/observability/shared_metrics_update.py
@@ -17,6 +17,9 @@ from __future__ import annotations
import json
import logging
+import os
+import re
+import shutil
import time
from datetime import datetime
from pathlib import Path
@@ -25,6 +28,11 @@ from typing import Any
logger = logging.getLogger(__name__)
PENDING_DIRNAME = "pending_updates"
+# One empty file per update_id already counted in this profile: the completion child and the
+# parent's parked copy can both finalize the same run.
+RECORDED_DIRNAME = "recorded_updates"
+_RECORDED_KEEP = 64
+_UPDATE_ID = re.compile(r"[0-9a-f]{8,64}")
# Receipt pm/Desktop outcome words → hermes.update.run outcome; anything else failed.
_RUN_OUTCOMES = {"success": "success", "refused": "refused", "noop": "noop"}
_FLEET_BAD_STATES = frozenset({"stale", "down"})
@@ -36,11 +44,11 @@ _DESKTOP_APPLY_MODES = {
def _epoch(value: Any) -> float | None:
- if isinstance(value, (int, float)) and not isinstance(value, bool):
- return float(value)
try:
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return float(value)
return datetime.fromisoformat(str(value)).timestamp()
- except (TypeError, ValueError):
+ except (OverflowError, TypeError, ValueError):
return None
@@ -140,44 +148,91 @@ def _collection_on() -> bool:
return isinstance(config, dict) and config.get("enabled") is True
-def record_update_receipt(receipt: dict[str, Any]) -> None:
- """Record one run row plus its stage rows from a final receipt. Never raises."""
+def _claim_update_id(update_id: Any) -> tuple[bool, Path | None]:
+ """``(first, latch)``: first is False when this profile already counted ``update_id``."""
+ from hermes_constants import get_hermes_home
+
+ if not isinstance(update_id, str) or not _UPDATE_ID.fullmatch(update_id):
+ return True, None # nothing stable to dedupe on
+ directory = get_hermes_home() / "telemetry" / "shared_metrics" / RECORDED_DIRNAME
+ directory.mkdir(parents=True, exist_ok=True)
+ latch = directory / update_id
+ try:
+ os.close(os.open(latch, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
+ except FileExistsError:
+ return False, None
+ try:
+ for stale in sorted(directory.iterdir(), key=lambda p: p.stat().st_mtime, reverse=True)[_RECORDED_KEEP:]:
+ stale.unlink(missing_ok=True)
+ except OSError: # a concurrent prune won; the next claim prunes again
+ pass
+ return True, latch
+
+
+def record_update_receipt(receipt: dict[str, Any], *, wait_saved: bool = False) -> bool:
+ """Record one run row plus its stage rows from a final receipt, once per update_id.
+
+ ``wait_saved`` (parked receipts) blocks until the rows are in the store; False means the caller
+ must keep the receipt for a later retry. True also covers "nothing to record". Never raises.
+ """
try:
if not _collection_on():
- return
+ return True
from . import shared_metrics_contract as contract
- from .shared_metrics_events import _emit
+ from .shared_metrics_events import _emit, emit_saved
derived = update_receipt_fields(receipt)
if derived is None:
- return
+ return True
+ first, latch = _claim_update_id(receipt.get("update_id"))
+ if not first:
+ return True
run, stage_rows = derived
- _emit(contract.UPDATE_RUN_MARK, lambda: run)
- for row in stage_rows:
- _emit(contract.UPDATE_STAGE_MARK, lambda row=row: row)
+ rows = [(contract.UPDATE_RUN_MARK, run), *((contract.UPDATE_STAGE_MARK, row) for row in stage_rows)]
+ if not wait_saved:
+ for mark, row in rows:
+ _emit(mark, lambda row=row: row)
+ return True
+ if emit_saved(rows):
+ return True # even partly: a retry would count again the rows that did land
+ if latch is not None:
+ latch.unlink(missing_ok=True) # nothing landed: let the retry count it
+ return False
except Exception:
logger.debug("Update shared metrics not recorded", exc_info=True)
+ return False
def pending_updates_dir(home: Path) -> Path:
return home / "telemetry" / "shared_metrics" / PENDING_DIRNAME
+def purge_pending_updates(home: Path) -> None:
+ shutil.rmtree(pending_updates_dir(home), ignore_errors=True)
+
+
def report_pending_updates() -> None:
"""Record receipts a pre-pull interpreter parked (it must not import pulled code). Never raises."""
try:
from hermes_constants import get_hermes_home
+ from .shared_metrics_process import _claim, settle_claim
+
directory = pending_updates_dir(get_hermes_home())
if not directory.is_dir():
return
- for path in sorted(directory.glob("*.json")):
+ for path in sorted(directory.iterdir()):
+ if path.name.startswith(".") or ".json" not in path.name:
+ continue
+ claimed = _claim(path) # a concurrent start that loses the rename records nothing
+ if claimed is None:
+ continue
try:
- receipt = json.loads(path.read_text(encoding="utf-8-sig"))
- path.unlink() # claim first: a concurrent start that loses the unlink records nothing
+ receipt = json.loads(claimed.read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
- continue
- record_update_receipt(receipt)
+ receipt = None
+ saved = not isinstance(receipt, dict) or record_update_receipt(receipt, wait_saved=True)
+ settle_claim(claimed, path, saved)
except Exception:
logger.debug("Pending update shared metrics not reported", exc_info=True)
diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.py
index 198678f8b2d..c6ce017d39e 100644
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@ -342,21 +342,63 @@ def finalize_update_receipt(outcome: str, fleet: list | None = None, stop_reason
return None
+def _collection_enabled_now() -> Optional[bool]:
+ """Shared-metrics consent via the ALREADY-LOADED config module (never an import: this interpreter
+ predates the checkout swap). None when it cannot tell (not loaded, unreadable config)."""
+ reader = getattr(sys.modules.get("hermes_cli.config"), "read_raw_config_readonly", None)
+ if reader is None:
+ return None
+ try:
+ config: Any = reader()
+ except Exception:
+ return None
+ if type(config) is not dict: # FailedConfigRead: a fallback, not what the user chose
+ return None
+ for key in ("telemetry", "shared_metrics"):
+ config = config.get(key) if isinstance(config, dict) else None
+ return isinstance(config, dict) and config.get("enabled") is True
+
+
+def _metric_receipt(data: dict[str, Any]) -> dict[str, Any]:
+ """Only what shared_metrics_update.update_receipt_fields reads; never argv or step text."""
+ pre = data.get("pre_update") if isinstance(data.get("pre_update"), dict) else {}
+ return {
+ "update_id": data.get("update_id"), "started_at": data.get("started_at"),
+ "finished_at": data.get("finished_at"), "outcome": data.get("outcome"),
+ "initiator": "desktop" if data.get("initiator") == "desktop" else None,
+ "pre_update": {"commit_date": pre.get("commit_date")},
+ "stages": [
+ {key: mark[key] for key in ("name", "outcome", "at", "mode") if key in mark}
+ for mark in data.get("stages") or () if isinstance(mark, dict)
+ ],
+ "steps": [
+ {"name": "admission", "ok": bool(step.get("ok"))}
+ for step in data.get("steps") or () if isinstance(step, dict) and step.get("name") == "admission"
+ ],
+ "fleet": [{"state": row.get("state")} for row in data.get("fleet") or () if isinstance(row, dict)],
+ }
+
+
def _publish_shared_metrics(data: dict[str, Any]) -> None:
"""hermes.update.run/stage from this FINAL receipt; must never fail or slow the update."""
with suppress(Exception):
pre, post = data.get("pre_update") or {}, data.get("post_update") or {}
if data.get("pid") == os.getpid() and not (pre.get("sha") and pre.get("sha") == post.get("sha")):
# This interpreter began the run before the checkout swap: importing now would load
- # pulled code into it. Park the receipt (stdlib only); the next Hermes start records it.
+ # pulled code into it. Park the bounded fields (stdlib + loaded modules only); the next
+ # Hermes start records them.
from hermes_constants import get_hermes_home
from hermes_cli.runtime_state import _atomic_bytes
- store = get_hermes_home() / "telemetry" / "shared_metrics"
- if store.is_dir(): # never enabled on this profile: nothing to park
- pending = store / "pending_updates" # = shared_metrics_update.PENDING_DIRNAME
- pending.mkdir(exist_ok=True)
- _atomic_bytes(pending / f"{data.get('update_id')}.json", json.dumps(data, default=str).encode())
+ pending = get_hermes_home() / "telemetry" / "shared_metrics" / "pending_updates" # = PENDING_DIRNAME
+ enabled = _collection_enabled_now()
+ if enabled is False:
+ import shutil
+
+ shutil.rmtree(pending, ignore_errors=True) # opted out: nothing parked may be counted later
+ elif enabled:
+ pending.mkdir(parents=True, exist_ok=True)
+ _atomic_bytes(pending / f"{data.get('update_id')}.json", json.dumps(_metric_receipt(data), default=str).encode())
return
from hermes_cli.observability.shared_metrics_update import record_update_receipt
diff --git a/tests/hermes_cli/test_relay_shared_metrics_runtime.py b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
index c83e5b45df1..f2bd7d94597 100644
--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py
+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
@@ -2878,3 +2878,20 @@ def test_token_usage_is_summed_per_model_and_auxiliary_task(direct_runtime, tmp_
("auxiliary", "compression", "input"): 7, ("auxiliary", "compression", "output"): 3,
("auxiliary", "other", "input"): 7, ("auxiliary", "other", "output"): 3,
}
+
+
+def test_recovered_rows_report_saved_only_once_the_store_holds_them(real_binding_runtime, monkeypatch):
+ from hermes_cli.observability.shared_metrics import SharedMetricsStore
+
+ row = ("hermes.process.exit", {"crash_class": "none", "exit_kind": "killed", "process_kind": "gateway"})
+ real_store_write = SharedMetricsStore.record_counter
+
+ def locked(*args, **kwargs):
+ raise sqlite3.OperationalError("database is locked")
+
+ monkeypatch.setattr(SharedMetricsStore, "record_counter", locked)
+ assert relay_shared_metrics.record_process_marks_saved([row]) == 0
+ monkeypatch.setattr(SharedMetricsStore, "record_counter", real_store_write)
+ assert relay_shared_metrics.record_process_marks_saved([row]) == 1
+ saved = [(r["metric_name"], r["dimensions"], r["value"]) for r in SharedMetricsStore().counter_snapshot()]
+ assert saved == [("hermes.process.exit", row[1], 1)]
diff --git a/tests/hermes_cli/test_shared_metrics_reliability.py b/tests/hermes_cli/test_shared_metrics_reliability.py
index 376f9210079..758b8b572dd 100644
--- a/tests/hermes_cli/test_shared_metrics_reliability.py
+++ b/tests/hermes_cli/test_shared_metrics_reliability.py
@@ -31,7 +31,15 @@ def marks(tmp_path, monkeypatch):
)
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")
+ store = {"saves": True} # rows recovered from files wait for the store; a test can make it refuse
+
+ def saved(rows):
+ if store["saves"]:
+ captured.extend(rows)
+ return len(rows) if store["saves"] else 0
+
+ monkeypatch.setattr(relay_shared_metrics, "record_process_marks_saved", saved, raising=False)
+ yield SimpleNamespace(rows=captured, policy=policy, home=tmp_path / "home", store=store)
def _identity(monkeypatch, *shas: str) -> None:
@@ -173,6 +181,58 @@ def test_v3_schema_accepts_exactly_the_contract_values():
field: set(values) for field, values in contract._COUNTER_DIMENSION_VALUES[metric].items()}
+def _pre_pull_finalize(monkeypatch) -> None:
+ _identity(monkeypatch, "a" * 40, "b" * 40) # the checkout moved under this interpreter
+ update_receipt.begin_update_receipt()
+ update_receipt.record_step("admission", True, "operator text /home/someone/checkout")
+ update_receipt.record_stage("plan", "success")
+ update_receipt.finalize_update_receipt("failed")
+
+
+def test_pre_pull_park_happens_only_while_opted_in_and_keeps_only_metric_fields(marks, monkeypatch):
+ pending = update_metrics.pending_updates_dir(marks.home)
+ pending.mkdir(parents=True)
+ (pending / "earlier.json").write_text(json.dumps({"update_id": "earlier", "argv": ["hermes", "update"]}))
+ marks.policy["on"] = False
+ _pre_pull_finalize(monkeypatch)
+ assert not pending.exists() or list(pending.iterdir()) == [] # nothing parked, the earlier one purged
+
+ marks.policy["on"] = True
+ _pre_pull_finalize(monkeypatch)
+ (parked,) = pending.glob("*.json")
+ text = parked.read_text()
+ assert "argv" not in text and "operator text" not in text and "/home/" not in text
+ update_metrics.report_pending_updates()
+ assert [mark for mark, _ in marks.rows].count(contract.UPDATE_RUN_MARK) == 1
+
+
+def test_one_update_id_is_counted_once_across_the_child_and_the_parked_copy(marks, monkeypatch):
+ _identity(monkeypatch, "a" * 40)
+ update_receipt.begin_update_receipt()
+ update_receipt.record_stage("plan", "success")
+ update_receipt.finalize_update_receipt("success") # the completion child records directly
+ receipt = update_receipt.read_latest_receipt()
+ pending = update_metrics.pending_updates_dir(marks.home)
+ pending.mkdir(parents=True) # the parent's boundary finalize parks the SAME run as failed
+ (pending / f"{receipt['update_id']}.json").write_text(json.dumps({**receipt, "outcome": "failed"}))
+ update_metrics.report_pending_updates()
+ assert [data["outcome"] for mark, data in marks.rows if mark == contract.UPDATE_RUN_MARK] == ["success"]
+ assert list(pending.iterdir()) == []
+
+
+def test_a_marker_the_store_did_not_save_is_kept_for_the_next_start(marks):
+ directory = process_metrics.markers_dir(marks.home)
+ directory.mkdir(parents=True)
+ marker = directory / "gateway-2.json"
+ marker.write_text(json.dumps({"kind": "gateway", "pid": _dead_pid(), "start_time": None, "state": "clean"}))
+ marks.store["saves"] = False # "database is locked"
+ process_metrics._report_dead_markers(marks.home, directory / "self.json")
+ assert marker.exists() and marks.rows == []
+ marks.store["saves"] = True
+ process_metrics._report_dead_markers(marks.home, directory / "self.json")
+ assert not marker.exists() and [data["exit_kind"] for _, data in marks.rows] == ["clean"]
+
+
def test_graceful_gateway_exit_stamps_the_marker_clean(marks, monkeypatch):
import gateway.run as gateway_run
@@ -193,3 +253,7 @@ def test_graceful_gateway_exit_stamps_the_marker_clean(marks, monkeypatch):
gateway_run._exit_after_graceful_shutdown(1)
marker = process_metrics.markers_dir(marks.home) / f"gateway-{os.getpid()}.json"
assert json.loads(marker.read_text())["state"] == "clean"
+
+
+def test_unrepresentable_timestamps_read_as_unknown():
+ assert update_metrics._epoch(10 ** 400) is None
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index 748bcdca3e5..b9332394387 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -313,7 +313,7 @@ itself ships.
| `hermes.gateway.reply_latency` | platform, first-response bucket (`lt_2s` … `gte_60s`) | Time from an accepted inbound message to the first visible reply text (stream first chunk or final message). |
| `hermes.cron.run` | outcome (`success`/`failed`/`missed`/`skipped`), delivery kind (`local`/`platform`/`webhook`/`none`/`other`), duration bucket | Do scheduled jobs run, fail, get skipped by a gate or overlap, or get missed while Hermes was down. Job names, prompts, schedules and targets are never included. |
| `hermes.startup.latency` | surface (`cli`, `tui`, `desktop_attach`, `gateway_boot`, `serve_boot`), latency bucket (`lt_500ms` … `gte_10s`) | How long each surface takes from launch to usable, so startup regressions show per surface and release. One row per process start: CLI = process start to first rendered prompt (or a `-q` query dispatched; Kanban workers excluded), TUI = Ink process start to gateway ready, Desktop = app start to backend attached, gateway = process start to adapters connected, `hermes serve` = process start to listening. |
-| `hermes.update.run` | kind, outcome, failed_stage, duration_bucket, from_version_age_bucket, apply_mode | Whether updates succeed, how long they take, where they fail, and how stale the version being updated from was. `hermes update` rows are derived from the final update receipt (`kind` is `desktop` when Desktop's source-checkout hand-off ran it); Desktop packaged self-updates (`apply_mode=package`) are reported once by the app, after the restart that applies them. |
+| `hermes.update.run` | kind, outcome, failed_stage, duration_bucket, from_version_age_bucket, apply_mode | Whether updates succeed, how long they take, where they fail, and how stale the version being updated from was. `hermes update` rows are derived from the final update receipt, once per run (`kind` is `desktop` when Desktop's source-checkout hand-off ran it); a run the pre-update interpreter finishes is parked locally with only these fields, only while collection is on, and counted by the next start; Desktop packaged self-updates (`apply_mode=package`) are reported once by the app, after the restart that applies them. |
| `hermes.update.stage` | stage, outcome, duration_bucket | Per-stage result and wall time of `hermes update` (plan, snapshot, apply, deps, build, restart, verify), from the receipt's stage timestamps. |
| `hermes.process.exit` | process_kind, exit_kind, crash_class | How CLI / TUI / gateway / serve / cron-tick processes end (`clean`, `crash` with an exception family only, `killed`, `watchdog`), reported by the next start in the same profile from a local marker. Turns aborted by a turn watchdog also count as `exit_kind=watchdog`. |