From 1cfbf7b5571c0440c142027197dfa2d0222e90f1 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 28 Oct 2026 13:56:47 +0000 Subject: [PATCH 1/6] docs(openspec): plan the metric instruments change for #817 --- .../.openspec.yaml | 2 + .../817-metrics-through-instruments/design.md | 58 +++++++++++++++++++ .../proposal.md | 54 +++++++++++++++++ .../specs/ci-gate-admission/spec.md | 9 +++ .../specs/metric-instruments/spec.md | 39 +++++++++++++ .../817-metrics-through-instruments/tasks.md | 32 ++++++++++ 6 files changed, 194 insertions(+) create mode 100644 openspec/changes/817-metrics-through-instruments/.openspec.yaml create mode 100644 openspec/changes/817-metrics-through-instruments/design.md create mode 100644 openspec/changes/817-metrics-through-instruments/proposal.md create mode 100644 openspec/changes/817-metrics-through-instruments/specs/ci-gate-admission/spec.md create mode 100644 openspec/changes/817-metrics-through-instruments/specs/metric-instruments/spec.md create mode 100644 openspec/changes/817-metrics-through-instruments/tasks.md diff --git a/openspec/changes/817-metrics-through-instruments/.openspec.yaml b/openspec/changes/817-metrics-through-instruments/.openspec.yaml new file mode 100644 index 0000000000..1bb6456d11 --- /dev/null +++ b/openspec/changes/817-metrics-through-instruments/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-28 diff --git a/openspec/changes/817-metrics-through-instruments/design.md b/openspec/changes/817-metrics-through-instruments/design.md new file mode 100644 index 0000000000..d2159252bd --- /dev/null +++ b/openspec/changes/817-metrics-through-instruments/design.md @@ -0,0 +1,58 @@ +# Design + +## Decisions + +- **One rule for each site.** A count of events becomes a counter. A duration or a size for each event becomes a histogram. A value that holds the state at one time, which the next value replaces, becomes a gauge. A name is deleted when it repeats a declared instrument, or when its value repeats each time the same data is read again. +- **Each text counts once.** `embed_texts` adds one lookup for each text that it gets: a hit from the memory cache, a hit from Valkey, or a miss. The counter adds a value only for a result that has texts, so a batch of 3 hits from memory and 2 misses sends the points `{result="hit", tier="memory"} 3` and `{result="miss"} 2`, one time each. +- **`result` and `tier` are two labels.** The issue asks for a counter by result (hit or miss). The Valkey hits had their own gauge, so a hit keeps its tier as a second label, and the hit share is `result="hit"` over all lookups. +- **The hit-share panel follows the response-cache panel.** It divides the hits of the last hour by the lookups of the last hour, and `or * 0` shows 0 for an hour with lookups and no hits. +- **`emit()` is the one writer.** The client's `increment_counter`, `record_gauge` and `record_histogram` stay public, because `emit()` in another module calls them. The check finds every call of a metric method by its attribute name and allows only the calls in `emit()` and the calls on `GLOBAL_METRICS`, the Prometheus registry of the Service. +- **Only declared instruments are emitted.** The check reads each module that imports `emit` from `devops_cli.telemetry.instruments`, and refuses an `emit()` whose first argument is not a name that the module imports from there and that `INSTRUMENTS` holds. + +## Call sites + +Paths are under `src/devops_cli/`. The line numbers are those of `origin/main` at bb46660c. + +| Site | Old name | Class | New instrument | +| :--- | :--- | :--- | :--- | +| `commands/telemetry.py:287` | `devops_cli.test_counter` | counter | `devops_cli_telemetry_tests_total` | +| `commands/sandbox.py:647` | `devops_cli.sandbox.metrics_invoked` | delete | Repeats the subcommand histogram of `devops sandbox metrics`. In a dry run the client sent nothing, so its `dry_run` label never left the process. | +| `commands/ci.py:557`, `:577`, `:947` | `ci.step_pass` | counter | `devops_cli_ci_checks_total`, by `step` and `outcome` (`pass` or `fail`) | +| `commands/ci.py:625` | `ci.gate_slot_wait_seconds` | histogram | `devops_cli_ci_gate_slot_wait_seconds` | +| `core/cli.py:28`, `:53`, `:71` | `devops_cli_subcommand_seconds` | histogram | `devops_cli_subcommand_duration_seconds`, by `command` and `status` | +| `sandbox/engine.py:605` | `devops_cli.sandbox.metrics_collected` | delete | One collection is one run of `devops sandbox metrics`, which the subcommand histogram counts. The health of the sandbox is in the report. | +| `sandbox/engine.py:670`, `:677` | `devops.sandbox.logs.lines`, `devops.sandbox.logs.panics` | delete | A second read of the same log counts the same lines and panics again, and the `instance_id` label has no bound. | +| `core/process.py:577`, `:729`, `:1128` | `devops_cli_subprocess_seconds` | histogram | `devops_cli_subprocess_duration_seconds`, by `bin` and `status` | +| `k8s/security_stream.py:207` | `devops_cli_k8s_security_alerts_total` | delete | The stream reads the last lines of the Falco log (`--tail`), so a second read counts the same alerts again. | +| `commands/ai.py:833` | `ai.prewarm.success` | counter | `devops_cli_ai_prewarms_total`, by `model`, `evict` and `outcome` (`ok` or `failed`) | +| `ai/gateway.py:503` | `ai.gateway.latency_ms` | histogram | `devops_cli_ai_gateway_probe_duration_seconds` | +| `ai/gateway.py:504` | `ai.gateway.healthy` | gauge | `devops_cli_ai_gateway_healthy` | +| `ai/gateway.py:541` | `ai.gateway.failover_events` | counter | `devops_cli_ai_gateway_failovers_total`, by `virtual_model` and `simulate` | +| `ai/capability.py:136`, `:151` | `ai.failover.capability_override`, `ai.failover.capability_rejection` | counter | `devops_cli_ai_capability_gate_total`, by `role`, `model` and `decision` (`override` or `rejection`) | +| `commands/test_cmd.py:525`, `:526`, `:532` | `test.profile_memory.invocations`, `.duration_seconds`, `.peak_kb` | delete | The run and its time repeat the subcommand histogram. The peak is in the report, and the `target` label is a path that a person types, with no bound. | +| `security/vulnerability_lookup.py:255`, `:313` | `devops_cli_vulnerability_lookups_total` | counter | `devops_cli_vulnerability_lookups_total`, by `source`, `status` and `batch` | +| `security/vulnerability_lookup.py:547`, `:557`, `:573`, `:584` | `devops_cli_threat_intel_lookups_total` | counter | `devops_cli_threat_intel_lookups_total`, by `source`, `status` and `cached` | +| `ai/client/structured.py:325`, `:335` | `ai.client.structured_success`, `ai.client.structured_validation_failure` | counter | `devops_cli_ai_structured_attempts_total`, by `model` and `outcome` (`valid` or `invalid`) | +| `ai/client/structured.py:261` | `ai.client.structured_retry_count` | delete | A retry follows each invalid attempt except the last, so the attempts counter gives it. | +| `ai/rag/embeddings.py:497`, `:531` | `rag.embedding.batch_size` | gauge | `devops_cli_rag_embedding_batch_size` | +| `ai/rag/embeddings.py:498`, `:532` | `rag.embedding.aimd_action` | counter | `devops_cli_rag_embedding_batch_resizes_total`, by `action` | +| `ai/rag/embeddings.py:617`, `:857`, `:858` | `devops_cli_embedding_valkey_hits_total`, `devops_cli_embedding_cache_hits_total`, `devops_cli_embedding_cache_misses_total` | counter | `devops_cli_embedding_cache_lookups_total`, by `result` and `tier` | +| `ai/rag/embeddings.py:859` | `devops_cli_embedding_cache_size` | gauge | `devops_cli_embedding_cache_size` | +| `ai/rag/drift.py:349` | `devops_cli_rag_drift_detected_total` | gauge | `devops_cli_rag_drift_detected`, by `project`. The value is 1 or 0 for the last check, a state, so the name loses `_total`. | +| `ai/rag/drift.py:354` | `devops_cli_rag_drift_score` | gauge | `devops_cli_rag_drift_score`, by `project` | +| `ai/rag/qdrant.py:542` | `qdrant.search_hits_count` | delete | The `db.response.returned_points` attribute of the search span holds it, and the investigations counter tells a retrieval that found context from one that did not. | +| `ai/client/unified.py:453` | `devops_cli_llm_inference_seconds` | histogram | `devops_cli_ai_chat_duration_seconds`, by `provider` and `model` | +| `ai/rag/indexer.py:985`, `:986` | `rag.indexed_files`, `rag.total_chunks` | delete | The root span of the index run holds both. `devops_cli_rag_points` holds the size of each collection. | +| `ai/rag/investigator.py:190` | `ai.rag.investigation.stopped` | counter | `devops_cli_rag_stops_total` | +| `ai/rag/investigator.py:384` | `ai.rag.investigation.duration_ms` | delete | Repeats `devops_cli_rag_query_duration_ms{stage="total"}`. | +| `ai/rag/investigator.py:386`, `:390` | `ai.rag.investigation.empty`, `ai.rag.investigation.hits` | counter | `devops_cli_rag_investigations_total`, by `outcome` (`found` or `empty`). The count of results stays on the span as `rag.results_count`. | + +Totals: 24 sites become counters, 9 become histograms, 6 become gauges, and 13 are deleted. The three sites in `telemetry/tracer.py` are the definitions that this change deletes. + +## Rejected alternatives + +- **Keep `record_metric` as the private path of gauges.** The issue's first answer was to keep it for `emit()`. Since #1253, `emit()` calls the client's `record_gauge`, and nothing else calls the module function. The update of 2026-10-08 on the issue proposes to delete it, and this change does. +- **Declare every old name as it is.** Names such as `ci.step_pass` and `ai.gateway.latency_ms` break the rule that `CONTRIBUTING.md` sets for a metric (`devops_cli_`, `_total` only on a counter), and several are counts that a gauge loses. No dashboard reads any of them, so a new name costs no reader. +- **Name the chat duration `gen_ai.client.operation.duration`.** The GenAI conventions define it, but the AI instruments of devops-cli (`devops_cli_ai_requests_total`, `devops_cli_ai_tokens_total`) use `devops_cli_` names, and the dashboard tests read only `devops_cli_` series. To move the AI metrics to the conventions is a change of its own. +- **Check the metric writes at run time.** A run-time check sees only the paths that a test runs. The AST check reads every module under `src/devops_cli/`. +- **Make the client's metric methods private.** `emit()` lives in another module, so it would call private methods across modules. The check by attribute name keeps the methods public and still finds every other caller. diff --git a/openspec/changes/817-metrics-through-instruments/proposal.md b/openspec/changes/817-metrics-through-instruments/proposal.md new file mode 100644 index 0000000000..bf3d196b6c --- /dev/null +++ b/openspec/changes/817-metrics-through-instruments/proposal.md @@ -0,0 +1,54 @@ +# Proposal + +## Why + +Issue #817: devops-cli sends embedding-cache use two times, and both times as single-point gauges. A command is a short-lived process, so a gauge keeps only the value of the last process, and no dashboard can add up the hits and misses. + +The gauge pair is one case of a wider fault. `record_metric` sends an OTLP gauge, and 52 call sites in 19 modules under `src/` call it with names that are not in `INSTRUMENTS` (`src/devops_cli/telemetry/instruments.py`). Most of the names are counts or durations, such as `devops_cli_subprocess_seconds` and `devops_cli_vulnerability_lookups_total`. The dashboard tests check what the dashboards read, but nothing checks what the code sends, so an earlier item fixed one or two sites at a time (#816). + +## What Changes + +- One counter, `devops_cli_embedding_cache_lookups_total`, counts each text that an embedding request looks up, by `result` (`hit` or `miss`). A hit also names its `tier` (`memory` or `valkey`). It replaces the gauges `devops_cli_embedding_cache_hits_total`, `devops_cli_embedding_cache_misses_total` and `devops_cli_embedding_valkey_hits_total`. +- The devops-cli dashboard gets the panel "Embedding Cache Hit Share". +- Each other `record_metric` call site becomes an `emit()` of a declared instrument: a counter for a count, a histogram for a duration, and a gauge for a true snapshot. A name that repeats a declared instrument, or whose value repeats when the same data is read again, is deleted. The design lists each site and its class. +- The gate wait of `devops ci` is the histogram `devops_cli_ci_gate_slot_wait_seconds`, not the gauge `ci.gate_slot_wait_seconds`. +- The module functions `record_metric` and `record_gauge` and the method `OTelTelemetryClient.record_metric` are deleted. `emit()` is the one caller of the client's `increment_counter`, `record_gauge` and `record_histogram`. +- A check in `tests/test_telemetry_instruments.py` fails on any other call that writes a metric by name, and on an `emit()` of an instrument that is not in `INSTRUMENTS`. The Prometheus registry of the Service (`GLOBAL_METRICS`, served on `/metrics`) is a different path and stays out of the check. +- The metric names that devops-cli sends are observable to a dashboard, so the change carries spec deltas: the new capability `metric-instruments`, and a MODIFIED requirement of `ci-gate-admission` for the name of the gate wait. +- This change fits one pull request. + +## Capabilities + +### New Capabilities + +- `metric-instruments`: the metrics that devops-cli sends over OTLP, each declared once in `INSTRUMENTS` and sent through `emit()`. + +### Modified Capabilities + +- `ci-gate-admission`: the gate wait is the histogram `devops_cli_ci_gate_slot_wait_seconds`. + +## Impact + +- `src/devops_cli/telemetry/instruments.py`, `src/devops_cli/telemetry/tracer.py`, `src/devops_cli/telemetry/__init__.py`, and the 19 modules that called `record_metric`. +- `src/devops_cli/config/constants.py`: the metric-name constants of the gate wait and of structured output go. +- `k8s/monitoring/dashboards/devops-cli.json`. +- `tests/test_telemetry_instruments.py`, `tests/test_rag_embeddings.py`, and the tests that patched `record_metric` or asserted a deleted name. +- `docs/TELEMETRY.md` (generated), `CONTRIBUTING.md`, and two knowledge-base pages that name the subprocess and subcommand metrics. + +## Feasibility + +Checked on `origin/main` at bb46660c: + +- `rg -n 'record_metric\(|record_gauge\(' src` lists 52 call sites outside `tracer.py`. No file under `k8s/` names any of their metrics (`rg` for each name, with dots read as underscores), so no dashboard or alert rule reads them. +- `emit()` dispatches `InstrumentKind.COUNTER` to `increment_counter`, `GAUGE` to `record_gauge` and `HISTOGRAM` to `record_histogram` on the client. `InstrumentKind.GAUGE` exists since #1253, so the item no longer waits for #974. +- #816 is closed and no `llm_cache` gauge remains, as the 2026-10-08 update of the issue says. +- `_partition_with_valkey_l2` (`src/devops_cli/ai/rag/embeddings.py`) returns the memory hits and the Valkey hits together, and counts the Valkey hits on its own, so each text has one result and, for a hit, one tier. +- `k8s/otel/values.yaml` sends names unchanged (`translation_strategy: UnderscoreEscapingWithoutSuffixes`) and filters no metric, so a new instrument reaches Prometheus under its own name. + +## Existing Tool Considered + +The OpenTelemetry metrics SDK, which the client already uses, gives the counter, histogram and gauge kinds and their delta export. `INSTRUMENTS` and `emit()` exist already. The change adds no library and builds no new mechanism: it moves the call sites onto the existing declaration and adds one AST check in the test suite, with the `ast` module of the standard library. + +The OpenTelemetry GenAI conventions name a duration metric for model calls, `gen_ai.client.operation.duration`. The design records why the chat duration keeps a `devops_cli_` name here. + +The change deletes `record_metric` and `record_gauge` from `src/devops_cli/telemetry/tracer.py` and their export from `src/devops_cli/telemetry/__init__.py`, the constants `CONST_CI_GATE_SLOT_WAIT_METRIC` and `CONST_METRIC_AI_STRUCTURED_*`, and 13 call sites whose metrics repeat another metric or count the same data again on a second read. diff --git a/openspec/changes/817-metrics-through-instruments/specs/ci-gate-admission/spec.md b/openspec/changes/817-metrics-through-instruments/specs/ci-gate-admission/spec.md new file mode 100644 index 0000000000..7c3a25afe4 --- /dev/null +++ b/openspec/changes/817-metrics-through-instruments/specs/ci-gate-admission/spec.md @@ -0,0 +1,9 @@ +## MODIFIED Requirements + +### Requirement: The wait is not gate time +The time a run waits for a slot SHALL NOT count in the elapsed time of the gate, in its summary or in its over-budget warning. The run SHALL record the wait as one observation of the histogram `devops_cli_ci_gate_slot_wait_seconds`. + +#### Scenario: A long wait and a fast gate +- **WHEN** a run waits 600 s for a slot and then runs checks that take 30 s +- **THEN** the summary reports an elapsed time of about 30 s and no over-budget warning +- **AND** the histogram `devops_cli_ci_gate_slot_wait_seconds` has one observation of about 600 diff --git a/openspec/changes/817-metrics-through-instruments/specs/metric-instruments/spec.md b/openspec/changes/817-metrics-through-instruments/specs/metric-instruments/spec.md new file mode 100644 index 0000000000..967a020487 --- /dev/null +++ b/openspec/changes/817-metrics-through-instruments/specs/metric-instruments/spec.md @@ -0,0 +1,39 @@ +## Purpose + +The metrics that devops-cli sends over OTLP: each one is declared one time in `INSTRUMENTS` with its kind, and sent through `emit()`, so a dashboard can add up the values that many short-lived processes send. + +## ADDED Requirements + +### Requirement: Every metric is a declared instrument sent through emit +devops-cli SHALL send each OTLP metric through `emit()` with an instrument that `INSTRUMENTS` holds. No module other than `telemetry/instruments.py` SHALL call a metric method of the telemetry client (`increment_counter`, `record_gauge`, `record_histogram`). The instrument check in `tests/test_telemetry_instruments.py` SHALL name the file and line of each call that breaks the rule. + +#### Scenario: The source tree keeps the rule +- **WHEN** the instrument check reads every module under `src/devops_cli/` +- **THEN** it finds no call of a metric method outside `emit()`, and no `emit()` of an instrument that `INSTRUMENTS` does not hold +- **AND** it allows the calls on `GLOBAL_METRICS`, the Prometheus registry that the Service serves on `/metrics`, which sends no OTLP metric + +#### Scenario: A module writes a metric by name +- **WHEN** a module calls `get_tracer().record_gauge("devops_cli_example", 1.0)` +- **THEN** the instrument check names that call + +#### Scenario: A module emits an undeclared instrument +- **WHEN** a module builds `Instrument("devops_cli_example_total", InstrumentKind.COUNTER, "1", "x")` and passes it to `emit()` +- **THEN** the instrument check names that call + +### Requirement: Embedding cache lookups count each text once +`devops_cli_embedding_cache_lookups_total` SHALL count each text that an embedding request looks up, one time, by `result`: `hit` or `miss`. A hit SHALL also carry `tier`: `memory` for the in-process cache, or `valkey` for the Valkey cache. A request SHALL add a value only for a result that has texts. No other metric SHALL count embedding cache hits or misses. + +#### Scenario: Three hits and two misses +- **WHEN** an embedding request gets five texts, three of which the in-process cache holds +- **THEN** `devops_cli_embedding_cache_lookups_total` gets the points `{result="hit", tier="memory"}` 3 and `{result="miss"}` 2, one time each + +#### Scenario: A hit from Valkey +- **WHEN** an embedding request gets one text that only the Valkey cache holds +- **THEN** `devops_cli_embedding_cache_lookups_total` gets the one point `{result="hit", tier="valkey"}` 1 + +### Requirement: The devops-cli dashboard shows the embedding cache hit share +The devops-cli dashboard SHALL have the panel "Embedding Cache Hit Share", which divides the embedding cache hits of the last hour by the lookups of the last hour, and shows 0 for an hour with lookups and no hits. + +#### Scenario: The panel query +- **WHEN** the panel "Embedding Cache Hit Share" of `k8s/monitoring/dashboards/devops-cli.json` is read +- **THEN** its query is `(sum(increase(devops_cli_embedding_cache_lookups_total{result="hit"}[1h])) or sum(increase(devops_cli_embedding_cache_lookups_total[1h])) * 0) / sum(increase(devops_cli_embedding_cache_lookups_total[1h]))` diff --git a/openspec/changes/817-metrics-through-instruments/tasks.md b/openspec/changes/817-metrics-through-instruments/tasks.md new file mode 100644 index 0000000000..705a9eadce --- /dev/null +++ b/openspec/changes/817-metrics-through-instruments/tasks.md @@ -0,0 +1,32 @@ +# Tasks + +## 1. Embedding cache lookups are one counter + +- [ ] Add failing tests: a request with three memory hits and two misses sends `{result="hit", tier="memory"}` 3 and `{result="miss"}` 2 one time each; a Valkey hit sends `{result="hit", tier="valkey"}` 1 + - Verification: `uv run devops ci test tests/test_rag_embeddings.py` +- [ ] Declare `devops_cli_embedding_cache_lookups_total` and the gauge `devops_cli_embedding_cache_size`, emit them from `embed_texts`, and delete the three hit and miss gauges + - Verification: `uv run devops ci test tests/test_rag_embeddings.py tests/test_telemetry_instruments.py` + +## 2. The devops-cli dashboard shows the hit share + +- [ ] Add a failing test for the query of the panel "Embedding Cache Hit Share" + - Verification: `uv run devops ci test tests/test_telemetry_instruments.py` +- [ ] Add the panel to `k8s/monitoring/dashboards/devops-cli.json`, with the limits of `increase()` in its description + - Verification: `uv run devops ci test tests/test_telemetry_instruments.py` + +## 3. Every metric is a declared instrument sent through emit + +- [ ] Add the failing instrument check: it fails on a call of a metric method outside `emit()` other than on `GLOBAL_METRICS`, and on an `emit()` of an instrument that `INSTRUMENTS` does not hold; a test shows that it names both kinds of call + - Verification: `uv run devops ci test tests/test_telemetry_instruments.py` +- [ ] Declare the instruments of the design's table, move each call site to `emit()`, and delete the sites that the table deletes, with the constants of their names + - Verification: `uv run devops ci test tests/test_telemetry_instruments.py tests/test_otel_command_coverage.py tests/test_ci_gate_admission.py tests/test_ci.py tests/test_ai_prewarm.py tests/test_sandbox_metrics.py tests/test_telemetry.py` +- [ ] Delete `record_metric` and `record_gauge` from `telemetry/tracer.py`, the method `OTelTelemetryClient.record_metric`, and their export from `telemetry/__init__.py`; the tests that patched `record_metric` read the captured metrics or patch nothing + - Verification: `uv run devops ci test tests/test_telemetry.py tests/test_ci.py tests/test_ai_prewarm.py tests/test_sandbox_metrics.py` +- [ ] Name the new gate wait metric in `CONTRIBUTING.md`, say there that a metric is an `INSTRUMENTS` entry sent with `emit()`, rename the subprocess and subcommand metrics in the knowledge base, and regenerate the documentation + - Verification: `uv run devops docs generate --sync-readme && uv run devops docs check` + +## 4. Archive + +- [ ] Archive the change + - Verification: `uv run devops openspec archive 817-metrics-through-instruments` +- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). From a6da0766e416392ecd428510759e8f1394dd0d0f Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 28 Oct 2026 14:00:02 +0000 Subject: [PATCH 2/6] feat(rag): count embedding cache lookups once per text, by result and tier --- .../817-metrics-through-instruments/tasks.md | 4 +- src/devops_cli/ai/rag/embeddings.py | 68 +++++++++++-------- src/devops_cli/telemetry/instruments.py | 17 +++++ tests/support/telemetry_capture.py | 5 ++ tests/test_rag_embeddings.py | 50 ++++++++++++++ 5 files changed, 113 insertions(+), 31 deletions(-) diff --git a/openspec/changes/817-metrics-through-instruments/tasks.md b/openspec/changes/817-metrics-through-instruments/tasks.md index 705a9eadce..b8a52d54d1 100644 --- a/openspec/changes/817-metrics-through-instruments/tasks.md +++ b/openspec/changes/817-metrics-through-instruments/tasks.md @@ -2,9 +2,9 @@ ## 1. Embedding cache lookups are one counter -- [ ] Add failing tests: a request with three memory hits and two misses sends `{result="hit", tier="memory"}` 3 and `{result="miss"}` 2 one time each; a Valkey hit sends `{result="hit", tier="valkey"}` 1 +- [x] Add failing tests: a request with three memory hits and two misses sends `{result="hit", tier="memory"}` 3 and `{result="miss"}` 2 one time each; a Valkey hit sends `{result="hit", tier="valkey"}` 1 - Verification: `uv run devops ci test tests/test_rag_embeddings.py` -- [ ] Declare `devops_cli_embedding_cache_lookups_total` and the gauge `devops_cli_embedding_cache_size`, emit them from `embed_texts`, and delete the three hit and miss gauges +- [x] Declare `devops_cli_embedding_cache_lookups_total` and the gauge `devops_cli_embedding_cache_size`, emit them from `embed_texts`, and delete the three hit and miss gauges - Verification: `uv run devops ci test tests/test_rag_embeddings.py tests/test_telemetry_instruments.py` ## 2. The devops-cli dashboard shows the hit share diff --git a/src/devops_cli/ai/rag/embeddings.py b/src/devops_cli/ai/rag/embeddings.py index 0e139372c1..0f5c2e5701 100644 --- a/src/devops_cli/ai/rag/embeddings.py +++ b/src/devops_cli/ai/rag/embeddings.py @@ -75,6 +75,11 @@ record_metric, trace_span, ) +from devops_cli.telemetry.instruments import ( + EMBEDDING_CACHE_LOOKUPS_TOTAL, + EMBEDDING_CACHE_SIZE, + emit, +) from devops_cli.valkey.cache import ValkeyCacheTier, configured_cache_tier logger = logging.getLogger(__name__) @@ -368,6 +373,17 @@ def _apply_model_prefix(text: str, model: str, *, is_query: bool = False) -> str return text +def _count_cache_lookups(*, memory: int, valkey: int, misses: int) -> None: + """Add each lookup result that has texts to the embedding cache lookup counter.""" + for count, attributes in ( + (memory, {"result": "hit", "tier": "memory"}), + (valkey, {"result": "hit", "tier": "valkey"}), + (misses, {"result": "miss"}), + ): + if count: + emit(EMBEDDING_CACHE_LOOKUPS_TOTAL, count, attributes) + + class EmbeddingsEngine: """Generates dense vector embeddings using Ollama or OpenAI endpoints.""" @@ -592,31 +608,29 @@ def _set_valkey_embedding( def _partition_with_valkey_l2( self, texts: list[str], *, is_query: bool = False ) -> tuple[dict[int, list[float]], list[int], list[str]]: - """Partition texts through L1 in-memory cache and L2 Valkey chunk cache.""" - cached, l1_miss_indices, l1_miss_texts = self._partition_cache(texts, is_query=is_query) - if not l1_miss_texts or self._l2 is None: - return cached, l1_miss_indices, l1_miss_texts - - final_miss_indices: list[int] = [] - final_miss_texts: list[str] = [] - valkey_hits = 0 - - for idx, text in zip(l1_miss_indices, l1_miss_texts, strict=True): - v_hit = self._get_valkey_embedding(text, self.model, is_query=is_query) - if v_hit is not None: - cached[idx] = v_hit - self._cache.put(text, self.model, v_hit, is_query=is_query) - valkey_hits += 1 - else: - final_miss_indices.append(idx) - final_miss_texts.append(text) - - if valkey_hits > 0: - from devops_cli.telemetry import record_metric + """Partition texts through L1 in-memory cache and L2 Valkey chunk cache. - record_metric("devops_cli_embedding_valkey_hits_total", valkey_hits, unit="1") - - return cached, final_miss_indices, final_miss_texts + Each text counts once on `devops_cli_embedding_cache_lookups_total`: as a hit of the tier + that held it, or as a miss. + """ + cached, miss_indices, miss_texts = self._partition_cache(texts, is_query=is_query) + memory_hits = len(cached) + if miss_texts and self._l2 is not None: + l1_miss_indices, l1_miss_texts = miss_indices, miss_texts + miss_indices, miss_texts = [], [] + for idx, text in zip(l1_miss_indices, l1_miss_texts, strict=True): + v_hit = self._get_valkey_embedding(text, self.model, is_query=is_query) + if v_hit is not None: + cached[idx] = v_hit + self._cache.put(text, self.model, v_hit, is_query=is_query) + else: + miss_indices.append(idx) + miss_texts.append(text) + + _count_cache_lookups( + memory=memory_hits, valkey=len(cached) - memory_hits, misses=len(miss_texts) + ) + return cached, miss_indices, miss_texts @property def dimension(self) -> int: @@ -848,15 +862,11 @@ def embed_texts(self, texts: list[str], *, is_query: bool = False) -> list[list[ "rag.is_query": is_query, }, ): - from devops_cli.telemetry import record_metric - prefixed_texts = self._apply_model_prefix(texts, is_query=is_query) cached, miss_indices, miss_texts = self._partition_with_valkey_l2( prefixed_texts, is_query=is_query ) - record_metric("devops_cli_embedding_cache_hits_total", len(cached), unit="1") - record_metric("devops_cli_embedding_cache_misses_total", len(miss_texts), unit="1") - record_metric("devops_cli_embedding_cache_size", self._cache.size, unit="1") + emit(EMBEDDING_CACHE_SIZE, self._cache.size) if miss_texts: fresh = self._dispatch_embed(miss_texts) diff --git a/src/devops_cli/telemetry/instruments.py b/src/devops_cli/telemetry/instruments.py index 7110c4484b..54507c7cf8 100644 --- a/src/devops_cli/telemetry/instruments.py +++ b/src/devops_cli/telemetry/instruments.py @@ -140,6 +140,19 @@ class Instrument: "1", "GraphQL points that GitHub reported each answer cost in its rateLimit field", ) +EMBEDDING_CACHE_LOOKUPS_TOTAL = Instrument( + "devops_cli_embedding_cache_lookups_total", + InstrumentKind.COUNTER, + "1", + "Embedding cache lookups, one for each text that an embedding request gets, by result: hit " + "or miss. A hit names its tier: memory for the cache of the process, or valkey", +) +EMBEDDING_CACHE_SIZE = Instrument( + "devops_cli_embedding_cache_size", + InstrumentKind.GAUGE, + "1", + "Embeddings that the memory cache of the process held after its last embedding request", +) PROJECT_RELEASES = Instrument( "devops_cli_project_releases", @@ -258,6 +271,8 @@ class Instrument: GITHUB_REQUESTS_TOTAL, GITHUB_THROTTLE_WAIT, GITHUB_GRAPHQL_POINTS_TOTAL, + EMBEDDING_CACHE_LOOKUPS_TOTAL, + EMBEDDING_CACHE_SIZE, PROJECT_RELEASES, PROJECT_COMMITS, PROJECT_PRS, @@ -316,6 +331,8 @@ def backend_name(served_by: str | None) -> str: "AI_TOKENS_TOTAL", "COMMAND_DURATION", "COMMAND_TOTAL", + "EMBEDDING_CACHE_LOOKUPS_TOTAL", + "EMBEDDING_CACHE_SIZE", "FINDINGS_TOTAL", "GITHUB_GRAPHQL_POINTS_TOTAL", "GITHUB_REQUESTS_TOTAL", diff --git a/tests/support/telemetry_capture.py b/tests/support/telemetry_capture.py index 4e2aedab30..c06681c7aa 100644 --- a/tests/support/telemetry_capture.py +++ b/tests/support/telemetry_capture.py @@ -26,6 +26,11 @@ def __call__(self, path: str, payload: dict[str, Any]) -> None: if "resourceMetrics" in payload: self.payloads.append(payload) + def clear(self) -> None: + """Send what the client holds now, and forget every payload captured so far.""" + tracer_module.get_tracer().flush() + self.payloads.clear() + @property def metrics(self) -> list[dict[str, Any]]: tracer_module.get_tracer().flush() diff --git a/tests/test_rag_embeddings.py b/tests/test_rag_embeddings.py index 283cb13ae7..14a3d605a5 100644 --- a/tests/test_rag_embeddings.py +++ b/tests/test_rag_embeddings.py @@ -24,8 +24,10 @@ CONST_RAG_MAX_CHUNK_TOKENS, ) from devops_cli.config.settings import AIConfig +from devops_cli.telemetry.instruments import EMBEDDING_CACHE_LOOKUPS_TOTAL from devops_cli.valkey.client import ValkeyClient from tests.support.fakes.clock import ClockFake +from tests.support.telemetry_capture import Captured from tests.support.waits import THREAD_HANDOFF_BOUND_SECONDS pytestmark = pytest.mark.usefixtures("mock_keyring") @@ -1621,3 +1623,51 @@ def test_probe_ollama_embed_dimension_sends_num_ctx_option( assert len(sent) == 1 body = json.loads(sent[0].content) assert body.get("options") == {"num_ctx": CONST_RAG_MAX_CHUNK_TOKENS} + + +# ============================================================================= +# Tests: embedding cache lookups are one counter (#817) +# ============================================================================= + + +def _lookups(captured: Captured) -> list[tuple[dict[str, Any], float]]: + """The points of the embedding cache lookup counter, hits before misses.""" + return sorted( + captured.points(EMBEDDING_CACHE_LOOKUPS_TOTAL.name), key=lambda point: point[0]["result"] + ) + + +def test_an_embedding_request_counts_each_text_once_by_its_cache_result( + monkeypatch: pytest.MonkeyPatch, captured: Captured +) -> None: + """Three texts that the memory cache holds and two that it does not are three hits and two + misses, each sent one time.""" + _serve(monkeypatch, _gateway_reply) + engine = _gateway_engine() + engine.embed_texts(["first", "second", "third"]) + captured.clear() + + engine.embed_texts(["first", "second", "third", "fourth", "fifth"]) + + assert _lookups(captured) == [ + ({"result": "hit", "tier": "memory"}, 3.0), + ({"result": "miss"}, 2.0), + ] + + +def test_a_text_that_only_valkey_holds_counts_as_a_valkey_hit( + monkeypatch: pytest.MonkeyPatch, captured: Captured, valkey_client: ValkeyClient +) -> None: + """A second process finds the text in Valkey and not in its own memory cache.""" + _serve(monkeypatch, _gateway_reply) + config = _gateway_config() + EmbeddingsEngine(config, api_key="sk-gateway", valkey_client=valkey_client).embed_texts( + ["shared chunk"] + ) + captured.clear() + + EmbeddingsEngine(config, api_key="sk-gateway", valkey_client=valkey_client).embed_texts( + ["shared chunk"] + ) + + assert _lookups(captured) == [({"result": "hit", "tier": "valkey"}, 1.0)] From 79849985e790f8743d3a2214f5c5ad38d1fe3356 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 28 Oct 2026 14:02:51 +0000 Subject: [PATCH 3/6] feat(monitoring): chart the embedding cache hit share on the devops-cli dashboard --- k8s/monitoring/dashboards/devops-cli.json | 64 ++++++++++++++++--- .../817-metrics-through-instruments/tasks.md | 4 +- tests/test_telemetry_instruments.py | 12 ++++ 3 files changed, 70 insertions(+), 10 deletions(-) diff --git a/k8s/monitoring/dashboards/devops-cli.json b/k8s/monitoring/dashboards/devops-cli.json index 33b31091e1..8c2af76f9e 100644 --- a/k8s/monitoring/dashboards/devops-cli.json +++ b/k8s/monitoring/dashboards/devops-cli.json @@ -584,13 +584,61 @@ } ] }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "description": "Share of the last hour's embedding cache lookups that a cache answered, from the memory cache of the process or from Valkey; an hour with lookups and no hits shows 0. Each text that an embedding request gets is one lookup. Approximate: increase() needs two samples of a series inside its window, so a series' first sample, and any series seen only once in the window, add nothing, and delta points from one process can arrive out of order (#792). The counts lost can fall on either side of the ratio, so a share can come out high or low.", + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisCenteredZero": false, + "drawStyle": "line", + "lineInterpolation": "smooth" + }, + "max": 1, + "min": 0, + "unit": "percentunit" + } + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 44 + }, + "id": 21, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + }, + "title": "Embedding Cache Hit Share", + "type": "timeseries", + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "(sum(increase(devops_cli_embedding_cache_lookups_total{result=\"hit\"}[1h])) or sum(increase(devops_cli_embedding_cache_lookups_total[1h])) * 0) / sum(increase(devops_cli_embedding_cache_lookups_total[1h]))", + "legendFormat": "hit share", + "refId": "A" + } + ] + }, { "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, - "y": 44 + "y": 52 }, "id": 5, "title": "AI Review Findings Breakdown", @@ -618,7 +666,7 @@ "h": 8, "w": 12, "x": 0, - "y": 45 + "y": 53 }, "id": 13, "options": { @@ -668,7 +716,7 @@ "h": 8, "w": 12, "x": 12, - "y": 45 + "y": 53 }, "id": 14, "options": { @@ -713,7 +761,7 @@ "h": 8, "w": 12, "x": 0, - "y": 53 + "y": 61 }, "id": 6, "options": { @@ -758,7 +806,7 @@ "h": 8, "w": 12, "x": 12, - "y": 53 + "y": 61 }, "id": 7, "options": { @@ -787,7 +835,7 @@ "h": 1, "w": 24, "x": 0, - "y": 61 + "y": 69 }, "id": 8, "title": "AI Spend & Economics", @@ -828,7 +876,7 @@ "h": 6, "w": 12, "x": 0, - "y": 62 + "y": 70 }, "id": 9, "options": { @@ -881,7 +929,7 @@ "h": 6, "w": 12, "x": 12, - "y": 62 + "y": 70 }, "id": 10, "options": { diff --git a/openspec/changes/817-metrics-through-instruments/tasks.md b/openspec/changes/817-metrics-through-instruments/tasks.md index b8a52d54d1..c7fa37caeb 100644 --- a/openspec/changes/817-metrics-through-instruments/tasks.md +++ b/openspec/changes/817-metrics-through-instruments/tasks.md @@ -9,9 +9,9 @@ ## 2. The devops-cli dashboard shows the hit share -- [ ] Add a failing test for the query of the panel "Embedding Cache Hit Share" +- [x] Add a failing test for the query of the panel "Embedding Cache Hit Share" - Verification: `uv run devops ci test tests/test_telemetry_instruments.py` -- [ ] Add the panel to `k8s/monitoring/dashboards/devops-cli.json`, with the limits of `increase()` in its description +- [x] Add the panel to `k8s/monitoring/dashboards/devops-cli.json`, with the limits of `increase()` in its description - Verification: `uv run devops ci test tests/test_telemetry_instruments.py` ## 3. Every metric is a declared instrument sent through emit diff --git a/tests/test_telemetry_instruments.py b/tests/test_telemetry_instruments.py index c9c017223a..26dd4092a1 100644 --- a/tests/test_telemetry_instruments.py +++ b/tests/test_telemetry_instruments.py @@ -409,6 +409,18 @@ def test_the_hit_share_panel_divides_cached_requests_by_all_requests_over_an_hou ) +def test_the_embedding_hit_share_panel_divides_hits_by_lookups_over_an_hour() -> None: + """Verify the embedding cache hit share is the hits of the last hour over its lookups, and + shows 0 for an hour with lookups and no hits (#817).""" + panels = {panel["title"]: panel for panel in _panels(DASHBOARDS / "devops-cli.json")} + + assert _panel_queries(panels["Embedding Cache Hit Share"]) == ( + '(sum(increase(devops_cli_embedding_cache_lookups_total{result="hit"}[1h])) ' + "or sum(increase(devops_cli_embedding_cache_lookups_total[1h])) * 0) " + "/ sum(increase(devops_cli_embedding_cache_lookups_total[1h]))" + ) + + def test_a_grouped_query_adds_no_unlabelled_zero_series() -> None: """Verify `or vector(0)` follows only an ungrouped result. From 8c2cf5009a5e00eef8cd15d84741402d35470e56 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 28 Oct 2026 14:26:16 +0000 Subject: [PATCH 4/6] refactor(telemetry): send every metric through emit() with a declared instrument --- CONTRIBUTING.md | 4 +- docs/TELEMETRY.md | 26 +++ k8s/monitoring/dashboards/devops-cli.json | 2 +- .../817-metrics-through-instruments/tasks.md | 8 +- src/devops_cli/ai/capability.py | 18 +- src/devops_cli/ai/client/structured.py | 28 ++- src/devops_cli/ai/client/unified.py | 10 +- src/devops_cli/ai/gateway.py | 21 ++- .../it_domains/tools/prometheus.md | 6 +- .../observability_and_distributed_tracing.md | 4 +- src/devops_cli/ai/rag/drift.py | 17 +- src/devops_cli/ai/rag/embeddings.py | 27 ++- src/devops_cli/ai/rag/indexer.py | 5 +- src/devops_cli/ai/rag/investigator.py | 12 +- src/devops_cli/ai/rag/qdrant.py | 3 +- src/devops_cli/commands/ai.py | 15 +- src/devops_cli/commands/ci.py | 19 +- src/devops_cli/commands/sandbox.py | 8 +- src/devops_cli/commands/telemetry.py | 4 +- src/devops_cli/commands/test_cmd.py | 16 +- src/devops_cli/config/constants.py | 4 - src/devops_cli/core/cli.py | 25 +-- src/devops_cli/core/process.py | 30 ++-- src/devops_cli/docs/generator.py | 4 + src/devops_cli/k8s/security_stream.py | 20 +-- src/devops_cli/sandbox/engine.py | 22 +-- .../security/vulnerability_lookup.py | 52 +++--- src/devops_cli/telemetry/__init__.py | 3 - src/devops_cli/telemetry/instruments.py | 170 ++++++++++++++++++ src/devops_cli/telemetry/tracer.py | 38 +--- tests/test_ai_prewarm.py | 45 ++--- tests/test_ci.py | 4 - tests/test_ci_gate_admission.py | 3 +- tests/test_otel_command_coverage.py | 4 +- tests/test_sandbox_metrics.py | 42 ++--- tests/test_telemetry.py | 8 +- tests/test_telemetry_instruments.py | 94 ++++++++++ 37 files changed, 490 insertions(+), 331 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bcd7589e5f..bd689d15ea 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -69,7 +69,7 @@ uv run pre-commit install ``` Validates every check `devops ci` runs concurrently: Python runtime, tests, the coverage floor, linting, formatting, strict typing, dependency audit, security scanning, the wheel and sdist build, workflow actionlint and zizmor, and documentation freshness. - Several agents share one host, and the full test suite starts one pytest worker for each CPU, so gates that run at once make each other several times slower (11189 tests took 247 s alone and 440 s each beside a second gate). A run that selects `test`, `security` or `typecheck`, and the full-suite `devops ci test` and `devops ci coverage`, therefore wait for a free gate slot first and say which process and worktree hold the slots. One slot exists for each 16 CPUs, and at least one; `ci.gate_slots` (or `DEVOPS_CLI_CI_GATE_SLOTS`) sets the number. The pre-push hook, a test run narrowed by paths or by `-n`, a dry run and a cached verdict never wait. The operating system frees a slot when its holder ends, also when it is killed. The wait is not part of the gate time and is recorded as the metric `ci.gate_slot_wait_seconds`. + Several agents share one host, and the full test suite starts one pytest worker for each CPU, so gates that run at once make each other several times slower (11189 tests took 247 s alone and 440 s each beside a second gate). A run that selects `test`, `security` or `typecheck`, and the full-suite `devops ci test` and `devops ci coverage`, therefore wait for a free gate slot first and say which process and worktree hold the slots. One slot exists for each 16 CPUs, and at least one; `ci.gate_slots` (or `DEVOPS_CLI_CI_GATE_SLOTS`) sets the number. The pre-push hook, a test run narrowed by paths or by `-n`, a dry run and a cached verdict never wait. The operating system frees a slot when its holder ends, also when it is killed. The wait is not part of the gate time and is recorded as the histogram `devops_cli_ci_gate_slot_wait_seconds`. --- @@ -125,7 +125,7 @@ This table holds the naming rules of the project. Each rule names the check that | Test file and test function | The behavior it checks, in the terms of [CONTEXT.md](CONTEXT.md) ([docs/TESTING.md](docs/TESTING.md#names-and-assertions)) | None. | | `devops` command and option | Lowercase words joined by hyphens | None. | | Environment variable | `DEVOPS_CLI_
_` | The settings model sets the prefix, and `docs/ENV_VARS.md` is generated from it. | -| Metric | `devops_cli_`; a counter ends in `_total` and no other metric does | `tests/test_telemetry_instruments.py` checks the `_total` suffix. | +| Metric | `devops_cli_`; a counter ends in `_total` and no other metric does. Each metric is an entry of `INSTRUMENTS` in `src/devops_cli/telemetry/instruments.py`, sent with `emit()` | `tests/test_telemetry_instruments.py` checks the `_total` suffix, and fails on a metric that a module writes by name or on an `emit()` of an instrument that `INSTRUMENTS` does not hold. | | Issue label | `/`, from `.github/labels.yml` | `devops gh labels sync`. | | Decision record | `docs/adr/-.md` | None. | | Release tag | `v..` | release-please writes it. Nobody tags by hand. | diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index ddc6c0d3c9..1dfde2846e 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -37,12 +37,21 @@ Prometheus 3 stores each histogram as a native histogram under the instrument's own name, with no `_bucket`, `_sum` or `_count` series; query it with `histogram_quantile`, `histogram_avg` and `histogram_count`. +Each metric is an entry of `INSTRUMENTS` in +`src/devops_cli/telemetry/instruments.py`, which gives its kind, and is sent with +`emit()`. `tests/test_telemetry_instruments.py` fails on a metric that a module +writes by name. `devops telemetry connect` points devops-cli at the cluster's collector. | Metric Name | Type | Unit | Description | |---|---|---|---| | `devops_cli_command_total` | Counter | `1` | Commands run, by command and status. | | `devops_cli_command_duration_seconds` | Histogram | `s` | Command wall time, by command. | +| `devops_cli_subcommand_duration_seconds` | Histogram | `s` | Subcommand wall time, by subcommand and status: ok or error. | +| `devops_cli_subprocess_duration_seconds` | Histogram | `s` | Wall time of a program that devops-cli ran, by program and status: ok or error. | +| `devops_cli_telemetry_tests_total` | Counter | `1` | Test points that devops telemetry test sent, to show that metrics reach the collector. | +| `devops_cli_ci_checks_total` | Counter | `1` | Checks that devops ci ran, by step and outcome: pass or fail. | +| `devops_cli_ci_gate_slot_wait_seconds` | Histogram | `s` | Time a devops ci run waited for a free gate slot before its checks started. | | `devops_cli_review_duration_seconds` | Histogram | `s` | Review wall time, by target type. | | `devops_cli_findings_total` | Counter | `1` | Review findings, by producer, severity and status. | | `devops_cli_ai_requests_total` | Counter | `1` | LLM calls and embedding requests, by operation (chat or embeddings), provider, model, server, serving backend and whether the cache answered. | @@ -51,12 +60,29 @@ native histogram under the instrument's own name, with no `_bucket`, `_sum` or | `devops_cli_ai_json_repairs_total` | Counter | `1` | LLM JSON replies repaired after strict parsing failed, by entry point source. | | `devops_cli_ai_gateway_slot_wait_seconds` | Histogram | `s` | Time a chat call to the LLM gateway waited in this process for one of the gateway's backend slots, by outcome: ok once it held one, or timeout. | | `devops_cli_ai_ollama_slot_wait_seconds` | Histogram | `s` | Time a call to Ollama waited in this process for a slot on one of its nodes, by priority (high, normal or as_available) and outcome: ok once it held one, or timeout. | +| `devops_cli_ai_chat_duration_seconds` | Histogram | `s` | LLM chat call wall time, by provider and model, from the request to the reply. A gateway call's time includes its wait for a backend slot. | +| `devops_cli_ai_structured_attempts_total` | Counter | `1` | Structured-output attempts, by model and outcome: valid when the reply matched its schema, else invalid. Each invalid attempt but the last is retried. | +| `devops_cli_ai_prewarms_total` | Counter | `1` | devops ai prewarm runs, by model, evict (true when the run unloaded the model) and outcome: ok or failed. | +| `devops_cli_ai_gateway_probe_duration_seconds` | Histogram | `s` | Time a health probe of the LLM gateway took. | +| `devops_cli_ai_gateway_healthy` | Gauge | `1` | Whether the last health probe of the LLM gateway passed: 1, or 0. | +| `devops_cli_ai_gateway_failovers_total` | Counter | `1` | Failovers of a gateway model alias to its fallback, by virtual model and simulate: true for a simulated failover. | +| `devops_cli_ai_capability_gate_total` | Counter | `1` | Failovers to a model below the capability tier of their role, by role, model and decision: rejection when the gate refused it, or override when --force let it through. | | `devops_cli_rag_query_duration_ms` | Histogram | `ms` | RAG retrieval time, by stage: embedding, search, ranking, or total for the whole query. | | `devops_cli_qdrant_retries_total` | Counter | `1` | Qdrant requests retried after a transient error, by operation and error type. | | `devops_cli_rag_points` | Gauge | `1` | Points stored in RAG vector collections, by collection. | | `devops_cli_github_requests_total` | Counter | `1` | GitHub requests the rate limiter paced, each attempt and retry once, by resource: the rate limit resource the request spends, such as core, graphql or search. A gh command and a request of the GitHub session both count. | | `devops_cli_github_throttle_wait_seconds` | Histogram | `s` | Time devops-cli waited before it sent a refused GitHub request again, by resource: one observation for each throttle. GitHub refused the request with a rate limit, or the GitHub session got a 5xx for a read. | | `devops_cli_github_graphql_points_total` | Counter | `1` | GraphQL points that GitHub reported each answer cost in its rateLimit field. | +| `devops_cli_embedding_cache_lookups_total` | Counter | `1` | Embedding cache lookups, one for each text that an embedding request gets, by result: hit or miss. A hit names its tier: memory for the cache of the process, or valkey. | +| `devops_cli_embedding_cache_size` | Gauge | `1` | Embeddings that the memory cache of the process held after its last embedding request. | +| `devops_cli_rag_embedding_batch_size` | Gauge | `1` | Texts in each embedding request after the last change of the adaptive batch size. | +| `devops_cli_rag_embedding_batch_resizes_total` | Counter | `1` | Changes of the adaptive embedding batch size, by action: additive_increase after enough fast batches, or multiplicative_decrease after a slow or failed batch. | +| `devops_cli_rag_drift_score` | Gauge | `1` | Share of a project's files that changed, were added or were deleted since its last index, from its last drift check, by project. A drifted knowledge base scores 1. | +| `devops_cli_rag_drift_detected` | Gauge | `1` | Whether the last drift check of a project found drift in its files, its git head or its knowledge base: 1, or 0, by project. | +| `devops_cli_rag_investigations_total` | Counter | `1` | RAG context retrievals that finished, by outcome: found when they returned context, or empty. | +| `devops_cli_rag_stops_total` | Counter | `1` | Processes that turned RAG off for the rest of their run after an embedding failure. | +| `devops_cli_vulnerability_lookups_total` | Counter | `1` | Packages looked up in a vulnerability database, by source, status and batch: true when one batch request looked them up. | +| `devops_cli_threat_intel_lookups_total` | Counter | `1` | Domains that a threat-intelligence source was asked about, by source and status: ok, unavailable or failed. A domain that the cache answered is not counted. | | `devops_cli_project_releases` | Gauge | `1` | Total project releases tracked. | | `devops_cli_project_commits` | Gauge | `1` | Project commits count by release. | | `devops_cli_project_prs` | Gauge | `1` | Project pull requests merged by release. | diff --git a/k8s/monitoring/dashboards/devops-cli.json b/k8s/monitoring/dashboards/devops-cli.json index 8c2af76f9e..5e33553767 100644 --- a/k8s/monitoring/dashboards/devops-cli.json +++ b/k8s/monitoring/dashboards/devops-cli.json @@ -611,7 +611,7 @@ "x": 0, "y": 44 }, - "id": 21, + "id": 26, "options": { "legend": { "displayMode": "list", diff --git a/openspec/changes/817-metrics-through-instruments/tasks.md b/openspec/changes/817-metrics-through-instruments/tasks.md index c7fa37caeb..4b53c3307a 100644 --- a/openspec/changes/817-metrics-through-instruments/tasks.md +++ b/openspec/changes/817-metrics-through-instruments/tasks.md @@ -16,13 +16,13 @@ ## 3. Every metric is a declared instrument sent through emit -- [ ] Add the failing instrument check: it fails on a call of a metric method outside `emit()` other than on `GLOBAL_METRICS`, and on an `emit()` of an instrument that `INSTRUMENTS` does not hold; a test shows that it names both kinds of call +- [x] Add the failing instrument check: it fails on a call of a metric method outside `emit()` other than on `GLOBAL_METRICS`, and on an `emit()` of an instrument that `INSTRUMENTS` does not hold; a test shows that it names both kinds of call - Verification: `uv run devops ci test tests/test_telemetry_instruments.py` -- [ ] Declare the instruments of the design's table, move each call site to `emit()`, and delete the sites that the table deletes, with the constants of their names +- [x] Declare the instruments of the design's table, move each call site to `emit()`, and delete the sites that the table deletes, with the constants of their names - Verification: `uv run devops ci test tests/test_telemetry_instruments.py tests/test_otel_command_coverage.py tests/test_ci_gate_admission.py tests/test_ci.py tests/test_ai_prewarm.py tests/test_sandbox_metrics.py tests/test_telemetry.py` -- [ ] Delete `record_metric` and `record_gauge` from `telemetry/tracer.py`, the method `OTelTelemetryClient.record_metric`, and their export from `telemetry/__init__.py`; the tests that patched `record_metric` read the captured metrics or patch nothing +- [x] Delete `record_metric` and `record_gauge` from `telemetry/tracer.py`, the method `OTelTelemetryClient.record_metric`, and their export from `telemetry/__init__.py`; the tests that patched `record_metric` read the captured metrics or patch nothing - Verification: `uv run devops ci test tests/test_telemetry.py tests/test_ci.py tests/test_ai_prewarm.py tests/test_sandbox_metrics.py` -- [ ] Name the new gate wait metric in `CONTRIBUTING.md`, say there that a metric is an `INSTRUMENTS` entry sent with `emit()`, rename the subprocess and subcommand metrics in the knowledge base, and regenerate the documentation +- [x] Name the new gate wait metric in `CONTRIBUTING.md`, say there that a metric is an `INSTRUMENTS` entry sent with `emit()`, rename the subprocess and subcommand metrics in the knowledge base, and regenerate the documentation - Verification: `uv run devops docs generate --sync-readme && uv run devops docs check` ## 4. Archive diff --git a/src/devops_cli/ai/capability.py b/src/devops_cli/ai/capability.py index 5f725cfadb..23435956af 100644 --- a/src/devops_cli/ai/capability.py +++ b/src/devops_cli/ai/capability.py @@ -14,7 +14,7 @@ CONST_MIN_REASONING_MODEL_TIER_B, ) from devops_cli.exceptions.ai import CapabilityDegradationError -from devops_cli.telemetry.tracer import record_metric +from devops_cli.telemetry.instruments import AI_CAPABILITY_GATE_TOTAL, emit logger = logging.getLogger(__name__) @@ -133,10 +133,10 @@ def validate_failover_capability( candidate_b = evaluate_model_capability(fallback_model, fallback_provider) if force: - record_metric( - "ai.failover.capability_override", - 1, - attributes={"role": role_or_virtual_model, "model": fallback_model}, + emit( + AI_CAPABILITY_GATE_TOTAL, + 1.0, + {"role": role_or_virtual_model, "model": fallback_model, "decision": "override"}, ) logger.warning( "Capability gate bypassed (--force) for role '%s': routing to '%s' (%sB vs required %sB)", @@ -148,10 +148,10 @@ def validate_failover_capability( return if candidate_b is not None and candidate_b < required_b: - record_metric( - "ai.failover.capability_rejection", - 1, - attributes={"role": role_or_virtual_model, "model": fallback_model}, + emit( + AI_CAPABILITY_GATE_TOTAL, + 1.0, + {"role": role_or_virtual_model, "model": fallback_model, "decision": "rejection"}, ) raise CapabilityDegradationError( f"Failover to '{fallback_model}' ({candidate_b}B) breaches minimum capability tier " diff --git a/src/devops_cli/ai/client/structured.py b/src/devops_cli/ai/client/structured.py index acc4c76bc6..b2576d5de6 100644 --- a/src/devops_cli/ai/client/structured.py +++ b/src/devops_cli/ai/client/structured.py @@ -29,9 +29,6 @@ from devops_cli.config.constants import ( CONST_JSON_REPAIR_SOURCE_CHAT_STRUCTURED, CONST_MAX_ERROR_DETAIL_LENGTH, - CONST_METRIC_AI_STRUCTURED_RETRY_COUNT, - CONST_METRIC_AI_STRUCTURED_SUCCESS, - CONST_METRIC_AI_STRUCTURED_VALIDATION_FAILURE, ) from devops_cli.config.defaults import ( DEFAULT_STRUCTURED_OUTPUT_MAX_RETRIES, @@ -40,7 +37,8 @@ from devops_cli.config.settings import AIConfig from devops_cli.exceptions.ai import StructuredOutputSchemaError from devops_cli.models.ai import ChatMessage -from devops_cli.telemetry import record_metric, trace_span +from devops_cli.telemetry import trace_span +from devops_cli.telemetry.instruments import AI_STRUCTURED_ATTEMPTS_TOTAL, emit logger = logging.getLogger(__name__) @@ -255,14 +253,8 @@ def _handle_structured_retry( failure: SchemaFailure, attempt: int, backoff_seconds: float, - model_name: str, ) -> None: - """Record retry telemetry, backoff, and append reflection messages.""" - record_metric( - CONST_METRIC_AI_STRUCTURED_RETRY_COUNT, - 1.0, - attributes={"model": model_name}, - ) + """Back off, and append the reply and the reflection on its failure to the messages.""" time.sleep(backoff_seconds * (2 ** (attempt - 1))) messages.append(ChatMessage(role="assistant", content=raw_text)) messages.append(_build_reflection_message(failure)) @@ -322,24 +314,24 @@ def chat_structured[T: BaseModel]( context_tag=context_tag, ) if model_inst is not None: - record_metric( - CONST_METRIC_AI_STRUCTURED_SUCCESS, + emit( + AI_STRUCTURED_ATTEMPTS_TOTAL, 1.0, - attributes={"model": model_name}, + {"model": model_name, "outcome": "valid"}, ) span_h.set_attribute("structured.attempts", attempt) span_h.set_attribute("structured.was_repaired", was_repaired) return model_inst last_error = failure or "Failed to validate schema." - record_metric( - CONST_METRIC_AI_STRUCTURED_VALIDATION_FAILURE, + emit( + AI_STRUCTURED_ATTEMPTS_TOTAL, 1.0, - attributes={"model": model_name, "attempt": str(attempt)}, + {"model": model_name, "outcome": "invalid"}, ) if attempt < max_attempts: self._handle_structured_retry( - messages, raw_text, last_error, attempt, backoff_seconds, model_name + messages, raw_text, last_error, attempt, backoff_seconds ) exc = _validation_failure(model_name, max_attempts, last_error) diff --git a/src/devops_cli/ai/client/unified.py b/src/devops_cli/ai/client/unified.py index 8781ba6d38..65cc85ea7a 100644 --- a/src/devops_cli/ai/client/unified.py +++ b/src/devops_cli/ai/client/unified.py @@ -48,7 +48,8 @@ from devops_cli.exceptions.ai import LLMInferenceError from devops_cli.http.client import request_timeout from devops_cli.models.ai import ChatMessage -from devops_cli.telemetry import get_tracer, record_metric, trace_span +from devops_cli.telemetry import get_tracer, trace_span +from devops_cli.telemetry.instruments import AI_CHAT_DURATION, emit if TYPE_CHECKING: from pydantic_ai.messages import FinishReason @@ -450,12 +451,7 @@ def _dispatch_messages( ) duration = time.perf_counter() - start - record_metric( - "devops_cli_llm_inference_seconds", - duration, - unit="s", - attributes={"provider": p, "model": self._config.model}, - ) + emit(AI_CHAT_DURATION, duration, {"provider": p, "model": self._config.model}) return res def _invoke_provider_messages( diff --git a/src/devops_cli/ai/gateway.py b/src/devops_cli/ai/gateway.py index 16bbcd6442..e1d1ca0558 100644 --- a/src/devops_cli/ai/gateway.py +++ b/src/devops_cli/ai/gateway.py @@ -33,7 +33,13 @@ from devops_cli.config.settings import AIConfig, load_settings from devops_cli.core.validation import validate_url_egress from devops_cli.exceptions import ConfigurationError, ValidationError -from devops_cli.telemetry import record_metric, trace_span +from devops_cli.telemetry import trace_span +from devops_cli.telemetry.instruments import ( + AI_GATEWAY_FAILOVERS_TOTAL, + AI_GATEWAY_HEALTHY, + AI_GATEWAY_PROBE_DURATION, + emit, +) logger = logging.getLogger(__name__) @@ -482,7 +488,8 @@ def probe_gateway( with httpx2.Client(timeout=timeout) as client: is_ok, status_code, err_msg = _probe_gateway_http(client, probe_base, self.provider) - latency = round((time.perf_counter() - start) * 1000, 2) + elapsed = time.perf_counter() - start + latency = round(elapsed * 1000, 2) # A healthy probe keeps a failover route: LiteLLM, not this route table, moves the # live traffic, so only a reset restores the default route (#1986). failover = _failover_virtual_models(self._active_routes) @@ -500,8 +507,8 @@ def probe_gateway( ] _save_gateway_state(self.state_file, self._circuit_breaker_active, self._active_routes) - record_metric("ai.gateway.latency_ms", latency) - record_metric("ai.gateway.healthy", 1 if is_ok else 0) + emit(AI_GATEWAY_PROBE_DURATION, elapsed) + emit(AI_GATEWAY_HEALTHY, 1.0 if is_ok else 0.0) span_h.set_attribute("ai.gateway.healthy", is_ok) span_h.set_attribute("ai.gateway.latency_ms", latency) @@ -538,7 +545,11 @@ def trigger_failover( "ai.gateway.failover", {"virtual_model": virtual_model, "simulate": simulate, "force": force}, ): - record_metric("ai.gateway.failover_events", 1) + emit( + AI_GATEWAY_FAILOVERS_TOTAL, + 1.0, + {"virtual_model": virtual_model, "simulate": str(simulate).lower()}, + ) fallback_target = MODEL_FAILOVER_PAIRS.get(virtual_model, "direct-ollama") target_m, b_type, b_url = _resolve_fallback_physical_route( virtual_model, fallback_target, self._active_routes diff --git a/src/devops_cli/ai/knowledge_base/it_domains/tools/prometheus.md b/src/devops_cli/ai/knowledge_base/it_domains/tools/prometheus.md index bfaa7693fa..a61b2da1e2 100644 --- a/src/devops_cli/ai/knowledge_base/it_domains/tools/prometheus.md +++ b/src/devops_cli/ai/knowledge_base/it_domains/tools/prometheus.md @@ -23,11 +23,11 @@ Prometheus is an open-source systems monitoring and alerting toolkit. It collect - **Pull Model Scraper**: Periodically scrapes configured HTTP endpoints (`/metrics`) formatted according to the OpenMetrics / Prometheus exposition format. - **PromQL Query Engine**: Flexible query language for computing percentiles, rates of change (`rate()`, `irate()`), aggregations (`sum()`, `avg()`), and histogram distributions. -- **Client SDK**: `devops_cli` exposes native metrics via `devops serve` on `GET /metrics` including: +- **Client SDK**: `devops_cli` sends its metrics over OTLP to the OpenTelemetry Collector, which writes them to Prometheus. `INSTRUMENTS` in `src/devops_cli/telemetry/instruments.py` declares each one, and `docs/TELEMETRY.md` lists them, including: - `devops_cli_command_total`: Total count of executed CLI commands. - `devops_cli_command_duration_seconds`: Histogram of command execution latencies. - - `devops_cli_subprocess_seconds`: Subprocess execution duration by binary. - - `devops_cli_subcommand_seconds`: Subcommand runtime duration and exit statuses. + - `devops_cli_subprocess_duration_seconds`: Histogram of subprocess execution durations by binary and status. + - `devops_cli_subcommand_duration_seconds`: Histogram of subcommand durations by subcommand and status. - **CLI Subcommand**: `devops prometheus` provides PromQL querying, target health inspection, and query execution. --- diff --git a/src/devops_cli/ai/knowledge_base/it_domains/topics/observability_and_distributed_tracing.md b/src/devops_cli/ai/knowledge_base/it_domains/topics/observability_and_distributed_tracing.md index 5e8faa6779..a31021a48c 100644 --- a/src/devops_cli/ai/knowledge_base/it_domains/topics/observability_and_distributed_tracing.md +++ b/src/devops_cli/ai/knowledge_base/it_domains/topics/observability_and_distributed_tracing.md @@ -54,10 +54,10 @@ with trace_span("k8s.deploy_stack", {"stack.name": "monitoring"}): ``` ### Automatic Prometheus Metrics -Exposed by `devops serve` on `GET /metrics` for Prometheus scraping: +Sent over OTLP to the OpenTelemetry Collector, which writes them to Prometheus (`docs/TELEMETRY.md` lists every metric): - `devops_cli_command_total`: Counter tracking command executions by command name and status. - `devops_cli_command_duration_seconds`: Histogram tracking command execution duration. -- `devops_cli_subprocess_seconds`: Subprocess runtime latency by binary. +- `devops_cli_subprocess_duration_seconds`: Histogram of subprocess runtime by binary and status. ### Common Commands ```bash diff --git a/src/devops_cli/ai/rag/drift.py b/src/devops_cli/ai/rag/drift.py index 8002c9c062..fc23ecd18b 100644 --- a/src/devops_cli/ai/rag/drift.py +++ b/src/devops_cli/ai/rag/drift.py @@ -23,7 +23,8 @@ DEFAULT_RAG_CACHE_DIR, ) from devops_cli.exceptions import DevOpsCLIError -from devops_cli.telemetry import record_metric, trace_span +from devops_cli.telemetry import trace_span +from devops_cli.telemetry.instruments import RAG_DRIFT_DETECTED, RAG_DRIFT_SCORE, emit logger = logging.getLogger(__name__) @@ -346,17 +347,9 @@ def detect_drift( if kb_drift and self.project == CONST_RAG_KB_PROJECT: drift_score = max(drift_score, 1.0) - record_metric( - "devops_cli_rag_drift_detected_total", - 1.0 if (drift_score > 0 or git_drift or kb_drift) else 0.0, - attributes={"project": self.project}, - ) - record_metric( - "devops_cli_rag_drift_score", - drift_score, - unit="ratio", - attributes={"project": self.project}, - ) + drifted = drift_score > 0 or git_drift or kb_drift + emit(RAG_DRIFT_DETECTED, 1.0 if drifted else 0.0, {"project": self.project}) + emit(RAG_DRIFT_SCORE, drift_score, {"project": self.project}) return RAGDriftReport( root_dir=str(self.root_dir), diff --git a/src/devops_cli/ai/rag/embeddings.py b/src/devops_cli/ai/rag/embeddings.py index 0f5c2e5701..f12c8b672b 100644 --- a/src/devops_cli/ai/rag/embeddings.py +++ b/src/devops_cli/ai/rag/embeddings.py @@ -71,13 +71,12 @@ from devops_cli.telemetry import ( ContextPropagatingThreadPoolExecutor as ThreadPoolExecutor, ) -from devops_cli.telemetry import ( - record_metric, - trace_span, -) +from devops_cli.telemetry import trace_span from devops_cli.telemetry.instruments import ( EMBEDDING_CACHE_LOOKUPS_TOTAL, EMBEDDING_CACHE_SIZE, + RAG_EMBEDDING_BATCH_RESIZES_TOTAL, + RAG_EMBEDDING_BATCH_SIZE, emit, ) from devops_cli.valkey.cache import ValkeyCacheTier, configured_cache_tier @@ -373,6 +372,12 @@ def _apply_model_prefix(text: str, model: str, *, is_query: bool = False) -> str return text +def _count_batch_resize(batch_size: int, action: str) -> None: + """Record the batch size after a change of it, and count the change by its action.""" + emit(RAG_EMBEDDING_BATCH_SIZE, float(batch_size)) + emit(RAG_EMBEDDING_BATCH_RESIZES_TOTAL, 1.0, {"action": action}) + + def _count_cache_lookups(*, memory: int, valkey: int, misses: int) -> None: """Add each lookup result that has texts to the embedding cache lookup counter.""" for count, attributes in ( @@ -510,12 +515,7 @@ def _apply_aimd_decrease(self, sent_size: int) -> None: DEFAULT_RAG_EMBEDDING_MIN_BATCH_SIZE, int(self._current_batch_size * CONST_AIMD_MULTIPLICATIVE_DECREASE_FACTOR), ) - record_metric("rag.embedding.batch_size", self._current_batch_size) - record_metric( - "rag.embedding.aimd_action", - 1, - attributes={"action": "multiplicative_decrease"}, - ) + _count_batch_resize(self._current_batch_size, "multiplicative_decrease") logger.debug( "AIMD multiplicative decrease applied: batch_size=%d (configured=%d)", self._current_batch_size, @@ -544,12 +544,7 @@ def _apply_aimd_increase(self) -> None: self._configured_batch_size, self._current_batch_size + CONST_AIMD_ADDITIVE_INCREASE_STEP, ) - record_metric("rag.embedding.batch_size", self._current_batch_size) - record_metric( - "rag.embedding.aimd_action", - 1, - attributes={"action": "additive_increase"}, - ) + _count_batch_resize(self._current_batch_size, "additive_increase") logger.debug( "AIMD additive increase applied: batch_size=%d (configured=%d)", self._current_batch_size, diff --git a/src/devops_cli/ai/rag/indexer.py b/src/devops_cli/ai/rag/indexer.py index 55f2d26a1c..95295c8c17 100644 --- a/src/devops_cli/ai/rag/indexer.py +++ b/src/devops_cli/ai/rag/indexer.py @@ -38,7 +38,7 @@ from devops_cli.exceptions import ConfigurationError, DevOpsCLIError from devops_cli.lang.en.errors import ERRORS from devops_cli.output.file_writer import write_json_file -from devops_cli.telemetry import record_metric, trace_span +from devops_cli.telemetry import trace_span logger = logging.getLogger(__name__) @@ -982,9 +982,6 @@ def index_workspace( self._save_cache(cache) self._save_project_counts(scanned_projects) - record_metric("rag.indexed_files", len(files) - len(files_to_reindex)) - record_metric("rag.total_chunks", len(all_chunks)) - root_span.set_attribute("rag.indexed_files", len(files_to_reindex)) root_span.set_attribute("rag.total_chunks", len(all_chunks)) root_span.set_attribute("rag.code_chunks", len(code_chunks)) diff --git a/src/devops_cli/ai/rag/investigator.py b/src/devops_cli/ai/rag/investigator.py index 70f43eaa90..b0a3f1f7ff 100644 --- a/src/devops_cli/ai/rag/investigator.py +++ b/src/devops_cli/ai/rag/investigator.py @@ -41,7 +41,8 @@ from devops_cli.config.settings import Settings from devops_cli.lang import MESSAGES from devops_cli.security.sanitizer import redact_text -from devops_cli.telemetry import record_metric, trace_span +from devops_cli.telemetry import trace_span +from devops_cli.telemetry.instruments import RAG_INVESTIGATIONS_TOTAL, RAG_STOPS_TOTAL, emit logger = logging.getLogger(__name__) @@ -187,7 +188,7 @@ def _stop_rag_for_run(model: str, exc: EmbeddingsError) -> None: if _RAG_STOPPED.is_set(): return _RAG_STOPPED.set() - record_metric("ai.rag.investigation.stopped", 1) + emit(RAG_STOPS_TOTAL, 1.0) logger.warning(MESSAGES.rag.stopped_for_run.format(model=model, error=exc.message)) @@ -379,15 +380,14 @@ def _investigation_attributes( def _recorded_results( ctx: RAGContext, r_span: Any, clean_query: str, start_time: float ) -> RAGContext | None: - """Record a retrieval's duration and hits; the context when it found any, else None.""" + """Count a finished retrieval as found or empty; the context when it found any, else None.""" duration_ms = (time.perf_counter() - start_time) * 1000.0 - record_metric("ai.rag.investigation.duration_ms", duration_ms) if not ctx.has_results: - record_metric("ai.rag.investigation.empty", 1) + emit(RAG_INVESTIGATIONS_TOTAL, 1.0, {"outcome": "empty"}) return None r_span.set_attribute("rag.results_count", len(ctx.results)) r_span.set_attribute("rag.total_chars", ctx.total_chars) - record_metric("ai.rag.investigation.hits", len(ctx.results)) + emit(RAG_INVESTIGATIONS_TOTAL, 1.0, {"outcome": "found"}) logger.debug( "RAG investigation retrieved %d chunks in %.1fms for query: %.50s", len(ctx.results), diff --git a/src/devops_cli/ai/rag/qdrant.py b/src/devops_cli/ai/rag/qdrant.py index 722cfcb98e..2d20463be8 100644 --- a/src/devops_cli/ai/rag/qdrant.py +++ b/src/devops_cli/ai/rag/qdrant.py @@ -24,7 +24,7 @@ ) from devops_cli.core.validation import validate_configured_service_url from devops_cli.exceptions import DevOpsCLIError, InvalidURLError -from devops_cli.telemetry import record_metric, trace_span +from devops_cli.telemetry import trace_span from devops_cli.telemetry.instruments import QDRANT_RETRIES_TOTAL, emit logger = logging.getLogger(__name__) @@ -539,7 +539,6 @@ def _query_op(c: NativeQdrantClient) -> Any: q_span.set_attribute("db.response.returned_points", len(hits)) if hits: q_span.set_attribute("db.response.top_score", hits[0]["score"]) - record_metric("qdrant.search_hits_count", float(len(hits)), unit="1") return hits except Exception as exc: err_str = str(exc).lower() diff --git a/src/devops_cli/commands/ai.py b/src/devops_cli/commands/ai.py index d044e27579..a6f7a36a7d 100644 --- a/src/devops_cli/commands/ai.py +++ b/src/devops_cli/commands/ai.py @@ -79,7 +79,8 @@ write_text_file, ) from devops_cli.output.serialization import emit_serialized, resolve_format -from devops_cli.telemetry.tracer import record_metric, trace_span +from devops_cli.telemetry.instruments import AI_PREWARMS_TOTAL, emit +from devops_cli.telemetry.tracer import trace_span app = new_typer( help=HELP.ai.app, @@ -830,10 +831,14 @@ def prewarm( output_format=output_format, json_output=json_output, ) - record_metric( - "ai.prewarm.success", - 1.0 if success else 0.0, - attributes={"model": str(target_model), "evict": str(evict)}, + emit( + AI_PREWARMS_TOTAL, + 1.0, + { + "model": str(target_model), + "evict": str(evict).lower(), + "outcome": "ok" if success else "failed", + }, ) if not success: raise typer.Exit(1) diff --git a/src/devops_cli/commands/ci.py b/src/devops_cli/commands/ci.py index 2c0a06e541..4266405a54 100644 --- a/src/devops_cli/commands/ci.py +++ b/src/devops_cli/commands/ci.py @@ -25,7 +25,6 @@ from devops_cli.config.constants import ( CONST_AST_GREP_SCAN_ARGS, CONST_BANDIT_INI_NAME, - CONST_CI_GATE_SLOT_WAIT_METRIC, CONST_CI_RUN_STOP_SIGNAL_NAMES, CONST_CI_SLOWEST_TESTS_SHOWN, CONST_CI_SUBCOMMAND_SHOWS_HELP_META_KEY, @@ -64,7 +63,8 @@ write_stderr, write_stdout, ) -from devops_cli.telemetry import record_metric, trace_span +from devops_cli.telemetry import trace_span +from devops_cli.telemetry.instruments import CI_CHECKS_TOTAL, CI_GATE_SLOT_WAIT, emit if TYPE_CHECKING: from devops_cli.ci.mutate import MutationTarget @@ -512,6 +512,11 @@ async def _run_check_commands( return functools.reduce(_merged_run, rest, first) +def _count_check(step: str, *, passed: bool) -> None: + """Count one check that the gate ran, by its step and outcome.""" + emit(CI_CHECKS_TOTAL, 1.0, {"step": step, "outcome": "pass" if passed else "fail"}) + + async def _execute_check_async( spec: CheckSpec | str, display_title: str | None = None, @@ -554,9 +559,7 @@ async def _execute_check_async( proc = await _run_check_commands(check_spec, root, timeout, capture_output) passed = proc.returncode == 0 dur = time.perf_counter() - start_time - record_metric( - "ci.step_pass", 1.0 if passed else 0.0, attributes={"step": check_spec.metric_step} - ) + _count_check(check_spec.metric_step, passed=passed) from devops_cli.output import format_duration badge = _format_check_badge(passed) @@ -574,7 +577,7 @@ async def _execute_check_async( ) except subprocess.TimeoutExpired as exc: dur = time.perf_counter() - start_time - record_metric("ci.step_pass", 0.0, attributes={"step": check_spec.metric_step}) + _count_check(check_spec.metric_step, passed=False) badge = _format_check_badge(False) timeout_val = exc.timeout or timeout timeout_str = f"{timeout_val:g}s" @@ -622,7 +625,7 @@ def _gate_slot(needed: bool) -> Iterator[None]: holder=f"{os.getpid()} {root}", notify=lambda message: print_info(message, safe=True), ) as waited: - record_metric(CONST_CI_GATE_SLOT_WAIT_METRIC, waited, unit="s") + emit(CI_GATE_SLOT_WAIT, waited) yield @@ -944,7 +947,7 @@ def _run_python_version_step() -> tuple[bool, CheckResult]: py_t0 = time.perf_counter() py_ok = _verify_python_314_environment() py_dur = time.perf_counter() - py_t0 - record_metric("ci.step_pass", 1.0 if py_ok else 0.0, attributes={"step": "python_version"}) + _count_check("python_version", passed=py_ok) py_result = CheckResult( name="python_version", display_title=MESSAGES.ci.python_version_check, diff --git a/src/devops_cli/commands/sandbox.py b/src/devops_cli/commands/sandbox.py index 3ff902fee0..e30f1e505d 100644 --- a/src/devops_cli/commands/sandbox.py +++ b/src/devops_cli/commands/sandbox.py @@ -52,7 +52,7 @@ SandboxStatus, ) from devops_cli.security.sanitizer import mask_dict_secrets, mask_secrets -from devops_cli.telemetry.tracer import record_metric, trace_span +from devops_cli.telemetry.tracer import trace_span app = new_typer(help=HELP.sandbox.app, no_args_is_help=True) @@ -644,12 +644,6 @@ def metrics( "sandbox.dry_run": is_dry_run(), }, ): - record_metric( - "devops_cli.sandbox.metrics_invoked", - 1.0, - unit="1", - attributes={"dry_run": is_dry_run()}, - ) if is_dry_run(): render_dry_run_result( command="devops sandbox metrics", diff --git a/src/devops_cli/commands/telemetry.py b/src/devops_cli/commands/telemetry.py index 6022e2384e..e4257970d5 100644 --- a/src/devops_cli/commands/telemetry.py +++ b/src/devops_cli/commands/telemetry.py @@ -38,10 +38,10 @@ render_dry_run_result, ) from devops_cli.output.serialization import emit_serialized, resolve_format +from devops_cli.telemetry.instruments import TELEMETRY_TESTS_TOTAL, emit from devops_cli.telemetry.tracer import ( OTelTelemetryClient, get_tracer, - record_metric, trace_span, ) from devops_cli.telemetry.waterfall import ( @@ -284,7 +284,7 @@ def telemetry_test_cmd( start = time.perf_counter() with trace_span(name, attributes={"test": True, "cli": "devops-cli"}) as span_id: - record_metric("devops_cli.test_counter", 1.0, unit="1", attributes={"test": True}) + emit(TELEMETRY_TESTS_TOTAL, 1.0) if logfire: from devops_cli.telemetry.logfire import logfire_agent_turn diff --git a/src/devops_cli/commands/test_cmd.py b/src/devops_cli/commands/test_cmd.py index 875a16ce61..ee42947b90 100644 --- a/src/devops_cli/commands/test_cmd.py +++ b/src/devops_cli/commands/test_cmd.py @@ -42,7 +42,7 @@ MemoryProfilerError, run_memory_profiler, ) -from devops_cli.telemetry.tracer import record_metric, trace_span +from devops_cli.telemetry.tracer import trace_span app = new_typer(help=HELP.test.app, no_args_is_help=False) @@ -522,20 +522,6 @@ def test_profile_memory( print_error(str(exc)[:256], prefix=False) raise typer.Exit(1) from exc - record_metric("test.profile_memory.invocations", 1.0, attributes={"target": target}) - record_metric( - "test.profile_memory.duration_seconds", - report.duration_seconds, - unit="s", - attributes={"target": target}, - ) - record_metric( - "test.profile_memory.peak_kb", - report.peak_kb, - unit="By", - attributes={"target": target}, - ) - resolved = resolve_format(output_format, json_output=json_output) if output: output.parent.mkdir(parents=True, exist_ok=True) diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index b7134a5531..1b0a4955c9 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -663,7 +663,6 @@ # subdirectories that `devops workspace clean` prunes, holds one lock file for each slot. CONST_CI_GATE_SLOTS_DIRNAME: Final[str] = "ci-gate-slots" CONST_CI_GATE_SLOT_FILENAME: Final[str] = "slot-{index}.lock" -CONST_CI_GATE_SLOT_WAIT_METRIC: Final[str] = "ci.gate_slot_wait_seconds" # The branch form `/-` (CONTRIBUTING.md, Naming). The types are those of # `release-please-config.json`, and the form is the one the `branch-name` pre-commit hook accepts; # `tests/test_branch_form.py` fails when either disagrees with these (#2337). @@ -1567,9 +1566,6 @@ class WebhookExposure(StrEnum): CONST_MAX_ERROR_DETAIL_LENGTH = 256 # ── AI Client Structured Output Metric Invariants ───────────────────────────── -CONST_METRIC_AI_STRUCTURED_SUCCESS = "ai.client.structured_success" -CONST_METRIC_AI_STRUCTURED_RETRY_COUNT = "ai.client.structured_retry_count" -CONST_METRIC_AI_STRUCTURED_VALIDATION_FAILURE = "ai.client.structured_validation_failure" CONST_JSON_REPAIR_SOURCE_REPAIR_JSON_STRING: Final[str] = "repair_json_string" CONST_JSON_REPAIR_SOURCE_EXTRACT_JSON_BLOCK: Final[str] = "extract_json_block" CONST_JSON_REPAIR_SOURCE_CHAT_STRUCTURED: Final[str] = "chat_structured" diff --git a/src/devops_cli/core/cli.py b/src/devops_cli/core/cli.py index d2ff2de427..c445b43b29 100644 --- a/src/devops_cli/core/cli.py +++ b/src/devops_cli/core/cli.py @@ -17,7 +17,7 @@ def _record_cli_success(span_h: Any, cmd_name: str, dur: float) -> None: """Record telemetry attributes, events, and metrics for successful CLI command execution.""" - from devops_cli.telemetry import record_metric + from devops_cli.telemetry.instruments import SUBCOMMAND_DURATION, emit span_h.set_attribute("cli.duration_seconds", dur) span_h.set_attribute("cli.status", "ok") @@ -25,12 +25,7 @@ def _record_cli_success(span_h: Any, cmd_name: str, dur: float) -> None: "subcommand_completed", {"command": cmd_name, "duration_seconds": dur}, ) - record_metric( - "devops_cli_subcommand_seconds", - dur, - unit="s", - attributes={"command": cmd_name, "status": "ok"}, - ) + emit(SUBCOMMAND_DURATION, dur, {"command": cmd_name, "status": "ok"}) def _record_cli_failure(span_h: Any, cmd_name: str, dur: float, exc: Exception) -> None: @@ -43,19 +38,14 @@ def _record_cli_failure(span_h: Any, cmd_name: str, dur: float, exc: Exception) if exit_code is not None: span_h.set_attribute("cli.exit_code", exit_code) - from devops_cli.telemetry import record_metric + from devops_cli.telemetry.instruments import SUBCOMMAND_DURATION, emit if is_clean_exit: span_h.add_event( "subcommand_completed", {"command": cmd_name, "duration_seconds": dur, "exit_code": 0}, ) - record_metric( - "devops_cli_subcommand_seconds", - dur, - unit="s", - attributes={"command": cmd_name, "status": "ok"}, - ) + emit(SUBCOMMAND_DURATION, dur, {"command": cmd_name, "status": "ok"}) else: if isinstance(exc, typer.TyperException): # A usage error of Typer, such as `typer.BadParameter`, quotes what the person typed, @@ -68,12 +58,7 @@ def _record_cli_failure(span_h: Any, cmd_name: str, dur: float, exc: Exception) detail = {"error": mask_secrets(str(exc))} span_h.set_attribute("cli.error", detail["error"]) span_h.add_event("subcommand_failed", {"command": cmd_name, **detail}) - record_metric( - "devops_cli_subcommand_seconds", - dur, - unit="s", - attributes={"command": cmd_name, "status": "error"}, - ) + emit(SUBCOMMAND_DURATION, dur, {"command": cmd_name, "status": "error"}) def _execute_traced_cli_command( diff --git a/src/devops_cli/core/process.py b/src/devops_cli/core/process.py index 1427a3622b..41dca34aa4 100644 --- a/src/devops_cli/core/process.py +++ b/src/devops_cli/core/process.py @@ -42,7 +42,8 @@ from devops_cli.exceptions.base import DevOpsCLIError from devops_cli.exceptions.git import GitHubUnauthenticatedError from devops_cli.exceptions.tools import SubprocessError -from devops_cli.telemetry.tracer import get_tracer, record_metric, trace_span +from devops_cli.telemetry.instruments import SUBPROCESS_DURATION, emit +from devops_cli.telemetry.tracer import get_tracer, trace_span _QUIET_SUBPROCESS_ARGS = frozenset( { @@ -641,14 +642,10 @@ def run( {"exit_code": ret_code, "duration_seconds": dur}, ) - record_metric( - "devops_cli_subprocess_seconds", + emit( + SUBPROCESS_DURATION, dur, - unit="s", - attributes={ - "bin": bin_name, - "status": "ok" if ret_code == 0 else "error", - }, + {"bin": bin_name, "status": "ok" if ret_code == 0 else "error"}, ) return proc @@ -793,14 +790,10 @@ async def run_async( {"exit_code": ret_code, "duration_seconds": dur}, ) - record_metric( - "devops_cli_subprocess_seconds", + emit( + SUBPROCESS_DURATION, dur, - unit="s", - attributes={ - "bin": bin_name, - "status": "ok" if ret_code == 0 else "error", - }, + {"bin": bin_name, "status": "ok" if ret_code == 0 else "error"}, ) return subprocess.CompletedProcess( full_cmd, @@ -1192,11 +1185,10 @@ async def run_subprocess_async( {"exit_code": ret_code, "duration_seconds": dur}, ) - record_metric( - "devops_cli_subprocess_seconds", + emit( + SUBPROCESS_DURATION, dur, - unit="s", - attributes={"bin": bin_name, "status": "ok" if ret_code == 0 else "error"}, + {"bin": bin_name, "status": "ok" if ret_code == 0 else "error"}, ) return subprocess.CompletedProcess( cmd, diff --git a/src/devops_cli/docs/generator.py b/src/devops_cli/docs/generator.py index ecc11a6cf0..835d62f3aa 100644 --- a/src/devops_cli/docs/generator.py +++ b/src/devops_cli/docs/generator.py @@ -1112,6 +1112,10 @@ def generate_telemetry_docs(self) -> str: "native histogram under the instrument's own name, with no `_bucket`, `_sum` or", "`_count` series; query it with `histogram_quantile`, `histogram_avg` and", "`histogram_count`.", + "Each metric is an entry of `INSTRUMENTS` in", + "`src/devops_cli/telemetry/instruments.py`, which gives its kind, and is sent with", + "`emit()`. `tests/test_telemetry_instruments.py` fails on a metric that a module", + "writes by name.", "`devops telemetry connect` points devops-cli at the cluster's collector.", "", "| Metric Name | Type | Unit | Description |", diff --git a/src/devops_cli/k8s/security_stream.py b/src/devops_cli/k8s/security_stream.py index b1ea65e3c1..1af50fb4f1 100644 --- a/src/devops_cli/k8s/security_stream.py +++ b/src/devops_cli/k8s/security_stream.py @@ -22,7 +22,7 @@ print_info, print_panel, ) -from devops_cli.telemetry import record_metric, trace_span +from devops_cli.telemetry import trace_span logger = logging.getLogger(__name__) @@ -197,18 +197,16 @@ def _build_stream_result( alerts: list[FalcoAlert], start_time: float, span: Any, - namespace: str, ) -> SecurityStreamResult: - """Construct SecurityStreamResult and record telemetry metrics.""" + """Construct SecurityStreamResult and record its counts on the stream span. + + The stream reads the last lines of the Falco log, so a second read finds the same alerts + again: a counter of them would count each alert once for each read. + """ crit, warn, note = _tally_severity_counts(alerts) elapsed = time.monotonic() - start_time span.set_attribute("alerts.count", len(alerts)) span.set_attribute("alerts.critical", crit) - record_metric( - "devops_cli_k8s_security_alerts_total", - float(len(alerts)), - attributes={"namespace": namespace, "critical": str(crit > 0)}, - ) return SecurityStreamResult( alerts=alerts, total_alerts=len(alerts), @@ -240,7 +238,7 @@ def stream_security_events( filtered = [ a for a in simulated if matches_severity_filter(a.priority, request.severity) ] - return _build_stream_result(filtered, start_time, span, request.namespace) + return _build_stream_result(filtered, start_time, span) cmd = _build_kubectl_command(request) timeout_sec = ( @@ -259,7 +257,7 @@ def stream_security_events( ) alerts = _process_stream_output(stdout_str, request.severity) span.set_attribute("stream.timed_out_gracefully", True) - return _build_stream_result(alerts, start_time, span, request.namespace) + return _build_stream_result(alerts, start_time, span) if proc.returncode != 0: logger.debug("kubectl logs failed with exit code %s", proc.returncode) @@ -274,7 +272,7 @@ def stream_security_events( ) alerts = _process_stream_output(proc.stdout, request.severity) - return _build_stream_result(alerts, start_time, span, request.namespace) + return _build_stream_result(alerts, start_time, span) def _get_severity_color(priority: str) -> str: diff --git a/src/devops_cli/sandbox/engine.py b/src/devops_cli/sandbox/engine.py index 578e009d2e..a24abdad73 100644 --- a/src/devops_cli/sandbox/engine.py +++ b/src/devops_cli/sandbox/engine.py @@ -46,7 +46,7 @@ ) from devops_cli.sandbox.ports import allocate_ports from devops_cli.sandbox.registry import SandboxRegistry -from devops_cli.telemetry import get_tracer, record_metric, trace_span +from devops_cli.telemetry import get_tracer, trace_span logger = logging.getLogger(__name__) @@ -602,12 +602,6 @@ def metrics( if snapshot.cgroup is not None: self._prior_samples[prior_key] = (now, snapshot.cgroup) - record_metric( - "devops_cli.sandbox.metrics_collected", - 1.0, - unit="1", - attributes={"healthy": snapshot.is_healthy}, - ) return snapshot def traces( @@ -667,20 +661,6 @@ def logs( follow=follow, ) - record_metric( - "devops.sandbox.logs.lines", - float(total_count), - unit="1", - attributes={"instance_id": inst.instance_id}, - ) - if incidents: - record_metric( - "devops.sandbox.logs.panics", - float(len(incidents)), - unit="1", - attributes={"instance_id": inst.instance_id}, - ) - return SandboxLogsReport( instance_id=inst.instance_id, container_id=inst.container_id, diff --git a/src/devops_cli/security/vulnerability_lookup.py b/src/devops_cli/security/vulnerability_lookup.py index 587ec8e34c..e22ee5ece8 100644 --- a/src/devops_cli/security/vulnerability_lookup.py +++ b/src/devops_cli/security/vulnerability_lookup.py @@ -37,7 +37,12 @@ classify_network_target, network_target_address, ) -from devops_cli.telemetry import record_metric, trace_span +from devops_cli.telemetry import trace_span +from devops_cli.telemetry.instruments import ( + THREAT_INTEL_LOOKUPS_TOTAL, + VULNERABILITY_LOOKUPS_TOTAL, + emit, +) if TYPE_CHECKING: from devops_cli.valkey.cache import ValkeyCacheTier @@ -252,10 +257,10 @@ def query_package( self._cache[cache_key] = vulns self._evict_cache() span_h.set_attribute("vulnerabilities_found", len(vulns)) - record_metric( - "devops_cli_vulnerability_lookups_total", + emit( + VULNERABILITY_LOOKUPS_TOTAL, 1.0, - attributes={"source": "osv", "status": "ok", "batch": False}, + {"source": "osv", "status": "ok", "batch": "false"}, ) return PackageLookupResult(status="ok", vulnerabilities=vulns) except Exception as exc: @@ -310,10 +315,10 @@ def query_batch( ) self._evict_cache() span_h.set_attribute("vulnerabilities_found", total_vulns) - record_metric( - "devops_cli_vulnerability_lookups_total", + emit( + VULNERABILITY_LOOKUPS_TOTAL, float(len(missing_queries)), - attributes={"source": "osv", "status": "ok", "batch": True}, + {"source": "osv", "status": "ok", "batch": "true"}, ) except Exception as exc: logger.debug("OSV batch lookup failed: %s", exc) @@ -451,6 +456,11 @@ def _unasked_radar_record(domain_or_url: str) -> NetworkReputationRecord | None: ) +def _count_threat_intel_lookup(status: str) -> None: + """Count one domain that Cloudflare Radar was asked about, by the status of its answer.""" + emit(THREAT_INTEL_LOOKUPS_TOTAL, 1.0, {"source": "cloudflare", "status": status}) + + class CloudflareRadarClient: """Queries Cloudflare Radar for domain reputation and threat intelligence.""" @@ -544,25 +554,13 @@ def _query_radar_http( record.outcome = "ok" span_h.set_attribute("categories_count", len(record.tags)) cacheable = True - record_metric( - "devops_cli_threat_intel_lookups_total", - 1.0, - attributes={"source": "cloudflare", "status": "ok", "cached": False}, - ) + _count_threat_intel_lookup("ok") elif res.status_code == 429: record.outcome = "unavailable" record.reputation_summary = "Cloudflare Radar rate limited (HTTP 429)" span_h.set_attribute("lookup.error", "HTTP 429 Rate Limit Exceeded") span_h.set_attribute("lookup.fallback", True) - record_metric( - "devops_cli_threat_intel_lookups_total", - 1.0, - attributes={ - "source": "cloudflare", - "status": "unavailable", - "cached": False, - }, - ) + _count_threat_intel_lookup("unavailable") else: record.outcome = "failed" record.reputation_summary = ( @@ -570,22 +568,14 @@ def _query_radar_http( ) span_h.set_attribute("lookup.error", f"HTTP {res.status_code}") span_h.set_attribute("lookup.fallback", True) - record_metric( - "devops_cli_threat_intel_lookups_total", - 1.0, - attributes={"source": "cloudflare", "status": "failed", "cached": False}, - ) + _count_threat_intel_lookup("failed") except Exception as exc: logger.debug("Cloudflare Radar lookup failed for %s: %s", target, exc) record.outcome = "failed" record.reputation_summary = f"Cloudflare Radar lookup failed: {exc}" span_h.set_attribute("lookup.error", str(exc)) span_h.set_attribute("lookup.fallback", True) - record_metric( - "devops_cli_threat_intel_lookups_total", - 1.0, - attributes={"source": "cloudflare", "status": "failed", "cached": False}, - ) + _count_threat_intel_lookup("failed") return record, cacheable return record, cacheable diff --git a/src/devops_cli/telemetry/__init__.py b/src/devops_cli/telemetry/__init__.py index 4781f9a82a..bfcbd99486 100644 --- a/src/devops_cli/telemetry/__init__.py +++ b/src/devops_cli/telemetry/__init__.py @@ -74,7 +74,6 @@ get_tracer, inject_trace_context, record_completed_span, - record_metric, reset_tracer, trace_span, traced, @@ -165,7 +164,6 @@ "get_tracer": ("devops_cli.telemetry.tracer", "get_tracer"), "inject_trace_context": ("devops_cli.telemetry.tracer", "inject_trace_context"), "record_completed_span": ("devops_cli.telemetry.tracer", "record_completed_span"), - "record_metric": ("devops_cli.telemetry.tracer", "record_metric"), "reset_tracer": ("devops_cli.telemetry.tracer", "reset_tracer"), "trace_span": ("devops_cli.telemetry.tracer", "trace_span"), "traced": ("devops_cli.telemetry.tracer", "traced"), @@ -239,7 +237,6 @@ def __getattr__(name: str) -> Any: "profile_http_pool_workload", "query_tempo_trace", "record_completed_span", - "record_metric", "render_agent_turn_panel", "render_agent_turn_table", "render_waterfall_bar", diff --git a/src/devops_cli/telemetry/instruments.py b/src/devops_cli/telemetry/instruments.py index 54507c7cf8..68fac07da2 100644 --- a/src/devops_cli/telemetry/instruments.py +++ b/src/devops_cli/telemetry/instruments.py @@ -43,6 +43,36 @@ class Instrument: "s", "Command wall time, by command", ) +SUBCOMMAND_DURATION = Instrument( + "devops_cli_subcommand_duration_seconds", + InstrumentKind.HISTOGRAM, + "s", + "Subcommand wall time, by subcommand and status: ok or error", +) +SUBPROCESS_DURATION = Instrument( + "devops_cli_subprocess_duration_seconds", + InstrumentKind.HISTOGRAM, + "s", + "Wall time of a program that devops-cli ran, by program and status: ok or error", +) +TELEMETRY_TESTS_TOTAL = Instrument( + "devops_cli_telemetry_tests_total", + InstrumentKind.COUNTER, + "1", + "Test points that devops telemetry test sent, to show that metrics reach the collector", +) +CI_CHECKS_TOTAL = Instrument( + "devops_cli_ci_checks_total", + InstrumentKind.COUNTER, + "1", + "Checks that devops ci ran, by step and outcome: pass or fail", +) +CI_GATE_SLOT_WAIT = Instrument( + "devops_cli_ci_gate_slot_wait_seconds", + InstrumentKind.HISTOGRAM, + "s", + "Time a devops ci run waited for a free gate slot before its checks started", +) REVIEW_DURATION = Instrument( "devops_cli_review_duration_seconds", InstrumentKind.HISTOGRAM, @@ -100,6 +130,53 @@ class Instrument: "Time a call to Ollama waited in this process for a slot on one of its nodes, by priority " "(high, normal or as_available) and outcome: ok once it held one, or timeout", ) +AI_CHAT_DURATION = Instrument( + "devops_cli_ai_chat_duration_seconds", + InstrumentKind.HISTOGRAM, + "s", + "LLM chat call wall time, by provider and model, from the request to the reply. A gateway " + "call's time includes its wait for a backend slot", +) +AI_STRUCTURED_ATTEMPTS_TOTAL = Instrument( + "devops_cli_ai_structured_attempts_total", + InstrumentKind.COUNTER, + "1", + "Structured-output attempts, by model and outcome: valid when the reply matched its schema, " + "else invalid. Each invalid attempt but the last is retried", +) +AI_PREWARMS_TOTAL = Instrument( + "devops_cli_ai_prewarms_total", + InstrumentKind.COUNTER, + "1", + "devops ai prewarm runs, by model, evict (true when the run unloaded the model) and outcome: " + "ok or failed", +) +AI_GATEWAY_PROBE_DURATION = Instrument( + "devops_cli_ai_gateway_probe_duration_seconds", + InstrumentKind.HISTOGRAM, + "s", + "Time a health probe of the LLM gateway took", +) +AI_GATEWAY_HEALTHY = Instrument( + "devops_cli_ai_gateway_healthy", + InstrumentKind.GAUGE, + "1", + "Whether the last health probe of the LLM gateway passed: 1, or 0", +) +AI_GATEWAY_FAILOVERS_TOTAL = Instrument( + "devops_cli_ai_gateway_failovers_total", + InstrumentKind.COUNTER, + "1", + "Failovers of a gateway model alias to its fallback, by virtual model and simulate: true " + "for a simulated failover", +) +AI_CAPABILITY_GATE_TOTAL = Instrument( + "devops_cli_ai_capability_gate_total", + InstrumentKind.COUNTER, + "1", + "Failovers to a model below the capability tier of their role, by role, model and decision: " + "rejection when the gate refused it, or override when --force let it through", +) RAG_QUERY_DURATION = Instrument( "devops_cli_rag_query_duration_ms", InstrumentKind.HISTOGRAM, @@ -153,6 +230,59 @@ class Instrument: "1", "Embeddings that the memory cache of the process held after its last embedding request", ) +RAG_EMBEDDING_BATCH_SIZE = Instrument( + "devops_cli_rag_embedding_batch_size", + InstrumentKind.GAUGE, + "1", + "Texts in each embedding request after the last change of the adaptive batch size", +) +RAG_EMBEDDING_BATCH_RESIZES_TOTAL = Instrument( + "devops_cli_rag_embedding_batch_resizes_total", + InstrumentKind.COUNTER, + "1", + "Changes of the adaptive embedding batch size, by action: additive_increase after enough " + "fast batches, or multiplicative_decrease after a slow or failed batch", +) +RAG_DRIFT_SCORE = Instrument( + "devops_cli_rag_drift_score", + InstrumentKind.GAUGE, + "1", + "Share of a project's files that changed, were added or were deleted since its last index, " + "from its last drift check, by project. A drifted knowledge base scores 1", +) +RAG_DRIFT_DETECTED = Instrument( + "devops_cli_rag_drift_detected", + InstrumentKind.GAUGE, + "1", + "Whether the last drift check of a project found drift in its files, its git head or its " + "knowledge base: 1, or 0, by project", +) +RAG_INVESTIGATIONS_TOTAL = Instrument( + "devops_cli_rag_investigations_total", + InstrumentKind.COUNTER, + "1", + "RAG context retrievals that finished, by outcome: found when they returned context, or empty", +) +RAG_STOPS_TOTAL = Instrument( + "devops_cli_rag_stops_total", + InstrumentKind.COUNTER, + "1", + "Processes that turned RAG off for the rest of their run after an embedding failure", +) +VULNERABILITY_LOOKUPS_TOTAL = Instrument( + "devops_cli_vulnerability_lookups_total", + InstrumentKind.COUNTER, + "1", + "Packages looked up in a vulnerability database, by source, status and batch: true when one " + "batch request looked them up", +) +THREAT_INTEL_LOOKUPS_TOTAL = Instrument( + "devops_cli_threat_intel_lookups_total", + InstrumentKind.COUNTER, + "1", + "Domains that a threat-intelligence source was asked about, by source and status: ok, " + "unavailable or failed. A domain that the cache answered is not counted", +) PROJECT_RELEASES = Instrument( "devops_cli_project_releases", @@ -257,6 +387,11 @@ class Instrument: INSTRUMENTS: tuple[Instrument, ...] = ( COMMAND_TOTAL, COMMAND_DURATION, + SUBCOMMAND_DURATION, + SUBPROCESS_DURATION, + TELEMETRY_TESTS_TOTAL, + CI_CHECKS_TOTAL, + CI_GATE_SLOT_WAIT, REVIEW_DURATION, FINDINGS_TOTAL, AI_REQUESTS_TOTAL, @@ -265,6 +400,13 @@ class Instrument: AI_JSON_REPAIRS_TOTAL, AI_GATEWAY_SLOT_WAIT, AI_OLLAMA_SLOT_WAIT, + AI_CHAT_DURATION, + AI_STRUCTURED_ATTEMPTS_TOTAL, + AI_PREWARMS_TOTAL, + AI_GATEWAY_PROBE_DURATION, + AI_GATEWAY_HEALTHY, + AI_GATEWAY_FAILOVERS_TOTAL, + AI_CAPABILITY_GATE_TOTAL, RAG_QUERY_DURATION, QDRANT_RETRIES_TOTAL, RAG_POINTS, @@ -273,6 +415,14 @@ class Instrument: GITHUB_GRAPHQL_POINTS_TOTAL, EMBEDDING_CACHE_LOOKUPS_TOTAL, EMBEDDING_CACHE_SIZE, + RAG_EMBEDDING_BATCH_SIZE, + RAG_EMBEDDING_BATCH_RESIZES_TOTAL, + RAG_DRIFT_SCORE, + RAG_DRIFT_DETECTED, + RAG_INVESTIGATIONS_TOTAL, + RAG_STOPS_TOTAL, + VULNERABILITY_LOOKUPS_TOTAL, + THREAT_INTEL_LOOKUPS_TOTAL, PROJECT_RELEASES, PROJECT_COMMITS, PROJECT_PRS, @@ -323,12 +473,21 @@ def backend_name(served_by: str | None) -> str: __all__ = [ + "AI_CAPABILITY_GATE_TOTAL", + "AI_CHAT_DURATION", + "AI_GATEWAY_FAILOVERS_TOTAL", + "AI_GATEWAY_HEALTHY", + "AI_GATEWAY_PROBE_DURATION", "AI_GATEWAY_SLOT_WAIT", "AI_JSON_REPAIRS_TOTAL", "AI_OLLAMA_SLOT_WAIT", + "AI_PREWARMS_TOTAL", "AI_REQUESTS_TOTAL", "AI_SPEND_USD_TOTAL", + "AI_STRUCTURED_ATTEMPTS_TOTAL", "AI_TOKENS_TOTAL", + "CI_CHECKS_TOTAL", + "CI_GATE_SLOT_WAIT", "COMMAND_DURATION", "COMMAND_TOTAL", "EMBEDDING_CACHE_LOOKUPS_TOTAL", @@ -354,11 +513,22 @@ def backend_name(served_by: str | None) -> str: "PROJECT_TRAFFIC_VIEWS", "PROJECT_TRAFFIC_VIEWS_UNIQUES", "QDRANT_RETRIES_TOTAL", + "RAG_DRIFT_DETECTED", + "RAG_DRIFT_SCORE", + "RAG_EMBEDDING_BATCH_RESIZES_TOTAL", + "RAG_EMBEDDING_BATCH_SIZE", + "RAG_INVESTIGATIONS_TOTAL", "RAG_POINTS", "RAG_QUERY_DURATION", + "RAG_STOPS_TOTAL", "REVIEW_DURATION", + "SUBCOMMAND_DURATION", + "SUBPROCESS_DURATION", + "TELEMETRY_TESTS_TOTAL", + "THREAT_INTEL_LOOKUPS_TOTAL", "UPSTREAM_COMPONENT_STATUS", "UPSTREAM_SERVICE_STATUS", + "VULNERABILITY_LOOKUPS_TOTAL", "Instrument", "InstrumentKind", "backend_name", diff --git a/src/devops_cli/telemetry/tracer.py b/src/devops_cli/telemetry/tracer.py index 1446abcc03..4e41008435 100644 --- a/src/devops_cli/telemetry/tracer.py +++ b/src/devops_cli/telemetry/tracer.py @@ -1077,7 +1077,7 @@ def export_log_record(self, log_record: dict[str, Any]) -> None: payload = self._build_logs_payload([log_record]) self._send_payload("/v1/logs", payload) - def record_metric( + def record_gauge( self, name: str, value: float, @@ -1085,7 +1085,10 @@ def record_metric( unit: str = CONST_OTEL_METRIC_UNIT_ONE, attributes: dict[str, Any] | None = None, ) -> None: - """Record a gauge data point in the in-process OTel SDK meter.""" + """Record a gauge data point in the in-process OTel SDK meter. + + `telemetry.instruments.emit()` is the one caller of the metric methods. + """ from devops_cli.dry_run.state import in_dry_run_invocation if not self.enabled or in_dry_run_invocation(): @@ -1093,17 +1096,6 @@ def record_metric( gauge = self._get_sdk_instrument("gauge", name, unit) gauge.set(float(value), _sdk_metric_attributes(attributes)) - def record_gauge( - self, - name: str, - value: float, - *, - unit: str = CONST_OTEL_METRIC_UNIT_ONE, - attributes: dict[str, Any] | None = None, - ) -> None: - """Record a gauge data point in the in-process OTel SDK meter.""" - self.record_metric(name, value, unit=unit, attributes=attributes) - def increment_counter( self, name: str, @@ -1577,26 +1569,6 @@ def trace_span( yield handle -def record_metric( - name: str, - value: float, - unit: str = CONST_OTEL_METRIC_UNIT_ONE, - attributes: dict[str, Any] | None = None, -) -> None: - """Convenience function to record a metric data point.""" - get_tracer().record_metric(name, value, unit=unit, attributes=attributes) - - -def record_gauge( - name: str, - value: float, - unit: str = CONST_OTEL_METRIC_UNIT_ONE, - attributes: dict[str, Any] | None = None, -) -> None: - """Convenience function to record a gauge metric data point.""" - get_tracer().record_gauge(name, value, unit=unit, attributes=attributes) - - def inject_trace_context(headers: dict[str, str] | None = None) -> dict[str, str]: """Convenience function to inject W3C traceparent into outgoing HTTP headers.""" return get_tracer().inject_trace_context(headers) diff --git a/tests/test_ai_prewarm.py b/tests/test_ai_prewarm.py index 4512841a39..3dae17eb30 100644 --- a/tests/test_ai_prewarm.py +++ b/tests/test_ai_prewarm.py @@ -8,6 +8,7 @@ if TYPE_CHECKING: from tests.support.fakes.model import ModelFake + from tests.support.telemetry_capture import Captured import httpx2 import pytest @@ -17,6 +18,7 @@ from devops_cli.commands.ai import _render_prewarm_results, _resolve_prewarm_urls from devops_cli.config.settings import AIConfig from devops_cli.exceptions import ValidationError +from devops_cli.telemetry.instruments import AI_PREWARMS_TOTAL runner = CliRunner() @@ -330,28 +332,27 @@ def test_cli_prewarm_single_node_flag(self, app: Any, model_fake: ModelFake) -> assert result.exit_code == 0 assert model_fake.preload_calls[-1]["urls"] == ["http://localhost:11434"] - def test_cli_prewarm_telemetry_recording(self, app: Any, model_fake: ModelFake) -> None: - """Verify devops ai prewarm records OpenTelemetry span and execution metric.""" - with ( - patch("devops_cli.commands.ai.record_metric") as mock_metric, - patch("devops_cli.commands.ai.trace_span") as mock_span, - ): - result = runner.invoke(app, ["ai", "prewarm"]) - - assert result.exit_code == 0 - assert (mock_span.called, mock_metric.called) == (True, True) - - def test_cli_prewarm_telemetry_recording_failure(self, app: Any, model_fake: ModelFake) -> None: - """Verify devops ai prewarm records failure metric when node prewarm fails.""" - model_fake.set_preload_results({"http://localhost:11434": False}) - with ( - patch("devops_cli.commands.ai.record_metric") as mock_metric, - patch("devops_cli.commands.ai.trace_span") as mock_span, - ): - result = runner.invoke(app, ["ai", "prewarm"]) - - assert result.exit_code == 1 - assert (mock_span.called, mock_metric.called) == (True, True) + @pytest.mark.parametrize( + ("node_ok", "exit_code", "outcome"), [(True, 0, "ok"), (False, 1, "failed")] + ) + def test_a_prewarm_run_counts_once_by_model_evict_and_outcome( + self, + app: Any, + model_fake: ModelFake, + captured: Captured, + node_ok: bool, + exit_code: int, + outcome: str, + ) -> None: + """Verify devops ai prewarm counts its run one time, by model, evict and outcome.""" + model_fake.set_preload_results({"http://localhost:11434": node_ok}) + + result = runner.invoke(app, ["ai", "prewarm", "--model", "gemma4:26b", "--single-node"]) + + assert (result.exit_code, captured.points(AI_PREWARMS_TOTAL.name)) == ( + exit_code, + [({"model": "gemma4:26b", "evict": "false", "outcome": outcome}, 1.0)], + ) class TestFastMCPPrewarmTool: diff --git a/tests/test_ci.py b/tests/test_ci.py index c2ece1e709..f89df6305c 100644 --- a/tests/test_ci.py +++ b/tests/test_ci.py @@ -212,7 +212,6 @@ async def run(cmd: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str] with ( patch("devops_cli.commands.ci.trace_span", side_effect=dummy_span), patch("devops_cli.core.process.run_subprocess_async", side_effect=run), - patch("devops_cli.commands.ci.record_metric"), patch("devops_cli.commands.ci.print_muted"), ): result = await ci_module._execute_check_async( @@ -1575,7 +1574,6 @@ def dummy_span(*a: Any, **kw: Any) -> Any: patch( "devops_cli.core.process.run_subprocess_async", new=AsyncMock(return_value=mock_proc_ok) ), - patch("devops_cli.commands.ci.record_metric"), patch("devops_cli.commands.ci.print_muted"), ): res_ok = await _execute_check_async( @@ -1588,7 +1586,6 @@ def dummy_span(*a: Any, **kw: Any) -> Any: "devops_cli.core.process.run_subprocess_async", new=AsyncMock(return_value=mock_proc_fail), ), - patch("devops_cli.commands.ci.record_metric"), patch("devops_cli.commands.ci.print_muted"), ): res_fail = await _execute_check_async( @@ -2444,7 +2441,6 @@ async def mock_subprocess_async(*a: Any, **kw: Any) -> Any: with ( patch("devops_cli.commands.ci.trace_span", side_effect=dummy_span), patch("devops_cli.core.process.run_subprocess_async", side_effect=mock_subprocess_async), - patch("devops_cli.commands.ci.record_metric"), patch("devops_cli.commands.ci.print_muted"), ): spec = CheckSpec( diff --git a/tests/test_ci_gate_admission.py b/tests/test_ci_gate_admission.py index fe4f0e3819..a3524e4a04 100644 --- a/tests/test_ci_gate_admission.py +++ b/tests/test_ci_gate_admission.py @@ -17,6 +17,7 @@ from devops_cli.core.repo import find_worktree_root from devops_cli.lang import MESSAGES from devops_cli.output import format_duration +from devops_cli.telemetry.instruments import CI_GATE_SLOT_WAIT from tests.support.fakes.process import ProcessFake from tests.support.session_spawns import RecordedSpawn, record_spawns @@ -25,7 +26,7 @@ runner = CliRunner() HOLDER = "4321 /work/w-1111" -WAIT_METRIC = "ci.gate_slot_wait_seconds" +WAIT_METRIC = CI_GATE_SLOT_WAIT.name Started = Callable[[], list[tuple[str, ...]]] """The argv of every process the command under test has started so far.""" diff --git a/tests/test_otel_command_coverage.py b/tests/test_otel_command_coverage.py index 3fa9defe60..770c24d478 100644 --- a/tests/test_otel_command_coverage.py +++ b/tests/test_otel_command_coverage.py @@ -78,7 +78,7 @@ def sample_subcommand(target: str = "cluster-1") -> None: assert len(metric_payloads) >= 1 metric_data = metric_payloads[0]["resourceMetrics"][0]["scopeMetrics"][0]["metrics"][0] - assert metric_data["name"] == "devops_cli_subcommand_seconds" + assert metric_data["name"] == "devops_cli_subcommand_duration_seconds" def test_otel_typer_subcommand_error_span( @@ -510,7 +510,7 @@ def test_subprocess_span_and_metrics( for p in metric_payloads for m in p["resourceMetrics"][0]["scopeMetrics"][0]["metrics"] ] - assert "devops_cli_subprocess_seconds" in metric_names + assert "devops_cli_subprocess_duration_seconds" in metric_names def test_subprocess_error_span_and_metrics( diff --git a/tests/test_sandbox_metrics.py b/tests/test_sandbox_metrics.py index e0f7192124..7ff07a954f 100644 --- a/tests/test_sandbox_metrics.py +++ b/tests/test_sandbox_metrics.py @@ -669,31 +669,24 @@ def test_cli_sandbox_metrics_help_metrics_timeout() -> None: def test_telemetry_tracing_instrumentation(tmp_path: Path) -> None: - """Test OpenTelemetry tracing and metric recording in CLI and engine.""" + """Test OpenTelemetry tracing in CLI and engine.""" from devops_cli.sandbox.engine import WorkloadSandboxEngine - # Test CLI command emits trace span and metric + # Test CLI command emits trace span with patch("devops_cli.commands.sandbox.trace_span") as mock_cli_span: - with patch("devops_cli.commands.sandbox.record_metric") as mock_cli_metric: - mock_cli_span.return_value.__enter__.return_value = MagicMock() - result = runner.invoke(app, ["sandbox", "metrics", "test-inst", "--dry-run"]) - assert result.exit_code == 0 - mock_cli_span.assert_called_once_with( - "sandbox.metrics", - attributes={ - "sandbox.identifier": "test-inst", - "sandbox.prom_endpoint": "/metrics", - "sandbox.dry_run": True, - }, - ) - mock_cli_metric.assert_called_once_with( - "devops_cli.sandbox.metrics_invoked", - 1.0, - unit="1", - attributes={"dry_run": True}, - ) + mock_cli_span.return_value.__enter__.return_value = MagicMock() + result = runner.invoke(app, ["sandbox", "metrics", "test-inst", "--dry-run"]) + assert result.exit_code == 0 + mock_cli_span.assert_called_once_with( + "sandbox.metrics", + attributes={ + "sandbox.identifier": "test-inst", + "sandbox.prom_endpoint": "/metrics", + "sandbox.dry_run": True, + }, + ) - # Test Engine metrics() emits trace span and metric + # Test Engine metrics() emits trace span engine = WorkloadSandboxEngine() mock_inst = SandboxInstance( instance_id="inst-tracer", @@ -708,7 +701,6 @@ def test_telemetry_tracing_instrumentation(tmp_path: Path) -> None: with ( patch.object(engine.registry, "get_instance", return_value=mock_inst), patch("devops_cli.sandbox.engine.trace_span") as mock_eng_span, - patch("devops_cli.sandbox.engine.record_metric") as mock_eng_metric, patch("devops_cli.sandbox.metrics.collect_sandbox_metrics") as mock_collect, ): mock_collect.return_value = SandboxMetricsSnapshot( @@ -730,12 +722,6 @@ def test_telemetry_tracing_instrumentation(tmp_path: Path) -> None: "sandbox.prom_endpoint": "/metrics", }, ) - mock_eng_metric.assert_called_once_with( - "devops_cli.sandbox.metrics_collected", - 1.0, - unit="1", - attributes={"healthy": True}, - ) def test_parse_cgroup_v2_cpu_delta_calculation(tmp_path: Path) -> None: diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index 8435edb2f3..5598d0119c 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -9,10 +9,10 @@ from devops_cli.ai.client.models import LLMResponse from devops_cli.ai.client.unified import _set_response_span_attributes from devops_cli.config.settings import TelemetryConfig +from devops_cli.telemetry.instruments import COMMAND_TOTAL, emit from devops_cli.telemetry.tracer import ( OTelTelemetryClient, get_tracer, - record_metric, reset_tracer, trace_span, ) @@ -30,7 +30,7 @@ def test_telemetry_disabled() -> None: with client.span("test_span") as span_id: assert span_id == "" # Should not raise - client.record_metric("test_metric", 1.0) + client.record_gauge("test_metric", 1.0) def test_telemetry_span_and_metric(monkeypatch: pytest.MonkeyPatch) -> None: @@ -41,7 +41,7 @@ def test_telemetry_span_and_metric(monkeypatch: pytest.MonkeyPatch) -> None: with client.span("pipeline_stage", {"persona": "devsecops"}) as span_id: assert len(span_id) == 16 # 8 bytes hex = 16 hex chars - client.record_metric("findings_count", 3, unit="1", attributes={"severity": "HIGH"}) + client.record_gauge("findings_count", 3, unit="1", attributes={"severity": "HIGH"}) client.flush() assert len(sent_payloads) == 2 @@ -78,7 +78,7 @@ def test_global_trace_helpers(monkeypatch: pytest.MonkeyPatch, config: Any) -> N monkeypatch.setattr(tracer, "_send_payload", lambda path, p: sent_payloads.append((path, p))) with trace_span("helper_span", {"env": "test"}): - record_metric("helper_metric", 42.0) + emit(COMMAND_TOTAL, 1.0, {"command": "helper", "status": "ok"}) tracer.flush() assert len(sent_payloads) == 2 diff --git a/tests/test_telemetry_instruments.py b/tests/test_telemetry_instruments.py index 26dd4092a1..de8e7eea93 100644 --- a/tests/test_telemetry_instruments.py +++ b/tests/test_telemetry_instruments.py @@ -259,6 +259,100 @@ def test_a_check_fails_when_two_paths_send_the_same_gauge_name(tmp_path: Path) - assert PROJECT_ITEMS.name in shared +_METRIC_METHODS = frozenset( + {"increment_counter", "record_gauge", "record_histogram", "record_metric"} +) +"""The telemetry client's methods that write a metric by its name.""" +_SERVICE_REGISTRY = "GLOBAL_METRICS" +"""The Prometheus registry that the Service serves on `/metrics`: no OTLP metric.""" +SRC = REPO_ROOT / "src" / "devops_cli" + + +def _declared_instrument_imports(tree: ast.AST) -> tuple[set[str], set[str]]: + """The local names of `emit`, and of the declared instruments, that a module imports from + the instruments module.""" + import devops_cli.telemetry.instruments as instruments + + emit_names: set[str] = set() + declared: set[str] = set() + for node in ast.walk(tree): + if not isinstance(node, ast.ImportFrom) or node.module != instruments.__name__: + continue + for alias in node.names: + local = alias.asname or alias.name + if alias.name == "emit": + emit_names.add(local) + elif getattr(instruments, alias.name, None) in INSTRUMENTS: + declared.add(local) + return emit_names, declared + + +def _writes_outside_emit(call: ast.Call, emit_names: set[str], declared: set[str]) -> bool: + """Whether a call writes a metric by its name, or emits an instrument that `INSTRUMENTS` + does not hold.""" + func = call.func + if isinstance(func, ast.Attribute) and func.attr in _METRIC_METHODS: + return not (isinstance(func.value, ast.Name) and func.value.id == _SERVICE_REGISTRY) + if isinstance(func, ast.Name) and func.id in _METRIC_METHODS: + return True + if isinstance(func, ast.Name) and func.id in emit_names: + first = call.args[0] if call.args else None + return not (isinstance(first, ast.Name) and first.id in declared) + return False + + +def _metric_writes_outside_emit(tree: ast.AST, label: str) -> list[str]: + """Each call of a module, as `