The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telemetry): per-row claiming, mid-pass consent re-check, narrower 4xx
Ben Barclayd0a7144ba184
diff --git a/docs/observability/relay-shared-metrics.md b/docs/observability/relay-shared-metrics.mdindex 98891103ec6..b965eaa6c8e 100644--- a/docs/observability/relay-shared-metrics.md+++ b/docs/observability/relay-shared-metrics.md@@ -369,7 +369,9 @@ qualifications now apply:service's storage under their derived identifier. There is no read-back ordelete API in the v1 contract.-Setting `send: false` stops transmission immediately. It does not delete+Setting `send: false` stops transmission immediately: consent is re-read+before every package, so a pass already in flight stops after the package it+is currently sending rather than draining its whole batch. It does not deletepreviously transmitted packages, and it does not stop local collection.### A.5 Retentiondiff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex cf321b4e3da..5303e020dfb 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -3339,10 +3339,10 @@ DEFAULT_CONFIG = {# before consent stays local."send": False,# Ingest endpoint. Production by default; override for staging or- # a local test server. The HERMES_TELEMETRY_ENDPOINT environment- # variable takes precedence (used by the live E2E so a test never- # has to mutate a user's config). Non-HTTPS is refused unless the- # host is localhost.+ # a local test server. Deliberately NOT overridable by an+ # environment variable: that would let an inherited value silently+ # redirect telemetry a user consented to send to Nous. Non-HTTPS+ # is refused unless the host is localhost."endpoint": "https://telemetry.nousresearch.com/v1/telemetry",},},diff --git a/hermes_cli/observability/relay_shared_metrics.py b/hermes_cli/observability/relay_shared_metrics.pyindex c3097114d9c..94a1eac64fc 100644--- a/hermes_cli/observability/relay_shared_metrics.py+++ b/hermes_cli/observability/relay_shared_metrics.py@@ -1119,9 +1119,21 @@ class _Runtime:SharedMetricsSender,)+ def still_consented() -> bool:+ """Re-read consent so revoking `send` stops an in-flight pass."""+ from hermes_cli.config import read_raw_config_readonly+ from hermes_cli.observability.shared_metrics_send_config import (+ resolve_send_config,+ )++ resolved = resolve_send_config(read_raw_config_readonly() or {})+ return resolved.send and resolved.endpoint == endpoint+try:SharedMetricsSender(- self.subscriber.store, endpoint+ self.subscriber.store,+ endpoint,+ consent_check=still_consented,).send_pending()except Exception:logger.warning("Shared-metrics send pass failed", exc_info=True)diff --git a/hermes_cli/observability/shared_metrics_identity.py b/hermes_cli/observability/shared_metrics_identity.pyindex 16e28a8b4ee..b4f8cda8e3b 100644--- a/hermes_cli/observability/shared_metrics_identity.py+++ b/hermes_cli/observability/shared_metrics_identity.py@@ -92,8 +92,12 @@ def current_salt(fresh = (salt is not Noneand issued_at is not None- # A clock that jumped backwards must not be read as "aged out"; a- # future issue time simply means not yet due.+ # Strictly within the window. A future issued_at means the clock moved+ # backwards (or the value was tampered with), so the recorded age+ # cannot be trusted and we reissue rather than keep using a salt of+ # unknown vintage. Reissuing is the safe direction: it shortens+ # linkability, and already-prepared packages keep their frozen+ # identifier so retries stay byte-identical.and issued_at <= moment < issued_at + ROTATION_INTERVAL)if fresh:diff --git a/hermes_cli/observability/shared_metrics_sender.py b/hermes_cli/observability/shared_metrics_sender.pyindex a55cbf9f7d7..23070355aed 100644--- a/hermes_cli/observability/shared_metrics_sender.py+++ b/hermes_cli/observability/shared_metrics_sender.py@@ -58,17 +58,30 @@ GZIP_THRESHOLD_BYTES = 4096#: Packages per pass. Bounds work on an interactive hook even after an outage.MAX_PACKAGES_PER_PASS = 20-#: How long a claimed row is held by the claiming pass. A claim writes a-#: LEASE INTO THE FUTURE: another process selecting on `next_attempt_at <= now`-#: therefore skips it. Long enough to cover three attempts plus backoff-#: (1+5+25s of jitter plus three 30s timeouts), short enough that a killed-#: process's rows become eligible again quickly.-_CLAIM_LEASE_SECONDS = 180+#: How long a claimed row is held. The claim writes a LEASE INTO THE FUTURE:+#: selection requires `next_attempt_at <= now`, so for the length of the lease+#: no other process can take the package.+#:+#: This must exceed the worst case for ONE package — three 30s request+#: timeouts plus 1s+5s of backoff, about 96s — which is why packages are+#: claimed one at a time, immediately before being sent. An earlier revision+#: claimed up to 20 rows under a single shared lease; a full batch can legally+#: run ~1900s, so the later rows' leases expired while the pass still held+#: them in memory and another process re-sent them.+_CLAIM_LEASE_SECONDS = 300#: Floor applied after a pass fails to deliver, so a hard-down service is not#: retried on every task completion._FAILURE_BACKOFF_SECONDS = 15 * 60+#: Statuses that are permanent per the ingest contract. Deliberately narrow:+#: 400 means the envelope is malformed and will never validate. 413 is added+#: because a package over the service's 1 MiB cap cannot shrink on retry.+#: Everything else — including 403 from the origin guard and 404 from a bad+#: path — is retried, because those are usually deployment or edge+#: misconfiguration that resolves without the package changing.+_PERMANENT_STATUSES = frozenset({400, 413})+OPT_IN_PERIOD_KEY = "send_opt_in_period"@@ -177,6 +190,7 @@ class SharedMetricsSender:sleep=time.sleep,now=_utc_now,max_attempts: int = MAX_ATTEMPTS,+ consent_check=None,) -> None:self._store = storeself._endpoint = endpoint@@ -184,95 +198,132 @@ class SharedMetricsSender:self._sleep = sleepself._now = nowself._max_attempts = max_attempts+ # Called before every package. None disables the check for callers+ # that have already established consent out of band (tests, E2E).+ self._consent_check = consent_check# -- selection ---------------------------------------------------------- def _claim(self, connection: sqlite3.Connection, now: datetime) -> list[dict]:- """Atomically take ownership of the packages this pass will try.+ def _claim_next(self, now: datetime, seen: set[str]) -> dict | None:+ """Claim exactly ONE package, immediately before it is sent.++ Claiming a whole batch up front does not work: a single shared lease+ has to cover the entire pass, and 20 retrying packages can legally run+ far longer than any sane lease (three 30s timeouts plus backoff each).+ The later rows' leases then expire while this pass still holds them in+ memory, and another process re-sends them. Taking one row at a time+ keeps the lease covering only the package actually in flight.- Claiming inside the write transaction is what stops two Hermes- processes sharing one database from sending the same package twice.- Duplicates would be harmless (the service dedupes by package_id and- the bytes are identical) but they waste the user's bandwidth.+ ``seen`` stops this pass re-claiming a row it has already finished+ with, which would otherwise spin on a deferred package."""- period = opt_in_period(connection, now=now)- stamp = _isoformat(now)- lease_until = now + timedelta(seconds=_CLAIM_LEASE_SECONDS)- rows = connection.execute(- """- SELECT package_id, payload_json, sent_install_id- FROM package_outbox- WHERE exported_at IS NOT NULL- AND (send_state IS NULL OR send_state = 'pending')- AND (next_attempt_at IS NULL OR next_attempt_at <= ?)- AND substr(period_start, 1, 10) >= ?- ORDER BY created_at, package_id- LIMIT ?- """,- (stamp, period, MAX_PACKAGES_PER_PASS),- ).fetchall()-- claimed: list[dict] = []- salt: str | None = None- for row in rows:- package_id = str(row[0])- derived = row[2]- if not derived:- # Freeze the derived identity on first attempt so a later salt- # rotation cannot change the bytes sent under this package_id.- if salt is None:- salt = current_salt(connection, now=now)- try:- payload = json.loads(row[1])- install_id = str(payload.get("install_id", ""))- except (TypeError, ValueError):- # A row we cannot parse can never be sent. Mark it and move- # on: one unreadable package must not block every other- # package behind it, and aborting here would roll back the- # whole claim transaction.- logger.warning(- "Shared-metrics package %s is unreadable; not sending",- package_id,- )- connection.execute(- """- UPDATE package_outbox- SET send_state = 'rejected', last_error = 'unreadable payload'- WHERE package_id = ?- """,- (package_id,),+ with self._store._connection() as connection:+ with write_txn(connection):+ period = opt_in_period(connection, now=now)+ stamp = _isoformat(now)+ lease_until = now + timedelta(seconds=_CLAIM_LEASE_SECONDS)++ row = connection.execute(+ """+ SELECT package_id, payload_json, sent_install_id+ FROM package_outbox+ WHERE exported_at IS NOT NULL+ AND (send_state IS NULL OR send_state = 'pending')+ AND (next_attempt_at IS NULL OR next_attempt_at <= ?)+ AND substr(period_start, 1, 10) >= ?+ ORDER BY created_at, package_id+ LIMIT 1+ """,+ (stamp, period),+ ).fetchone()+ if row is None:+ return None++ package_id = str(row[0])+ if package_id in seen:+ # Already handled this pass; leave it for a later one.+ return None++ derived = row[2]+ if not derived:+ derived = self._freeze_identity(+ connection, package_id, row[1], now)- continue- derived = derive_install_id(install_id, salt)+ if derived is None:+ # Unusable row, already marked rejected. Signal the+ # caller to continue rather than stop.+ return {"package_id": package_id, "skip": True}+connection.execute(- "UPDATE package_outbox SET sent_install_id = ? WHERE package_id = ?",- (derived, package_id),+ """+ UPDATE package_outbox+ SET send_state = 'pending',+ send_attempts = send_attempts + 1,+ next_attempt_at = ?+ WHERE package_id = ?+ """,+ # Lease INTO THE FUTURE: selection requires+ # next_attempt_at <= now, so no other process can take+ # this row while it is in flight. Success or a real+ # backoff overwrites it; if this process dies, it expires.+ (_isoformat(lease_until), package_id),)+ return {+ "package_id": package_id,+ "payload_json": str(row[1]),+ "derived": str(derived),+ "skip": False,+ }++ def _freeze_identity(+ self,+ connection: sqlite3.Connection,+ package_id: str,+ payload_json,+ now: datetime,+ ) -> str | None:+ """Derive and persist the transmitted id, or reject an unusable row.++ Returns None when the package can never be sent. Rejecting rather than+ raising matters: an exception here rolls back the claim transaction+ and blocks every healthy package behind this one.+ """+ reason = None+ try:+ payload = json.loads(payload_json)+ except (TypeError, ValueError):+ reason = "unreadable payload"+ else:+ # Valid JSON is not enough: a top-level array, string, number or+ # null parses cleanly and then has no .get().+ if not isinstance(payload, dict):+ reason = f"payload is {type(payload).__name__}, expected object"+ else:+ install_id = payload.get("install_id")+ if not isinstance(install_id, str) or not install_id.strip():+ reason = "payload has no usable install_id"++ if reason is not None:+ logger.warning(+ "Shared-metrics package %s cannot be sent (%s)", package_id, reason+ )connection.execute("""UPDATE package_outbox- SET send_state = 'pending',- send_attempts = send_attempts + 1,- next_attempt_at = ?+ SET send_state = 'rejected', last_error = ?WHERE package_id = ?""",- # Lease the row INTO THE FUTURE. Selection above requires- # next_attempt_at <= now, so for the length of the lease no- # other process can claim this package. Writing `now` here (as- # an earlier revision did) claimed nothing: a concurrent pass- # matched the same predicate immediately and sent a duplicate.- # Success or a real backoff overwrites this below; if this- # process dies mid-pass, the lease simply expires.- (_isoformat(lease_until), package_id),- )- claimed.append(- {- "package_id": package_id,- "payload_json": str(row[1]),- "derived": str(derived),- }+ (reason, package_id),)- return claimed+ return None++ salt = current_salt(connection, now=now)+ derived = derive_install_id(payload["install_id"], salt)+ connection.execute(+ "UPDATE package_outbox SET sent_install_id = ? WHERE package_id = ?",+ (derived, package_id),+ )+ return derived# -- transmission ------------------------------------------------------@@ -345,14 +396,13 @@ class SharedMetricsSender:)return "sent"- if response.status == 400 or (- 400 <= response.status < 500 and response.status != 429- ):- # The contract only names 400, but every other 4xx is equally- # permanent for an unauthenticated fire-and-forget sender: a- # wrong path (404), an edge rejection (403), or an oversized- # body (413) will not fix itself by being retried every 15- # minutes until local retention prunes the package.+ if response.status in _PERMANENT_STATUSES:+ # Only statuses the contract (or the envelope schema) makes+ # terminal. Everything else retries: 403 in particular is the+ # ingest service's origin guard, which returns 403 during an+ # edge/Transform-Rule misconfiguration — treating that as+ # permanent would discard every package sent during the+ # incident instead of retrying after recovery.logger.warning("Telemetry package %s rejected with HTTP %s; not retrying",package_id,@@ -392,24 +442,42 @@ class SharedMetricsSender:# -- entry point -------------------------------------------------------def send_pending(self) -> SendOutcome:- """Run one bounded pass. Never raises."""- outcome = SendOutcome()- try:- now = self._now()- with self._store._connection() as connection:- with write_txn(connection):- claimed = self._claim(connection, now)- except Exception:- logger.warning("Unable to select shared-metrics packages", exc_info=True)- return outcome+ """Run one bounded pass. Never raises.- for package in claimed:+ Claims and sends ONE package at a time so each row's lease only has to+ cover its own transmission, and re-checks consent before every send so+ revoking `send` mid-pass stops the remaining packages.+ """+ outcome = SendOutcome()+ seen: set[str] = set()++ for _ in range(MAX_PACKAGES_PER_PASS):+ if not self._still_consented():+ # The user turned sending off while this pass was running.+ # Stop without transmitting anything further; unclaimed rows+ # stay pending and claimed-but-unsent rows expire naturally.+ logger.info("Shared-metrics sending disabled mid-pass; stopping")+ breaktry:- result = self._send_one(package)+ package = self._claim_next(self._now(), seen)except Exception:logger.warning(- "Unable to send shared-metrics package", exc_info=True+ "Unable to select shared-metrics packages", exc_info=True)+ break+ if package is None:+ break++ seen.add(package["package_id"])+ if package.get("skip"):+ # Unusable row already marked rejected during the claim.+ outcome.rejected += 1+ continue++ try:+ result = self._send_one(package)+ except Exception:+ logger.warning("Unable to send shared-metrics package", exc_info=True)outcome.deferred += 1continueif result == "sent":@@ -419,3 +487,23 @@ class SharedMetricsSender:else:outcome.deferred += 1return outcome++ def _still_consented(self) -> bool:+ """Re-read profile-owned send consent.++ Consent is a boundary, not cached configuration: the documentation+ promises that setting `send: false` stops transmission immediately,+ and a pass can run for minutes. Injected senders (tests, the staging+ E2E) opt out by passing consent_check=None.+ """+ if self._consent_check is None:+ return True+ try:+ return bool(self._consent_check())+ except Exception:+ # Fail CLOSED: if consent cannot be established, do not transmit.+ logger.warning(+ "Unable to confirm shared-metrics send consent; stopping",+ exc_info=True,+ )+ return Falsediff --git a/tests/hermes_cli/test_shared_metrics_identity.py b/tests/hermes_cli/test_shared_metrics_identity.pyindex 1887d47ccb5..1ea1d95961c 100644--- a/tests/hermes_cli/test_shared_metrics_identity.py+++ b/tests/hermes_cli/test_shared_metrics_identity.py@@ -76,11 +76,15 @@ class TestSaltLifecycle:conn.close()assert len(salts) == 5, "salts must be random per install, not derived"- def test_clock_rollback_does_not_force_rotation(self, connection):- """A backwards clock jump must not look like an expired salt."""+ def test_clock_rollback_reissues_rather_than_trusting_the_stamp(self, connection):+ """A future issued_at means the clock moved; the age is unknowable.++ Reissuing is the safe direction — it shortens linkability rather than+ extending it, and packages already prepared keep their frozen id.+ """first = current_salt(connection, now=T0)rolled_back = current_salt(connection, now=T0 - timedelta(days=5))- assert rolled_back != first, "an out-of-window time reissues rather than trusting it"+ assert rolled_back != firstdef test_corrupt_issued_at_reissues_rather_than_crashing(self, connection):current_salt(connection, now=T0)diff --git a/tests/hermes_cli/test_shared_metrics_sender.py b/tests/hermes_cli/test_shared_metrics_sender.pyindex 4da879dfc3c..2fdc3878b28 100644--- a/tests/hermes_cli/test_shared_metrics_sender.py+++ b/tests/hermes_cli/test_shared_metrics_sender.py@@ -114,6 +114,10 @@ def _row(store, package_id):)+def _iso(moment):+ return moment.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")++def _sender(store, transport, **kwargs):return SharedMetricsSender(store,@@ -148,17 +152,22 @@ class TestContractResponses:_sender(store, transport2).send_pending()assert transport2.calls == []- @pytest.mark.parametrize("status", [401, 403, 404, 413, 422])- def test_other_4xx_are_permanent_too(self, store, status):- """Retrying these every 15 minutes for 30 days fixes nothing."""+ @pytest.mark.parametrize("status", [401, 403, 404, 422, 500, 503])+ def test_unspecified_statuses_are_retried_not_discarded(self, store, status):+ """403 is the ingest origin guard; a bad edge config must not lose data."""_add_package(store, "pkg-1", "2026-08-26")- transport = FakeTransport(FakeResponse(status))+ transport = FakeTransport(*[FakeResponse(status)] * 3)+ outcome = _sender(store, transport).send_pending()+ assert outcome.deferred == 1+ assert _row(store, "pkg-1")["send_state"] == "pending"++ def test_413_is_permanent(self, store):+ """A package over the 1 MiB cap cannot shrink by being retried."""+ _add_package(store, "pkg-1", "2026-08-26")+ transport = FakeTransport(FakeResponse(413))outcome = _sender(store, transport).send_pending()assert outcome.rejected == 1assert len(transport.calls) == 1- row = _row(store, "pkg-1")- assert row["send_state"] == "rejected"- assert str(status) in row["last_error"]def test_429_defers_using_retry_after(self, store):_add_package(store, "pkg-1", "2026-08-26")@@ -391,14 +400,54 @@ class TestClaimingAndBounds:def test_a_claim_leases_the_row_into_the_future(self, store):"""The lease, not the send result, is what blocks a concurrent pass."""_add_package(store, "pkg-1", "2026-08-26")- with store._connection() as connection:- with __import__(- "hermes_cli.sqlite_util", fromlist=["write_txn"]- ).write_txn(connection):- claimed = _sender(store, FakeTransport())._claim(connection, NOW)- assert len(claimed) == 1+ claimed = _sender(store, FakeTransport())._claim_next(NOW, set())+ assert claimed is not Noneassert _row(store, "pkg-1")["next_attempt_at"] > "2026-08-26T12:00:00Z"+ def test_a_slow_multi_package_pass_does_not_lose_its_lease(self, store):+ """Regression: a batch-wide lease expired while later rows were sent.++ One package can legally take ~96s (three 30s timeouts plus backoff).+ With 20 rows claimed under one shared lease, the later rows' leases+ expired mid-pass and a second process re-sent them. Packages are now+ claimed one at a time, immediately before transmission.+ """+ for i in range(3):+ _add_package(store, f"pkg-{i}", "2026-08-26")++ clock = {"t": NOW}+ first_posts, second_posts = [], []+++ def transport(endpoint, payload, *, timeout):+ pid = json.loads(payload)["package_id"]+ first_posts.append(pid)+ # Burn the worst-case time budget for a single package.+ clock["t"] += timedelta(seconds=96)+ # A concurrent process probes for work while this package is still+ # in flight. It must not be able to claim the package we hold.+ # Restricted to that package so the probe cannot legitimately pick+ # up the OTHER pending rows and make the assertion ambiguous.+ held = _row(store, pid)+ if held["next_attempt_at"] is not None:+ eligible = held["next_attempt_at"] <= _iso(clock["t"])+ if eligible and held["send_state"] != "sent":+ second_posts.append(pid)+ return FakeResponse(202)++ SharedMetricsSender(+ store,+ ENDPOINT,+ post=transport,+ sleep=lambda _s: None,+ now=lambda: clock["t"],+ ).send_pending()++ assert sorted(first_posts) == ["pkg-0", "pkg-1", "pkg-2"]+ assert second_posts == [], (+ f"a concurrent pass re-sent {second_posts} after a lease expired"+ )+def test_an_expired_lease_is_reclaimed(self, store):"""A process killed mid-pass must not strand its packages."""_add_package(store, "pkg-1", "2026-08-26")@@ -444,12 +493,113 @@ class TestResilience:outcome = _sender(store, transport).send_pending()assert outcome.sent >= 1+ @pytest.mark.parametrize(+ "payload_json",+ [+ '["a", "list"]',+ "null",+ '"a string"',+ "42",+ '{"no_install_id": true}',+ '{"install_id": ""}',+ '{"install_id": null}',+ ],+ )+ def test_valid_json_that_is_not_a_usable_package_is_skipped(+ self, store, payload_json+ ):+ """Regression: a top-level array parsed fine, then .get() raised.++ The AttributeError escaped the claim transaction and blocked every+ healthy package behind it.+ """+ with store._connection() as connection:+ connection.execute(+ """+ INSERT INTO package_outbox(+ package_id, period_start, period_end, payload_json,+ created_at, exported_at+ ) VALUES ('bad', '2026-08-26T00:00:00Z', '2026-08-26T23:59:59Z',+ ?, '2026-08-26T00:00:00Z', '2026-08-26T01:00:00Z')+ """,+ (payload_json,),+ )+ _add_package(store, "good", "2026-08-26")++ transport = FakeTransport(*[FakeResponse(202)] * 5)+ outcome = _sender(store, transport).send_pending()++ assert outcome.sent == 1, "the healthy package must still go out"+ assert [json.loads(c["payload"])["package_id"] for c in transport.calls] == [+ "good"+ ]+ assert _row(store, "bad")["send_state"] == "rejected"+def test_send_pending_never_raises_on_a_broken_database(self, store, tmp_path):store.database_path.write_text("this is not a database")outcome = _sender(store, FakeTransport(FakeResponse(202))).send_pending()assert outcome.sent == 0+class TestConsentRevocation:+ """`send: false` must stop an in-flight pass, not just the next one."""++ def test_revoking_consent_mid_pass_stops_further_sends(self, store):+ for i in range(4):+ _add_package(store, f"pkg-{i}", "2026-08-26")++ consented = {"value": True}+ posts = []++ def transport(endpoint, payload, *, timeout):+ posts.append(json.loads(payload)["package_id"])+ consented["value"] = False # user flips send off during the pass+ return FakeResponse(202)++ outcome = SharedMetricsSender(+ store,+ ENDPOINT,+ post=transport,+ sleep=lambda _s: None,+ now=lambda: NOW,+ consent_check=lambda: consented["value"],+ ).send_pending()++ assert len(posts) == 1, f"kept sending after consent was revoked: {posts}"+ assert outcome.sent == 1++ def test_no_send_at_all_when_consent_is_already_false(self, store):+ _add_package(store, "pkg-1", "2026-08-26")+ posts = []+ SharedMetricsSender(+ store,+ ENDPOINT,+ post=lambda *a, **k: posts.append(1) or FakeResponse(202),+ sleep=lambda _s: None,+ now=lambda: NOW,+ consent_check=lambda: False,+ ).send_pending()+ assert posts == []++ def test_an_unreadable_consent_check_fails_closed(self, store):+ """If consent cannot be established, do not transmit."""+ _add_package(store, "pkg-1", "2026-08-26")+ posts = []++ def explode():+ raise OSError("config unreadable")++ SharedMetricsSender(+ store,+ ENDPOINT,+ post=lambda *a, **k: posts.append(1) or FakeResponse(202),+ sleep=lambda _s: None,+ now=lambda: NOW,+ consent_check=explode,+ ).send_pending()+ assert posts == []++class TestCompression:"""Compression lives in the real transport, so exercise _post directly."""