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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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] <expr>` | Execute an instant PromQL query. |
| | `devops prometheus query-range [OPTIONS] <expr>` | Execute a range PromQL query and summarise the result. |
| | `devops prometheus analyze [OPTIONS] <expr>` | 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] <name>` | Synchronize an ArgoCD application (or multi-cluster fleet when --fleet is passed). |
Expand Down
23 changes: 23 additions & 0 deletions docs/CLI_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -1497,6 +1497,29 @@ devops prometheus query-range [OPTIONS] <expr>
| `--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] <expr>
```

**Arguments:**

| Argument | Type | Required | Description |
|---|---|---|---|
| `<expr>` | `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.**
Expand Down
4 changes: 2 additions & 2 deletions docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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) |
Expand Down
Original file line number Diff line number Diff line change
@@ -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`
Expand All @@ -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 <expr>` 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.
25 changes: 25 additions & 0 deletions docs/commands/prometheus.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,31 @@ devops prometheus query-range [OPTIONS] <expr>

---

## `devops prometheus analyze`

**Detect anomalies and project the trend of a metric series, computed locally.**

```bash
devops prometheus analyze [OPTIONS] <expr>
```

**Arguments:**

| Argument | Type | Required | Description |
|---|---|---|---|
| `<expr>` | `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.**
Expand Down
115 changes: 115 additions & 0 deletions src/devops_cli/commands/prometheus.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -57,13 +58,28 @@ 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),
prefix=False,
)
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."""
Expand Down Expand Up @@ -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
# =============================================================================
Expand Down
12 changes: 12 additions & 0 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
11 changes: 11 additions & 0 deletions src/devops_cli/config/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/devops_cli/lang/en/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ class PrometheusErrorMessages:
"Prometheus URL not configured. Run: devops config set prometheus.url <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}"

Expand Down
Loading
Loading