Skip to content

The agent that grows with you

fix(telemetry): engagement reads its day clock under the write lock; busy writes defer instead of failing (M2, m7)

teknium1876072459e31
diff --git a/hermes_cli/observability/shared_metrics.py b/hermes_cli/observability/shared_metrics.py
index 7882e7a5912..558d201cf2c 100644
--- a/hermes_cli/observability/shared_metrics.py
+++ b/hermes_cli/observability/shared_metrics.py
@@ -2,9 +2,11 @@
from __future__ import annotations
+import atexit
import json
import logging
import sqlite3
+import threading
import uuid
from collections.abc import Callable, Iterator
from contextlib import contextmanager
@@ -33,6 +35,8 @@ _PACKAGE_SCHEMA_VERSION = "hermes.shared_metrics.v3"
_STORE_SCHEMA_VERSION = "2"
_BUSY_TIMEOUT_MS = 250
_SCHEMA_BUSY_TIMEOUT_MS = 5_000
+# Writes a busy store could not take within _BUSY_TIMEOUT_MS, kept in memory for the next write.
+_DEFERRED_WRITES_MAX = 1_024
_LOCAL_HISTORY_RETENTION_DAYS = 30
_ACTIVE_INSTALL_STATE_KEY = "client_active_recorded_at"
_INSTALL_SNAPSHOT_STATE_KEY = "install_snapshot_recorded_at"
@@ -191,6 +195,9 @@ class SharedMetricsStore:
_ensure_private(self.outbox_directory, 0o700)
_ensure_private(self.database_path, 0o600)
self._ensure_schema()
+ self._deferred: list[Callable[[sqlite3.Connection], None]] = []
+ self._deferred_lock = threading.Lock()
+ self._drain_at_exit = False
def record_model_call(self, dimensions: dict[str, str], resource: dict[str, str]) -> None:
"""Increment the terminal model-call counter for the current UTC day."""
@@ -261,10 +268,10 @@ class SharedMetricsStore:
amount != 1 and metric_name not in SUM_METRICS
):
raise ValueError(f"Unsupported amount for shared metric: {metric_name}")
- with self._connection() as connection:
- self._record_counter_in_transaction(
- connection, metric_name, dimensions, resource, _utc_now().date().isoformat(), amount
- )
+ period_start = _utc_now().date().isoformat()
+ self._write_or_defer(lambda connection: self._record_counter_in_transaction(
+ connection, metric_name, dimensions, resource, period_start, amount
+ ))
def update_rollup_state(
self, state_key: str,
@@ -273,29 +280,35 @@ class SharedMetricsStore:
"""Read-modify-write one JSON rollup state and record the ``(metric, dimensions, resource,
period_start)`` rows ``update`` closes, in one write transaction: every process of the profile
serializes here, so a closed period is emitted exactly once. Rows the contract rejects are
- dropped (never retried) so one bad row cannot wedge the rollup."""
- with self._write() as connection:
- row = connection.execute(
- "SELECT value FROM telemetry_state WHERE key = ?", (state_key,)
- ).fetchone()
- try:
- state = json.loads(row["value"]) if row is not None else None
- except (TypeError, ValueError):
- state = None
- new_state, rows = update(state if isinstance(state, dict) else None)
- valid = [
- r for r in rows
- if counter_dimensions_are_valid(r[0], r[1]) and client_resource_is_valid(r[2])
- ]
- if valid:
- self._install_id(connection)
- for metric_name, dimensions, resource, period_start in valid:
- self._record_counter_in_transaction(connection, metric_name, dimensions, resource, period_start)
- connection.execute(
- "INSERT INTO telemetry_state(key, value) VALUES (?, ?)"
- " ON CONFLICT(key) DO UPDATE SET value = excluded.value",
- (state_key, _compact_json(new_state)),
- )
+ dropped (never retried) so one bad row cannot wedge the rollup. A busy store defers the update
+ to the next write (it then runs with that write's clock)."""
+ self._write_or_defer(lambda connection: self._update_rollup_state(connection, state_key, update))
+
+ def _update_rollup_state(
+ self, connection: sqlite3.Connection, state_key: str,
+ update: Callable[[dict[str, Any] | None], tuple[dict[str, Any], list[tuple[str, dict, dict, str]]]],
+ ) -> None:
+ row = connection.execute(
+ "SELECT value FROM telemetry_state WHERE key = ?", (state_key,)
+ ).fetchone()
+ try:
+ state = json.loads(row["value"]) if row is not None else None
+ except (TypeError, ValueError):
+ state = None
+ new_state, rows = update(state if isinstance(state, dict) else None)
+ valid = [
+ r for r in rows
+ if counter_dimensions_are_valid(r[0], r[1]) and client_resource_is_valid(r[2])
+ ]
+ if valid:
+ self._install_id(connection)
+ for metric_name, dimensions, resource, period_start in valid:
+ self._record_counter_in_transaction(connection, metric_name, dimensions, resource, period_start)
+ connection.execute(
+ "INSERT INTO telemetry_state(key, value) VALUES (?, ?)"
+ " ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+ (state_key, _compact_json(new_state)),
+ )
def recorded_milestones(self) -> frozenset[str]:
return self._latched(_MILESTONE_STATE_PREFIX)
@@ -397,8 +410,43 @@ class SharedMetricsStore:
break
return self._export_and_prune()
+ def _write_or_defer(self, write: Callable[[sqlite3.Connection], None]) -> None:
+ """Run ``write`` (after any deferred ones) in one write transaction. A store another writer
+ holds past the short busy timeout keeps them in memory for the next write or process exit
+ instead of losing them or stalling the caller."""
+ with self._deferred_lock:
+ pending, self._deferred = [*self._deferred, write], []
+ try:
+ with self._write() as connection:
+ for item in pending:
+ item(connection)
+ except sqlite3.OperationalError as exc:
+ busy = "locked" in str(exc) or "busy" in str(exc)
+ with self._deferred_lock:
+ # A failure that is not contention drops only this write: the earlier ones stay queued.
+ self._deferred = [*(pending if busy else pending[:-1]), *self._deferred][-_DEFERRED_WRITES_MAX:]
+ register, self._drain_at_exit = not self._drain_at_exit, True
+ if register:
+ atexit.register(self.drain_deferred)
+ if not busy:
+ raise
+
+ def drain_deferred(self, busy_timeout_ms: int = _SCHEMA_BUSY_TIMEOUT_MS) -> None:
+ """Write the deferred writes (process exit / export waits longer than the user's path does)."""
+ with self._deferred_lock:
+ pending, self._deferred = self._deferred, []
+ if not pending:
+ return
+ try:
+ with self._write(busy_timeout_ms=busy_timeout_ms) as connection:
+ for item in pending:
+ item(connection)
+ except Exception:
+ logger.warning("Unable to write %d deferred shared-metrics updates", len(pending), exc_info=True)
+
def create_and_export_package_if_due(self) -> list[Path]:
"""Create pending packages at most once per UTC day, then export them."""
+ self.drain_deferred(_BUSY_TIMEOUT_MS)
self._create_pending_packages_if_due()
return self._export_and_prune()
diff --git a/hermes_cli/observability/shared_metrics_engagement.py b/hermes_cli/observability/shared_metrics_engagement.py
index 2188930a488..50765effbad 100644
--- a/hermes_cli/observability/shared_metrics_engagement.py
+++ b/hermes_cli/observability/shared_metrics_engagement.py
@@ -98,21 +98,26 @@ def turn_route(event: Any) -> tuple[str, str] | None:
def record(store: Any, resource: dict[str, str], *, surface: str | None, route: tuple[str, str] | None) -> None:
- now_ms = int(_now() * 1000)
+ """The clock is read inside each write transaction: writers then apply in clock order, so no
+ process closes a day another already closed. A busy store defers the interaction, never drops it."""
profile_home = Path(store.database_path).parent.parent.parent
root_home = _root_home(profile_home)
owner = root_home == profile_home
profile = _profile_hash(profile_home) if surface is not None else None
store.update_rollup_state(STATE_KEY, lambda state: apply(
- state, now_ms=now_ms, resource=resource, surface=surface, route=route,
+ state, now_ms=_now_ms(), resource=resource, surface=surface, route=route,
profile=profile if owner else None, owner=owner,
))
if profile is not None and not owner and _collects(root_home):
_root_store(root_home).update_rollup_state(STATE_KEY, lambda state: apply(
- state, now_ms=now_ms, resource=resource, profile=profile, owner=True,
+ state, now_ms=_now_ms(), resource=resource, profile=profile, owner=True,
))
+def _now_ms() -> int:
+ return int(_now() * 1000)
+
+
def _root_home(profile_home: Path) -> Path:
from hermes_constants import get_default_hermes_root
@@ -186,11 +191,10 @@ def apply(
today, rows = _utc_day(now_ms), []
if state is not None and not _valid_state(state):
state = None
- if state is not None and state["day"] != today:
- # A day behind the clock closes; a day ahead of it (clock correction) is dropped unemitted.
- if state["day"] < today:
- rows = close_day(state)
- state = None
+ if state is not None and state["day"] < today:
+ # The only close path. A stored day ahead of the clock (a step back across midnight) keeps
+ # the interaction: the stored day never moves backwards, so no day is re-opened or emitted twice.
+ rows, state = close_day(state), None
state = state or _fresh(today, resource, owner)
state["owner"] = owner
profiles = state.setdefault("profiles", [])
diff --git a/tests/hermes_cli/test_relay_shared_metrics.py b/tests/hermes_cli/test_relay_shared_metrics.py
index 118b31918bd..eb2d044cd80 100644
--- a/tests/hermes_cli/test_relay_shared_metrics.py
+++ b/tests/hermes_cli/test_relay_shared_metrics.py
@@ -1451,6 +1451,22 @@ def test_cross_process_model_call_updates_are_transactional(tmp_path):
assert restarted.counter_snapshot()[0]["value"] == 20
+def test_a_write_the_busy_store_cannot_take_is_deferred_not_lost(tmp_path):
+ """Another writer holding the store past the short busy timeout: the caller returns at once and the
+ increment lands with the next write (or the exit drain), never raised or dropped."""
+ store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
+ blocker = sqlite3.connect(tmp_path / "metrics.sqlite3")
+ blocker.execute("BEGIN IMMEDIATE")
+ try:
+ store.record_model_call(_dimensions(), _resource())
+ finally:
+ blocker.rollback()
+ blocker.close()
+ assert store.counter_snapshot() == []
+ store.record_model_call(_dimensions(), _resource())
+ assert store.counter_snapshot()[0]["value"] == 2
+
+
def test_cross_process_client_active_attempts_record_one_install(tmp_path):
database_path = tmp_path / "metrics.sqlite3"
outbox_directory = tmp_path / "outbox"
diff --git a/tests/hermes_cli/test_shared_metrics_engagement.py b/tests/hermes_cli/test_shared_metrics_engagement.py
index b669931d4d8..26fcbc1e1ac 100644
--- a/tests/hermes_cli/test_shared_metrics_engagement.py
+++ b/tests/hermes_cli/test_shared_metrics_engagement.py
@@ -106,6 +106,20 @@ def test_internal_and_unattended_turns_are_not_engagement(direct_runtime, tmp_pa
assert [d["surface"] for d, _ in _stored_values(tmp_path, "hermes.engagement.surface_day.count")] == ["cli"]
+def test_a_late_interaction_never_reopens_a_closed_day():
+ """An interaction sampled before midnight that lands after the day rolled folds into the newer day:
+ the closed day is reported once, and the only close path is a later clock."""
+ resource = {"architecture": "x86_64", "hermes_version": "0.0.0", "install_method": "git", "os_family": "linux"}
+ midnight = int(datetime(2026, 9, 28, tzinfo=timezone.utc).timestamp() * 1000)
+ state, _ = engagement.apply(None, now_ms=midnight - 3_600_000, resource=resource, surface="cli")
+ state, closed = engagement.apply(state, now_ms=midnight + 500, resource=resource, surface="cli")
+ assert [r[3] for r in closed] == ["2026-09-27", "2026-09-27"]
+ state, late = engagement.apply(state, now_ms=midnight - 500, resource=resource, surface="cli")
+ assert late == [] and state["day"] == "2026-09-28"
+ _, next_day = engagement.apply(state, now_ms=midnight + 86_400_000, resource=resource, surface="cli")
+ assert {r[3] for r in next_day} == {"2026-09-28"}
+
+
def test_collection_off_writes_no_engagement_state(direct_runtime, tmp_path, clock, monkeypatch):
monkeypatch.setattr("hermes_cli.config.read_raw_config_readonly", lambda: {})
_turn("s1", "t1", clock=clock, at=DAY1)