The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telemetry): one context_peak row per conversation across compression
teknium12c9b79a5a33e
diff --git a/hermes_cli/observability/relay_shared_metrics.py b/hermes_cli/observability/relay_shared_metrics.pyindex c71c9f006c9..6b2abd9b38d 100644--- a/hermes_cli/observability/relay_shared_metrics.py+++ b/hermes_cli/observability/relay_shared_metrics.py@@ -13,6 +13,7 @@ from time import monotonic_nsfrom typing import Any, Callablefrom agent import relay_runtime+from agent.portal_tags import get_conversation_contextfrom hermes_cli.version_info import get_version_infofrom .shared_metrics import SharedMetricsStore@@ -155,6 +156,27 @@ class _MetricsSession:first_turn_ns: int = 0last_turn_ns: int = 0model_state: model_.ModelSessionState = field(default_factory=model_.ModelSessionState)+ lineage_root: str = ""+++@dataclass+class _PeakLineage:+ """Open segments of one conversation (compression rotates the session id) and their merged peak."""++ open: set[str] = field(default_factory=set)+ peak: model_.ModelSessionState = field(default_factory=model_.ModelSessionState)+++def _absorb_peak(into: model_.ModelSessionState, segment: model_.ModelSessionState) -> None:+ """Merge one closed segment's context peak (fullest fill wins, a limit hit anywhere sticks)."""+ if segment.peak_route is None:+ return+ into.limit_hit = into.limit_hit or segment.limit_hit+ fuller = segment.peak_window is not None and (+ into.peak_window is None or segment.peak_tokens / segment.peak_window > into.peak_tokens / into.peak_window+ )+ if into.peak_route is None or fuller:+ into.peak_route, into.peak_tokens, into.peak_window = segment.peak_route, segment.peak_tokens, segment.peak_windowclass _Runtime:@@ -171,6 +193,9 @@ class _Runtime:self._task_sessions: dict[tuple[str, str], _MetricsSession] = {}self._turn_sessions: dict[tuple[str, str], _MetricsSession] = {}self._sessions_lock = threading.RLock()+ # Leaf lock (nothing is acquired under it): taken while a session.lock is held.+ self._lineages: dict[str, _PeakLineage] = {}+ self._lineage_lock = threading.Lock()self._task_creation_lock = threading.RLock()self._task_sessions_lock = threading.RLock()# Guards the opt-in send pass: at most one in flight per process.@@ -354,6 +379,7 @@ class _Runtime:if model_call is None:returnmodel_call.fields = contract.model_call_fields(event)+ self._join_lineage(session, session.tasks.get(model_call.task_id))if finish:session.model_state.observe_call(model_call.fields, event.get("usage"), event.get("context_length"))model_call.ttft_bucket = fields_.ttft_bucket(event)@@ -543,6 +569,8 @@ class _Runtime:with self._task_sessions_lock:self._task_sessions.clear()self._turn_sessions.clear()+ with self._lineage_lock:+ self._lineages.clear()self._release()def _release(self) -> None:@@ -835,10 +863,38 @@ class _Runtime:session, None, contract.MODEL_FRICTION_MARK, model_.friction_fields("interrupt", route),)- def _emit_model_session_marks(self, session: _MetricsSession) -> None:- state = session.model_state- marks = [(contract.CONTEXT_PEAK_MARK, state.context_peak_fields())]- abandoned = state.quick_abandon_route(monotonic_ns())+ def _join_lineage(self, session: _MetricsSession, task: _TaskRun | None) -> None:+ """Compression rotates the session id mid-conversation. The turn publishes the lineage root+ (the Portal conversation id), so every segment joins one context-peak lineage. Delegated+ children share their parent's root but are their own conversation."""+ if session.lineage_root or (task is not None and task.start_fields.get("entrypoint") == "delegated"):+ return+ root = get_conversation_context()+ if not root:+ return+ session.lineage_root = root+ with self._lineage_lock:+ self._lineages.setdefault(root, _PeakLineage()).open.add(session.session_id)++ def _context_peak_fields(self, session: _MetricsSession, counted: bool) -> dict[str, str] | None:+ """This session's peak, or, for a lineage segment, the conversation's merged peak once its+ last open segment closes (None before that)."""+ state = session.model_state if counted else None+ with self._lineage_lock:+ lineage = self._lineages.get(session.lineage_root) if session.lineage_root else None+ if lineage is None:+ return state.context_peak_fields() if state is not None else None+ lineage.open.discard(session.session_id)+ if state is not None:+ _absorb_peak(lineage.peak, state)+ if lineage.open:+ return None+ del self._lineages[session.lineage_root]+ return lineage.peak.context_peak_fields()++ def _emit_model_session_marks(self, session: _MetricsSession, counted: bool) -> None:+ marks = [(contract.CONTEXT_PEAK_MARK, self._context_peak_fields(session, counted))]+ abandoned = session.model_state.quick_abandon_route(monotonic_ns()) if counted else Noneif abandoned is not None and model_.attended(session.start_fields):marks.append((contract.MODEL_FRICTION_MARK, model_.friction_fields("quick_abandon", abandoned)))for mark, data in marks:@@ -859,9 +915,10 @@ class _Runtime:def _emit_session_summary(self, session: _MetricsSession) -> None:"""One hermes.session.count row per closed top-level session (delegated children excluded)."""start = session.start_fields- if not session.turns or start is None or start.get("entrypoint") == "delegated":+ counted = bool(session.turns) and start is not None and start.get("entrypoint") != "delegated"+ self._emit_model_session_marks(session, counted)+ if not counted:return- self._emit_model_session_marks(session)summary = fields_.session_fields(start, turns=session.turns, failed_turns=session.failed_turns,last_outcome=session.last_outcome,diff --git a/tests/hermes_cli/test_shared_metrics_model_attribution.py b/tests/hermes_cli/test_shared_metrics_model_attribution.pyindex 9df7fd6625a..b66184eb47f 100644--- a/tests/hermes_cli/test_shared_metrics_model_attribution.py+++ b/tests/hermes_cli/test_shared_metrics_model_attribution.py@@ -9,6 +9,7 @@ from types import SimpleNamespaceimport pytest+from agent.portal_tags import reset_conversation_context, set_conversation_contextfrom hermes_cli import lifecyclefrom hermes_cli.observability import relay_shared_metricsfrom tests.hermes_cli.test_relay_shared_metrics_runtime import ( # noqa: F401 - fixture@@ -242,3 +243,26 @@ def test_cli_undo_counts_friction_only_when_something_was_undone(direct_runtime,assert done.conversation_history == []assert _stored_values(tmp_path, "hermes.model_friction.count") == [({"model": PUBLIC, "provider": "openrouter", "signal": "undo"}, 1)]+++def test_context_peak_is_one_row_per_conversation_across_compression_rotation(direct_runtime, tmp_path):+ """Compression rotates the session id (s1 -> s1c) under one published conversation root: the+ conversation reports its fullest segment once, whatever order the segments close in. A+ delegated child shares the root but is its own (unreported) conversation and holds nothing open."""+ token = set_conversation_context("s1")+ try:+ _turn("s1", "t1", "openrouter", PUBLIC, prompt_tokens=176_000)+ _turn("child", "c1", "openrouter", PUBLIC, prompt_tokens=199_000, parent_session_id="s1")+ _turn("s1c", "t2", "openrouter", PUBLIC, prompt_tokens=30_000)+ finally:+ reset_conversation_context(token)+ lifecycle.finalize_session(session_id="child")+ lifecycle.finalize_session(session_id="s1c")+ _flush()+ assert not _stored_values(tmp_path, "hermes.context_peak.count"), "emitted before the lineage closed"+ lifecycle.finalize_session(session_id="s1")+ _flush()++ assert _stored_values(tmp_path, "hermes.context_peak.count") == [+ ({"limit_hit": "no", "model": PUBLIC, "peak_fill_bucket": "75_to_90", "provider": "openrouter",+ "window_bucket": "128k_to_256k"}, 1)]diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex 24b8cdff5bf..748bcdca3e5 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -332,7 +332,7 @@ whose provider is unknown reads `custom`.|---|---|---|| `hermes.model_tool_quality.count` | provider, model, call role, issue (`none`, `invalid_json`, `unknown_tool`, `schema_mismatch`, `empty_arguments`, `repaired`) | Which models emit broken tool calls, and how often Hermes had to repair them. Every emitted call counts once (clean ones as `none`), so the value is a rate denominator. `empty_arguments` only counts for tools with required parameters; `repaired` means Hermes fixed the tool name or the argument JSON and ran the call. || `hermes.model_friction.count` | provider, model, signal (`retry`, `undo`, `interrupt`, `quick_abandon`, `switch_away`) | Which models users fight with. Attributed to the model that produced the turn: `/retry` and `/undo` where they execute, a user interrupt of an interactive turn, a session that ends within 60 seconds of a failed turn, and `/model` switching away from the model. |-| `hermes.context_peak.count` | provider, model, peak fill bucket, window bucket (`lt_32k` … `gte_1m`), limit hit (`yes`/`no`) | How close sessions get to each model's context window, and how often they overflow it. One row per closed session; `limit_hit` means a primary call was rejected as too large (context overflow or HTTP 413), the rejections Hermes answers with a forced compression. |+| `hermes.context_peak.count` | provider, model, peak fill bucket, window bucket (`lt_32k` … `gte_1m`), limit hit (`yes`/`no`) | How close sessions get to each model's context window, and how often they overflow it. One row per closed conversation: the session ids a compression rotation continues it under report once, with the fullest segment; `limit_hit` means a primary call was rejected as too large (context overflow or HTTP 413), the rejections Hermes answers with a forced compression. |Local state is written under: