Skip to content

The agent that grows with you

feat(telemetry): count messages that arrive while a chat's agent is busy, and the day's peak of busy chats

Teknium6f55623cc9ed
diff --git a/gateway/run.py b/gateway/run.py
index 37be85eeb04..85e40971cf3 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -3708,12 +3708,6 @@ class GatewayRunner(
restart_requested=self._restart_requested, active_agents=self._active_work_count(),
active_work=active_work)
- def _persist_active_agents(self) -> None:
- """Persist the live in-flight agent count to ``gateway_state.json`` at every turn boundary.
- Passes ONLY ``active_agents`` so the read-merge-write keeps lifecycle state (gateway_state=None
- would clobber it). Best-effort: a failed write must never disrupt a turn."""
- _write_runtime_status_quiet(active_agents=self._active_work_count())
-
def _running_agent_ids(self) -> set:
"""``id()`` of every agent mid-turn — identity-keyed so the lookup is O(1) and independent of
``AIAgent.__eq__`` (MagicMock overrides it in tests)."""
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.py
index 3e5bee60c58..71e6eb0ab02 100644
--- a/gateway/run_agent_cache.py
+++ b/gateway/run_agent_cache.py
@@ -19,6 +19,7 @@ from gateway.session_prompt_pin import PROMPT_PIN_VERSION, sanitize_prompt_pin
from gateway.run_shutdown import _log_suppressed
from hermes_cli.config import DEFAULT_CONFIG, cfg_get
from hermes_cli.local_runtime.endpoint import LLAMACPP_ALIASES
+from hermes_cli.observability.shared_metrics_busy import observe_running_chats
if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
from gateway.run import GatewayRunner
@@ -293,6 +294,15 @@ class GatewayAgentCacheMixin:
model = pin_model_for_route(provider, primary.get("base_url", getattr(agent, "base_url", None)), model)
return model
+ def _persist_active_agents(self) -> None:
+ """Persist the live in-flight agent count to ``gateway_state.json`` at every turn boundary.
+ Passes ONLY ``active_agents`` so the read-merge-write keeps lifecycle state (gateway_state=None
+ would clobber it). Best-effort: a failed write must never disrupt a turn. The running-turn
+ set also feeds the day's peak of chats running at once (in memory, see shared_metrics_busy)."""
+ from gateway.run import _write_runtime_status_quiet
+ _write_runtime_status_quiet(active_agents=self._active_work_count())
+ observe_running_chats(key for key, _ in self._running_agent_items())
+
def _release_running_agent_state(
self, session_key: str, *, run_generation: Optional[int] = None
) -> bool:
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index e5d71a8172d..0875a2d4d77 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -37,6 +37,7 @@ from gateway.session import (
neutralize_untrusted_inline_text,
)
from gateway.turn_lease import TurnLeaseTimeoutError
+from hermes_cli.observability.shared_metrics_busy import note_busy_admitting, note_busy_outcome
from typing import Any, Dict, List, Optional, Tuple
if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
@@ -739,6 +740,7 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayInboundTranscriptionM
and self._effective_busy_text_mode(source) == "queue")):
return False
outcome = await self._resolve_busy_steer_or_redirect(event, _quick_key, mode, running_agent)
+ note_busy_outcome(event, outcome)
await self._busy_interrupt_and_ack(event, _quick_key, adapter, state, running_agent, outcome)
return bool(outcome.steered or outcome.redirected)
@@ -1235,6 +1237,7 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayInboundTranscriptionM
return True, None # a /stop or /new came after its command, as it clears the slot
# A failed admit stays the authority's answer (refusal notice or turn error), never a
# pending legacy turn: that would run unadmitted, outside the FIFO's order.
+ note_busy_admitting(event)
return True, await admit_message(authority, event)
if (authority is None and not is_internal and not event.get_command()
and getattr(self, 'session_authority', None) is not None):
diff --git a/gateway/session_ingress.py b/gateway/session_ingress.py
index 2761f5c7230..d86eafae7e7 100644
--- a/gateway/session_ingress.py
+++ b/gateway/session_ingress.py
@@ -8,6 +8,7 @@ from dataclasses import replace
from gateway.platforms.event import MessageEvent, ProcessingOutcome
from gateway.session_envelope import restore_native
from gateway.session_producer_lifecycle import close_producer_turn, producer_turn
+from hermes_cli.observability.shared_metrics_busy import busy_turn_started, note_busy_admitted, settle_busy_arrival
from hermes_state_runtime import RuntimeStoreError
logger = logging.getLogger(__name__)
@@ -75,6 +76,7 @@ async def admit_message(authority, event):
from hermes_state_runtime import get_session_admission
row = get_session_admission(authority.db, admission_id=receipt.admission_id)
status = 'terminal' if row is None else row['status'] # None: deleted with its chat, nothing owed
+ note_busy_admitted(event, receipt.admission_id, status)
if status in ('terminal', 'unknown'):
authority.native_waiters.discard(receipt.admission_id)
if authority.waiters.get(receipt.admission_id) is waiter:
@@ -231,6 +233,7 @@ def row_turn_author(policy, row):
async def execute_admission(authority, ref, row):
+ busy_turn_started(row['admission_id'])
from gateway.session_completion_notes import note_if_unviewed
noted = await note_if_unviewed(authority, ref, row) # #134889 LC-7: no viewer, no turn
if noted is not None:
@@ -472,6 +475,7 @@ async def dispatch_shared_busy(adapter, event, session_key, *, durable=False):
logger.error('[%s] Queued busy follow-up failed: %s', adapter.name, exc, exc_info=True)
await adapter._notify_turn_error(delivery_event, exc)
finally:
+ settle_busy_arrival(event)
# Clears the marker if no ledgered send did, then wakes the drain's bounded wait,
# which listens on the adopter (``event``).
await adapter._release_turn_marker(delivery_event)
diff --git a/gateway/session_ingress_burst.py b/gateway/session_ingress_burst.py
index 73b2614afac..4f22d0d5982 100644
--- a/gateway/session_ingress_burst.py
+++ b/gateway/session_ingress_burst.py
@@ -19,6 +19,7 @@ import logging
import time
from gateway.platforms.event import MessageEvent, MessageType
+from hermes_cli.observability.shared_metrics_busy import note_busy_merged, settle_busy_arrival, stamp_busy_arrival
logger = logging.getLogger(__name__)
@@ -79,12 +80,14 @@ async def dispatch_busy_burst(adapter, event, session_key):
queue-mode TEXT+TEXT burst first."""
from gateway.platforms.base import merge_pending_message_event
from gateway.session_ingress import dispatch_shared_busy
+ stamp_busy_arrival(adapter, event)
kind, bursts = _kind(adapter, event), _state(adapter, '_shared_bursts')
while (burst := bursts.get(session_key)) is not None:
if kind is not None and kind == _kind(adapter, burst.head) and adapter._can_merge_text_debounce_events(
burst.head, event):
merge_pending_message_event({session_key: burst.head}, session_key, event, merge_text=kind == 'text')
burst.absorbed.append(event)
+ note_busy_merged(burst.head, event)
burst.last_ts = time.monotonic()
_arm(adapter, session_key, burst)
return await _accepted(adapter, burst, event)
@@ -210,4 +213,5 @@ def discard_busy_burst(adapter, session_key):
burst = adapter.__dict__.get('_shared_bursts', {}).pop(session_key, None)
if burst is not None:
burst.timer.cancel()
+ settle_busy_arrival(burst.head, discarded=True)
burst.done.done() or burst.done.set_result(None)
diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
index 4d7e0044b63..a0e113df8a3 100644
--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v4.schema.json
@@ -289,6 +289,9 @@
},
{
"$ref": "#/$defs/prepared_compaction_counter"
+ },
+ {
+ "$ref": "#/$defs/busy_arrival_counter"
}
]
}
@@ -3808,9 +3811,12 @@
"3",
"gte_4"
]
+ },
+ "gateway_peak_busy_chats_bucket": {
+ "$ref": "#/$defs/count_bucket"
}
},
- "description": "v5 engagement: one per closed UTC day with activity: total active time (inter-interaction gaps capped at 5 minutes), surfaces used, and the model that served most attended turns (none when no attended turn). active_profile_count_bucket: distinct profiles of the host with a user turn that day, reported only on the root (default) profile's row; other profiles' rows carry 0."
+ "description": "v5 engagement: one per closed UTC day with activity: total active time (inter-interaction gaps capped at 5 minutes), surfaces used, and the model that served most attended turns (none when no attended turn). active_profile_count_bucket: distinct profiles of the host with a user turn that day, reported only on the root (default) profile's row; other profiles' rows carry 0. gateway_peak_busy_chats_bucket (optional: rows recorded before it omit it): the most chats of this profile with a turn running at the same moment that day, as its gateway process saw them; 0 when no gateway served the profile."
},
"value": {
"type": "integer",
@@ -5402,6 +5408,63 @@
"minimum": 1
}
}
+ },
+ "busy_arrival_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.gateway.busy_arrival.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "disposition",
+ "platform",
+ "wait_bucket"
+ ],
+ "properties": {
+ "disposition": {
+ "enum": [
+ "queued",
+ "steered",
+ "interrupted",
+ "merged",
+ "dropped",
+ "other"
+ ]
+ },
+ "platform": {
+ "$ref": "#/$defs/catalog_identifier"
+ },
+ "wait_bucket": {
+ "enum": [
+ "lt_5s",
+ "5s_to_30s",
+ "30s_to_2m",
+ "2m_to_10m",
+ "gte_10m",
+ "never"
+ ]
+ }
+ },
+ "description": "busy-wait: one per human message that arrived while its chat's turn was running, once its fate is known. disposition: queued (ran later as its own turn), steered (delivered into the running turn), interrupted (stopped the running turn, then ran), merged (folded into another busy message), dropped (never ran: cleared, /stop, /new, refused or over the queue cap), other. wait_bucket: arrival to the moment it reached the agent; never when it did not."
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
}
}
}
diff --git a/hermes_cli/observability/shared_metrics_busy.py b/hermes_cli/observability/shared_metrics_busy.py
new file mode 100644
index 00000000000..f814792b405
--- /dev/null
+++ b/hermes_cli/observability/shared_metrics_busy.py
@@ -0,0 +1,251 @@
+"""Is the agent making people wait? Busy-chat arrivals and the day's peak of chats running at once.
+
+``hermes.gateway.busy_arrival.count``: one row per human message that arrives while its chat's turn
+is still running (the adapter's busy path), recorded once its fate is known: it reached the agent
+(its own turn started, or it was steered into the running one), it was folded into another busy
+message, or it never ran. Commands, internal events, plain-text approval answers and plugin-consumed
+input are not counted. The arrival rides the event object itself (``_busy_arrival``), so the merge,
+admission and settle seams need no lookup; the durable FIFO's admission id links it to the turn that
+later runs the restored copy.
+
+``gateway_peak_busy_chats_bucket`` (on ``hermes.engagement.day.count``): the most distinct chats
+(session keys) that had a turn running at the same moment during the UTC day, per owning profile.
+Tracked in memory from the runner's running-turn set at every turn boundary and folded into the
+profile's engagement day state, which reports it when the day closes. No chat id leaves the process.
+
+This module is imported by the contract at import time: stdlib only at module level.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import threading
+import time
+from collections import OrderedDict
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any, Callable
+
+logger = logging.getLogger(__name__)
+
+BUSY_ARRIVAL_METRIC = "hermes.gateway.busy_arrival.count"
+BUSY_ARRIVAL_DISPOSITIONS = frozenset({"queued", "steered", "interrupted", "merged", "dropped", "other"})
+BUSY_WAIT_BUCKETS = frozenset({"lt_5s", "5s_to_30s", "30s_to_2m", "2m_to_10m", "gte_10m", "never"})
+BUSY_PEAK_FIELD = "gateway_peak_busy_chats_bucket"
+_WAIT_THRESHOLDS = ((5.0, "lt_5s"), (30.0, "5s_to_30s"), (120.0, "30s_to_2m"), (600.0, "2m_to_10m"))
+
+
+def wait_bucket(seconds: float | None) -> str:
+ if seconds is None:
+ return "never"
+ seconds = max(0.0, seconds)
+ return next((label for limit, label in _WAIT_THRESHOLDS if seconds < limit), "gte_10m")
+
+
+def busy_arrival_fields(*, platform: Any, disposition: str, seconds: float | None) -> dict[str, str]:
+ from .shared_metrics_gateway import _platform
+
+ return {
+ "disposition": disposition if disposition in BUSY_ARRIVAL_DISPOSITIONS else "other",
+ "platform": _platform(platform),
+ "wait_bucket": wait_bucket(seconds),
+ }
+
+
+# ---- busy arrivals ----
+
+class _Arrival:
+ __slots__ = ("admission_id", "admitting", "arrived", "disposition", "done", "home", "merged", "platform")
+
+ def __init__(self, platform: Any, home: str | None) -> None:
+ self.arrived = time.monotonic()
+ self.platform, self.home = platform, home
+ self.disposition = "queued" # admitted to the FIFO unless the busy resolution says otherwise
+ self.admitting = False # reached the runner's admission: from here on, never running = dropped
+ self.admission_id: str | None = None
+ self.merged: list[_Arrival] = []
+ self.done = False
+
+
+# FIFO admission id -> arrival whose row is still queued. Touched only on the gateway loop.
+_queued: OrderedDict[str, _Arrival] = OrderedDict()
+_QUEUED_MAX = 4096
+
+
+def _tag(event: Any) -> _Arrival | None:
+ tag = getattr(event, "_busy_arrival", None)
+ return tag if isinstance(tag, _Arrival) and not tag.done else None
+
+
+def stamp_busy_arrival(adapter: Any, event: Any) -> None:
+ """A message reached the adapter while its chat is busy (``_handle_message_while_active`` hands
+ it to the shared runtime's busy dispatch, re-entered for the same event when a burst ends)."""
+ if getattr(event, "_busy_arrival", None) is not None or getattr(event, "internal", False) or event.get_command():
+ return
+ try:
+ from .shared_metrics_gateway import _chat_home, _source_platform
+
+ chat_id = getattr(event.source, "chat_id", None)
+ event._busy_arrival = _Arrival(_source_platform(adapter, chat_id), _chat_home(adapter, chat_id))
+ except Exception:
+ logger.debug("Busy arrival not stamped", exc_info=True)
+
+
+def note_busy_merged(head: Any, event: Any) -> None:
+ """``event`` was folded into the held burst ``head``: its fate is the head's."""
+ tag, head_tag = _tag(event), _tag(head)
+ if tag is not None and head_tag is not None:
+ tag.done = True
+ head_tag.merged.append(tag)
+
+
+def note_busy_outcome(event: Any, outcome: Any) -> None:
+ """The busy resolution for a follow-up (``_BusySteerOutcome``): steered into the running turn
+ (steer or redirect) reaches the agent now; a hard interrupt ends the turn so it runs next."""
+ tag = _tag(event)
+ if tag is None:
+ return
+ _bind_home(tag)
+ if outcome.steered or outcome.redirected:
+ _resolve(tag, "steered", time.monotonic())
+ elif outcome.effective_mode == "interrupt":
+ tag.disposition = "interrupted"
+
+
+def note_busy_admitting(event: Any) -> None:
+ """The runner is admitting the message to the routed profile's FIFO (in that profile's scope)."""
+ tag = _tag(event)
+ if tag is not None:
+ tag.admitting = True
+ _bind_home(tag)
+
+
+def _bind_home(tag: _Arrival) -> None:
+ from hermes_constants import get_hermes_home
+
+ tag.home = str(get_hermes_home())
+
+
+def note_busy_admitted(event: Any, admission_id: str, status: str) -> None:
+ """The row is committed; ``status`` as read right after. A drain that already claimed it ran it."""
+ tag = _tag(event)
+ if tag is None:
+ return
+ if status == "queued":
+ tag.admission_id = str(admission_id)
+ _queued[tag.admission_id] = tag
+ while len(_queued) > _QUEUED_MAX:
+ _queued.popitem(last=False)[1].done = True
+ elif status in ("started", "terminal"):
+ _resolve(tag, tag.disposition, time.monotonic())
+
+
+def busy_turn_started(admission_id: Any) -> None:
+ """The FIFO claimed this row and is running it: a queued busy arrival reached the agent."""
+ tag = _queued.pop(str(admission_id), None)
+ if tag is not None and not tag.done:
+ _resolve(tag, tag.disposition, time.monotonic())
+
+
+def settle_busy_arrival(event: Any, *, discarded: bool = False) -> None:
+ """The busy handler for ``event`` returned (or its held burst was dropped by /stop, /new):
+ an arrival that reached admission and never ran was dropped. One stopped by a restart is not
+ counted: its committed row outlives this process."""
+ tag = _tag(event)
+ if tag is None:
+ return
+ if tag.admission_id is not None:
+ _queued.pop(tag.admission_id, None)
+ if not discarded and _cancelling():
+ tag.done = True
+ elif discarded or tag.admitting:
+ _resolve(tag, "dropped", None)
+ else:
+ tag.done = True # answered before admission (approval reply, plugin consume, refused sender)
+
+
+def _cancelling() -> bool:
+ try:
+ task = asyncio.current_task()
+ except RuntimeError: # no running loop
+ return False
+ return task is not None and task.cancelling() > 0
+
+
+def _resolve(tag: _Arrival, disposition: str, reached: float | None) -> None:
+ rows = [(tag, disposition)] + [(merged, "merged") for merged in tag.merged]
+ for arrival, kind in rows:
+ arrival.done = True
+ seconds = None if reached is None else reached - arrival.arrived
+ from .shared_metrics_gateway import _in_home, _submit
+
+ _submit(_in_home, tag.home, _emit_busy_arrival, arrival.platform, kind, seconds)
+
+
+def _emit_busy_arrival(platform: Any, disposition: str, seconds: float | None) -> None:
+ from .shared_metrics_events import _emit
+
+ _emit(BUSY_ARRIVAL_METRIC, busy_arrival_fields, platform=platform, disposition=disposition, seconds=seconds)
+
+
+# ---- peak of chats with a running turn, per owning profile and UTC day ----
+
+_peak_lock = threading.Lock()
+_running: dict[str, str] = {} # session key -> owning profile home (resolved)
+_peaks: dict[str, tuple[str, int]] = {} # home -> (UTC day, most chats running at once that day)
+_resolved: dict[str, str] = {}
+_now: Callable[[], float] = time.time # test / live-probe seam
+
+
+def _day(epoch: float) -> str:
+ return datetime.fromtimestamp(epoch, tz=UTC).date().isoformat()
+
+
+def _home_key(home: Any) -> str:
+ raw = str(home)
+ if raw not in _resolved:
+ try:
+ _resolved[raw] = str(Path(raw).resolve())
+ except OSError:
+ _resolved[raw] = raw
+ return _resolved[raw]
+
+
+def observe_running_chats(session_keys: Any) -> None:
+ """The runner's running-turn set at a turn boundary (claim or release). A newly running chat
+ belongs to the profile whose scope claimed it."""
+ try:
+ keys = {str(key) for key in session_keys}
+ home = None
+ with _peak_lock:
+ for key in [k for k in _running if k not in keys]:
+ del _running[key]
+ for key in keys - set(_running):
+ if home is None:
+ from hermes_constants import get_hermes_home
+
+ home = _home_key(get_hermes_home())
+ _running[key] = home
+ counts: dict[str, int] = {}
+ for owner in _running.values():
+ counts[owner] = counts.get(owner, 0) + 1
+ today = _day(_now())
+ for owner, count in counts.items():
+ day, peak = _peaks.get(owner, (today, 0))
+ _peaks[owner] = (today, count if day != today else max(peak, count))
+ except Exception:
+ logger.debug("Running-chat peak not updated", exc_info=True)
+
+
+def day_peak(home: Any, day: str) -> int:
+ """Most chats of ``home``'s profile running at once on UTC ``day``, as seen by this process.
+ A later stored day means ``day`` closed with what was folded before; chats still running when
+ the day turned count toward the new one."""
+ owner = _home_key(home)
+ with _peak_lock:
+ running = sum(1 for h in _running.values() if h == owner)
+ stored_day, peak = _peaks.get(owner, (day, 0))
+ if stored_day == day:
+ return max(peak, running)
+ return running if stored_day < day else 0
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index a50ca9c1341..8a899ac79d0 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -20,6 +20,7 @@ from .shared_metrics_prepared_compaction import (
PREPARED_COMPACTION_DIMENSIONS, PREPARED_COMPACTION_MARK, PREPARED_COMPACTION_METRIC,
PREPARED_COMPACTION_SNAPSHOT_DIMENSIONS,
)
+from .shared_metrics_busy import BUSY_ARRIVAL_DISPOSITIONS, BUSY_ARRIVAL_METRIC, BUSY_PEAK_FIELD, BUSY_WAIT_BUCKETS
SCHEMA_KEY = "hermes.metrics.schema_version"
# A random per-emit token (no payload) on rows whose producer waits to learn they were SAVED: facts
@@ -1024,7 +1025,7 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {
# ---- v5 engagement ----
ENGAGEMENT_DAY_METRIC: {
"active_minutes_bucket": ACTIVE_MINUTES_BUCKETS, "active_profile_count_bucket": SIZE_BUCKETS,
- "surfaces_used_count": SURFACES_USED_BUCKETS,
+ "surfaces_used_count": SURFACES_USED_BUCKETS, BUSY_PEAK_FIELD: COUNT_BUCKETS,
},
ENGAGEMENT_SURFACE_METRIC: {"active_minutes_bucket": ACTIVE_MINUTES_BUCKETS, "surface": ENGAGEMENT_SURFACES},
MODEL_SWITCH_AFTER_METRIC: {"turns_before_switch_bucket": TURNS_BEFORE_SWITCH_BUCKETS},
@@ -1068,6 +1069,7 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {
},
# ---- end v4 connectors ----
PREPARED_COMPACTION_METRIC: {**PREPARED_COMPACTION_DIMENSIONS, "failure_class": COMPRESSION_FAILURE_CLASSES},
+ BUSY_ARRIVAL_METRIC: {"disposition": BUSY_ARRIVAL_DISPOSITIONS, "platform": ADAPTER_PLATFORMS, "wait_bucket": BUSY_WAIT_BUCKETS},
}
_MODEL_ROUTE_MAX_LENGTHS = {
"model": MODEL_IDENTIFIER_MAX_LENGTH, "provider": PROVIDER_IDENTIFIER_MAX_LENGTH,
@@ -1164,6 +1166,7 @@ _LEGACY_METRIC_FIELDS[EXTENSION_INSTALL_METRIC] = (
)
_LEGACY_METRIC_FIELDS[UPDATE_RUN_METRIC] = (_METRIC_FIELDS[UPDATE_RUN_METRIC] - {"failure_class"},)
# ---- end iuf c1 ----
+_LEGACY_METRIC_FIELDS[ENGAGEMENT_DAY_METRIC] = (_METRIC_FIELDS[ENGAGEMENT_DAY_METRIC] - {BUSY_PEAK_FIELD},) # busy-wait
COUNTER_METRICS = frozenset(_METRIC_FIELDS) - {LEGACY_MODEL_CALL_METRIC}
# Counters whose value is a summed quantity rather than an event count.
SUM_METRICS = frozenset({MODEL_TOKENS_METRIC})
@@ -1220,6 +1223,7 @@ _DECISION_MARK_METRICS = {
# ---- end iuf c2 ----
TOOL_SEARCH_MARK: TOOL_SEARCH_METRIC, TOOL_BATCH_MARK: TOOL_BATCH_METRIC,
CONNECTOR_CHAIN_MARK: CONNECTOR_CHAIN_METRIC, PREPARED_COMPACTION_MARK: PREPARED_COMPACTION_METRIC,
+ BUSY_ARRIVAL_METRIC: BUSY_ARRIVAL_METRIC, # busy-wait: the gateway marks under the metric's own name
}
diff --git a/hermes_cli/observability/shared_metrics_engagement.py b/hermes_cli/observability/shared_metrics_engagement.py
index d9912f2a650..7d8ff223dbb 100644
--- a/hermes_cli/observability/shared_metrics_engagement.py
+++ b/hermes_cli/observability/shared_metrics_engagement.py
@@ -17,6 +17,10 @@ profile's day row reports the count; every other profile's row carries ``0`` so
host total twice. When the root profile has collection off, nothing is written to its store and
the count is not reported.
+The day row also carries ``gateway_peak_busy_chats_bucket``: the most chats of this profile that had
+a turn running at the same moment that day, as the gateway process serving them saw it
+(``shared_metrics_busy``); folded in at every interaction, ``0`` for a profile no gateway served.
+
Only closed enums, buckets, catalog-sanitized provider/model names and profile hashes are stored
in the state row; the hashes never leave it.
"""
@@ -49,6 +53,7 @@ _SWITCH_THRESHOLDS = ((2, "1"), (4, "2_to_3"), (11, "4_to_10"), (31, "11_to_30")
_ENGAGED_ENTRYPOINTS = frozenset({"gateway_message", "interactive", "one_shot"})
_INTERACTION_METRICS = frozenset({contract.TASK_STARTED_METRIC, contract.TASK_FINISHED_METRIC})
_ALL = "*"
+_BUSY_PEAK = "busy_chats_peak"
# Test / live-probe seam: wall clock in epoch seconds.
_now: Callable[[], float] = time.time
@@ -106,9 +111,11 @@ def record(store: Any, resource: dict[str, str], *, surface: str | None, route:
root_home = _root_home(profile_home)
owner = root_home == profile_home
profile = _profile_hash(profile_home) if surface is not None else None
+ from .shared_metrics_busy import day_peak
+
store.update_rollup_state(STATE_KEY, lambda state: apply(
state, now_ms=_now_ms(), resource=resource, surface=surface, route=route,
- profile=profile if owner else None, owner=owner,
+ profile=profile if owner else None, owner=owner, busy_peak=lambda day: day_peak(profile_home, day),
))
if profile is not None and not owner and _collects(root_home):
_root_store(root_home).update_rollup_state(STATE_KEY, lambda state: apply(
@@ -185,11 +192,11 @@ def _valid_state(state: Any) -> bool:
def apply(
state: dict[str, Any] | None, *, now_ms: int, resource: dict[str, str],
surface: str | None = None, route: tuple[str, str] | None = None, profile: str | None = None,
- owner: bool = False,
+ owner: bool = False, busy_peak: Callable[[str], int] | None = None,
) -> tuple[dict[str, Any], list[tuple[str, dict, dict, str]]]:
- """Fold one interaction (``surface``), attended turn (``route``) and/or a profile's user turn
- (``profile``, host accumulator only) into the day's state; close the stored day first when the
- clock has moved past it."""
+ """Fold one interaction (``surface``), attended turn (``route``), a profile's user turn
+ (``profile``, host accumulator only) and/or the day's running-chat peak (``busy_peak(day)``) into
+ the day's state; close the stored day first when the clock has moved past it."""
today, rows = _utc_day(now_ms), []
if state is not None and not _valid_state(state):
state = None
@@ -211,6 +218,9 @@ def apply(
if route is not None:
key = " ".join(route)
state["models"][key] = int(state["models"].get(key, 0)) + 1
+ if busy_peak is not None:
+ stored = state.get(_BUSY_PEAK)
+ state[_BUSY_PEAK] = max(stored if isinstance(stored, int) else 0, busy_peak(today))
return state, rows
@@ -238,9 +248,11 @@ def close_day(state: dict[str, Any]) -> list[tuple[str, dict, dict, str]]:
for name, v in sorted(surfaces.items())
]
provider, model = _primary(state["models"])
+ peak = state.get(_BUSY_PEAK)
rows.append((contract.ENGAGEMENT_DAY_METRIC, {
"active_minutes_bucket": active_minutes_bucket(int((streams.get(_ALL) or [0])[0])),
"active_profile_count_bucket": contract.size_bucket(active_profiles),
+ contract.BUSY_PEAK_FIELD: contract.count_bucket(peak if isinstance(peak, int) else 0),
"primary_model": model, "primary_provider": provider,
"surfaces_used_count": surfaces_used_bucket(len(surfaces)),
}, resource, day))
diff --git a/tests/hermes_cli/test_shared_metrics_busy.py b/tests/hermes_cli/test_shared_metrics_busy.py
new file mode 100644
index 00000000000..a29da75b4cd
--- /dev/null
+++ b/tests/hermes_cli/test_shared_metrics_busy.py
@@ -0,0 +1,190 @@
+"""Invariants for "is the agent making people wait?": every human message that reaches a busy chat
+is counted exactly once, when its fate is known, and the day row reports the most chats a profile
+had running at once."""
+
+import asyncio
+from datetime import UTC, datetime
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import Platform
+from gateway.platforms.base import BasePlatformAdapter
+from gateway.platforms.event import MessageEvent
+from gateway.session import SessionSource
+from gateway.session_ingress_burst import discard_busy_burst, dispatch_busy_burst
+from hermes_cli.observability import relay_shared_metrics as rsm
+from hermes_cli.observability import shared_metrics_busy as busy
+from hermes_cli.observability import shared_metrics_contract as contract
+from hermes_cli.observability import shared_metrics_engagement as engagement
+from hermes_cli.observability import shared_metrics_gateway as smg
+from hermes_cli.observability.shared_metrics import SharedMetricsStore
+
+KEY = "agent:main:telegram:dm:42"
+RESOURCE = {"architecture": "x86_64", "hermes_version": "0.0.0", "install_method": "git", "os_family": "linux"}
+DAY1 = datetime(2026, 9, 27, 9, 0, tzinfo=UTC).timestamp()
+
+
+def rows(monkeypatch):
+ got, collecting = [], {"on": True}
+ monkeypatch.setattr(rsm, "enabled", lambda: collecting["on"])
+ monkeypatch.setattr(rsm, "record_process_mark", lambda mark, data: got.append((mark, dict(data))))
+ monkeypatch.setattr(busy, "_queued", type(busy._queued)())
+
+ def read():
+ smg.drain()
+ out = [(contract._DECISION_MARK_METRICS[mark], data) for mark, data in got]
+ got.clear()
+ return out
+
+ read.collecting = collecting
+ return read
+
+
+class _Adapter:
+ """The busy-dispatch surface of a platform adapter; ``handler`` stands in for the runner."""
+
+ platform = Platform.TELEGRAM
+ name = "telegram"
+ serial_receive_loop = False
+ gateway_runner = None
+ _busy_text_mode = "queue"
+ _busy_text_debounce_seconds = 120.0
+ _busy_text_hard_cap_seconds = 120.0
+ _is_queue_text_debounce_candidate = BasePlatformAdapter._is_queue_text_debounce_candidate
+ _can_merge_text_debounce_events = BasePlatformAdapter._can_merge_text_debounce_events
+ _unwrap_ephemeral = BasePlatformAdapter._unwrap_ephemeral
+
+ def __init__(self, handler):
+ self._message_handler = handler
+ self._background_tasks = set()
+
+ async def _release_turn_marker(self, event):
+ return None
+
+
+def _message(text):
+ return MessageEvent(text=text, source=SessionSource(platform=Platform.TELEGRAM, chat_id="42", user_id="7"))
+
+
+def test_every_busy_arrival_counts_once_when_its_fate_is_known(rows):
+ """Through the adapter's real busy dispatch: a held burst that /stop drops counts its head as
+ dropped and the message folded into it as merged (both never reached the agent); a burst that
+ commits and later runs as its own turn counts queued + merged with the wait until that turn; a
+ busy message answered before admission (an approval reply) and a command are not counted."""
+
+ async def scenario():
+ stop = _Adapter(handler=None)
+ first, second = _message("first"), _message("second")
+ held = [asyncio.create_task(dispatch_busy_burst(stop, e, KEY)) for e in (first, second)]
+ await asyncio.sleep(0)
+ discard_busy_burst(stop, KEY) # /stop while the burst is held
+ await asyncio.gather(*held)
+
+ async def runner_queues(event): # the runner admits it to the FIFO; the turn starts later
+ busy.note_busy_admitting(event)
+ busy.note_busy_admitted(event, "adm-1", "queued")
+ await asyncio.sleep(0)
+ busy.busy_turn_started("adm-1")
+
+ queue = _Adapter(runner_queues)
+ tasks = [asyncio.create_task(dispatch_busy_burst(queue, e, KEY)) for e in (_message("a"), _message("b"))]
+ await asyncio.sleep(0)
+ queue.__dict__["_shared_bursts"][KEY].timer.cancel()
+ from gateway.session_ingress_burst import _flush
+ await _flush(queue, KEY, queue.__dict__["_shared_bursts"][KEY])
+ await asyncio.gather(*tasks)
+ await asyncio.gather(*queue._background_tasks)
+
+ async def approval_reply(event):
+ return None # answered by the approval intercept: never admitted
+
+ answered = _Adapter(approval_reply)
+ answered._busy_text_mode = "interrupt" # not a debounced burst: straight to the runner
+ await dispatch_busy_burst(answered, _message("yes"), KEY)
+ await dispatch_busy_burst(answered, _message("/status"), KEY)
+
+ asyncio.run(scenario())
+ got = sorted((data["disposition"], data["wait_bucket"]) for _metric, data in rows())
+ assert got == [("dropped", "never"), ("merged", "lt_5s"), ("merged", "never"), ("queued", "lt_5s")]
+
+
+def test_busy_dispositions_follow_the_busy_resolution_and_collection_off_records_nothing(rows):
+ steer, interrupt, cleared = _message("s"), _message("i"), _message("c")
+ for event in (steer, interrupt, cleared):
+ busy.stamp_busy_arrival(_Adapter(None), event)
+ busy.note_busy_outcome(steer, SimpleNamespace(steered=False, redirected=True, effective_mode="interrupt"))
+ busy.note_busy_outcome(interrupt, SimpleNamespace(steered=False, redirected=False, effective_mode="interrupt"))
+ busy.note_busy_admitting(interrupt)
+ busy.note_busy_admitted(interrupt, "adm-2", "queued")
+ interrupt._busy_arrival.arrived -= 45 # the interrupted turn took 45 s to stop
+ busy.busy_turn_started("adm-2")
+ busy.note_busy_admitting(cleared)
+ busy.note_busy_admitted(cleared, "adm-3", "queued")
+ busy.settle_busy_arrival(cleared) # /new cancelled the queued row: its handler returned, never ran
+ for event in (steer, interrupt, cleared):
+ busy.settle_busy_arrival(event)
+ got = rows()
+ assert sorted((d["disposition"], d["wait_bucket"]) for _m, d in got) == [
+ ("dropped", "never"), ("interrupted", "30s_to_2m"), ("steered", "lt_5s")]
+ for metric, data in got:
+ assert metric == "hermes.gateway.busy_arrival.count"
+ assert data["platform"] == "telegram"
+ assert contract.counter_dimensions_are_valid(metric, data)
+
+ rows.collecting["on"] = False
+ late = _message("late")
+ busy.stamp_busy_arrival(_Adapter(None), late)
+ busy.note_busy_outcome(late, SimpleNamespace(steered=True, redirected=False, effective_mode="steer"))
+ assert rows() == []
+
+
+def _store(home):
+ root = home / "telemetry" / "shared_metrics"
+ return SharedMetricsStore(root / "metrics.sqlite3", root / "outbox")
+
+
+def test_day_row_reports_each_profiles_peak_of_chats_running_at_once(tmp_path, monkeypatch):
+ """Profile A runs two chats at once, then one; profile B one. Each profile's closed day row
+ carries its own peak (claimed in the owning profile's scope, not the launch profile's), and a
+ row recorded before the field existed still packages."""
+ from gateway.run_agent_cache import GatewayAgentCacheMixin
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ monkeypatch.setattr("gateway.run._write_runtime_status_quiet", lambda **_: None)
+ monkeypatch.setattr(busy, "_running", {})
+ monkeypatch.setattr(busy, "_peaks", {})
+ clock = {"now": DAY1}
+ monkeypatch.setattr(busy, "_now", lambda: clock["now"])
+ monkeypatch.setattr(engagement, "_now", lambda: clock["now"])
+ a, b = tmp_path / "a", tmp_path / "b"
+ running: list[str] = []
+ runner = SimpleNamespace(_active_work_count=lambda: len(running),
+ _running_agent_items=lambda: [(key, object()) for key in running])
+
+ def turn_boundary(home, keys):
+ running[:] = keys
+ token = set_hermes_home_override(str(home))
+ try:
+ GatewayAgentCacheMixin._persist_active_agents(runner)
+ finally:
+ reset_hermes_home_override(token)
+
+ turn_boundary(a, ["a:1"])
+ turn_boundary(a, ["a:1", "a:2"])
+ turn_boundary(b, ["a:1", "a:2", "b:1"])
+ turn_boundary(a, ["b:1"]) # A's turns end; the release runs in whatever scope
+ for home in (a, b):
+ engagement.record(_store(home), RESOURCE, surface="gateway", route=None)
+ clock["now"] = DAY1 + 86_400
+ for home in (a, b):
+ engagement.record(_store(home), RESOURCE, surface="gateway", route=None)
+
+ for home, peak in ((a, "2"), (b, "1")):
+ [row] = [c["dimensions"] for c in _store(home).counter_snapshot()
+ if c["metric_name"] == contract.ENGAGEMENT_DAY_METRIC]
+ assert row[contract.BUSY_PEAK_FIELD] == peak
+ assert contract.counter_dimensions_are_valid(contract.ENGAGEMENT_DAY_METRIC, row)
+ legacy = {k: v for k, v in row.items() if k != contract.BUSY_PEAK_FIELD}
+ assert contract.counter_dimensions_are_valid(contract.ENGAGEMENT_DAY_METRIC, legacy)
diff --git a/tests/hermes_cli/test_shared_metrics_engagement.py b/tests/hermes_cli/test_shared_metrics_engagement.py
index f17e662edf0..42bca06f1fe 100644
--- a/tests/hermes_cli/test_shared_metrics_engagement.py
+++ b/tests/hermes_cli/test_shared_metrics_engagement.py
@@ -82,7 +82,7 @@ def test_a_closed_day_reports_active_time_surfaces_and_primary_model_once(direct
])
assert _stored_values(tmp_path, "hermes.engagement.day.count") == [(
{"active_minutes_bucket": "5m_to_30m", "active_profile_count_bucket": "1", "primary_model": PUBLIC,
- "primary_provider": "openrouter", "surfaces_used_count": "2"}, 1)]
+ "primary_provider": "openrouter", "surfaces_used_count": "2", "gateway_peak_busy_chats_bucket": "0"}, 1)]
periods = {c["period_start"] for c in other_process.counter_snapshot() if c["metric_name"].startswith("hermes.engagement")}
assert periods == {"2026-09-27"}
@@ -299,13 +299,13 @@ def test_active_profiles_are_counted_once_per_host_day_on_the_root_profiles_row(
engagement.record(_profile_store(home), resource, surface="cli", route=None)
zero = {"active_minutes_bucket": "lt_5m", "active_profile_count_bucket": "0", "primary_model": "none",
- "primary_provider": "none", "surfaces_used_count": "1"}
+ "primary_provider": "none", "surfaces_used_count": "1", "gateway_peak_busy_chats_bucket": "0"}
assert _day_rows(a) == [("2026-09-27", zero)]
assert _day_rows(b) == [] # B has not seen a later day yet; its row will carry 0 too
if root_collects:
assert _day_rows(root) == [("2026-09-27", {
"active_minutes_bucket": "0", "active_profile_count_bucket": "2", "primary_model": "none",
- "primary_provider": "none", "surfaces_used_count": "0"})]
+ "primary_provider": "none", "surfaces_used_count": "0", "gateway_peak_busy_chats_bucket": "0"})]
else:
assert not (root / "telemetry").exists()
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index f950604250c..a727deab73c 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -496,6 +496,7 @@ itself ships.
| `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. `outcome` is `success`, `noop`, `failed`, `refused`, or `partial` (committed, then interrupted or left the user's stashed changes parked; `hermes update` rows only). A `partial` run counts as an attempt and as a failure in the per-user update rate (these runs read `failed` before, so the trend stays continuous), and its reasons sit with the runs that applied the code and then failed a follow-up. `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, or the bare bootstrap interpreter finishes after dependency preparation failed (it cannot load the config reader), is parked locally with only the bounded fields the row needs and counted by the next start, which purges it unrecorded when collection is off (nothing is parked when that interpreter can already tell collection is off); Desktop packaged self-updates (`apply_mode=package`) are reported once by the app, after the restart that applies them. A lock refusal (`lock_held`) of the update child a Desktop hand-off launched (the update marker names it, or its parent, as the hand-off's delegate) reads `failed`, not `refused`: the Desktop already quit to run that update and reports it as a failed one. That includes the checkout lock held by another mutator (a Desktop build, a venv sync), not only another update running. |
| `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 (a start with collection off deletes these markers, and pending `provider_setup` ones, unreported). Turns aborted by a turn watchdog also count as `exit_kind=watchdog`. |
+| `hermes.gateway.busy_arrival.count` | platform, disposition (`queued`/`steered`/`interrupted`/`merged`/`dropped`/`other`), wait bucket (`lt_5s`, `5s_to_30s`, `30s_to_2m`, `2m_to_10m`, `gte_10m`, `never`) | How often people message an agent that is still busy in their chat, and how long that message waits before the agent sees it. One row per human message that arrives while the chat's turn is running, recorded once its fate is known: `queued` (ran later as its own turn), `steered` (delivered into the running turn: `busy_input_mode: steer`, or an interrupt-mode correction that redirects the turn), `interrupted` (stopped the running turn, then ran as the next one), `merged` (folded into another busy message of the same burst; its wait is until that message reached the agent), `dropped` (never ran: cleared by `/stop` or `/new`, refused, or over the queue cap). The wait runs from arrival to its own turn starting or the steer landing, `never` when dropped. Commands, approval answers, internal events and background-process notifications are not counted. A message still queued when the gateway restarts is not counted: its saved row runs in the next process. |
Replies the relay connector carries report the platform the conversation lives
on (the inbound's platform, else the platform the connector fronts when it
@@ -619,7 +620,7 @@ subagents count there; background review and the curator never do.
| Metric | Dimensions | Question it answers |
|---|---|---|
| `hermes.engagement.surface_day.count` | surface (`cli`, `tui`, `desktop`, `gateway`, `acp`), active-minutes bucket (`0`, `lt_5m`, `5m_to_30m`, `30m_to_2h`, `2h_to_6h`, `gte_6h`) | How long each surface is actually used per day. One row per surface used on a closed UTC day. |
-| `hermes.engagement.day.count` | active-minutes bucket, surfaces-used count (`0`–`3`, `gte_4`), primary provider, primary model, active-profile count bucket | Days active per week, multi-surface use, and next-day / next-week return by model. One row per closed UTC day a person used Hermes on. The root (default) profile also writes a host row on days only other profiles were active: `surfaces_used_count` `0`, active minutes `0`, carrying the active-profile count; exclude `surfaces_used_count=0` rows when counting days active. |
+| `hermes.engagement.day.count` | active-minutes bucket, surfaces-used count (`0`–`3`, `gte_4`), primary provider, primary model, active-profile count bucket, gateway peak busy-chats bucket (`0`, `1`, `2`, `3_to_5`, `6_to_10`, `gte_11`) | Days active per week, multi-surface use, next-day / next-week return by model, and whether an install ever runs several chats at once. One row per closed UTC day a person used Hermes on. The root (default) profile also writes a host row on days only other profiles were active: `surfaces_used_count` `0`, active minutes `0`, carrying the active-profile count; exclude `surfaces_used_count=0` rows when counting days active. |
| `hermes.model_switch_after.count` | provider, model (the model switched away from), turns-before-switch bucket (`1`, `2_to_3`, `4_to_10`, `11_to_30`, `gte_31`) | How long users stay on a model before `/model` leaves it. Counts the user turns sent on the old model in the conversation (compression segments included; a turn that failed over to a fallback still counts for the model it was sent on; background review forks are not turns); a switch before any turn on the current model is not counted. |
Active time is accumulated locally per UTC day: the sum of the gaps between
@@ -645,6 +646,13 @@ day row carries the count (it reports a day even when the root itself was
idle, with `0` active minutes and surfaces); every other profile's row reads
`0`. When the root profile has collection off, nothing is written to its
database and the count is not reported.
+
+`gateway_peak_busy_chats_bucket` is the most distinct chats (session keys) of the profile that had a
+turn running at the same moment during that UTC day, as the gateway process serving the profile saw
+them. The gateway keeps the running set and the day's maximum in memory per owning profile (the
+profile whose scope claimed the turn, not the launch profile) and folds the maximum into the
+profile's day state at each interaction; no chat id or session key is stored or sent. A profile no
+gateway served reads `0`; rows recorded before the field existed omit it.
<!-- ---- end v5 engagement ---- -->
<!-- ---- v5 signals ---- -->