Files
stack/tests/bcda/test_ui_metrics.py
kert e31282c02d
Some checks failed
CI / lint (push) Successful in 51s
CI / test (push) Failing after 2m28s
CI / notebooks-smoke (push) Successful in 1m37s
Infra CI / zotero (push) Successful in 16s
Infra CI / mc (push) Failing after 32s
Infra CI / bcda (push) Successful in 1m31s
Infra CI / notebooks (push) Successful in 55s
Infra CI / docs (push) Successful in 1m40s
Infra CI / api (push) Successful in 1m4s
Infra CI / llm (push) Successful in 53s
CI / lint (pull_request) Successful in 45s
CI / test (pull_request) Failing after 2m33s
CI / notebooks-smoke (pull_request) Successful in 1m39s
Infra CI / notebooks (pull_request) Successful in 1m5s
Package Supply Chain / pkg-supply-chain (push) Successful in 1m30s
Infra CI / zotero (pull_request) Successful in 22s
Infra CI / llm (pull_request) Successful in 21s
Infra CI / mc (pull_request) Failing after 40s
Infra CI / docs (pull_request) Successful in 15s
Infra CI / api (pull_request) Successful in 15s
Infra CI / bcda (pull_request) Successful in 15s
feat(bcda): /metrics for the BCDA manager — OTel instruments on a second port, scraped by Prometheus
bcda.ui.metrics follows the #579 convention: perf.meter hands back an
OTel meter + PrometheusMetricReader when STACK_TELEMETRY is on and a
no-op MockMeter otherwise. Streamlit cannot mount a route and only
executes the app script when a browser session opens, so the registry is
published from a second port (BCDA_METRICS_PORT, 8502) by a new
`python -m bcda.ui` entrypoint that starts the metrics server first and
then boots Streamlit's CLI in the same process; the image CMD and
`stack bcda ui` use it. Prometheus scrapes bcda:8502/metrics directly
(infra/prometheus/targets/services.yml) like api and llm.

Instruments: stack_bcda_runs_total{kind,state}, stack_bcda_runs_inflight
{kind}, stack_bcda_run_seconds{kind} (recorded by the runner, which now
labels runs export / adopt / load / vendor_check / other),
stack_bcda_page_views_total{page}, and two observable gauges read at
scrape time, stack_bcda_store_jobs{status} and stack_bcda_store_bytes.
Attribute values are closed sets. The image installs the perf extra;
the compose service joins the observability network with
OTEL_SERVICE_NAME=bcda. polars joins the bcda extra: the views import it,
and it had only been a dev dependency, so the first metrics image
crash-looped on `No module named polars` the moment the entrypoint
imported the app at process start.

Verified in the stack: bcda:8502/metrics serves stack_bcda_* series,
the prometheus target is up and stack_bcda_store_jobs answers a query.

refs #1139
2026-10-25 14:40:31 -04:00

128 lines
4.2 KiB
Python

"""bcda.ui.metrics — instruments, store gauges and the /metrics server."""
from __future__ import annotations
import socket
import urllib.request
import pytest
from bcda.store import Store
from bcda.ui import metrics
from bcda.ui.runner import Runner
@pytest.fixture(autouse=True)
def _fresh_instruments(monkeypatch):
"""Rebuild the instrument set per test; keep any server from leaking state."""
monkeypatch.setattr(metrics, "_instruments", None)
yield
monkeypatch.setattr(metrics, "_instruments", None)
def test_mock_meter_path_is_free(monkeypatch) -> None:
monkeypatch.setenv("STACK_TELEMETRY", "false")
metrics.run_started("export")
metrics.run_finished("export", "done", 1.5)
metrics.run_finished("bogus kind", "failed", -1) # clamps and folds to "other"
metrics.page_view("connect")
metrics.observe_store(None)
assert metrics.serve(port=0) is None
assert metrics._kind("load") == "load" and metrics._kind("nope") == "other"
def test_store_observations(tmp_path, monkeypatch) -> None:
assert (
metrics.store_job_counts(tmp_path) == {} and metrics.store_bytes(tmp_path) == 0
)
store = Store(path=str(tmp_path))
store._append_job(key="A", status="complete")
store._append_job(key="B", status="failed")
store._append_job(key="C", status="complete")
d = tmp_path / "exports" / "A"
d.mkdir(parents=True)
(d / "Patient.ndjson").write_bytes(b"x" * 10)
assert metrics.store_job_counts(tmp_path) == {"complete": 2, "failed": 1}
assert metrics.store_bytes(tmp_path) == 10
# errors never propagate to a scrape
from bcda.ui import service as svc
def boom(*a, **k): # noqa: ANN002, ANN003, ANN202
raise OSError("disk gone")
monkeypatch.setattr(svc, "make_store", boom)
monkeypatch.setattr(svc, "export_dirs", boom)
assert (
metrics.store_job_counts(tmp_path) == {} and metrics.store_bytes(tmp_path) == 0
)
def test_runner_records_runs(monkeypatch) -> None:
seen: list = []
monkeypatch.setattr(
metrics, "run_started", lambda kind: seen.append(("start", kind))
)
monkeypatch.setattr(
metrics,
"run_finished",
lambda kind, state, secs: seen.append(("end", kind, state, secs >= 0)),
)
r = Runner()
r.wait(r.submit("ok", lambda: 1, kind="load").id)
def boom() -> None:
raise RuntimeError("x")
r.wait(r.submit("bad", boom).id)
assert seen == [
("start", "load"),
("end", "load", "done", True),
("start", "other"),
("end", "other", "failed", True),
]
assert r.all()[0].kind == "other" and r.all()[1].kind == "load"
def _free_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def test_serve_publishes_registry(monkeypatch, tmp_path) -> None:
"""With telemetry on, /metrics carries stack_bcda_* series incl. the store gauges."""
import perf
from perf import _meter
monkeypatch.setenv("STACK_TELEMETRY", "true")
monkeypatch.setattr(perf, "_initialised", False)
monkeypatch.setattr(_meter, "_provider_ready", False)
monkeypatch.setattr(metrics, "_server_port", None)
store = Store(path=str(tmp_path))
store._append_job(key="A", status="complete")
port = metrics.serve(port=_free_port())
assert port and metrics.serve() == port # idempotent
metrics.observe_store(tmp_path)
metrics.run_started("export")
metrics.run_finished("export", "done", 2.0)
metrics.page_view("exports")
body = (
urllib.request.urlopen(f"http://127.0.0.1:{port}/metrics", timeout=5)
.read()
.decode()
)
assert 'stack_bcda_runs_total{kind="export",state="done"} 1.0' in body
assert 'stack_bcda_page_views_total{page="exports"} 1.0' in body
assert 'stack_bcda_store_jobs{status="complete"} 1.0' in body
assert "stack_bcda_store_bytes 0.0" in body
assert "stack_bcda_run_seconds" in body
# the default port comes from the environment
monkeypatch.setattr(metrics, "_server_port", None)
env_port = _free_port()
monkeypatch.setenv("BCDA_METRICS_PORT", str(env_port))
assert metrics.serve() == env_port
perf.shutdown()