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
4 changes: 4 additions & 0 deletions docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,10 @@ High-density product roadmap, engineering milestones, and open-source integratio
- [ ] **Local-Path Provisioner Volume Reclaim Failures (P2 - Medium)**:
- *Context & Rationale*: `VolumeFailedDelete` with `create process timeout after 120 seconds` leaves the helper pod `Terminating` indefinitely — three days, in the observed case — and the `PersistentVolume` is never reclaimed. Storage leaks silently and the only evidence is an event nobody is watching.
- *Constraint*: Reclamation deletes data. Any automated remediation must confirm the volume is genuinely orphaned rather than merely slow to detach, so the first deliverable is detection and reporting, not deletion.
- [ ] **Reachable `--dry-run` Previews for Delegated Commands (P1 - High)**:
- *Context & Rationale*: Every command group is registered lazily as a module path, and the lazy proxy short-circuits under dry-run: it prints the command line you typed and returns without loading the target module. So no command in the CLI ever reaches its own dry-run branch. 160 of 306 registered commands contain one — detailed previews of exactly what would be written — and none of them is reachable from the command line. `devops k8s configure-urls --dry-run` had eight hardcoded NodePort URLs pointing at a minikube node nobody in this project uses, and the reason it went unnoticed is that the block could not be reached.
- *Deliverable*: Delegate under dry-run so a command renders its own preview, with the generic line kept for commands that have none.
- *Constraint*: The short-circuit is load-bearing. 146 registered commands have no dry-run branch, and delegating to those would execute them for real under a flag that promises the opposite. Each has to be classified — read-only, or needing a branch — before the switch flips, so the audit is the work and the switch is the last step.
- [ ] **Model-in-the-Loop Prompt Benchmarking (P1 - High)**:
- *Context & Rationale*: `devops ai prompt-eval` now measures the deterministic suppression layer against recorded verdicts, which is honest but covers only the checks that run before a model is asked. Nothing measures a prompt. The two hot-path prompts were compressed by 32% in v0.2.22 on the argument that no decision was lost, and that argument rests on a keyword coverage test rather than on any observed change in output. Every prompt edit since this project began has shipped the same way.
- *Deliverable*: Replay a fixed corpus of reviewed segments through a candidate prompt and the current one, with a pinned model and temperature, and report the difference in findings produced, findings later invalidated, and tokens spent. A prompt change becomes a measured trade rather than an assertion.
Expand Down
85 changes: 64 additions & 21 deletions src/devops_cli/commands/k8s/networking.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
CONST_ADDRESSING_MODES,
CONST_ADDRESSING_NODEPORT,
CONST_ADDRESSING_PROXY,
CONST_K8S_URL_SCHEME,
CONST_PLACEHOLDER_NODE,
CONST_PLACEHOLDER_PORT,
)
from devops_cli.config.defaults import (
DEFAULT_ARGOCD_PORT,
Expand Down Expand Up @@ -384,6 +387,66 @@ def _configure_proxy_urls(
configured[key] = address


# The endpoints nodeport addressing writes, per stack. Proxy addressing derives its own
# from `_PROXY_TARGETS_*`, which is why the two previews differ: proxy mode configures only
# the services it can address through the API server.
_NODEPORT_KEYS_INFRA: tuple[str, ...] = (
"argocd.url",
"grafana.url",
"prometheus.url",
"jaeger.url",
"otel.endpoint",
)
_NODEPORT_KEYS_LLM: tuple[str, ...] = (
"ai.ollama_urls",
"open_webui.url",
"qdrant.url",
"valkey.url",
)


def _preview_proxy_addresses(stacks: Sequence[str]) -> dict[str, str]:
"""Render the cluster-native address each key will receive."""
targets: list[tuple[str, str, tuple[str, ...], tuple[str, ...]]] = []
if "infra" in stacks:
targets.extend(_PROXY_TARGETS_INFRA)
if "llm" in stacks:
targets.extend(_PROXY_TARGETS_LLM)

preview: dict[str, str] = {}
for key, namespace, patterns, port_hints in targets:
port = next((hint for hint in port_hints if hint.isdigit()), CONST_PLACEHOLDER_PORT)
preview[key] = f"{CONST_K8S_URL_SCHEME}://{namespace}/{patterns[0]}:{port}"
return preview


def _preview_nodeport_addresses(stacks: Sequence[str]) -> dict[str, str]:
"""Render the shape of a node address, which is only known after discovery.

A fixed address was written here -- a minikube node IP with assigned port numbers --
so the preview described a cluster the command was not going to configure, and did so
identically whichever addressing mode was asked for.
"""
keys: list[str] = []
if "infra" in stacks:
keys.extend(_NODEPORT_KEYS_INFRA)
if "llm" in stacks:
keys.extend(_NODEPORT_KEYS_LLM)

preview: dict[str, str] = {}
for key in keys:
scheme = "tcp" if key.startswith("valkey") else "http"
preview[key] = f"{scheme}://{CONST_PLACEHOLDER_NODE}:{CONST_PLACEHOLDER_PORT}"
return preview


def _dry_run_preview(stacks: Sequence[str], addressing: str) -> dict[str, str]:
"""Describe what `configure-urls` would write under the requested addressing mode."""
if addressing == CONST_ADDRESSING_PROXY:
return _preview_proxy_addresses(stacks)
return _preview_nodeport_addresses(stacks)


def configure_urls(
stack: Annotated[str, typer.Option("--stack", "-s", help=HELP.k8s.stack)] = DEFAULT_K8S_STACK,
context: Annotated[
Expand All @@ -406,31 +469,11 @@ def configure_urls(

selected_stacks = _resolve_stacks(stack)

dry_run_details: dict[str, str] = {}
if "infra" in selected_stacks:
dry_run_details.update(
{
"argocd.url": "http://192.168.49.2:30080",
"grafana.url": "http://192.168.49.2:32047",
"prometheus.url": "http://192.168.49.2:30090",
"jaeger.url": "http://192.168.49.2:30686",
}
)
if "llm" in selected_stacks:
dry_run_details.update(
{
"ai.ollama_urls": "http://192.168.49.2:31434",
"open_webui.url": "http://192.168.49.2:30080",
"qdrant.url": "http://192.168.49.2:30633",
"valkey.url": "tcp://192.168.49.2:30379",
}
)

if is_dry_run():
render_dry_run_result(
command="devops k8s configure-urls",
action="configure_monitoring_urls",
details=dry_run_details,
details=_dry_run_preview(selected_stacks, addressing),
)
return

Expand Down
5 changes: 5 additions & 0 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -1493,3 +1493,8 @@
# from one `feat(release)` pull request, so the summary lists that pull request alone and
# carries no information the changelog does not.
CONST_GENERATED_NOTES_HEADING: Final[str] = "What's Changed"
# Stand-ins for values a dry run cannot know. A node address and an assigned NodePort are
# only resolved by talking to the cluster, so a preview names their shape rather than
# inventing a concrete one that describes some other cluster.
CONST_PLACEHOLDER_NODE: Final[str] = "<node>"
CONST_PLACEHOLDER_PORT: Final[str] = "<port>"
2 changes: 2 additions & 0 deletions src/devops_cli/dry_run/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from devops_cli.dry_run.decorator import dry_run_command
from devops_cli.dry_run.models import CommandDryRunResult
from devops_cli.dry_run.state import (
dry_run_requested_by_environment,
format_command,
is_dry_run,
is_dry_run_requested,
Expand All @@ -15,6 +16,7 @@
__all__ = [
"CommandDryRunResult",
"dry_run_command",
"dry_run_requested_by_environment",
"format_command",
"is_dry_run",
"is_dry_run_requested",
Expand Down
18 changes: 18 additions & 0 deletions src/devops_cli/dry_run/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,33 @@

_DRY_RUN_ENV = "DEVOPS_CLI_DRY_RUN"

# Whether this process turned dry-run on, as opposed to inheriting it. The variable alone
# cannot answer that, and the difference decides whether a command without `--dry-run`
# should clear it: a request the caller exported outlives one invocation, a `--dry-run`
# flag does not.
_ACTIVATED_HERE = False


def set_dry_run(enabled: bool) -> None:
"""Set global dry-run mode in environment."""
global _ACTIVATED_HERE
_ACTIVATED_HERE = enabled
if enabled:
os.environ[_DRY_RUN_ENV] = "true"
return
os.environ.pop(_DRY_RUN_ENV, None)


def dry_run_requested_by_environment() -> bool:
"""Report whether the caller's environment asked for dry-run.

A `--dry-run` flag applies to the invocation that carried it, so a later command in the
same process must not inherit it. An exported `DEVOPS_CLI_DRY_RUN` applies to every
command in that environment, so a later command must not discard it.
"""
return is_dry_run() and not _ACTIVATED_HERE


def is_dry_run() -> bool:
"""Check if dry-run mode is enabled."""
value = os.environ.get(_DRY_RUN_ENV, "")
Expand Down
13 changes: 10 additions & 3 deletions src/devops_cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

from devops_cli import __version__
from devops_cli.core.cli import new_typer
from devops_cli.dry_run import is_dry_run, set_dry_run
from devops_cli.dry_run import dry_run_requested_by_environment, is_dry_run, set_dry_run
from devops_cli.lang import HELP

_timing: dict[str, float] = {}
Expand Down Expand Up @@ -224,8 +224,15 @@ def main(
) -> None:
"""DevOps CLI — manage repos, SSH keys, Kubernetes, and more."""
_timing["start"] = time.monotonic()
set_dry_run(dry_run)
ctx.obj = {"dry_run": dry_run}
# The flag turns dry-run on; its absence must not turn off a `DEVOPS_CLI_DRY_RUN`
# the caller exported. `set_dry_run(False)` clears that variable, so every invocation
# without the flag discarded it -- a wrapper or CI job that exported it got a live run
# and no indication that its request had been dropped. A flag set by an earlier
# invocation in this process is a different thing and is still cleared, or one
# `--dry-run` would latch for the life of the process.
requested = dry_run or dry_run_requested_by_environment()
set_dry_run(requested)
ctx.obj = {"dry_run": requested}


def main_entry() -> None:
Expand Down
66 changes: 66 additions & 0 deletions tests/test_k8s_proxy_addressing.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,69 @@ def test_a_failing_service_address_falls_back_and_names_the_endpoint() -> None:
summary = data_providers.fetch_telemetry_status()

assert (address in summary.error_message, summary.source) == (True, "in-process")


# =============================================================================
# Dry-run preview
# =============================================================================


def test_the_preview_follows_the_requested_addressing_mode() -> None:
"""A fixed block of NodePort URLs was previewed whatever `--addressing` asked for.

Running `--addressing proxy --dry-run` described the NodePort result, which is not what
the command would have written.
"""
from devops_cli.commands.k8s.networking import _dry_run_preview

proxy = _dry_run_preview(["llm"], "proxy")
nodeport = _dry_run_preview(["llm"], "nodeport")
assert proxy != nodeport


def test_the_proxy_preview_renders_cluster_native_addresses() -> None:
"""Proxy addressing writes `k8s://` addresses, so the preview must show those."""
from devops_cli.commands.k8s.networking import _dry_run_preview

preview = _dry_run_preview(["llm"], "proxy")
assert preview["qdrant.url"].startswith("k8s://llm/qdrant:")


def test_the_preview_carries_no_host_address() -> None:
"""A minikube node IP was hardcoded here with assigned port numbers.

It described some other cluster on every run, and it was the only concrete private
address left in `src`.
"""
import re

from devops_cli.commands.k8s.networking import _dry_run_preview

rendered = " ".join(
value
for mode in ("proxy", "nodeport")
for value in _dry_run_preview(["infra", "llm"], mode).values()
)
assert re.search(r"\b\d{1,3}(\.\d{1,3}){3}\b", rendered) is None


def test_the_nodeport_preview_names_the_shape_of_what_it_cannot_know() -> None:
"""A node address and an assigned port are only resolved by asking the cluster."""
from devops_cli.commands.k8s.networking import _dry_run_preview

preview = _dry_run_preview(["infra"], "nodeport")
assert preview["grafana.url"] == "http://<node>:<port>"


def test_the_valkey_preview_keeps_its_scheme() -> None:
"""Valkey is addressed over tcp, not http; a preview that said otherwise would mislead."""
from devops_cli.commands.k8s.networking import _dry_run_preview

assert _dry_run_preview(["llm"], "nodeport")["valkey.url"].startswith("tcp://")


def test_a_stack_that_was_not_selected_is_absent_from_the_preview() -> None:
"""The preview describes what this invocation would write, not the full catalogue."""
from devops_cli.commands.k8s.networking import _dry_run_preview

assert "qdrant.url" not in _dry_run_preview(["infra"], "proxy")
62 changes: 62 additions & 0 deletions tests/test_main_dry_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,65 @@ def _fake_delegate(module_path: str, command_name: str, args: list[str]) -> None
result = runner.invoke(main_module.app, ["repos", "sync", "--dry-run"])

assert (result.exit_code, delegated_args) == (0, ["sync", "--dry-run"])


def test_an_exported_dry_run_variable_is_honoured(monkeypatch) -> None:
"""`is_dry_run()` reads `DEVOPS_CLI_DRY_RUN`, but the root callback cleared it.

Without the flag the callback called `set_dry_run(False)`, which pops the variable, so
a wrapper or CI job that exported it got a live run and no indication that its request
had been dropped. That is how a `sync-notes --all` intended as a preview republished
every release description in this repository.
"""
called = False

def _fake_delegate(module_path: str, command_name: str, args: list[str]) -> None:
nonlocal called
called = True

from devops_cli.dry_run import set_dry_run

monkeypatch.setattr(main_module, "_delegate", _fake_delegate)
set_dry_run(False) # this process has not asked; the variable below is the caller's
monkeypatch.setenv("DEVOPS_CLI_DRY_RUN", "1")

result = runner.invoke(main_module.app, ["repos", "sync"])

assert (result.exit_code, called) == (0, False)


def test_a_dry_run_flag_does_not_latch_for_later_commands(monkeypatch) -> None:
"""The flag applies to the invocation carrying it, not to the rest of the process.

Honouring an inherited variable naively made one `--dry-run` turn every later command
in the same process into a preview, which in a long-lived process means it never runs
anything again.
"""
calls: list[str] = []

def _fake_delegate(module_path: str, command_name: str, args: list[str]) -> None:
calls.append(command_name)

monkeypatch.setattr(main_module, "_delegate", _fake_delegate)
monkeypatch.delenv("DEVOPS_CLI_DRY_RUN", raising=False)

runner.invoke(main_module.app, ["--dry-run", "repos", "sync"])
runner.invoke(main_module.app, ["repos", "sync"])

assert calls == ["repos"]


def test_no_flag_and_no_variable_still_executes(monkeypatch) -> None:
"""Honouring the variable must not leave dry-run latched on for ordinary runs."""
called = False

def _fake_delegate(module_path: str, command_name: str, args: list[str]) -> None:
nonlocal called
called = True

monkeypatch.setattr(main_module, "_delegate", _fake_delegate)
monkeypatch.delenv("DEVOPS_CLI_DRY_RUN", raising=False)

result = runner.invoke(main_module.app, ["repos", "sync"])

assert (result.exit_code, called) == (0, True)
Loading