Skip to content

The agent that grows with you

fix(telemetry): smoke waits for the gateway's turn rows instead of assuming the stop settles them

Teknium95aed4f8de3b
diff --git a/scripts/smoke_nemo_relay_shared_metrics.py b/scripts/smoke_nemo_relay_shared_metrics.py
index c4b07a4e188..50cccb49293 100644
--- a/scripts/smoke_nemo_relay_shared_metrics.py
+++ b/scripts/smoke_nemo_relay_shared_metrics.py
@@ -12,6 +12,7 @@ import sys
import tempfile
import threading
import time
+from contextlib import closing
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
@@ -432,10 +433,9 @@ EXPECTED_METRIC_NAMES = frozenset({
})
-def _validate_store(database_path: Path) -> list[dict[str, Any]]:
- if not database_path.is_file():
- raise AssertionError(f"Metrics database was not created: {database_path}")
- with sqlite3.connect(database_path) as connection:
+def _read_counters(database_path: Path) -> list[dict[str, Any]]:
+ # Read-only: polling must never create the store before the gateway does.
+ with closing(sqlite3.connect(f"{database_path.as_uri()}?mode=ro", uri=True)) as connection:
rows = connection.execute(
"""
SELECT metric_name, dimensions_json, value, packaged_value
@@ -443,7 +443,7 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:
ORDER BY metric_name, dimensions_json
"""
).fetchall()
- counters = [
+ return [
{
"name": name,
"dimensions": json.loads(dimensions),
@@ -452,9 +452,38 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:
}
for name, dimensions, value, packaged_value in rows
]
+
+
+def _by_name(counters: list[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]:
by_name: dict[str, list[dict[str, Any]]] = {}
for counter in counters:
by_name.setdefault(counter["name"], []).append(counter)
+ return by_name
+
+
+def _wait_for_gateway_turn_rows(database_path: Path, timeout: float = 30.0) -> bool:
+ """Poll the probe home's store until the auto-started gateway's turn rows have landed.
+
+ The gateway records them after the reply reached the chat client, and stopping it does not
+ settle them: its graceful exit ends in ``os._exit``, which skips the shared-metrics flush. So the
+ smoke waits for the rows before it stops the gateway. False when ``timeout`` passed first.
+ """
+ deadline = time.monotonic() + timeout
+ while True:
+ try:
+ _validate_gateway_turn_rows(_by_name(_read_counters(database_path)))
+ return True
+ except (sqlite3.Error, KeyError, AssertionError):
+ if time.monotonic() >= deadline:
+ return False
+ time.sleep(0.25)
+
+
+def _validate_store(database_path: Path) -> list[dict[str, Any]]:
+ if not database_path.is_file():
+ raise AssertionError(f"Metrics database was not created: {database_path}")
+ counters = _read_counters(database_path)
+ by_name = _by_name(counters)
if set(by_name) != EXPECTED_METRIC_NAMES:
raise AssertionError(
f"Unexpected SQLite counters:\n{json.dumps(counters, indent=2)}"
@@ -824,6 +853,9 @@ def main() -> int:
server.shutdown()
server.server_close()
thread.join(timeout=5)
+ metrics_db = home / "telemetry" / "shared_metrics" / "metrics.sqlite3"
+ if not _wait_for_gateway_turn_rows(metrics_db):
+ print(f"Gateway turn rows did not reach {metrics_db} in time", file=sys.stderr)
_stop_auto_started_gateway(home)
(root / "hermes.stdout.txt").write_text(result.stdout, encoding="utf-8")
diff --git a/tests/scripts/test_smoke_nemo_relay_shared_metrics.py b/tests/scripts/test_smoke_nemo_relay_shared_metrics.py
index 9bfcf2c7865..233f4a2b683 100644
--- a/tests/scripts/test_smoke_nemo_relay_shared_metrics.py
+++ b/tests/scripts/test_smoke_nemo_relay_shared_metrics.py
@@ -8,6 +8,7 @@ import pytest
from gateway import status
from hermes_cli.observability import shared_metrics_contract as contract
+from hermes_cli.observability.shared_metrics import SharedMetricsStore
from hermes_cli.observability.shared_metrics_update import update_receipt_fields
from scripts import smoke_nemo_relay_shared_metrics as smoke
@@ -81,6 +82,26 @@ def test_gateway_stop_spares_a_process_that_is_not_the_homes_live_gateway(tmp_pa
decoy.wait()
+def test_gateway_turn_wait_settles_only_on_the_rows_in_the_real_store(tmp_path):
+ """The stop does not flush the gateway's rows, so the smoke waits for them in the store itself."""
+ database = tmp_path / "metrics.sqlite3"
+ assert not smoke._wait_for_gateway_turn_rows(database, timeout=0)
+ assert not database.exists() # polling never creates the store ahead of the gateway
+
+ resource = {"architecture": "x86_64", "hermes_version": "0.0.0", "install_method": "git", "os_family": "linux"}
+ store = SharedMetricsStore(database, tmp_path / "outbox")
+ for name, dimensions in [
+ *smoke.GATEWAY_TURN_EXPECTED_DIMENSIONS.items(),
+ ("hermes.gateway.reply_latency", {"first_response_bucket": "lt_2s", "platform": "local"}),
+ ("hermes.startup.latency", {"latency_bucket": "lt_500ms", "surface": "cli"}),
+ ]:
+ store.record_counter(name, dimensions, resource)
+ assert not smoke._wait_for_gateway_turn_rows(database, timeout=0) # gateway_boot still pending
+
+ store.record_counter("hermes.startup.latency", {"latency_bucket": "2s_to_5s", "surface": "gateway_boot"}, resource)
+ assert smoke._wait_for_gateway_turn_rows(database, timeout=0)
+
+
def test_smoke_update_expectations_match_the_receipt_projection():
run, stage_rows = update_receipt_fields(smoke.UPDATE_RECEIPT)