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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-25
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Design

## Decisions
- Split by dependency: the spec model has no SDK import, the builder keeps the module-level SDK import.
- The test names the blocked package in its own input. A test of this repository reads no config.

## Rejected alternatives
- Move `grafana-foundation-sdk` to the runtime dependencies: #5184 keeps it out, as it runs only in `make dashboards`.
- Import the SDK inside the builder functions: many functions use its types.
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Proposal: #7212

## Why
`devops mcp serve` of the newest release does not start: `ModuleNotFoundError: No module named 'grafana_foundation_sdk'`. #7185 made `k8s/catalog.py` import `grafana/service_dashboard.py`, which imports a dev-only package at module level. The MCP server imports each command module to build its tools.

## What Changes
- New module `grafana/service_specs.py` holds `ServiceSpec`, `load_specs` and the spec file name, with no Grafana SDK.
- `grafana/service_dashboard.py` and `k8s/catalog.py` import them from it.
- A test imports each command module with `grafana_foundation_sdk` blocked.

## Capabilities
### Modified Capabilities
- `mcp-server-image`: the commands import with no dev-only package.

## Impact
No change of a command, a setting or the dashboard JSON.

## Feasibility
The new test fails on `main` with `devops_cli.commands.k8s: No module named 'grafana_foundation_sdk.builders'`, the error of the crashing pod.

## Existing Tool Considered
`deptry` already reads the imports. Its rule `DEP004` ignores the SDK by name, and it cannot say which command imports reach a module. A lazy import in `k8s/catalog.py` would leave the model and the builder in one module, so the next import would break it again. The split costs no new tool.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
## ADDED Requirements

### Requirement: The commands import with no dev-only package
Each module of `devops_cli.commands` SHALL import in an install with no `dev` dependency group, such as the `mcp-server` image.

#### Scenario: Dev-only packages are blocked
- **WHEN** a Python process blocks `grafana_foundation_sdk` and imports each module of `devops_cli.commands`
- **THEN** no import fails
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Tasks

## 1. Behavior

- [x] 1.1 Write failing test
- Verification: `$ uv run devops ci test tests/grafana/test_service_specs.py`
- [x] 1.2 Move the spec model to `grafana/service_specs.py`
- Verification: `$ uv run devops ci test tests/grafana tests/k8s/test_k8s_catalog.py`

## 2. Documents

- [x] 2.1 Spec delta of `mcp-server-image`; no user document changes
- Verification: `$ uv run devops openspec check`
7 changes: 7 additions & 0 deletions openspec/specs/mcp-server-image/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,10 @@ The `mcp-server` target SHALL copy `kubectl` and `helm` from the devtools image
#### Scenario: The cluster tools run
- **WHEN** the stage `mcp-server-smoke` of `smoke.Dockerfile` runs `kubectl version --client` and `helm version` on the image
- **THEN** each command exits 0 and prints the version of the devtools image

### Requirement: The commands import with no dev-only package
Each module of `devops_cli.commands` SHALL import in an install with no `dev` dependency group, such as the `mcp-server` image.

#### Scenario: Dev-only packages are blocked
- **WHEN** a Python process blocks `grafana_foundation_sdk` and imports each module of `devops_cli.commands`
- **THEN** no import fails
65 changes: 6 additions & 59 deletions src/devops_cli/grafana/service_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,19 @@

import argparse
import json
import tomllib
import warnings
from collections.abc import Iterator, Sequence
from dataclasses import dataclass
from decimal import Decimal
from pathlib import Path
from string import Template
from typing import Any, Final, Literal

from pydantic import BaseModel, ConfigDict, Field
from typing import Any, Final

from devops_cli.design import tokens
from devops_cli.grafana.service_specs import (
ServiceSpec,
load_specs,
)

with warnings.catch_warnings():
# The classic builder is the one whose JSON the dashboard sidecar provisions.
Expand All @@ -52,13 +53,7 @@
from grafana_foundation_sdk.models import common
from grafana_foundation_sdk.models import dashboard as dashboard_models

type Resource = Literal["memory", "cpu"]
type ProfileType = Literal[
"process_cpu:cpu:nanoseconds:cpu:nanoseconds", "memory:inuse_space:bytes:space:bytes"
]

# The file of the specs, and the file that `make dashboards` writes for each spec next to it.
SPEC_FILE_NAME: Final = "services.toml"
# The file that `make dashboards` writes for each spec next to the spec file.
DASHBOARD_SUFFIX: Final = ".json"

# The Grafana color names that change with the theme (docs/DESIGN.md, "Grafana"): `text` for a
Expand Down Expand Up @@ -119,48 +114,6 @@
}


class ServiceSpec(BaseModel):
"""The spec of the dashboard of one Kubernetes service: its identity, its request metrics
and its SLO. Each selector can name the Grafana variables `$namespace` and `$workload`."""

model_config = ConfigDict(frozen=True, extra="forbid")

uid: str = Field(pattern=r"^[a-z0-9][a-z0-9-]{0,39}$")
title: str
description: str
namespace: str
workload: str
variables: bool = False
# The counter of the requests of the service, with the matchers that select the service. It
# ends with its matchers in braces, because `errors` goes into them.
requests: str = Field(
default='traefik_service_requests_total{service=~"$namespace-$workload-[0-9]+@kubernetes"}',
pattern=r"\}$",
)
# The matcher, added to `requests`, that selects the failed requests.
errors: str = 'code=~"5.."'
# The histogram buckets of the latency of the successful requests.
latency: str = (
"traefik_service_request_duration_seconds_bucket"
'{service=~"$namespace-$workload-[0-9]+@kubernetes", code!~"5.."}'
)
slo_target: Decimal = Field(default=Decimal("0.999"), gt=0, lt=1)
slo_window_days: int = Field(default=30, gt=0)
saturation: tuple[Resource, ...] = Field(default=("memory", "cpu"), min_length=1, max_length=2)
logs: bool = True
profiles: tuple[ProfileType, ...] = ()

@property
def budget(self) -> Decimal:
"""The error budget: the share of the requests that can fail."""
return 1 - self.slo_target

@property
def window(self) -> str:
"""The SLO window as a PromQL duration."""
return f"{self.slo_window_days}d"


@dataclass(frozen=True)
class _Line:
"""One line of a time series: its legend name, its query, its color and its dash. A
Expand Down Expand Up @@ -846,12 +799,6 @@ def dashboard_text(spec: ServiceSpec) -> str:
return json.dumps(service_dashboard(spec), indent=2, sort_keys=True, ensure_ascii=False) + "\n"


def load_specs(spec_file: Path) -> list[ServiceSpec]:
"""The specs of the `[[service]]` tables of `spec_file`."""
document = tomllib.loads(spec_file.read_text(encoding="utf-8"))
return [ServiceSpec.model_validate(entry) for entry in document["service"]]


def write_dashboards(spec_file: Path) -> list[Path]:
"""Write `<uid>.json` next to `spec_file` for each of its specs, and return the paths."""
written = []
Expand Down
71 changes: 71 additions & 0 deletions src/devops_cli/grafana/service_specs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""The specs of the service dashboards (`[[service]]` tables), with no Grafana SDK (#7212).

`grafana/service_dashboard.py` builds the dashboard JSON with `grafana-foundation-sdk`, which is a
dev-only package. The commands that only read the specs, such as the service catalog, import this
module.
"""

from __future__ import annotations

import tomllib
from decimal import Decimal
from pathlib import Path
from typing import Final, Literal

from pydantic import BaseModel, ConfigDict, Field

type Resource = Literal["memory", "cpu"]
type ProfileType = Literal[
"process_cpu:cpu:nanoseconds:cpu:nanoseconds", "memory:inuse_space:bytes:space:bytes"
]

# The file of the specs.
SPEC_FILE_NAME: Final = "services.toml"


class ServiceSpec(BaseModel):
"""The spec of the dashboard of one Kubernetes service: its identity, its request metrics
and its SLO. Each selector can name the Grafana variables `$namespace` and `$workload`."""

model_config = ConfigDict(frozen=True, extra="forbid")

uid: str = Field(pattern=r"^[a-z0-9][a-z0-9-]{0,39}$")
title: str
description: str
namespace: str
workload: str
variables: bool = False
# The counter of the requests of the service, with the matchers that select the service. It
# ends with its matchers in braces, because `errors` goes into them.
requests: str = Field(
default='traefik_service_requests_total{service=~"$namespace-$workload-[0-9]+@kubernetes"}',
pattern=r"\}$",
)
# The matcher, added to `requests`, that selects the failed requests.
errors: str = 'code=~"5.."'
# The histogram buckets of the latency of the successful requests.
latency: str = (
"traefik_service_request_duration_seconds_bucket"
'{service=~"$namespace-$workload-[0-9]+@kubernetes", code!~"5.."}'
)
slo_target: Decimal = Field(default=Decimal("0.999"), gt=0, lt=1)
slo_window_days: int = Field(default=30, gt=0)
saturation: tuple[Resource, ...] = Field(default=("memory", "cpu"), min_length=1, max_length=2)
logs: bool = True
profiles: tuple[ProfileType, ...] = ()

@property
def budget(self) -> Decimal:
"""The error budget: the share of the requests that can fail."""
return 1 - self.slo_target

@property
def window(self) -> str:
"""The SLO window as a PromQL duration."""
return f"{self.slo_window_days}d"


def load_specs(spec_file: Path) -> list[ServiceSpec]:
"""The specs of the `[[service]]` tables of `spec_file`."""
document = tomllib.loads(spec_file.read_text(encoding="utf-8"))
return [ServiceSpec.model_validate(entry) for entry in document["service"]]
12 changes: 3 additions & 9 deletions src/devops_cli/k8s/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,9 @@

from devops_cli.core.serialization import YAML_SAFE_LOADER
from devops_cli.exceptions.k8s import CatalogError
from devops_cli.grafana.service_dashboard import (
SPEC_FILE_NAME as DASHBOARD_SPEC_FILE,
)
from devops_cli.grafana.service_dashboard import (
ServiceSpec,
)
from devops_cli.grafana.service_dashboard import (
load_specs as load_dashboard_specs,
)
from devops_cli.grafana.service_specs import SPEC_FILE_NAME as DASHBOARD_SPEC_FILE
from devops_cli.grafana.service_specs import ServiceSpec
from devops_cli.grafana.service_specs import load_specs as load_dashboard_specs
from devops_cli.k8s.app_sources import (
SourceTrees,
application_sources,
Expand Down
3 changes: 1 addition & 2 deletions tests/grafana/test_service_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,12 @@
from devops_cli.design import THEME_MODES, tokens
from devops_cli.grafana.service_dashboard import (
GRAFANA_COLOR_NAMES,
SPEC_FILE_NAME,
ServiceSpec,
dashboard_text,
load_specs,
main,
service_dashboard,
)
from devops_cli.grafana.service_specs import SPEC_FILE_NAME, load_specs
from tests.support.design_tokens import DESIGN_SPEC, GRAFANA_BACKGROUNDS
from tests.support.paths import REPO_ROOT

Expand Down
49 changes: 49 additions & 0 deletions tests/grafana/test_service_specs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""The commands import without the dev-only Grafana SDK (#7212).

`grafana/service_specs.py` holds the specs of the service dashboards with no SDK. An install with no
`dev` dependency group, such as the MCP server image, must import each command module: the MCP
server imports them all to build its tools.
"""

from __future__ import annotations

import os
import subprocess
import sys

import pytest

from tests.support.paths import REPO_ROOT

CHILD_TIMEOUT_SECONDS = 180

# The child blocks the SDK (`None` in `sys.modules` fails its import), then imports every module of
# `devops_cli.commands` and prints each one that fails.
CHILD_SOURCE = """
import importlib, pkgutil, sys

sys.modules["grafana_foundation_sdk"] = None

import devops_cli.commands

for found in pkgutil.walk_packages(devops_cli.commands.__path__, "devops_cli.commands."):
try:
importlib.import_module(found.name)
except ModuleNotFoundError as error:
print(f"{found.name}: {error}")
"""


@pytest.mark.live("python")
def test_each_command_module_imports_without_the_grafana_sdk() -> None:
child = subprocess.run(
[sys.executable, "-P", "-c", CHILD_SOURCE],
env={**os.environ, "PYTHONPATH": str(REPO_ROOT / "src")},
capture_output=True,
text=True,
timeout=CHILD_TIMEOUT_SECONDS,
check=False,
)

assert child.returncode == 0, child.stderr[-2000:]
assert child.stdout == ""