Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,9 @@ High-density product roadmap, engineering milestones, and open-source integratio
- [x] **devops-cli Telemetry Never Reaches the Collector (P1 - High, Issue #547)**:
- *Context & Rationale*: devops-cli exports OTLP to `telemetry.endpoint`, `http://localhost:4318` by default, where nothing listens: the collector is a ClusterIP service. Jaeger has no services, no `devops_cli_*` metric reaches Prometheus, and the `devops-cli.json` and `ai-spend.json` dashboards are empty. The exporter fails silently.
- *Delivered*: The collector is a NodePort, and `devops telemetry connect` finds it through kubectl, checks it answers and saves the endpoint, with no host or port in the repository. Failed exports are counted and reported to an interactive user once a day. Exports in flight are drained at exit rather than cancelled. The collector keeps metric names as sent, so `devops_cli_command_total` no longer arrives as `devops_cli_command_total_ratio`. Checked through a port-forward: devops-cli's traces reached Jaeger and its metrics reached Prometheus. Dashboard metrics nothing sends over OTLP are #564.
- [x] **Review, Findings and AI Spend Metrics Reach Prometheus (P2 - Medium, Issue #564)**:
- *Context & Rationale*: With telemetry reaching the collector (#547), the dashboards still queried review and findings metrics nothing emitted, and AI spend metrics only `devops server` exposed. Every metric was sent as a gauge from a short-lived process, so counters and histograms could not accumulate.
- *Delivered*: Counters and histograms are sent as OTLP deltas from a per-host resource, and the collector's `deltatocumulative` processor keeps running totals. Reviews send their wall time and findings by persona, severity and status. AI calls count requests, tokens and spend by backend and model as they happen. Both dashboards read only sent metrics, checked by a test, and `docs/TELEMETRY.md` is generated from the one list of sent metrics.
- [x] **Review Verification on Its Own Model Task (P1 - High, Issue #486)**:
- *Context & Rationale*: One LLM client served persona review and verification. Faster `devops-review` weights (#476) let top-severity false positives through verification, and the hypothesis was that a stronger verifier would restore the check.
- *Delivered*: `ai.tasks.verification` is layered on the analysis task and used by both verification call sites. Unset, analysis verifies. Validated live with the tuned weights and the 32B model verifying: reviews were slower (median 284 s against 229 s), one stalled on an uncapped verification reply (#494), nearly every candidate was rejected, and the registry-mirror HTTP false positive still passed. The false positive comes from the verification prompt, not the model (#413, #475). The setting ships unset.
Expand Down
28 changes: 16 additions & 12 deletions docs/TELEMETRY.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
# DevOps CLI Telemetry & Distributed Tracing Reference

DevOps CLI instruments all CLI subcommands, background tasks, and AI pipeline stages
with distributed OpenTelemetry traces (`@trace_span`) and in-memory Prometheus metrics (`GLOBAL_METRICS`).
with distributed OpenTelemetry traces (`@trace_span`) and OTLP metrics.

---

## Prometheus Metric Instruments

| Metric Name | Type | Description |
|---|---|---|
| `devops_cli_command_duration_seconds` | Histogram | CLI execution latency waterfall in seconds by subcommand. |
| `devops_cli_command_total` | Counter | Total CLI command invocations partitioned by status and command group. |
| `devops_cli_subprocess_duration_seconds` | Histogram | Subprocess execution latency in seconds across external binaries. |
| `devops_cli_subprocess_total` | Counter | Total external tool executions partitioned by binary and exit status. |
| `devops_cli_ai_llm_requests_total` | Counter | Total AI / LLM completions dispatched by provider and model. |
| `devops_cli_ai_token_usage_total` | Counter | Cumulative input and output token consumption across review stages. |
| `devops_cli_security_findings_total` | Counter | Total security vulnerabilities and anti-patterns flagged by scanner. |
| `devops_cli_cache_hits_total` | Counter | Semantic cache hits for embeddings and AI review prompt hashes. |
| `devops_cli_cache_misses_total` | Counter | Semantic cache misses triggering fresh LLM inference requests. |
Each command runs as its own short-lived process, so counters and histograms are sent
as OTLP deltas. The collector's `deltatocumulative` processor keeps each series' running
total per host (`instance`) before Prometheus stores it. `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_review_duration_seconds` | Histogram | `s` | Review wall time, by target type. |
| `devops_cli_findings_total` | Counter | `1` | Review findings, by persona, severity and status. |
| `devops_cli_ai_requests_total` | Counter | `1` | LLM calls, by provider, model, server, serving backend and whether the cache answered. |
| `devops_cli_ai_tokens_total` | Counter | `1` | LLM tokens, by type (prompt or completion), provider, model, server and backend. |
| `devops_cli_ai_spend_usd_total` | Counter | `USD` | Approximate LLM spend, by provider, model, server and backend. |
| `devops_cli_rag_query_duration_ms` | Histogram | `ms` | RAG retrieval time. |

---

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Task 564: Review, Findings and AI Spend Metrics Reach Prometheus

**Issue**: [#564](https://github.com/dan-petty/devops-cli/issues/564)
**Status**: Done
**Milestone**: `v0.2.23`
**Priority**: `priority/p2-medium`
**Scope**: `type/bug`, `scope/telemetry`, `priority/p2-medium`

---

## 1. Description & Objectives

Found while fixing #547. With telemetry reaching the collector, the `devops-cli.json` and
`ai-spend.json` dashboards still queried metrics nothing sent over OTLP:
- `devops_cli_review_duration_seconds` and `devops_cli_findings_total` were emitted nowhere;
- `devops_cli_ai_spend_usd_total`, `devops_cli_ai_requests_total`,
`devops_cli_ai_server_spend_usd` and `devops_cli_ai_active_servers` existed only as Prometheus
text on `devops server`'s `/metrics`, which nothing in the cluster scrapes.

Every metric was also sent as a gauge. Counters and histograms therefore could not accumulate:
each command is its own short-lived process, so no process holds a running total.
`increase(devops_cli_command_total[1h])` read a constant 1. And because the process id was in
the resource, each command started a new stream.

### Key Deliverables Completed:

- [x] **Counters and histograms as deltas** (`telemetry/tracer.py`):
- `increment_counter` sends a monotonic delta sum;
- `record_histogram` sends a delta histogram with explicit buckets;
- `record_metric` stays a gauge.

Metrics carry a host resource: `service.instance.id` is the host name, which Prometheus
stores as `instance`. The process id and version are left out, so one host's commands add to
one series.
- [x] **The collector adds them up**: the `deltatocumulative` processor (`max_stale: 1h`) runs
before remote write (`k8s/otel/values.yaml`).
- [x] **One list of sent metrics** (`telemetry/instruments.py`): commands, reviews, findings,
AI requests, tokens, spend, and RAG query time, each with its kind, unit and description.
`docs/TELEMETRY.md` is generated from it. The old table named six metrics nothing emitted.
- [x] **Reviews** send their wall time by target type, and their findings by persona, severity
and status.
- [x] **AI calls** count, as they happen, by provider, model, server and serving backend:
- requests, and whether the cache answered;
- prompt and completion tokens;
- approximate spend.
- [x] **Dashboards** read only sent metrics:
- active backends are those that served an uncached call in the last 15 minutes;
- spend by backend sums `devops_cli_ai_spend_usd_total`;
- total tokens sums both types.
- [x] **Automated Tests & Quality Gates** (`tests/test_telemetry_instruments.py`):
- every query in both dashboards names a sent series;
- counter payload shape and host resource;
- histogram buckets;
- AI call metrics by backend, cached calls included;
- review duration and findings counts;
- the collector pipeline;
- backend names.

100% passing status across Gated CI validation suite (`uv run devops ci`).

### Not verified in the cluster

The collector change was checked by parsing its values, not deployed. After merge:
1. Upgrade the collector release with `k8s/otel/values.yaml`.
2. Run a review with telemetry connected.
3. Check the dashboards' review, findings and spend panels.
8 changes: 4 additions & 4 deletions k8s/monitoring/dashboards/ai-spend.json
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(devops_cli_ai_tokens_total{type=\"total\"}) or vector(0)",
"expr": "sum(devops_cli_ai_tokens_total) or vector(0)",
"legendFormat": "Total Tokens",
"refId": "A"
}
Expand Down Expand Up @@ -220,7 +220,7 @@
"type": "prometheus",
"uid": "prometheus"
},
"expr": "devops_cli_ai_active_servers or vector(0)",
"expr": "count(sum by (server, backend) (increase(devops_cli_ai_requests_total{cached=\"false\"}[15m])) > 0) or vector(0)",
"legendFormat": "Active Backends",
"refId": "A"
}
Expand Down Expand Up @@ -321,8 +321,8 @@
"type": "prometheus",
"uid": "prometheus"
},
"expr": "devops_cli_ai_server_spend_usd or vector(0)",
"legendFormat": "{{server}} ({{provider}})",
"expr": "sum by (server, backend, provider) (devops_cli_ai_spend_usd_total) or vector(0)",
"legendFormat": "{{backend}} via {{server}} ({{provider}})",
"refId": "A"
}
]
Expand Down
8 changes: 7 additions & 1 deletion k8s/otel/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ config:
limit_mib: 400
spike_limit_mib: 100

# devops-cli runs each command as its own short-lived process, so it sends counters and
# histograms as deltas. This keeps each series' running total, which Prometheus needs; a
# series idle for max_stale starts again from zero, read by rate() as a counter reset.
deltatocumulative:
max_stale: 1h

exporters:
# Debug exporter for local development visibility.
# In production environments, remove 'debug' from service.pipelines or gate verbosity.
Expand Down Expand Up @@ -89,7 +95,7 @@ config:

metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
processors: [memory_limiter, deltatocumulative, batch]
exporters: [debug, prometheusremotewrite]

logs:
Expand Down
9 changes: 3 additions & 6 deletions src/devops_cli/ai/rag/retriever.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
DEFAULT_RAG_SCORE_THRESHOLD,
DEFAULT_RAG_TOP_K,
)
from devops_cli.telemetry import record_metric, trace_span
from devops_cli.telemetry import trace_span
from devops_cli.telemetry.instruments import RAG_QUERY_DURATION, emit

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -294,11 +295,7 @@ def search(
if final_results:
search_span.set_attribute("rag.top_score", final_results[0].score)

record_metric(
"devops_cli_rag_query_duration_ms",
(time.perf_counter() - start) * 1000,
unit="ms",
)
emit(RAG_QUERY_DURATION, (time.perf_counter() - start) * 1000)
return final_results

def filter_and_validate_results(
Expand Down
27 changes: 25 additions & 2 deletions src/devops_cli/ai/review/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import json
import logging
import time
from collections import Counter
from collections.abc import Callable
from datetime import datetime
from pathlib import Path
Expand All @@ -23,6 +24,7 @@
)
from devops_cli.ai.review.flags import ReviewStageFlags
from devops_cli.ai.review.profile import (
ReviewProfile,
ReviewProfiler,
active_profiler,
profiling,
Expand Down Expand Up @@ -1768,7 +1770,7 @@ def _record_profile_findings(payloads: list[Any], candidates: int) -> None:

def _write_review_profile(
profiler: ReviewProfiler, orchestrator: Any, target: str, files: int
) -> None:
) -> ReviewProfile:
"""Write the session's profile.json and summarise where the time went."""
profile = profiler.build(session_id=orchestrator.session_id, target=target, files=files)
path = profile.write(orchestrator.session_dir)
Expand All @@ -1783,6 +1785,26 @@ def _write_review_profile(
f"{profile.llm_calls} LLM calls; {stages} -> {path}[/dim]",
prefix=False,
)
return profile


def _record_review_metrics(
results: list[tuple[PersonaDefinition, ReviewResult | str]],
seconds: float,
target_type: str,
) -> None:
"""Send the review's wall time, and its findings by persona, severity and status."""
from devops_cli.telemetry.instruments import FINDINGS_TOTAL, REVIEW_DURATION, emit

emit(REVIEW_DURATION, seconds, {"target_type": target_type})
counts = Counter(
(persona.name, finding.severity.upper(), finding.status.upper())
for persona, result in results
if isinstance(result, ReviewResult)
for finding in result.findings
)
for (persona, severity, status), count in counts.items():
emit(FINDINGS_TOTAL, count, {"persona": persona, "severity": severity, "status": status})


def _run_profiled_session(
Expand Down Expand Up @@ -1818,7 +1840,8 @@ def _run_profiled_session(
stage_flags=stage_flags,
)
if not is_dry_run():
_write_review_profile(profiler, orchestrator, target_ref, len(all_files))
profile = _write_review_profile(profiler, orchestrator, target_ref, len(all_files))
_record_review_metrics(results, profile.total_wall_seconds, target_type)
return results


Expand Down
29 changes: 18 additions & 11 deletions src/devops_cli/ai/spend/ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,13 @@ def track_request_spend(
) -> SpendRecord | None:
"""Calculate pricing, persist to lifetime ledger, and emit OpenTelemetry metrics."""
from devops_cli.ai.spend.pricing import get_pricing_registry
from devops_cli.telemetry.tracer import record_metric
from devops_cli.telemetry.instruments import (
AI_REQUESTS_TOTAL,
AI_SPEND_USD_TOTAL,
AI_TOKENS_TOTAL,
backend_name,
emit,
)

active_ledger = ledger or get_spend_ledger()
pricing = get_pricing_registry().get_pricing(model, server)
Expand Down Expand Up @@ -470,14 +476,15 @@ def track_request_spend(
"duration_seconds": duration_seconds,
}
)
record_metric(
"devops_cli_ai_estimated_cost_usd",
cost,
attributes={"provider": provider, "model": model, "server": server},
)
record_metric(
"devops_cli_ai_tokens_total",
prompt_tokens + completion_tokens,
attributes={"provider": provider, "model": model, "server": server},
)
source = {
"provider": provider,
"model": model,
"server": server,
"backend": backend_name(served_by),
}
emit(AI_REQUESTS_TOTAL, 1, source | {"cached": str(cached).lower()})
emit(AI_TOKENS_TOTAL, prompt_tokens, source | {"type": "prompt"})
emit(AI_TOKENS_TOTAL, completion_tokens, source | {"type": "completion"})
if cost:
emit(AI_SPEND_USD_TOTAL, cost, source)
return rec
2 changes: 2 additions & 0 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,8 @@
CONST_OTEL_SCOPE_NAME = "devops-cli.telemetry"
CONST_OTEL_SPAN_KIND_INTERNAL = "internal"
CONST_OTEL_METRIC_UNIT_ONE = "1"
# OTLP AggregationTemporality: a delta covers only its own interval.
CONST_OTEL_AGGREGATION_TEMPORALITY_DELTA = 1
CONST_OTEL_SERVICE_NAME = "devops-cli"
CONST_OTEL_OTLP_HTTP_PORT = 4318
# The cluster's collector, as k8s/otel deploys it.
Expand Down
26 changes: 14 additions & 12 deletions src/devops_cli/docs/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -883,27 +883,29 @@ def get_all_subclasses(cls: type[DevOpsCLIError]) -> list[type[DevOpsCLIError]]:

def generate_telemetry_docs(self) -> str:
"""Programmatically generate OpenTelemetry and Prometheus telemetry reference."""
from devops_cli.telemetry.instruments import INSTRUMENTS

lines: list[str] = [
"# DevOps CLI Telemetry & Distributed Tracing Reference",
"",
"DevOps CLI instruments all CLI subcommands, background tasks, and AI pipeline stages",
"with distributed OpenTelemetry traces (`@trace_span`) and in-memory Prometheus metrics (`GLOBAL_METRICS`).",
"with distributed OpenTelemetry traces (`@trace_span`) and OTLP metrics.",
"",
"---",
"",
"## Prometheus Metric Instruments",
"",
"| Metric Name | Type | Description |",
"|---|---|---|",
"| `devops_cli_command_duration_seconds` | Histogram | CLI execution latency waterfall in seconds by subcommand. |",
"| `devops_cli_command_total` | Counter | Total CLI command invocations partitioned by status and command group. |",
"| `devops_cli_subprocess_duration_seconds` | Histogram | Subprocess execution latency in seconds across external binaries. |",
"| `devops_cli_subprocess_total` | Counter | Total external tool executions partitioned by binary and exit status. |",
"| `devops_cli_ai_llm_requests_total` | Counter | Total AI / LLM completions dispatched by provider and model. |",
"| `devops_cli_ai_token_usage_total` | Counter | Cumulative input and output token consumption across review stages. |",
"| `devops_cli_security_findings_total` | Counter | Total security vulnerabilities and anti-patterns flagged by scanner. |",
"| `devops_cli_cache_hits_total` | Counter | Semantic cache hits for embeddings and AI review prompt hashes. |",
"| `devops_cli_cache_misses_total` | Counter | Semantic cache misses triggering fresh LLM inference requests. |",
"Each command runs as its own short-lived process, so counters and histograms are sent",
"as OTLP deltas. The collector's `deltatocumulative` processor keeps each series' running",
"total per host (`instance`) before Prometheus stores it. `devops telemetry connect`",
"points devops-cli at the cluster's collector.",
"",
"| Metric Name | Type | Unit | Description |",
"|---|---|---|---|",
*(
f"| `{i.name}` | {i.kind.value.title()} | `{i.unit}` | {i.description}. |"
for i in INSTRUMENTS
),
"",
"---",
"",
Expand Down
Loading
Loading