Skip to content

The agent that grows with you

fix(install-metrics): count the install note on a consented day; purge receipts on every opt-out

Teknium717d8a3e5e64
diff --git a/hermes_cli/observability/shared_metrics_consent.py b/hermes_cli/observability/shared_metrics_consent.py
index 5ab01088282..b1313c962ae 100644
--- a/hermes_cli/observability/shared_metrics_consent.py
+++ b/hermes_cli/observability/shared_metrics_consent.py
@@ -111,6 +111,12 @@ def save_consent(enabled: bool, send: bool, config: dict | None = None) -> None:
set_answer(config, enabled, send)
# Unconditional: a send key already false may still have an open consent window.
_record_send_consent_change(enabled=send)
+ if not enabled:
+ from hermes_constants import get_hermes_home
+
+ from .shared_metrics_process import purge_pending_receipts
+
+ purge_pending_receipts(get_hermes_home())
def offer_consent(config: dict | None = None, *, reask: bool = False) -> bool:
diff --git a/hermes_cli/observability/shared_metrics_install_run.py b/hermes_cli/observability/shared_metrics_install_run.py
index 4fce3375312..012c218603e 100644
--- a/hermes_cli/observability/shared_metrics_install_run.py
+++ b/hermes_cli/observability/shared_metrics_install_run.py
@@ -2,18 +2,28 @@
The installer runs before the user is asked about shared metrics and must never send anything, so a
full-ladder run only leaves ONE small local receipt (closed tokens plus two epoch timestamps) under
-the profile's store dir. The next Hermes start that runs the process-exit reporter reads it: with
-collection on it records one row per receipt id and deletes the receipt once the row is saved; with
-collection off ``shared_metrics_process.begin_process`` deletes every receipt unreported (the same
-rule as parked update receipts). A receipt with any value outside the contract is deleted unreported.
+the profile's store dir. A later Hermes start that runs the process-exit reporter reads it:
+
+- collection off: ``shared_metrics_process.begin_process`` (and every opt-out answer) deletes every
+ receipt unreported, the same rule as parked update receipts;
+- collection on, sending off: the row is recorded now (it stays on this machine);
+- collection on, sending on: the row is recorded only on a day whose package the sender's consent
+ gate can ever pass, i.e. a send consent window opened at or before today 00:00Z. On the opt-in day
+ itself (setup asked during the install) the receipt waits for the first start on a later day;
+- a receipt older than ``MAX_RECEIPT_AGE_SECONDS``, unparseable, or with any value outside the
+ contract is deleted unreported (an old receipt would count under whatever version records it).
"""
from __future__ import annotations
import json
import logging
+import os
import re
import shutil
+import sqlite3
+import time
+from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@@ -26,6 +36,9 @@ RECORDED_DIRNAME = "recorded_installs"
_RECORDED_KEEP = 64
_RECEIPT_ID = re.compile(r"[0-9a-f]{32}")
_RECEIPT_KEYS = frozenset({"id", "installer", "outcome", "failed_stage", "failure_class", "started_at", "finished_at"})
+# A receipt no start recorded within a week is dropped: the row would carry the recording client's
+# version, not the installer's, and per-version install failure rates would drift onto later releases.
+MAX_RECEIPT_AGE_SECONDS = 7 * 86_400
def pending_installs_dir(home: Path) -> Path:
@@ -83,20 +96,81 @@ def _mark_recorded(latch: Path) -> None:
pass
+def _today_start() -> str:
+ """Today's package ``period_start``, in the store's stamp format (``shared_metrics._isoformat``)."""
+ from .shared_metrics import _isoformat, _utc_now
+
+ return _isoformat(datetime.combine(_utc_now().date(), datetime.min.time(), tzinfo=timezone.utc))
+
+
+def consented_day(home: Path) -> bool:
+ """Whether a row recorded now lands in a package the user agreed to: collection on, and either
+ sending off (it stays local) or a send consent window opened at or before today 00:00Z. The
+ sender's ``CONSENT_GATE_SQL`` passes a day's package only when ``period_start >= opened_at``, so a
+ row recorded on the opt-in day itself would sit in a package that is never sent."""
+ from hermes_cli.config import read_raw_config_readonly
+
+ from .shared_metrics_send_config import resolve_send_config
+
+ send = resolve_send_config(read_raw_config_readonly() or {})
+ if not send.enabled:
+ return False
+ if not send.send:
+ return True
+ from .shared_metrics import SharedMetricsStore
+
+ root = home / "telemetry" / "shared_metrics"
+ try:
+ with SharedMetricsStore(root / "metrics.sqlite3", root / "outbox")._connection() as connection:
+ row = connection.execute(
+ "SELECT 1 FROM send_consent_windows WHERE closed_at IS NULL AND opened_at <= ? LIMIT 1",
+ (_today_start(),),
+ ).fetchone()
+ except sqlite3.Error: # a busy store: try again on a later start
+ return False
+ return row is not None
+
+
+def _claim_receipt(path: Path) -> Path | None:
+ """Rename a receipt so exactly one reporter owns it. Unlike the process-marker claim it never
+ reads the file first: an unparseable receipt is claimed too, so it can be deleted."""
+ from .shared_metrics_process import _REPORTING, _claimer_alive
+
+ if path.name.endswith(_REPORTING) and _claimer_alive(path):
+ return None
+ claimed = path.with_name(f"{path.name.split('.json')[0]}.json.{os.getpid()}{_REPORTING}")
+ try:
+ os.replace(path, claimed)
+ except OSError: # a concurrent reporter won
+ return None
+ return claimed
+
+
+def _stale(receipt: dict) -> bool:
+ return time.time() - receipt["finished_at"] > MAX_RECEIPT_AGE_SECONDS
+
+
def report_pending_installs(home: Path) -> None:
- """Record each receipt once (the caller runs only with collection on). Never raises."""
+ """Record each receipt once, on a consented day (see the module docstring). Never raises."""
try:
+ from agent import relay_runtime
+
from . import shared_metrics_contract as contract
from .shared_metrics_events import emit_saved
- from .shared_metrics_process import _claim, settle_claim
+ from .shared_metrics_process import settle_claim
directory = pending_installs_dir(home)
if not directory.is_dir():
return
+ # With Relay instrumentation off the store reports a row "settled" without recording it, which
+ # would latch and delete the receipt uncounted: leave everything for a start that records.
+ if not relay_runtime.relay_instrumentation_enabled():
+ return
+ reportable = consented_day(home)
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
+ claimed = _claim_receipt(path) # a concurrent start that loses the rename records nothing
if claimed is None:
continue
try:
@@ -104,13 +178,16 @@ def report_pending_installs(home: Path) -> None:
except (OSError, ValueError):
receipt = None
fields = install_run_fields(receipt)
- if fields is None or not isinstance(receipt, dict): # out of contract or unreadable
+ if fields is None or not isinstance(receipt, dict) or _stale(receipt): # never to be counted
settle_claim(claimed, path, True)
continue
latch = _recorded_latch(home, receipt["id"])
if latch.exists(): # counted before; only the delete had failed
settle_claim(claimed, path, True)
continue
+ if not reportable: # kept for the first start on a fully consented day
+ settle_claim(claimed, path, False)
+ continue
# The claim rename already keeps concurrent starts apart; a busy store keeps the receipt.
saved = emit_saved([(contract.INSTALL_RUN_MARK, fields)]) == 1
if saved:
diff --git a/hermes_cli/observability/shared_metrics_process.py b/hermes_cli/observability/shared_metrics_process.py
index e7f46847bd2..95c94e5ec5e 100644
--- a/hermes_cli/observability/shared_metrics_process.py
+++ b/hermes_cli/observability/shared_metrics_process.py
@@ -71,6 +71,20 @@ def _excepthook(previous: Any) -> Any:
return hook
+def purge_pending_receipts(home: Path) -> None:
+ """Collection is off: drop the files kept for a later start to count (parked update receipts,
+ installer receipts). Every opt-out answer calls this too, not only an opted-out start, so a
+ receipt never survives a "No" to be counted after a later opt-in. Never raises."""
+ try:
+ from .shared_metrics_install_run import purge_pending_installs
+ from .shared_metrics_update import purge_pending_updates
+
+ purge_pending_updates(home)
+ purge_pending_installs(home)
+ except Exception:
+ logger.debug("Pending shared-metrics receipts not purged", exc_info=True)
+
+
def begin_process(kind: str) -> None:
"""Mark this process as a running ``kind`` and report dead predecessors. Once per process."""
try:
@@ -78,19 +92,14 @@ def begin_process(kind: str) -> None:
from .shared_metrics_desktop import ONBOARDING_LATCH_DIRNAME
from .shared_metrics_setup import markers_dir as setup_markers_dir
- from .shared_metrics_update import _collection_on, purge_pending_updates
+ from .shared_metrics_update import _collection_on
if _STATE:
return
_STATE["kind"] = kind # watchdog turn rows name the surface even when this home is off
if not _collection_on():
home = get_hermes_home()
- purge_pending_updates(home) # parked while on, never to be counted once off
- # ---- iuf c2 ----
- from .shared_metrics_install_run import purge_pending_installs
-
- purge_pending_installs(home) # an installer receipt is counted only while collection is on
- # ---- end iuf c2 ----
+ purge_pending_receipts(home) # parked while on / left by the installer, never counted once off
latches = home / "telemetry" / "shared_metrics" / ONBOARDING_LATCH_DIRNAME # an opt-out outside Desktop
for directory in (markers_dir(home), setup_markers_dir(home), latches): # likewise pending exits/setups
shutil.rmtree(directory, ignore_errors=True)
diff --git a/tests/hermes_cli/test_shared_metrics_install_run.py b/tests/hermes_cli/test_shared_metrics_install_run.py
index 289af50e1f3..cf758b5c7e9 100644
--- a/tests/hermes_cli/test_shared_metrics_install_run.py
+++ b/tests/hermes_cli/test_shared_metrics_install_run.py
@@ -7,15 +7,19 @@ import os
import re
import shutil
import signal
+import sqlite3
import subprocess
import sys
import time
+from datetime import datetime, timedelta, timezone
from pathlib import Path
from types import SimpleNamespace
import pytest
+from agent import relay_runtime
from hermes_cli.observability import relay_shared_metrics
+from hermes_cli.observability import shared_metrics as store_module
from hermes_cli.observability import shared_metrics_contract as contract
from hermes_cli.observability import shared_metrics_install_run as install_run
from hermes_cli.observability import shared_metrics_process as process_metrics
@@ -161,6 +165,111 @@ def test_real_install_sh_ladder_leaves_only_closed_tokens(tmp_path):
}
+_REAL_RECORD_SAVED = relay_shared_metrics.record_process_marks_saved
+_RESOURCE = {"architecture": "x86_64", "hermes_version": "0.0.0", "install_method": "git", "os_family": "linux"}
+
+
+def test_receipt_is_recorded_only_on_a_day_the_sender_can_ever_send(marks, monkeypatch):
+ """The opt-in usually happens inside the install (setup asks), so the first start is the opt-in day,
+ whose package CONSENT_GATE_SQL never passes (period_start < opened_at). The receipt waits for the
+ first start on a later day, and the package carrying it then passes the real gate."""
+ from hermes_cli.observability.shared_metrics_sender import CONSENT_GATE_SQL, reconcile_send_consent
+ from hermes_cli.sqlite_util import write_txn
+
+ t0 = datetime(2026, 10, 6, tzinfo=timezone.utc)
+ clock = {"now": t0 + timedelta(hours=9)}
+ monkeypatch.setattr(store_module, "_utc_now", lambda: clock["now"])
+ monkeypatch.setattr("hermes_cli.config.read_raw_config_readonly",
+ lambda: {"telemetry": {"shared_metrics": {"enabled": True, "send": True}}})
+ store = store_module.SharedMetricsStore()
+
+ def observe(send=True):
+ with store._connection() as connection, write_txn(connection):
+ reconcile_send_consent(connection, send, now=clock["now"])
+
+ def record(rows): # the real store, on the store's own clock
+ for mark, data in rows:
+ store.record_counter(contract._DECISION_MARK_METRICS[mark], data, _RESOURCE)
+ return len(rows)
+
+ monkeypatch.setattr(relay_shared_metrics, "record_process_marks_saved", record, raising=False)
+ receipt = _park(marks.home, _receipt(finished_at=int(clock["now"].timestamp()) - 60,
+ started_at=int(clock["now"].timestamp()) - 400))
+ observe() # "Yes, send" in the install's setup stage opens the window now
+ clock["now"] += timedelta(hours=1)
+ install_run.report_pending_installs(marks.home) # first start, same UTC day
+ assert receipt.exists() and store.counter_snapshot() == []
+
+ clock["now"] = t0 + timedelta(days=1, hours=8)
+ observe()
+ install_run.report_pending_installs(marks.home) # first start on a later day
+ assert not receipt.exists()
+ clock["now"] = t0 + timedelta(days=2, hours=1)
+ observe() # the heartbeat that confirms the whole recorded day
+ store.create_and_export_package()
+ with store._connection() as connection:
+ packages = connection.execute(
+ f"SELECT payload_json, {CONSENT_GATE_SQL} FROM package_outbox").fetchall()
+ carrying = [bool(ok) for body, ok in packages
+ if any(m["name"] == contract.INSTALL_RUN_METRIC for m in json.loads(body)["metrics"])]
+ assert carrying == [True]
+
+
+def test_receipt_waits_without_an_open_send_window_and_is_recorded_at_once_when_kept_local(marks, monkeypatch):
+ config = {"enabled": True, "send": True}
+ monkeypatch.setattr("hermes_cli.config.read_raw_config_readonly",
+ lambda: {"telemetry": {"shared_metrics": config}})
+ receipt = _park(marks.home, _receipt())
+ install_run.report_pending_installs(marks.home) # send on, no window recorded yet
+ assert receipt.exists() and marks.rows == []
+ config["send"] = False # collected on this machine only: nothing waits on a send window
+ install_run.report_pending_installs(marks.home)
+ assert not receipt.exists() and len(marks.rows) == 1
+
+
+def test_unreadable_and_week_old_receipts_are_deleted_unreported(marks):
+ directory = install_run.pending_installs_dir(marks.home)
+ directory.mkdir(parents=True)
+ bad = [directory / f"{'c' * 32}.json", directory / f"{'d' * 32}.json"]
+ bad[0].write_text('{"id":"' + "c" * 32 + '","started_at":,"finished_at":}\n', encoding="utf-8")
+ bad[1].write_text("[]", encoding="utf-8")
+ old = int(time.time()) - install_run.MAX_RECEIPT_AGE_SECONDS - 3600
+ stale = _park(marks.home, _receipt(id="e" * 32, started_at=old - 100, finished_at=old))
+ install_run.report_pending_installs(marks.home)
+ assert not any(p.exists() for p in [*bad, stale])
+ assert list(directory.iterdir()) == [] and marks.rows == []
+
+
+def test_relay_instrumentation_off_keeps_the_receipt_instead_of_latching_it_unrecorded(marks, monkeypatch):
+ """With Relay off the real store call settles a row without recording it; the receipt must not be
+ latched and deleted on that answer."""
+ monkeypatch.setattr(relay_shared_metrics, "record_process_marks_saved", _REAL_RECORD_SAVED)
+ monkeypatch.setattr(relay_runtime, "relay_instrumentation_enabled", lambda: False)
+ receipt = _park(marks.home, _receipt())
+ install_run.report_pending_installs(marks.home)
+ assert receipt.exists()
+ assert not install_run._recorded_latch(marks.home, receipt.stem).exists()
+
+
+def test_every_opt_out_answer_purges_pending_receipts(marks, monkeypatch):
+ """A "No" from setup, the pre-chat offer, the dashboard banner or `hermes config` goes through
+ save_consent; none of them starts a process that purges, so the answer itself must."""
+ from hermes_cli.observability import shared_metrics_consent as consent
+ from hermes_cli.observability import shared_metrics_update as update_metrics
+
+ monkeypatch.setattr("hermes_cli.config.is_managed", lambda: False)
+ monkeypatch.setattr("hermes_cli.setup._record_send_consent_change", lambda **_: None)
+ install = _park(marks.home, _receipt())
+ parked = update_metrics.pending_updates_dir(marks.home)
+ parked.mkdir(parents=True)
+ (parked / f"{'f' * 32}.json").write_text("{}", encoding="utf-8")
+
+ consent.save_consent(True, False)
+ assert install.exists() and parked.exists()
+ consent.save_consent(False, False)
+ assert not install.exists() and not parked.exists()
+
+
_MAIN_GUARD = 'if [ "${BASH_SOURCE[0]:-$0}" = "$0" ]; then\n'
_CHILD = """
import pathlib, sys, time
diff --git a/tests/tui_gateway/test_shared_metrics_consent_rpc.py b/tests/tui_gateway/test_shared_metrics_consent_rpc.py
index ed3bb67b245..c783727d11f 100644
--- a/tests/tui_gateway/test_shared_metrics_consent_rpc.py
+++ b/tests/tui_gateway/test_shared_metrics_consent_rpc.py
@@ -84,3 +84,19 @@ def test_only_the_first_run_answer_records_desktop_setup_completed(tmp_path, mon
_call("shared_metrics.set", {"profile": "code", "enabled": True, "send": True})
assert calls == [{"surface": "desktop", "provider": "nous"}]
+
+
+def test_an_opt_out_purges_receipts_kept_for_a_later_start(tmp_path, monkeypatch):
+ """A Desktop "No" must not leave an installer receipt or a parked update receipt for a later opt-in
+ to count; only the named profile is touched."""
+ launch, worker = _bind_homes(monkeypatch, tmp_path)
+ kept = [worker / "telemetry" / "shared_metrics" / name for name in ("pending_installs", "pending_updates")]
+ for directory in kept + [launch / "telemetry" / "shared_metrics" / "pending_installs"]:
+ directory.mkdir(parents=True, exist_ok=True)
+ (directory / f"{'a' * 32}.json").write_text("{}", encoding="utf-8")
+
+ _call("shared_metrics.set", {"profile": "code", "enabled": True, "send": False})
+ assert all(d.exists() for d in kept)
+ _call("shared_metrics.set", {"profile": "code", "enabled": False, "send": False})
+ assert not any(d.exists() for d in kept)
+ assert (launch / "telemetry" / "shared_metrics" / "pending_installs").exists()
diff --git a/tui_gateway/methods_shared_metrics.py b/tui_gateway/methods_shared_metrics.py
index 87cb4d25ca7..59459469ef7 100644
--- a/tui_gateway/methods_shared_metrics.py
+++ b/tui_gateway/methods_shared_metrics.py
@@ -73,8 +73,11 @@ def _(rid, params: dict) -> dict:
_record_send_consent_change(enabled=send)
if not enabled:
from hermes_cli.observability.shared_metrics_desktop import purge_onboarding_latches
+ from hermes_cli.observability.shared_metrics_process import purge_pending_receipts
+ from hermes_constants import get_hermes_home
purge_onboarding_latches()
+ purge_pending_receipts(get_hermes_home())
if params.get("first_run") is True:
_shared_metrics_record_setup_completed(cfg)
return _ok(rid, _shared_metrics_consent(cfg))
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index caee729267b..434fb679c47 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -513,7 +513,7 @@ they failed. Rows recorded before the change keep their old field set and still
| Metric | Dimensions | Question it answers |
|---|---|---|
-| `hermes.install.run` | installer (`install_sh`, `install_ps1`, `other`), outcome (`success`, `failed`), failed_stage (`prerequisites`, `repository`, `venv`, `python_deps`, `config`, `products`, `setup`, `gateway`, `complete`, `other`; `none` on success), failure_class (`unsupported_platform`, `download_failed`, `download_digest_mismatch`, `uv_unusable`, `git_missing`, `curl_missing`, `libstdcxx_missing`, `git_extract_failed`, `dir_not_checkout`, `git_clone_failed`, `git_fetch_failed`, `local_changes_blocked`, `git_checkout_failed`, `git_reset_failed`, `commit_not_on_branch`, `filesystem_error`, `python_install_failed`, `deps_install_failed`, `products_build_failed`, `setup_failed`, `gateway_failed`, `interrupted`, `other`; `none` on success), duration bucket (`lt_30s` … `gte_15m`) | How often a fresh `install.sh` / `install.ps1` run succeeds, and at which stage and for which closed reason it fails. The installer runs before the consent question and never sends anything: a full run (not a single `--stage` / `-Stage` call, so the Desktop bootstrap installer's per-stage calls are not counted) leaves one small local file under `$HERMES_HOME/telemetry/shared_metrics/pending_installs/` holding only these tokens, a random id and the start/finish times (never the error text, paths, URLs or host names). The next Hermes start in that profile counts it once, and only when collection is on at that moment; a start with collection off deletes the files unreported. So a failed install is counted only once a later install or Hermes start in the same profile succeeds with collection on; a failed install that is never followed by one is never counted. |
+| `hermes.install.run` | installer (`install_sh`, `install_ps1`, `other`), outcome (`success`, `failed`), failed_stage (`prerequisites`, `repository`, `venv`, `python_deps`, `config`, `products`, `setup`, `gateway`, `complete`, `other`; `none` on success), failure_class (`unsupported_platform`, `download_failed`, `download_digest_mismatch`, `uv_unusable`, `git_missing`, `curl_missing`, `libstdcxx_missing`, `git_extract_failed`, `dir_not_checkout`, `git_clone_failed`, `git_fetch_failed`, `local_changes_blocked`, `git_checkout_failed`, `git_reset_failed`, `commit_not_on_branch`, `filesystem_error`, `python_install_failed`, `deps_install_failed`, `products_build_failed`, `setup_failed`, `gateway_failed`, `interrupted`, `other`; `none` on success), duration bucket (`lt_30s` … `gte_15m`) | How often a fresh `install.sh` / `install.ps1` run succeeds, and at which stage and for which closed reason it fails. The installer runs before the consent question and never sends anything: a full run (not a single `--stage` / `-Stage` call, so the Desktop bootstrap installer's per-stage calls are not counted) leaves one small local file under `$HERMES_HOME/telemetry/shared_metrics/pending_installs/` holding only these tokens, a random id and the start/finish times (never the error text, paths, URLs or host names). A later Hermes start in that profile counts it once, and only when collection is on at that moment; a start with collection off, or any opt-out answer, deletes the files unreported. With sending on, the row is recorded only on a UTC day whose package the send consent gate can pass, that is when a send consent window opened at or before 00:00 UTC that day: an opt-in given during the install itself (the setup stage) opens the window mid-day, so the receipt waits for the first start on a later day instead of landing in the opt-in day's package, which is never sent. With collection on and sending off the row is recorded at the first start and stays on this machine. A receipt that no start counted within 7 days is deleted unreported, so an old install is never counted under a later Hermes version; an unreadable receipt is deleted too. A Ctrl-C, SIGTERM or closed terminal (SIGHUP) that stops the install reads `interrupted`, even when the stage's child caught it and exited with its own error; a Ctrl-C a stage handles and recovers from (setup's provider picker) does not stop the install. So a failed install is counted only once a later install or Hermes start in the same profile succeeds with collection on; a failed install that is never followed by one is never counted. |
<!-- ---- end iuf c2 ---- -->
Local state is written under: