Skip to content

The agent that grows with you

fix(metrics): startup latency counts once per client launch, never after an in-place exec

teknium188eb76f02e49
diff --git a/apps/desktop/src/app/gateway/report-startup-latency.test.ts b/apps/desktop/src/app/gateway/report-startup-latency.test.ts
index b567ea5e746..ae212c7d43e 100644
--- a/apps/desktop/src/app/gateway/report-startup-latency.test.ts
+++ b/apps/desktop/src/app/gateway/report-startup-latency.test.ts
@@ -15,7 +15,11 @@ describe('reportStartupLatency', () => {
await reportStartupLatency({ claimStartupLatency }, request)
expect(request).toHaveBeenCalledTimes(1)
- expect(request).toHaveBeenCalledWith('shared_metrics.startup_latency', { elapsed_ms: 1234, surface: 'desktop_attach' })
+ expect(request).toHaveBeenCalledWith('shared_metrics.startup_latency', {
+ elapsed_ms: 1234,
+ launch_id: expect.any(String),
+ surface: 'desktop_attach'
+ })
})
it('skips the metric on an Electron shell without the claim bridge', async () => {
diff --git a/apps/desktop/src/app/gateway/report-startup-latency.ts b/apps/desktop/src/app/gateway/report-startup-latency.ts
index 674250647e3..9e13e6bbba6 100644
--- a/apps/desktop/src/app/gateway/report-startup-latency.ts
+++ b/apps/desktop/src/app/gateway/report-startup-latency.ts
@@ -1,6 +1,6 @@
type GatewayRequest = (
method: 'shared_metrics.startup_latency',
- params: { elapsed_ms: number; surface: 'desktop_attach' }
+ params: { elapsed_ms: number; launch_id: string; surface: 'desktop_attach' }
) => Promise<unknown>
/** Fire-and-forget: the main process hands out the launch latency to exactly one renderer
@@ -16,8 +16,12 @@ export async function reportStartupLatency(
return
}
+ // The main-process claim succeeds once per app launch, so an id minted on success names the
+ // launch; the backend latches on it, so a long-lived backend still counts the next launch.
// Declared, not env-detected: a URL/cloud backend has no HERMES_DESKTOP to tell it who attached.
- await request('shared_metrics.startup_latency', { elapsed_ms: elapsedMs, surface: 'desktop_attach' }).catch(
- () => undefined
- )
+ await request('shared_metrics.startup_latency', {
+ elapsed_ms: elapsedMs,
+ launch_id: crypto.randomUUID(),
+ surface: 'desktop_attach'
+ }).catch(() => undefined)
}
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 9d88dc37695..9d5b69dbb48 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -665,11 +665,12 @@ export interface SharedMetricsSlashCommandParams {
export interface SharedMetricsSlashCommandResult {
ok: boolean
}
-/** ``elapsed_ms`` = the client's own launch (TUI process start / Desktop app start) to ready (TUI gateway ready / Desktop backend attached), measured once per launch by the client. The client names its surface because a Desktop may attach to a URL/cloud backend where ``HERMES_DESKTOP`` is unset; without it the backend falls back to its own client detection. */
+/** ``elapsed_ms`` = the client's own launch (TUI process start / Desktop app start) to ready (TUI gateway ready / Desktop backend attached), measured once per launch by the client. The client names its surface because a Desktop may attach to a URL/cloud backend where ``HERMES_DESKTOP`` is unset; without it the backend falls back to its own client detection. ``launch_id`` is an opaque per-launch token the backend latches on (never recorded), so a reconnect re-sending the same launch counts once while a new launch counts again. */
export interface SharedMetricsStartupLatencyParams {
profile?: string | null
elapsed_ms: number
surface?: 'desktop_attach' | 'tui' | null
+ launch_id?: string | null
}
export interface SharedMetricsStartupLatencyResult {
ok: boolean
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 117904febb8..82e5b6fb11b 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -32072,7 +32072,7 @@
},
"SharedMetricsStartupLatencyParams": {
"additionalProperties": false,
- "description": "``elapsed_ms`` = the client's own launch (TUI process start / Desktop app start) to ready\n(TUI gateway ready / Desktop backend attached), measured once per launch by the client. The\nclient names its surface because a Desktop may attach to a URL/cloud backend where\n``HERMES_DESKTOP`` is unset; without it the backend falls back to its own client detection.",
+ "description": "``elapsed_ms`` = the client's own launch (TUI process start / Desktop app start) to ready\n(TUI gateway ready / Desktop backend attached), measured once per launch by the client. The\nclient names its surface because a Desktop may attach to a URL/cloud backend where\n``HERMES_DESKTOP`` is unset; without it the backend falls back to its own client detection.\n``launch_id`` is an opaque per-launch token the backend latches on (never recorded), so a\nreconnect re-sending the same launch counts once while a new launch counts again.",
"properties": {
"profile": {
"anyOf": [
@@ -32105,6 +32105,18 @@
],
"default": null,
"title": "Surface"
+ },
+ "launch_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Launch Id"
}
},
"required": [
diff --git a/hermes_cli/observability/shared_metrics_startup.py b/hermes_cli/observability/shared_metrics_startup.py
index 07efe7373dd..e52eed88070 100644
--- a/hermes_cli/observability/shared_metrics_startup.py
+++ b/hermes_cli/observability/shared_metrics_startup.py
@@ -24,9 +24,16 @@ logger = logging.getLogger(__name__)
_THRESHOLDS_MS = (
(500, "lt_500ms"), (1_000, "500ms_to_1s"), (2_000, "1s_to_2s"), (5_000, "2s_to_5s"), (10_000, "5s_to_10s"),
)
-# (pid, surface): a forked child re-arms, a surface in this process counts once.
-_recorded: set[tuple[int, str]] = set()
+# (pid, surface, client launch id): a forked child re-arms, a surface in this process counts once,
+# and an RPC-reporting client counts once per launch (a Desktop reconnect re-sends the same launch).
+_recorded: set[tuple[int, str, str]] = set()
_lock = threading.Lock()
+# A local client minting a fresh launch id per call must not grow this set without bound.
+_MAX_RECORDED = 1024
+_LAUNCH_ID_MAX_LEN = 64
+# ``os.execvp`` keeps the PID, so a relaunched process (``sessions browse`` -> resume) would count
+# the picker time as startup; relaunch() stamps its PID here right before the exec.
+RELAUNCHED_PID_ENV = "HERMES_RELAUNCHED_PID"
def latency_bucket(elapsed_ms: Any) -> str | None:
@@ -58,15 +65,31 @@ def process_started_at() -> float | None:
return None
-def _claim(surface: str) -> bool:
- key = (os.getpid(), surface)
+def mark_in_place_relaunch() -> None:
+ """Called right before an in-place ``exec``: the new program inherits this PID and env."""
+ os.environ[RELAUNCHED_PID_ENV] = str(os.getpid())
+
+
+def _relaunched_in_place() -> bool:
+ # A child spawned later inherits the env but has its own PID, so it still counts.
+ return os.environ.get(RELAUNCHED_PID_ENV) == str(os.getpid())
+
+
+def _claim(surface: str, launch_id: str = "") -> bool:
+ key = (os.getpid(), surface, launch_id)
with _lock:
- if key in _recorded:
+ if key in _recorded or len(_recorded) >= _MAX_RECORDED:
return False
_recorded.add(key)
return True
+def _collection_enabled() -> bool:
+ from .relay_shared_metrics import enabled
+
+ return enabled()
+
+
def _record_since_process_start(surface: str, ready_at: float) -> None:
started = process_started_at()
if started is not None:
@@ -82,7 +105,8 @@ def record_process_ready(surface: str, *, background: bool = False) -> None:
"""
ready_at = time.time()
try:
- if not _claim(surface):
+ # Claim before the gate so a later opt-in never records a stale "startup" mid-session.
+ if _relaunched_in_place() or not _claim(surface) or not _collection_enabled():
return
if not background:
_record_since_process_start(surface, ready_at)
@@ -112,10 +136,17 @@ def record_cli_one_shot_ready() -> None:
record_process_ready("cli")
-def record_rpc_startup_latency(*, client_surface: Any, elapsed_ms: Any) -> None:
- """The TUI / Desktop client's own launch -> ready measurement, reported once per launch by the
- client. ``client_surface`` is the client's declared surface or the backend's detection
- (``desktop``/``tui``); anything else records nothing."""
+def _launch_key(launch_id: Any) -> str:
+ """The client's per-launch id, only ever a local latch key (never recorded). Older clients send
+ none and latch on their side; they count once per backend process and surface."""
+ return launch_id if isinstance(launch_id, str) and len(launch_id) <= _LAUNCH_ID_MAX_LEN else ""
+
+
+def record_rpc_startup_latency(*, client_surface: Any, elapsed_ms: Any, launch_id: Any = None) -> None:
+ """The TUI / Desktop client's own launch -> ready measurement, once per (surface, client launch)
+ in this backend process. ``client_surface`` is the client's declared surface or the backend's
+ detection (``desktop``/``tui``); anything else records nothing."""
surface = {"desktop": "desktop_attach", "desktop_attach": "desktop_attach", "tui": "tui"}.get(client_surface)
- if surface is not None:
+ # Only a usable measurement spends the launch's claim.
+ if surface is not None and latency_bucket(elapsed_ms) is not None and _claim(surface, _launch_key(launch_id)):
record_startup_latency(surface=surface, elapsed_ms=elapsed_ms)
diff --git a/hermes_cli/relaunch.py b/hermes_cli/relaunch.py
index 790ca1026ee..1a3abd3159c 100644
--- a/hermes_cli/relaunch.py
+++ b/hermes_cli/relaunch.py
@@ -139,4 +139,7 @@ def relaunch(
)
sys.exit(1)
else:
+ from hermes_cli.observability.shared_metrics_startup import mark_in_place_relaunch
+
+ mark_in_place_relaunch()
os.execvp(new_argv[0], new_argv)
\ No newline at end of file
diff --git a/tests/hermes_cli/test_shared_metrics_install_v4.py b/tests/hermes_cli/test_shared_metrics_install_v4.py
index 72c008b26d5..16c4dfc9bc2 100644
--- a/tests/hermes_cli/test_shared_metrics_install_v4.py
+++ b/tests/hermes_cli/test_shared_metrics_install_v4.py
@@ -95,11 +95,11 @@ def test_rpc_takes_the_declared_surface_else_env_detection(marks, monkeypatch):
monkeypatch.delenv("HERMES_DESKTOP_TERMINAL", raising=False)
# A Desktop attached to a URL/cloud backend: no HERMES_DESKTOP here, the client says who it is.
- assert _rpc({"elapsed_ms": 2500, "surface": "desktop_attach"})["result"] == {"ok": True}
- assert _rpc({"elapsed_ms": 700})["result"] == {"ok": True}
+ assert _rpc({"elapsed_ms": 2500, "surface": "desktop_attach", "launch_id": "a"})["result"] == {"ok": True}
+ assert _rpc({"elapsed_ms": 700, "launch_id": "b"})["result"] == {"ok": True}
monkeypatch.setenv("HERMES_DESKTOP", "1")
- assert _rpc({"elapsed_ms": 12_000})["result"] == {"ok": True}
- assert _rpc({"elapsed_ms": -5, "surface": "tui"})["result"] == {"ok": True}
+ assert _rpc({"elapsed_ms": 12_000, "launch_id": "c"})["result"] == {"ok": True}
+ assert _rpc({"elapsed_ms": -5, "surface": "tui", "launch_id": "d"})["result"] == {"ok": True}
assert [data for _, data in marks] == [
{"latency_bucket": "2s_to_5s", "surface": "desktop_attach"},
@@ -108,6 +108,56 @@ def test_rpc_takes_the_declared_surface_else_env_detection(marks, monkeypatch):
]
+def test_rpc_counts_each_client_launch_once_per_backend_process(marks):
+ # A Desktop reconnecting to the same backend re-sends its launch; a later Desktop launch
+ # against the same long-lived backend is a new launch and still counts.
+ for _ in range(3):
+ _rpc({"elapsed_ms": 1200, "surface": "desktop_attach", "launch_id": "launch-1"})
+ _rpc({"elapsed_ms": 300, "surface": "desktop_attach", "launch_id": "launch-2"})
+ # Older clients send no id and latch on their side; the backend still counts them once.
+ for _ in range(2):
+ _rpc({"elapsed_ms": 1200, "surface": "tui"})
+
+ assert [data for _, data in marks] == [
+ {"latency_bucket": "1s_to_2s", "surface": "desktop_attach"},
+ {"latency_bucket": "lt_500ms", "surface": "desktop_attach"},
+ {"latency_bucket": "1s_to_2s", "surface": "tui"},
+ ]
+
+
+def test_in_place_relaunch_is_not_a_startup_but_its_children_are(marks, monkeypatch):
+ """``sessions browse`` -> resume execs in place: same PID, so process start covers the picker."""
+ from hermes_cli import relaunch as relaunch_mod
+
+ monkeypatch.setenv(startup.RELAUNCHED_PID_ENV, "") # restored after relaunch() stamps it
+ monkeypatch.setattr(relaunch_mod.sys, "platform", "linux")
+ monkeypatch.setattr(startup, "process_started_at", lambda: time.time() - 30)
+ # The exec'd program keeps this PID and environment and reaches its first prompt.
+ monkeypatch.setattr(relaunch_mod.os, "execvp", lambda *_a: startup.record_process_ready("cli"))
+
+ relaunch_mod.relaunch(["--resume", "x"], preserve_inherited=False)
+ assert marks == []
+
+ # A child it spawns later inherits the env but not the PID: a real start of its own.
+ child_pid = os.getpid() + 1
+ monkeypatch.setattr(startup.os, "getpid", lambda: child_pid)
+ startup.record_process_ready("gateway_boot")
+ assert [data["surface"] for _, data in marks] == ["gateway_boot"]
+
+
+def test_process_ready_when_off_starts_no_thread_and_reads_no_process_time(monkeypatch):
+ monkeypatch.setattr(relay, "enabled", lambda: False)
+ monkeypatch.setattr(startup, "_recorded", set())
+ touched: list[str] = []
+ monkeypatch.setattr(startup, "process_started_at", lambda: touched.append("psutil"))
+ monkeypatch.setattr(startup.threading, "Thread", lambda *a, **k: touched.append("thread"))
+
+ startup.record_process_ready("serve_boot", background=True)
+ startup.record_process_ready("cli")
+
+ assert touched == []
+
+
def test_cli_first_rendered_prompt_records_once(marks, monkeypatch):
monkeypatch.setattr(startup, "process_started_at", lambda: time.time() - 0.2)
on_render = startup.cli_prompt_ready_handler()
diff --git a/tui_gateway/contracts/config_free_tier_control.py b/tui_gateway/contracts/config_free_tier_control.py
index 3c6e166ed25..a538ef25fd6 100644
--- a/tui_gateway/contracts/config_free_tier_control.py
+++ b/tui_gateway/contracts/config_free_tier_control.py
@@ -261,10 +261,13 @@ class SharedMetricsStartupLatencyParams(ProfileParams):
"""``elapsed_ms`` = the client's own launch (TUI process start / Desktop app start) to ready
(TUI gateway ready / Desktop backend attached), measured once per launch by the client. The
client names its surface because a Desktop may attach to a URL/cloud backend where
- ``HERMES_DESKTOP`` is unset; without it the backend falls back to its own client detection."""
+ ``HERMES_DESKTOP`` is unset; without it the backend falls back to its own client detection.
+ ``launch_id`` is an opaque per-launch token the backend latches on (never recorded), so a
+ reconnect re-sending the same launch counts once while a new launch counts again."""
elapsed_ms: float
surface: Literal["desktop_attach", "tui"] | None = None
+ launch_id: str | None = None
class SharedMetricsStartupLatencyResult(Result):
diff --git a/tui_gateway/methods_shared_metrics.py b/tui_gateway/methods_shared_metrics.py
index 4c21eb00501..5ac2481ba34 100644
--- a/tui_gateway/methods_shared_metrics.py
+++ b/tui_gateway/methods_shared_metrics.py
@@ -101,12 +101,14 @@ def _(rid, params: dict) -> dict:
@_profile_scoped
def _(rid, params: dict) -> dict:
"""The Ink TUI (gateway ready) and Desktop (backend attached) each report their own launch ->
- ready time once per launch. A Desktop on a URL/cloud backend has no ``HERMES_DESKTOP`` here, so
- the client's declared surface wins over env detection. Always ``{ok: true}``."""
+ ready time once per launch; ``launch_id`` latches it here too, so a reconnect to this backend
+ never re-counts. A Desktop on a URL/cloud backend has no ``HERMES_DESKTOP`` here, so the
+ client's declared surface wins over env detection. Always ``{ok: true}``."""
from hermes_cli.observability.shared_metrics_startup import record_rpc_startup_latency
record_rpc_startup_latency(
client_surface=params.get("surface") or _resolve_session_platform(), elapsed_ms=params.get("elapsed_ms"),
+ launch_id=params.get("launch_id"),
)
return _ok(rid, {"ok": True})
diff --git a/ui-tui/src/__tests__/startupLatency.test.ts b/ui-tui/src/__tests__/startupLatency.test.ts
index 65a36dba028..a63e0993a39 100644
--- a/ui-tui/src/__tests__/startupLatency.test.ts
+++ b/ui-tui/src/__tests__/startupLatency.test.ts
@@ -52,7 +52,7 @@ describe('startup latency metric', () => {
const calls = latencyCalls(request)
expect(calls).toHaveLength(1)
- expect(calls[0]![1]).toEqual({ elapsed_ms: expect.any(Number), surface: 'tui' })
+ expect(calls[0]![1]).toEqual({ elapsed_ms: expect.any(Number), launch_id: expect.any(String), surface: 'tui' })
expect(calls[0]![1].elapsed_ms).toBeGreaterThanOrEqual(0)
})
})
diff --git a/ui-tui/src/app/startupLatency.ts b/ui-tui/src/app/startupLatency.ts
index 8dca2d728b3..8df2db56778 100644
--- a/ui-tui/src/app/startupLatency.ts
+++ b/ui-tui/src/app/startupLatency.ts
@@ -1,3 +1,5 @@
+import { randomUUID } from 'node:crypto'
+
import { DASHBOARD_TUI_MODE } from '../config/env.js'
import type { GatewayClient } from '../gatewayClient.js'
@@ -5,6 +7,9 @@ import type { GatewayClient } from '../gatewayClient.js'
// handler) never re-reports: the metric is launch -> first ready, once per TUI process.
let reported = false
+// One TUI process is one launch; the backend latches on it too, so a re-sent report counts once.
+const LAUNCH_ID = randomUUID()
+
/** Node process start is the earliest moment the TUI owns, so uptime at the first
* gateway.ready is the launch latency. The backend buckets it and drops it unless the
* user opted in; older backends lack the method, so errors are swallowed.
@@ -18,6 +23,7 @@ export function reportStartupLatency(gw: Pick<GatewayClient, 'request'>): void {
reported = true
gw.request('shared_metrics.startup_latency', {
elapsed_ms: Math.round(process.uptime() * 1000),
+ launch_id: LAUNCH_ID,
surface: 'tui'
}).catch(() => undefined)
}
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index 7ddf58f2275..7f921ae0d91 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -312,7 +312,7 @@ itself ships.
| `hermes.platform.delivery` | platform, outcome (`sent`/`failed`), failure class (`rate_limited`/`too_long`/`auth`/`network`/`forbidden`/`other`) | How often replies fail to reach the user per platform (one count per logical reply, retries included). |
| `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.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. Not counted: a process re-exec'd in place (e.g. `hermes sessions browse` resuming a session) and each dashboard Chat-tab terminal; a TUI/Desktop reconnect to the same backend never re-counts. |
| `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`. |