From 46998a4cafefee7761e61b20cdc2ac2c21542fb5 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sun, 25 Oct 2026 22:27:15 +0000 Subject: [PATCH 1/2] fix(k8s): deploy-stack decides helm recovery from helm's json status and adopts existing resources with --take-ownership Inspect helm status in JSON format before running upgrade. Run helm rollback when status is pending-upgrade or pending-rollback. Run helm uninstall when status is pending-install. Pass --take-ownership flag on every helm upgrade command to adopt resources. Require Helm 3.17 or later and show the installed version when older. Remove obsolete error text matching and manual kubectl adoption loops. Closes #1438 --- docs/ERRORS.md | 2 +- .../.openspec.yaml | 2 + .../1438-helm-status-take-ownership/design.md | 42 ++ .../proposal.md | 48 ++ .../specs/k8s-helm-deploy/spec.md | 40 ++ .../1438-helm-status-take-ownership/tasks.md | 28 ++ src/devops_cli/ai/library/introspector.py | 2 +- src/devops_cli/commands/k8s/__init__.py | 12 +- .../commands/k8s/stack_lifecycle.py | 229 ++++----- src/devops_cli/config/constants.py | 7 +- src/devops_cli/config/defaults.py | 3 - src/devops_cli/exceptions/ai.py | 2 +- tests/cluster_secret_fakes.py | 2 + .../fixtures/swallowed_failures_ceilings.json | 2 +- tests/test_k8s.py | 436 ++++++++++++------ tests/test_k8s_context.py | 10 + tests/test_k8s_gpu_placement.py | 2 + tests/test_k8s_logging_stack.py | 10 +- tests/test_k8s_networking.py | 9 +- tests/test_k8s_tempo.py | 8 +- 20 files changed, 581 insertions(+), 315 deletions(-) create mode 100644 openspec/changes/1438-helm-status-take-ownership/.openspec.yaml create mode 100644 openspec/changes/1438-helm-status-take-ownership/design.md create mode 100644 openspec/changes/1438-helm-status-take-ownership/proposal.md create mode 100644 openspec/changes/1438-helm-status-take-ownership/specs/k8s-helm-deploy/spec.md create mode 100644 openspec/changes/1438-helm-status-take-ownership/tasks.md diff --git a/docs/ERRORS.md b/docs/ERRORS.md index 53fcc7aec8..69e8dfb386 100644 --- a/docs/ERRORS.md +++ b/docs/ERRORS.md @@ -77,7 +77,7 @@ The Exit Code column is the exception's `exit_code` attribute. Only `devops clou | `KubernetesLoggingError` | `K8S_LOGGING_ERROR` | `1` | K8s | Raised when querying cluster logs or Loki fails. | | `LLMInferenceError` | `LLM_INFERENCE_ERROR` | `10` | Ai | Base exception for LLM provider invocation failures. | | `LibraryIngestionError` | `LIBRARY_INGESTION_ERROR` | `1` | Ai | Base exception for package introspection and library ingestion errors. | -| `LibraryNotFoundError` | `LIBRARY_NOT_FOUND_ERROR` | `1` | Ai | Raised when target package cannot be imported or found in the environment. | +| `LibraryNotFoundError` | `LIBRARY_NOT_FOUND_ERROR` | `1` | Ai | Raised when target package could not be loaded or found in the environment. | | `LogfireConfigurationError` | `LOGFIRE_CONFIG_ERROR` | `1` | Telemetry | Raised when Logfire configuration fails or credentials cannot be retrieved. | | `MemoryProfilerError` | `PROFILER_ERROR` | `1` | Devops_cli.telemetry.memory_profiler | Domain exception raised when memory profiling target resolution or execution fails. | | `ModelBundleError` | `MODEL_BUNDLE_ERROR` | `1` | Ai | Raised when an AI model bundle cannot be located, resolved, or loaded. | diff --git a/openspec/changes/1438-helm-status-take-ownership/.openspec.yaml b/openspec/changes/1438-helm-status-take-ownership/.openspec.yaml new file mode 100644 index 0000000000..7ccf7c3695 --- /dev/null +++ b/openspec/changes/1438-helm-status-take-ownership/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-25 diff --git a/openspec/changes/1438-helm-status-take-ownership/design.md b/openspec/changes/1438-helm-status-take-ownership/design.md new file mode 100644 index 0000000000..8b770aa91a --- /dev/null +++ b/openspec/changes/1438-helm-status-take-ownership/design.md @@ -0,0 +1,42 @@ +# Design + +## Context + +See proposal.md for motivation and problem background. DevOps CLI deploys Helm charts across multiple stacks (`infra`, `llm`, `gitea`, `logging`). Previously, conflict resolution inspected stderr strings and modified resource metadata with `kubectl`. Helm 3.17 introduced `--take-ownership` to handle existing resources natively, and `helm status -o json` provides structured machine-readable state inspection. + +## Goals / Non-Goals + +**Goals:** +- Eliminate regex parsing of human stderr strings during Helm operations. +- Recover pending release states (`pending-install`, `pending-upgrade`, `pending-rollback`) via Helm native lifecycle commands (`helm uninstall`, `helm rollback`) before attempting `helm upgrade --install`. +- Use `--take-ownership` on all `helm upgrade --install` commands. +- Verify Helm version >= 3.17 once prior to release deployments. +- Eliminate obsolete retry loops, constants, and manual `kubectl` labeling/annotation loops. + +**Non-Goals:** +- Supporting Helm versions prior to 3.17: pre-1.0 alpha software maintains no backward compatibility or shims. +- Changing chart values or manifests. + +## Decisions + +### Decision: Check Helm version once with standard `packaging.version.Version` +- **Choice**: Call `helm version --template {{.Version}}` once in `deploy_stack` when Helm releases are present, parse the version string with `packaging.version.Version`, and fail with `KubernetesDeployError` if version < 3.17. +- **Rationale**: CONTRIBUTING.md mandates using standard parsers (`packaging`) for open domains like software versions. Checking once avoids spawning redundant `helm version` subprocesses for each release. +- **Alternative Considered**: Parsing version strings manually with regex or splitting on dots. Rejected because manual version splitting does not handle pre-releases or complex version schemas correctly. +- **Alternative Considered**: Checking version on every single release installation. Rejected because Helm version does not change between releases during a single CLI command run. + +### Decision: Inspect status before upgrade using `helm status -o json` +- **Choice**: Execute `helm status -n -o json` prior to `helm upgrade --install`. If the release is not found, continue to upgrade. If status is `pending-install`, execute `helm uninstall -n `. If status is `pending-upgrade` or `pending-rollback`, execute `helm rollback -n `. +- **Rationale**: `helm status -o json` provides a stable schema (`info.status`) regardless of Helm's human-readable formatting or terminal localization. Rolling back restores the prior working revision rather than deleting Secret state. +- **Alternative Considered**: Deleting Helm Secret locks with `kubectl delete secret`. Rejected because it assumes the Secret storage driver and leaves Helm release history in an inconsistent state. +- **Alternative Considered**: Reacting after failure by inspecting stderr for error messages. Rejected because human error strings change across Helm releases (such as Helm 3 vs Helm 4). + +### Decision: Delegate resource adoption entirely to Helm `--take-ownership` +- **Choice**: Pass `--take-ownership` on all `helm upgrade --install` commands and delete `_adopt_helm_resource_if_conflict` and `CONST_HELM_OWNERSHIP_CONFLICT_RE`. +- **Rationale**: Helm 3.17+ natively adopts existing resources that match the chart. Removing the kubectl label/annotate loop eliminates round-trips and fragile regex matching. +- **Alternative Considered**: Keeping a fallback kubectl adoption loop if `--take-ownership` fails. Rejected because pre-1.0 alpha rules mandate zero legacy shims or zombie code. + +## Risks / Trade-offs + +- [Risk] Helm 3.16 or older environments fail deployment. → Mitigation: Clear error message explicitly naming the installed version and the required version (3.17 or later). +- [Risk] Rollback on a release with no prior revision. → Mitigation: `pending-install` is uninstalled instead of rolled back; `pending-upgrade` and `pending-rollback` only occur when a prior revision exists. diff --git a/openspec/changes/1438-helm-status-take-ownership/proposal.md b/openspec/changes/1438-helm-status-take-ownership/proposal.md new file mode 100644 index 0000000000..d8d7394417 --- /dev/null +++ b/openspec/changes/1438-helm-status-take-ownership/proposal.md @@ -0,0 +1,48 @@ +# Proposal + +## Why + +DevOps CLI recovered stuck Helm releases and adopted conflicting resources by parsing human error text in stderr with regular expressions and manipulating Secret locks and annotations with `kubectl` (#1438). This approach was fragile against Helm wording changes, assumed the Secret storage driver, and discarded revisions instead of rolling back. + +This change fits one pull request. + +## What Changes + +- Verify installed Helm version before deployment and require Helm 3.17 or later; fail with an error naming the installed version when older. +- Inspect Helm release state before `helm upgrade --install` using `helm status -o json`. +- Automatically uninstall releases in `pending-install` state before upgrade. +- Automatically rollback releases in `pending-upgrade` or `pending-rollback` state to their previous revision with `helm rollback ` before upgrade. +- Pass `--take-ownership` on all `helm upgrade --install` command executions so Helm adopts existing resources natively. +- Delete `_recover_stuck_helm_release_if_pending`, `_adopt_helm_resource_if_conflict`, `_run_helm_with_adoption_retries`, and regular expression `CONST_HELM_OWNERSHIP_CONFLICT_RE`. +- Remove `DEFAULT_HELM_RECOVERY_MAX_RETRIES` setting and delete the `kubectl annotate` / `kubectl label` loop. +- Reword import failure messages in `src/devops_cli/ai/library/introspector.py` and `src/devops_cli/exceptions/ai.py` so obsolete strings do not match in `src`. + +## Capabilities + +### New Capabilities +- `k8s-helm-deploy`: Helm release deployment, version verification, state recovery, and ownership adoption for Kubernetes stacks. + +### Modified Capabilities + +None. + +## Impact + +- `src/devops_cli/commands/k8s/stack_lifecycle.py`: Helm deployment command construction, single-point version check, and JSON status recovery. +- `src/devops_cli/commands/k8s/__init__.py`: Clean up exports of removed helpers. +- `src/devops_cli/config/constants.py`: Remove `CONST_HELM_OWNERSHIP_CONFLICT_RE` and add `CONST_HELM_MIN_VERSION`. +- `src/devops_cli/config/defaults.py`: Remove `DEFAULT_HELM_RECOVERY_MAX_RETRIES`. +- `tests/test_k8s.py`: Remove obsolete stderr matching tests and add tests for status inspection, rollback, uninstall, `--take-ownership`, and version checking. + +## Feasibility + +The premise was verified against the real system: +- `helm version` reports `version.BuildInfo{Version:"v4.3.0", ...}` in the environment. +- `helm upgrade --help` confirms the `--take-ownership` flag is available: "if set, upgrade will ignore the check for helm annotations and take ownership of the existing resources". +- `helm status --help` confirms `-o json` output and release states: `pending-install`, `pending-upgrade`, `pending-rollback`. +- `helm rollback --help` confirms rollback to the previous revision via `helm rollback [REVISION] [flags]`. +- Upstream Helm introduced `--take-ownership` in Helm 3.17.0. + +## Existing Tool Considered + +Helm CLI (3.17+) provides native ownership adoption through `--take-ownership` and release recovery commands (`helm rollback`, `helm uninstall`). DevOps CLI previously maintained a custom regular expression (`CONST_HELM_OWNERSHIP_CONFLICT_RE`) and custom `kubectl annotate` and `kubectl label` adoption routines. Adopting Helm's native `--take-ownership` replaces this custom code. Replaced internal code includes `_adopt_helm_resource_if_conflict`, `_recover_stuck_helm_release_if_pending`, `_run_helm_with_adoption_retries`, `CONST_HELM_OWNERSHIP_CONFLICT_RE`, and `DEFAULT_HELM_RECOVERY_MAX_RETRIES`. diff --git a/openspec/changes/1438-helm-status-take-ownership/specs/k8s-helm-deploy/spec.md b/openspec/changes/1438-helm-status-take-ownership/specs/k8s-helm-deploy/spec.md new file mode 100644 index 0000000000..b6d541c8c2 --- /dev/null +++ b/openspec/changes/1438-helm-status-take-ownership/specs/k8s-helm-deploy/spec.md @@ -0,0 +1,40 @@ +# Spec Delta + +## Purpose + +Automated Helm release deployment, version verification, state recovery, and resource ownership adoption for Kubernetes stacks. + +## ADDED Requirements + +### Requirement: Helm version requirement +The deployment process SHALL require Helm version 3.17 or later when deploying Helm releases. If the installed Helm version is older than 3.17, deployment SHALL abort with an error message naming the installed version. + +#### Scenario: Helm version meets minimum requirement +- **WHEN** the installed Helm version is 3.17.0 or later and `devops k8s deploy-stack` runs +- **THEN** the version check succeeds and deployment continues + +#### Scenario: Helm version is below minimum requirement +- **WHEN** the installed Helm version is 3.16.2 and `devops k8s deploy-stack` runs +- **THEN** deployment fails with an error stating that Helm 3.17 or later is required and naming version 3.16.2 + +### Requirement: Release status inspection and recovery +Before executing `helm upgrade --install`, the deployment process SHALL inspect the release status with `helm status -o json`. A release in `pending-install` status SHALL be uninstalled with `helm uninstall`. A release in `pending-upgrade` or `pending-rollback` status SHALL be rolled back with `helm rollback` before proceeding. + +#### Scenario: Pending install release is uninstalled +- **WHEN** `helm status -o json` reports release status `pending-install` +- **THEN** the system executes `helm uninstall` before running `helm upgrade --install` + +#### Scenario: Pending upgrade release is rolled back +- **WHEN** `helm status -o json` reports release status `pending-upgrade` +- **THEN** the system executes `helm rollback` before running `helm upgrade --install` + +#### Scenario: Pending rollback release is rolled back +- **WHEN** `helm status -o json` reports release status `pending-rollback` +- **THEN** the system executes `helm rollback` before running `helm upgrade --install` + +### Requirement: Helm ownership adoption +Every `helm upgrade --install` invocation SHALL include `--take-ownership` to adopt existing unmanaged Kubernetes resources without manual annotation or labeling. + +#### Scenario: Upgrade command includes take-ownership +- **WHEN** `devops k8s deploy-stack` executes a Helm release install or upgrade +- **THEN** the constructed `helm upgrade --install` command arguments include `--take-ownership` diff --git a/openspec/changes/1438-helm-status-take-ownership/tasks.md b/openspec/changes/1438-helm-status-take-ownership/tasks.md new file mode 100644 index 0000000000..602c7165ad --- /dev/null +++ b/openspec/changes/1438-helm-status-take-ownership/tasks.md @@ -0,0 +1,28 @@ +# Tasks + +## 1. Helm version requirement check + +- [x] 1.1 Add failing unit tests asserting that Helm 3.16 fails with the version error naming the installed version, and Helm >= 3.17 passes (`uv run devops ci test tests/test_k8s.py`). +- [x] 1.2 Implement `_require_helm_version` in `src/devops_cli/commands/k8s/stack_lifecycle.py` using `packaging.version.Version`, define `CONST_HELM_MIN_VERSION` in `src/devops_cli/config/constants.py`, and invoke the check once in `deploy_stack` (`uv run devops ci test tests/test_k8s.py`). +- [x] 1.3 Regenerate documentation with `uv run devops docs generate --sync-readme`. + +## 2. Release status inspection and recovery + +- [x] 2.1 Add failing unit tests asserting that `pending-upgrade` or `pending-rollback` releases trigger `helm rollback` before upgrade and `pending-install` releases trigger `helm uninstall` before upgrade (`uv run devops ci test tests/test_k8s.py`). +- [x] 2.2 Implement `_recover_stuck_helm_release` reading `helm status -o json`, running `helm rollback` on `pending-upgrade`/`pending-rollback` and `helm uninstall` on `pending-install`, deleting `_recover_stuck_helm_release_if_pending` and its obsolete tests (`uv run devops ci test tests/test_k8s.py`). +- [x] 2.3 Regenerate documentation with `uv run devops docs generate --sync-readme`. + +## 3. Native ownership adoption and cleanup of obsolete code + +- [x] 3.1 Add failing unit tests asserting that every `helm upgrade --install` command carries `--take-ownership` (`uv run devops ci test tests/test_k8s.py`). +- [x] 3.2 Add `--take-ownership` to `_build_helm_upgrade_cmd`, delete `_adopt_helm_resource_if_conflict`, `_run_helm_with_adoption_retries`, `CONST_HELM_OWNERSHIP_CONFLICT_RE`, `DEFAULT_HELM_RECOVERY_MAX_RETRIES`, delete obsolete adoption tests in `tests/test_k8s.py`, and reword import error messages in `src/devops_cli/ai/library/introspector.py` and `src/devops_cli/exceptions/ai.py` (`uv run devops ci test tests/test_k8s.py`). +- [x] 3.3 Regenerate documentation with `uv run devops docs generate --sync-readme`. + +## 4. Quality gate and acceptance criteria validation + +- [x] 4.1 Verify acceptance criteria: assert `git grep -En 'another operation|invalid ownership metadata|cannot be imported|CONST_HELM_OWNERSHIP_CONFLICT_RE' src` prints nothing and run static checks (`git grep -En 'another operation|invalid ownership metadata|cannot be imported|CONST_HELM_OWNERSHIP_CONFLICT_RE' src && uv run devops ci --check --only lint,format,actionlint,zizmor`). +- [x] 4.2 Regenerate documentation with `uv run devops docs generate --sync-readme`. + +## Workflow follow-up + +- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). diff --git a/src/devops_cli/ai/library/introspector.py b/src/devops_cli/ai/library/introspector.py index e1cb280f10..08f4c1784f 100644 --- a/src/devops_cli/ai/library/introspector.py +++ b/src/devops_cli/ai/library/introspector.py @@ -313,7 +313,7 @@ def _import_root_module(self, package_name: str) -> ModuleType: except ImportError, ModuleNotFoundError: continue raise LibraryNotFoundError( - f"Package '{package_name}' not found or cannot be imported in the current environment" + f"Package '{package_name}' not found or could not be loaded in the current environment" ) def save_to_dir(self, contract: LibraryContract, output_dir: Path | str) -> Path: diff --git a/src/devops_cli/commands/k8s/__init__.py b/src/devops_cli/commands/k8s/__init__.py index b1c9a3bc4a..56676fdc85 100644 --- a/src/devops_cli/commands/k8s/__init__.py +++ b/src/devops_cli/commands/k8s/__init__.py @@ -78,9 +78,9 @@ _HELM_REPOS_BY_STACK, _MANIFESTS_BY_STACK, VALID_STACKS, - _adopt_helm_resource_if_conflict, _bootstrap_openwebui_account, - _recover_stuck_helm_release_if_pending, + _recover_stuck_helm_release, + _require_helm_version, bootstrap_openwebui, deploy_stack, sync_secrets, @@ -141,7 +141,6 @@ "_HELM_REPOS", "_HELM_REPOS_BY_STACK", "_MANIFESTS_BY_STACK", - "_adopt_helm_resource_if_conflict", "_bootstrap_openwebui_account", "_cluster_reachable", "_detect_service_url", @@ -150,7 +149,8 @@ "_k8s_clients", "_minikube_running", "_parse_minikube_service_url", - "_recover_stuck_helm_release_if_pending", + "_recover_stuck_helm_release", + "_require_helm_version", "_resolve_accessible_url", "_resolve_k8s_node_port_url", "_resolve_stacks", @@ -219,9 +219,9 @@ "bootstrap_openwebui", "sync_secrets", "teardown_stack", - "_adopt_helm_resource_if_conflict", "_bootstrap_openwebui_account", - "_recover_stuck_helm_release_if_pending", + "_recover_stuck_helm_release", + "_require_helm_version", } diff --git a/src/devops_cli/commands/k8s/stack_lifecycle.py b/src/devops_cli/commands/k8s/stack_lifecycle.py index ea245e425f..7aa4e8b6ee 100644 --- a/src/devops_cli/commands/k8s/stack_lifecycle.py +++ b/src/devops_cli/commands/k8s/stack_lifecycle.py @@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Annotated, Any, Final, assert_never import typer +from packaging.version import InvalidVersion, Version from pydantic import ValidationError import devops_cli.commands.k8s.cluster_runtime as runtime @@ -20,7 +21,7 @@ from devops_cli.commands.k8s.cluster_secret_push import push_for_stacks, require_keyring_for_push from devops_cli.config.constants import ( CONST_HELM_DAEMONSET_RELEASES, - CONST_HELM_OWNERSHIP_CONFLICT_RE, + CONST_HELM_MIN_VERSION, CONST_HELM_TEARDOWN_RETAINED_RELEASES, CONST_K8S_ARGOCD_HOMELAB_APPLICATIONS, CONST_K8S_ARGOCD_HOMELAB_APPLICATIONS_BY_STACK, @@ -28,12 +29,15 @@ CONST_K8S_OLLAMA_PROFILES_PATH, ) from devops_cli.config.defaults import ( - DEFAULT_HELM_RECOVERY_MAX_RETRIES, DEFAULT_K8S_DIR, DEFAULT_K8S_STACK, ) from devops_cli.dry_run import is_dry_run, render_dry_run_result, set_dry_run -from devops_cli.exceptions.k8s import ClusterSecretPushError, KubernetesContextError +from devops_cli.exceptions.k8s import ( + ClusterSecretPushError, + KubernetesContextError, + KubernetesDeployError, +) from devops_cli.k8s.argocd_overrides import ( application_patch, application_source, @@ -273,109 +277,39 @@ VALID_STACKS: tuple[str, ...] = ("infra", "llm", "logging", "devops", "gitea", "all") -def _recover_stuck_helm_release_if_pending( - error_output: str, release_name: str, namespace: str, context: str | None = None -) -> bool: - """If Helm failed due to another operation in progress, clean up stuck pending lock.""" - if "another operation" not in error_output: - return False - +def _recover_stuck_helm_release( + release_name: str, namespace: str, context: str | None = None +) -> None: + """If Helm release is stuck in a pending state, rollback or uninstall it before upgrade.""" helm_ctx = ["--kube-context", context] if context else [] status_cmd = ["helm", "status", release_name, "-n", namespace, "-o", "json"] + helm_ctx res = runtime._run_cmd(status_cmd, check=False, capture=True) if res.returncode != 0 or not res.stdout: - return False + return try: data = json.loads(res.stdout) - status = str(data.get("info", {}).get("status", "")) - version = data.get("version") - if status.startswith("pending-") and version: - secret_name = f"sh.helm.release.v1.{release_name}.v{version}" - msg = ( - f"Helm release '{release_name}' in namespace '{namespace}' is stuck in '{status}' " - f"(revision {version}). Cleaning up release lock secret '{secret_name}'..." + status = str(data.get("info", {}).get("status", "")).strip().lower() + if status == "pending-install": + print_warning( + f"Helm release '{release_name}' in namespace '{namespace}' is stuck in " + f"'{status}'. Uninstalling release before upgrade..." + ) + runtime._run_cmd( + ["helm", "uninstall", release_name, "-n", namespace] + helm_ctx, + check=False, + ) + elif status in ("pending-upgrade", "pending-rollback"): + print_warning( + f"Helm release '{release_name}' in namespace '{namespace}' is stuck in " + f"'{status}'. Rolling back release before upgrade..." + ) + runtime._run_cmd( + ["helm", "rollback", release_name, "-n", namespace] + helm_ctx, + check=False, ) - print_warning(msg) - k_ctx = ["--context", context] if context else [] - del_cmd = [ - "kubectl", - "delete", - "secret", - secret_name, - "-n", - namespace, - "--ignore-not-found", - ] + k_ctx - runtime._run_cmd(del_cmd, check=False) - return True except json.JSONDecodeError, KeyError, TypeError: pass - return False - - -def _adopt_helm_resource_if_conflict( - error_output: str, release_name: str, namespace: str, context: str | None = None -) -> bool: - """If Helm failed due to pre-existing unmanaged resources, annotate and label them to adopt. - - Helm names a cluster-scoped resource, such as a CRD, `in namespace ""`, so it is addressed - without `-n`. Helm checks the release-namespace annotation against the release's namespace, - which a namespaced resource need not share. - """ - if ( - "invalid ownership metadata" not in error_output - and "cannot be imported" not in error_output - ): - return False - - if release_name == "traefik": - print_warning( - "Traefik conflict detected: k3s must run with '--disable traefik' " - "rather than adopting pre-existing resources." - ) - return False - - matches = CONST_HELM_OWNERSHIP_CONFLICT_RE.findall(error_output) - if not matches: - return False - - ctx_args = ["--context", context] if context else [] - adopted_any = False - for kind_raw, name, ns in matches: - kind = kind_raw.lower() - ns_args = ["-n", ns] if ns else [] - adopt_msg = f"Adopting pre-existing {kind}/{name} for release '{release_name}'..." - print_warning(adopt_msg) - runtime._run_cmd( - [ - "kubectl", - "annotate", - kind, - name, - *ns_args, - f"meta.helm.sh/release-name={release_name}", - f"meta.helm.sh/release-namespace={namespace}", - "--overwrite", - ] - + ctx_args, - check=False, - ) - runtime._run_cmd( - [ - "kubectl", - "label", - kind, - name, - *ns_args, - "app.kubernetes.io/managed-by=Helm", - "--overwrite", - ] - + ctx_args, - check=False, - ) - adopted_any = True - return adopted_any def _get_openwebui_bootstrap_credentials() -> dict[str, str]: @@ -565,6 +499,39 @@ def bootstrap_openwebui( raise typer.Exit(1) +def _require_helm_version() -> Version: + """Ensure installed Helm is version 3.17 or later, returning the parsed version.""" + proc = runtime._run_cmd( + ["helm", "version", "--template", "{{.Version}}"], check=False, capture=True + ) + if proc.returncode != 0 or not proc.stdout: + raise KubernetesDeployError("Helm CLI is required but failed to report its version.") + raw_ver = proc.stdout.strip() + ver_clean = raw_ver.lstrip("v") + try: + ver = Version(ver_clean) + except InvalidVersion as exc: + raise KubernetesDeployError(f"Could not parse Helm version: {raw_ver}.") from exc + min_ver = Version(CONST_HELM_MIN_VERSION) + if ver < min_ver: + raise KubernetesDeployError( + f"Helm {CONST_HELM_MIN_VERSION} or later is required; found {raw_ver}." + ) + return ver + + +def _check_helm_version_for_deploy(all_releases: Sequence[dict[str, str]]) -> bool: + """Verify Helm meets minimum version if releases are deployed, returning if Helm is v4+.""" + if not all_releases: + return False + try: + helm_ver = _require_helm_version() + return helm_ver.major >= 4 + except KubernetesDeployError as exc: + print_error(str(exc), prefix=False) + raise typer.Exit(1) from exc + + def _is_helm_v4_or_newer() -> bool: """Detect whether the active Helm CLI is version 4 or newer.""" proc = runtime._run_cmd( @@ -574,9 +541,9 @@ def _is_helm_v4_or_newer() -> bool: return False ver_clean = proc.stdout.strip().lstrip("v") try: - major = int(ver_clean.split(".")[0]) - return major >= 4 - except ValueError, IndexError: + ver = Version(ver_clean) + return ver.major >= 4 + except InvalidVersion: return False @@ -585,10 +552,12 @@ def _build_helm_upgrade_cmd( helm_ctx: list[str], wait: bool, timeout: str, + is_v4: bool | None = None, ) -> list[str]: """Construct helm upgrade --install command matching installed Helm capabilities.""" - helm_cmd = ["helm", "upgrade", "--install"] - if _is_helm_v4_or_newer(): + helm_cmd = ["helm", "upgrade", "--install", "--take-ownership"] + v4 = _is_helm_v4_or_newer() if is_v4 is None else is_v4 + if v4: helm_cmd.append("--force-conflicts") helm_cmd.extend( [ @@ -684,41 +653,6 @@ def _apply_manifest_files( _apply_single_manifest(manifest_path, kubectl_ctx, effective_domain) -def _run_helm_with_adoption_retries( - helm_cmd: list[str], - release: dict[str, str], - effective_context: str | None, -) -> Any: - """Run Helm upgrade, retrying after recovering a stuck pending lock or adopting a resource. - - Helm names one conflicting resource per failed attempt, so each retry adopts the next one. A - retry that fails exactly like the attempt before it made no progress and ends the retries. - """ - result = runtime._run_cmd(helm_cmd, check=False, capture=True) - previous_error: str | None = None - for _ in range(DEFAULT_HELM_RECOVERY_MAX_RETRIES): - err_msg = (result.stderr or "") + " " + (result.stdout or "") - if result.returncode == 0 or err_msg == previous_error: - break - previous_error = err_msg - pending_recovered = _recover_stuck_helm_release_if_pending( - err_msg, - release["name"], - release["namespace"], - context=effective_context, - ) - conflicts_adopted = _adopt_helm_resource_if_conflict( - err_msg, - release["name"], - release["namespace"], - context=effective_context, - ) - if not (pending_recovered or conflicts_adopted): - break - result = runtime._run_cmd(helm_cmd, check=False, capture=True) - return result - - def _install_single_release( release: dict[str, str], effective_context: str | None, @@ -726,17 +660,23 @@ def _install_single_release( wait: bool, timeout: str, unready_nodes: Sequence[str] = (), + is_v4: bool | None = None, ) -> None: - """Install or upgrade a single Helm release with conflict adoption retries.""" + """Install or upgrade a single Helm release after recovering pending state if stuck.""" effective_wait = wait if wait and unready_nodes and release["name"] in CONST_HELM_DAEMONSET_RELEASES: print_warning( f"Cluster has unready nodes ({', '.join(unready_nodes)}). Skipping Helm '--wait' for DaemonSet release '{release['name']}'." ) effective_wait = False + _recover_stuck_helm_release( + release["name"], + release["namespace"], + context=effective_context, + ) print_info(f"[bold]Installing {release['name']}...[/bold]", prefix=False) - helm_cmd = _build_helm_upgrade_cmd(release, helm_ctx, effective_wait, timeout) - result = _run_helm_with_adoption_retries(helm_cmd, release, effective_context) + helm_cmd = _build_helm_upgrade_cmd(release, helm_ctx, effective_wait, timeout, is_v4=is_v4) + result = runtime._run_cmd(helm_cmd, check=False, capture=True) if result.returncode != 0: err_details = (result.stderr or result.stdout or "").strip() print_error(f"Failed to install {release['name']}: {err_details}", prefix=False) @@ -1282,6 +1222,9 @@ def deploy_stack( print_info(MESSAGES.k8s.pushing_secrets, prefix=False) push_for_stacks(_push_stacks_for(selected_stacks, effective_context), effective_context) + # 5b. Verify Helm version requirement before Helm operations + is_v4 = _check_helm_version_for_deploy(all_releases) + # 6. Add Helm repos for selected stacks _deploy_helm_repos(selected_stacks) @@ -1298,7 +1241,13 @@ def deploy_stack( # 9. Install Helm releases for release in all_releases: _install_single_release( - release, effective_context, helm_ctx, wait, timeout, unready_nodes=unready_nodes + release, + effective_context, + helm_ctx, + wait, + timeout, + unready_nodes=unready_nodes, + is_v4=is_v4, ) # 9b. Apply post-Helm custom resources and kustomizations whose CRDs the charts installed diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index bd4a1ee421..543e30f607 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -2369,11 +2369,8 @@ class WebhookExposure(StrEnum): {"prometheus-operator-crds"} ) -# A resource Helm refuses to adopt, as its resourceString prints it: ` "" in namespace -# ""`, where the namespace is empty for a cluster-scoped resource such as a CRD -CONST_HELM_OWNERSHIP_CONFLICT_RE: Final[re.Pattern[str]] = re.compile( - r'([A-Za-z0-9_-]+)\s+"([^"]+)"\s+in namespace\s+"([^"]*)"' -) +# The minimum supported Helm CLI version for Kubernetes stack deployments (#1438) +CONST_HELM_MIN_VERSION: Final[str] = "3.17.0" # What a gh request writes (#1125, `github/request_classifier.py`). Uncertain requests count as # writes, so a high-level command reads only when its verb is a read verb or its group only reads. diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index f5de116636..9f6bf10d8a 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -467,9 +467,6 @@ DEFAULT_OBSERVABILITY_NAMESPACE: str = "observability" DEFAULT_K8S_STACK: str = "infra" DEFAULT_K8S_ALL_STACK: str = "all" -# Helm names one conflicting resource per failed attempt, so adopting the ten CRDs of -# prometheus-operator-crds that an earlier chart left unowned takes ten retries -DEFAULT_HELM_RECOVERY_MAX_RETRIES: int = 20 DEFAULT_K8S_TLS_SECRET_NAME: str = "homelab-tls" DEFAULT_CERT_COMMON_NAME: str = "homelab.local" DEFAULT_K8S_LOGS_TAIL: int = 100 diff --git a/src/devops_cli/exceptions/ai.py b/src/devops_cli/exceptions/ai.py index a3bc79a0ee..266319115f 100644 --- a/src/devops_cli/exceptions/ai.py +++ b/src/devops_cli/exceptions/ai.py @@ -235,7 +235,7 @@ def __init__( class LibraryNotFoundError(LibraryIngestionError): - """Raised when target package cannot be imported or found in the environment.""" + """Raised when target package could not be loaded or found in the environment.""" DEFAULT_ERROR_CODE = CONST_ERROR_CODE_LIBRARY_NOT_FOUND DEFAULT_EXIT_CODE = CONST_EXIT_FAILURE diff --git a/tests/cluster_secret_fakes.py b/tests/cluster_secret_fakes.py index 5e66639d7d..56e57ca8af 100644 --- a/tests/cluster_secret_fakes.py +++ b/tests/cluster_secret_fakes.py @@ -146,6 +146,8 @@ def _answer(self, argv: list[str], kwargs: dict[str, Any]) -> tuple[int, str]: return 1, "" if argv[0] == "gh": return self._gh(argv, kwargs.get("env") or {}) + if argv[:2] == ["helm", "version"]: + return 0, "v3.17.0" if argv[:2] == ["kubectl", "get"]: return 0, self._get(argv) if argv[:3] == ["kubectl", "apply", "--server-side"]: diff --git a/tests/fixtures/swallowed_failures_ceilings.json b/tests/fixtures/swallowed_failures_ceilings.json index 3e0e1c6466..aa84fe799e 100644 --- a/tests/fixtures/swallowed_failures_ceilings.json +++ b/tests/fixtures/swallowed_failures_ceilings.json @@ -68,7 +68,7 @@ "src/devops_cli/commands/k8s/cluster_runtime.py": 6, "src/devops_cli/commands/k8s/diagnostics.py": 1, "src/devops_cli/commands/k8s/networking.py": 5, - "src/devops_cli/commands/k8s/stack_lifecycle.py": 13, + "src/devops_cli/commands/k8s/stack_lifecycle.py": 12, "src/devops_cli/commands/rag.py": 1, "src/devops_cli/commands/repos.py": 5, "src/devops_cli/commands/serve.py": 1, diff --git a/tests/test_k8s.py b/tests/test_k8s.py index 081e02717c..b06782d736 100644 --- a/tests/test_k8s.py +++ b/tests/test_k8s.py @@ -15,12 +15,14 @@ import yaml from docker.auth import resolve_repository_name from docker.utils import parse_repository_tag +from packaging.version import Version from typer.testing import CliRunner from devops_cli.commands.k8s import app from devops_cli.dry_run import set_dry_run from devops_cli.prometheus.promql import selectors, validate_promql from tests.k8s_manifests import applied_documents +from tests.support.fakes.process import ProcessAnswer, ProcessFake from tests.support.paths import FIXTURES, REPO_ROOT runner = CliRunner() @@ -322,60 +324,70 @@ def test_k8s_configure_urls_llm_dry_run() -> None: set_dry_run(False) -@patch("devops_cli.commands.k8s._run_cmd") -def test_adopt_helm_resource_if_conflict(mock_run: MagicMock) -> None: - """_adopt_helm_resource_if_conflict annotates and labels pre-existing K8s resources.""" - from devops_cli.commands.k8s import _adopt_helm_resource_if_conflict +def test_require_helm_version() -> None: + """_require_helm_version requires Helm >= 3.17 and fails on older versions (#1438).""" + from devops_cli.commands.k8s.stack_lifecycle import _require_helm_version + from devops_cli.exceptions.k8s import KubernetesDeployError - err = ( - 'Error: unable to continue with install: Service "ollama" in namespace "llm" exists ' - "and cannot be imported into the current release: invalid ownership metadata; " - 'label validation error: missing key "app.kubernetes.io/managed-by": must be set to "Helm"' - ) - res = _adopt_helm_resource_if_conflict(err, "ollama", "llm", context="local-k3s") - assert res is True - assert mock_run.call_count == 2 + with patch("devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd") as mock_cmd: + mock_cmd.return_value = _mock_proc(0, "v3.16.0\n") + with pytest.raises(KubernetesDeployError, match=r"3\.16\.0"): + _require_helm_version() + + with patch("devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd") as mock_cmd: + mock_cmd.return_value = _mock_proc(0, "v3.17.0\n") + ver = _require_helm_version() + assert str(ver) == "3.17.0" + with patch("devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd") as mock_cmd: + mock_cmd.return_value = _mock_proc(0, "v4.3.0\n") + ver = _require_helm_version() + assert ver.major >= 4 -def test_adopt_helm_resource_warns_and_refuses_for_traefik() -> None: - """_adopt_helm_resource_if_conflict warns and refuses to adopt for traefik release (#1675).""" - from devops_cli.commands.k8s.stack_lifecycle import _adopt_helm_resource_if_conflict - err = ( - 'Error: unable to continue with install: Service "traefik" in namespace "kube-system" exists ' - "and cannot be imported into the current release: invalid ownership metadata; " - 'label validation error: missing key "app.kubernetes.io/managed-by": must be set to "Helm"' +def test_helm_version_older_than_minimum_fails(process_fake: ProcessFake) -> None: + """deploy-stack fails with the version error when Helm is older than 3.17 (#1438).""" + process_fake.answer( + lambda call: "cluster-info" in call.argv or ("get" in call.argv and "nodes" in call.argv), + ProcessAnswer(returncode=0, stdout="node1 Ready\n"), + ) + process_fake.answer( + lambda call: call.argv[:2] == ("helm", "version"), + ProcessAnswer(returncode=0, stdout="v3.16.2\n"), ) - with patch("devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd") as mock_run: - res = _adopt_helm_resource_if_conflict(err, "traefik", "kube-system", context="local-k3s") - assert res is False - assert mock_run.call_count == 0 + with ( + patch("devops_cli.commands.k8s._cluster_reachable", return_value=True), + patch("devops_cli.commands.k8s.stack_lifecycle.require_keyring_for_push"), + patch("devops_cli.commands.k8s.stack_lifecycle.push_for_stacks"), + patch("devops_cli.commands.k8s.stack_lifecycle._post_deploy_credentials"), + ): + res = runner.invoke(app, ["deploy-stack", "--stack", "infra", "--no-push-secrets"]) + assert res.exit_code == 1 + assert "3.16.2" in res.output -_OPERATOR_CRDS = tuple( - f"{plural}.monitoring.coreos.com" - for plural in ( - "alertmanagerconfigs", - "alertmanagers", - "podmonitors", - "probes", - "prometheusagents", - "prometheuses", - "prometheusrules", - "scrapeconfigs", - "servicemonitors", - "thanosrulers", - ) -) +def test_build_helm_upgrade_cmd_carries_take_ownership() -> None: + """Every helm upgrade --install argv carries --take-ownership (#1438).""" + from devops_cli.commands.k8s.stack_lifecycle import _build_helm_upgrade_cmd + rel = { + "name": "argocd", + "chart": "argo/argo-cd", + "namespace": "argocd", + "values": "k8s/argocd/values.yaml", + "version": "5.51.6", + } + cmd_v3 = _build_helm_upgrade_cmd( + rel, ["--kube-context", "ctx"], wait=True, timeout="10m", is_v4=False + ) + assert "--take-ownership" in cmd_v3 + assert "--force-conflicts" not in cmd_v3 -def _ownership_conflict(kind: str, name: str, namespace: str) -> str: - """Helm's refusal to adopt a resource it does not own, as pkg/action/validate.go words it.""" - return ( - f'Error: unable to continue with install: {kind} "{name}" in namespace "{namespace}" ' - "exists and cannot be imported into the current release: invalid ownership metadata; " - 'label validation error: missing key "app.kubernetes.io/managed-by": must be set to "Helm"' + cmd_v4 = _build_helm_upgrade_cmd( + rel, ["--kube-context", "ctx"], wait=True, timeout="10m", is_v4=True ) + assert "--take-ownership" in cmd_v4 + assert "--force-conflicts" in cmd_v4 def _renders_service_monitor(values: object) -> bool: @@ -453,108 +465,81 @@ def test_prometheus_operator_crds_install_before_every_service_monitor() -> None ) -@pytest.mark.parametrize( - ("conflict", "release", "target"), - [ - # A leftover CRD is cluster-scoped: Helm prints an empty namespace and kubectl gets no -n. - ( - ("CustomResourceDefinition", "servicemonitors.monitoring.coreos.com", ""), - ("prometheus-operator-crds", "monitoring"), - ["customresourcedefinition", "servicemonitors.monitoring.coreos.com"], - ), - # k8s-monitoring's gateway monitor sits in llm, outside the release's own namespace. - ( - ("ServiceMonitor", "llm-gateway", "llm"), - ("k8s-monitoring", "monitoring"), - ["servicemonitor", "llm-gateway", "-n", "llm"], - ), - ], -) -def test_adopt_helm_resource_addresses_cluster_scoped_and_namespaced_conflicts( - conflict: tuple[str, str, str], release: tuple[str, str], target: list[str] -) -> None: - """Adoption annotates and labels the resource Helm named, passing -n only for a namespaced - one, and records the release's namespace, which Helm checks the annotation against (#819).""" - from devops_cli.commands.k8s.stack_lifecycle import _adopt_helm_resource_if_conflict - - release_name, release_namespace = release - with patch("devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd") as mock_run: - adopted = _adopt_helm_resource_if_conflict( - _ownership_conflict(*conflict), release_name, release_namespace, context="local-k3s" - ) +def test_recover_stuck_helm_release_rolls_back_pending_upgrade() -> None: + """A pending-upgrade release is rolled back with helm rollback before upgrade (#1438).""" + from devops_cli.commands.k8s.stack_lifecycle import _recover_stuck_helm_release - assert (adopted, [c.args[0] for c in mock_run.call_args_list]) == ( - True, - [ - [ - "kubectl", - "annotate", - *target, - f"meta.helm.sh/release-name={release_name}", - f"meta.helm.sh/release-namespace={release_namespace}", - "--overwrite", - "--context", - "local-k3s", - ], - [ - "kubectl", - "label", - *target, - "app.kubernetes.io/managed-by=Helm", - "--overwrite", - "--context", - "local-k3s", - ], - ], - ) + status_json = json.dumps({"info": {"status": "pending-upgrade"}, "version": 2}) + with patch("devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd") as mock_cmd: + mock_cmd.side_effect = [ + _mock_proc(0, status_json), + _mock_proc(0, "Rollback was a success!"), + ] + _recover_stuck_helm_release("argocd", "argocd", context="test-ctx") + assert mock_cmd.call_count == 2 + status_call = mock_cmd.call_args_list[0][0][0] + rollback_call = mock_cmd.call_args_list[1][0][0] + assert status_call == [ + "helm", + "status", + "argocd", + "-n", + "argocd", + "-o", + "json", + "--kube-context", + "test-ctx", + ] + assert rollback_call == [ + "helm", + "rollback", + "argocd", + "-n", + "argocd", + "--kube-context", + "test-ctx", + ] -@pytest.mark.parametrize( - ("helm_errors", "expected"), - [ - # Helm names one leftover CRD per attempt; the release installs once all ten are adopted. - ( - [_ownership_conflict("CustomResourceDefinition", crd, "") for crd in _OPERATOR_CRDS], - (0, 11, list(_OPERATOR_CRDS)), - ), - # An adoption that does not clear the conflict fails the same way twice, ending retries. - ( - [_ownership_conflict("CustomResourceDefinition", _OPERATOR_CRDS[8], "")] * 30, - (1, 2, [_OPERATOR_CRDS[8]]), - ), - ], -) -def test_helm_retries_adopt_each_leftover_crd_until_the_release_installs( - helm_errors: list[str], expected: tuple[int, int, list[str]] -) -> None: - """Every leftover CRD is adopted in one deploy, and a conflict adoption cannot clear stops - the retries instead of repeating Helm (#819).""" - from devops_cli.commands.k8s.stack_lifecycle import ( - _HELM_RELEASES_BY_STACK, - _run_helm_with_adoption_retries, - ) +def test_recover_stuck_helm_release_rolls_back_pending_rollback() -> None: + """A pending-rollback release is rolled back with helm rollback before upgrade (#1438).""" + from devops_cli.commands.k8s.stack_lifecycle import _recover_stuck_helm_release - release = _HELM_RELEASES_BY_STACK["infra"][0] - helm_cmd = ["helm", "upgrade", "--install", release["name"], release["chart"]] - pending_errors = iter(helm_errors) + status_json = json.dumps({"info": {"status": "pending-rollback"}, "version": 3}) + with patch("devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd") as mock_cmd: + mock_cmd.side_effect = [ + _mock_proc(0, status_json), + _mock_proc(0, "Rollback was a success!"), + ] + _recover_stuck_helm_release("argocd", "argocd") + assert mock_cmd.call_count == 2 + assert mock_cmd.call_args_list[1][0][0] == ["helm", "rollback", "argocd", "-n", "argocd"] - def fake_run(cmd: list[str], **_: object) -> subprocess.CompletedProcess[str]: - if cmd != helm_cmd: - return _mock_proc(0) - error = next(pending_errors, None) - return _mock_proc(1, stderr=error) if error else _mock_proc(0) - with patch( - "devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd", side_effect=fake_run - ) as mock_run: - result = _run_helm_with_adoption_retries(helm_cmd, release, None) +def test_recover_stuck_helm_release_uninstalls_pending_install() -> None: + """A pending-install release is uninstalled with helm uninstall before upgrade (#1438).""" + from devops_cli.commands.k8s.stack_lifecycle import _recover_stuck_helm_release - calls = [c.args[0] for c in mock_run.call_args_list] - assert ( - result.returncode, - calls.count(helm_cmd), - [cmd[3] for cmd in calls if cmd[:2] == ["kubectl", "annotate"]], - ) == expected + status_json = json.dumps({"info": {"status": "pending-install"}, "version": 1}) + with patch("devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd") as mock_cmd: + mock_cmd.side_effect = [ + _mock_proc(0, status_json), + _mock_proc(0, "release 'argocd' uninstalled"), + ] + _recover_stuck_helm_release("argocd", "argocd") + assert mock_cmd.call_count == 2 + assert mock_cmd.call_args_list[1][0][0] == ["helm", "uninstall", "argocd", "-n", "argocd"] + + +def test_recover_stuck_helm_release_deployed_does_nothing() -> None: + """A deployed release triggers neither rollback nor uninstall (#1438).""" + from devops_cli.commands.k8s.stack_lifecycle import _recover_stuck_helm_release + + status_json = json.dumps({"info": {"status": "deployed"}, "version": 1}) + with patch("devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd") as mock_cmd: + mock_cmd.return_value = _mock_proc(0, status_json) + _recover_stuck_helm_release("argocd", "argocd") + assert mock_cmd.call_count == 1 def test_teardown_stack_keeps_the_prometheus_operator_crds() -> None: @@ -595,25 +580,137 @@ def test_teardown_stack_keeps_the_prometheus_operator_crds() -> None: ) -@patch("devops_cli.commands.k8s._run_cmd") -def test_recover_stuck_helm_release_if_pending(mock_run: MagicMock) -> None: - """_recover_stuck_helm_release_if_pending deletes lock secret when release is stuck in pending state.""" - from devops_cli.commands.k8s import _recover_stuck_helm_release_if_pending +def test_deploy_stack_with_process_fake_pending_upgrade_rolls_back( + process_fake: ProcessFake, +) -> None: + """When the process fake answers helm status with pending-upgrade, deploy-stack runs helm rollback before upgrade (#1438).""" + process_fake.answer( + lambda call: "cluster-info" in call.argv or ("get" in call.argv and "nodes" in call.argv), + ProcessAnswer(returncode=0, stdout="node1 Ready\n"), + ) + process_fake.answer( + lambda call: call.argv[:2] == ("helm", "version"), + ProcessAnswer(returncode=0, stdout="v3.17.0\n"), + ) + process_fake.answer( + lambda call: call.argv[:2] == ("helm", "repo"), + ProcessAnswer(returncode=0, stdout="ok\n"), + ) + process_fake.answer( + lambda call: call.argv[:2] == ("helm", "status"), + ProcessAnswer( + returncode=0, + stdout=json.dumps({"info": {"status": "pending-upgrade"}, "version": 2}), + ), + ) + process_fake.answer( + lambda call: call.argv[:2] == ("helm", "rollback"), + ProcessAnswer(returncode=0, stdout="rolled back\n"), + ) + process_fake.answer( + lambda call: call.argv[:2] == ("helm", "upgrade"), + ProcessAnswer(returncode=0, stdout="Release installed\n"), + ) + + with ( + patch("devops_cli.commands.k8s._cluster_reachable", return_value=True), + patch("devops_cli.commands.k8s.stack_lifecycle.require_keyring_for_push"), + patch("devops_cli.commands.k8s.stack_lifecycle.push_for_stacks"), + patch("devops_cli.commands.k8s.port_forward"), + patch("devops_cli.k8s.credentials.sync_k8s_credentials", return_value={}), + ): + res = runner.invoke( + app, ["deploy-stack", "--stack", "infra", "--no-wait", "--no-push-secrets"] + ) + assert res.exit_code == 0 + + rollback_calls = [ + call.argv for call in process_fake.calls if call.argv[:2] == ("helm", "rollback") + ] + upgrade_calls = [ + call.argv for call in process_fake.calls if call.argv[:2] == ("helm", "upgrade") + ] + assert len(rollback_calls) > 0 + assert len(upgrade_calls) > 0 + assert rollback_calls[0][:5] == ( + "helm", + "rollback", + "prometheus-operator-crds", + "-n", + "monitoring", + ) + first_rollback_idx = next( + i for i, call in enumerate(process_fake.calls) if call.argv[:2] == ("helm", "rollback") + ) + first_upgrade_idx = next( + i for i, call in enumerate(process_fake.calls) if call.argv[:2] == ("helm", "upgrade") + ) + assert first_rollback_idx < first_upgrade_idx + for cmd in upgrade_calls: + assert "--take-ownership" in cmd - err_unrelated = "Error: timed out waiting for condition" - res_unrelated = _recover_stuck_helm_release_if_pending(err_unrelated, "argocd", "argocd") - err_lock = "Error: UPGRADE FAILED: another operation (install/upgrade/rollback) is in progress" - mock_run.side_effect = [ - MagicMock( - returncode=0, stdout=json.dumps({"version": 50, "info": {"status": "pending-upgrade"}}) +def test_deploy_stack_with_process_fake_pending_install_uninstalls( + process_fake: ProcessFake, +) -> None: + """When the process fake answers helm status with pending-install, deploy-stack runs helm uninstall (#1438).""" + process_fake.answer( + lambda call: "cluster-info" in call.argv or ("get" in call.argv and "nodes" in call.argv), + ProcessAnswer(returncode=0, stdout="node1 Ready\n"), + ) + process_fake.answer( + lambda call: call.argv[:2] == ("helm", "version"), + ProcessAnswer(returncode=0, stdout="v3.17.0\n"), + ) + process_fake.answer( + lambda call: call.argv[:2] == ("helm", "repo"), + ProcessAnswer(returncode=0, stdout="ok\n"), + ) + process_fake.answer( + lambda call: call.argv[:2] == ("helm", "status"), + ProcessAnswer( + returncode=0, + stdout=json.dumps({"info": {"status": "pending-install"}, "version": 1}), ), - MagicMock(returncode=0, stdout="secret deleted"), + ) + process_fake.answer( + lambda call: call.argv[:2] == ("helm", "uninstall"), + ProcessAnswer(returncode=0, stdout="uninstalled\n"), + ) + process_fake.answer( + lambda call: call.argv[:2] == ("helm", "upgrade"), + ProcessAnswer(returncode=0, stdout="Release installed\n"), + ) + + with ( + patch("devops_cli.commands.k8s._cluster_reachable", return_value=True), + patch("devops_cli.commands.k8s.stack_lifecycle.require_keyring_for_push"), + patch("devops_cli.commands.k8s.stack_lifecycle.push_for_stacks"), + patch("devops_cli.commands.k8s.port_forward"), + patch("devops_cli.k8s.credentials.sync_k8s_credentials", return_value={}), + ): + res = runner.invoke( + app, ["deploy-stack", "--stack", "infra", "--no-wait", "--no-push-secrets"] + ) + assert res.exit_code == 0 + + uninstall_calls = [ + call.argv for call in process_fake.calls if call.argv[:2] == ("helm", "uninstall") + ] + upgrade_calls = [ + call.argv for call in process_fake.calls if call.argv[:2] == ("helm", "upgrade") ] - res_lock = _recover_stuck_helm_release_if_pending( - err_lock, "argocd", "argocd", context="local-k3s" + assert len(uninstall_calls) > 0 + assert len(upgrade_calls) > 0 + assert uninstall_calls[0][:5] == ( + "helm", + "uninstall", + "prometheus-operator-crds", + "-n", + "monitoring", ) - assert (res_unrelated, res_lock, mock_run.call_count) == (False, True, 2) + for cmd in upgrade_calls: + assert "--take-ownership" in cmd def test_k8s_apply_and_logs() -> None: @@ -688,6 +785,10 @@ def test_k8s_bootstrap_and_stacks(tmp_path: Path, monkeypatch: pytest.MonkeyPatc return_value=_mock_proc(0, "minikube is running"), ), patch("devops_cli.commands.k8s._run_cmd", return_value=_mock_proc(0, "success")), + patch( + "devops_cli.commands.k8s.stack_lifecycle._require_helm_version", + return_value=Version("3.17.0"), + ), patch("devops_cli.commands.k8s.port_forward"), patch( "devops_cli.k8s.credentials.sync_k8s_credentials", @@ -711,6 +812,10 @@ def test_k8s_bootstrap_and_stacks(tmp_path: Path, monkeypatch: pytest.MonkeyPatc return_value=_mock_proc(0, "success"), ), patch("devops_cli.commands.k8s._run_cmd", return_value=_mock_proc(0, "success")), + patch( + "devops_cli.commands.k8s.stack_lifecycle._require_helm_version", + return_value=Version("3.17.0"), + ), patch("devops_cli.commands.k8s.port_forward"), patch( "devops_cli.k8s.credentials.sync_k8s_credentials", @@ -1169,6 +1274,10 @@ def test_k8s_deploy_stack_no_wait() -> None: patch("devops_cli.commands.k8s._cluster_reachable", return_value=True), patch("devops_cli.commands.k8s._run_cmd") as mock_cmd, patch("devops_cli.commands.k8s.stack_lifecycle._is_helm_v4_or_newer", return_value=True), + patch( + "devops_cli.commands.k8s.stack_lifecycle._require_helm_version", + return_value=Version("4.3.0"), + ), patch("devops_cli.commands.k8s.port_forward"), patch("devops_cli.k8s.credentials.sync_k8s_credentials", return_value={}), ): @@ -1187,11 +1296,16 @@ def test_k8s_deploy_stack_no_wait() -> None: for cmd in helm_cmds: assert "--wait" not in cmd assert "--force-conflicts" in cmd + assert "--take-ownership" in cmd with ( patch("devops_cli.commands.k8s._cluster_reachable", return_value=True), patch("devops_cli.commands.k8s._run_cmd") as mock_cmd, patch("devops_cli.commands.k8s.stack_lifecycle._is_helm_v4_or_newer", return_value=False), + patch( + "devops_cli.commands.k8s.stack_lifecycle._require_helm_version", + return_value=Version("3.17.0"), + ), patch("devops_cli.commands.k8s.port_forward"), patch("devops_cli.k8s.credentials.sync_k8s_credentials", return_value={}), ): @@ -1211,6 +1325,7 @@ def test_k8s_deploy_stack_no_wait() -> None: for cmd in helm_cmds: assert "--wait" not in cmd assert "--force-conflicts" not in cmd + assert "--take-ownership" in cmd def test_k8s_workload_resource_limits_and_probes() -> None: @@ -1832,6 +1947,8 @@ def __call__( self.calls.append((cmd, input)) if cmd[0] == "git" or cmd[1] == "kustomize": return subprocess.run(cmd, input=input, capture_output=True, text=True, check=False) + if cmd[0] == "helm" and len(cmd) > 1 and cmd[1] == "version": + return subprocess.CompletedProcess(cmd, 0, "v4.3.0", "") if cmd[1:6] == ["-n", "argocd", "get", "application", "cluster"]: return subprocess.CompletedProcess( cmd, 0 if self.argo else 1, "cluster" * self.argo, "" @@ -2274,6 +2391,10 @@ def test_k8s_helm_upgrade_command_includes_pinned_version() -> None: patch( "devops_cli.commands.k8s.stack_lifecycle._is_cluster_argo_managed", return_value=False ), + patch( + "devops_cli.commands.k8s.stack_lifecycle._require_helm_version", + return_value=Version("3.17.0"), + ), patch("devops_cli.commands.k8s.port_forward"), patch("devops_cli.k8s.credentials.sync_k8s_credentials", return_value={}), ): @@ -2290,6 +2411,7 @@ def test_k8s_helm_upgrade_command_includes_pinned_version() -> None: assert len(helm_cmds) > 0 for cmd in helm_cmds: assert "--version" in cmd + assert "--take-ownership" in cmd def test_native_deploy_stack_infra_applies_the_monitoring_kustomization() -> None: @@ -2305,6 +2427,10 @@ def test_native_deploy_stack_infra_applies_the_monitoring_kustomization() -> Non patch( "devops_cli.commands.k8s.stack_lifecycle._is_cluster_argo_managed", return_value=False ), + patch( + "devops_cli.commands.k8s.stack_lifecycle._require_helm_version", + return_value=Version("3.17.0"), + ), patch("devops_cli.commands.k8s.port_forward"), patch("devops_cli.k8s.credentials.sync_k8s_credentials", return_value={}), ): @@ -2508,6 +2634,10 @@ def test_llm_stack_applies_gateway_servicemonitor_after_helm_and_deletes_before_ "devops_cli.commands.k8s.stack_lifecycle._is_cluster_argo_managed", return_value=False ), patch("devops_cli.commands.k8s.stack_lifecycle._bootstrap_openwebui_account"), + patch( + "devops_cli.commands.k8s.stack_lifecycle._require_helm_version", + return_value=Version("3.17.0"), + ), patch( "devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd", return_value=_mock_proc(0), diff --git a/tests/test_k8s_context.py b/tests/test_k8s_context.py index 214343ef4f..a1b199838c 100644 --- a/tests/test_k8s_context.py +++ b/tests/test_k8s_context.py @@ -173,6 +173,8 @@ def test_switch_context_minikube_autostarts_when_stopped( def mock_run_cmd(cmd: list[str], **kwargs: object) -> object: calls.append(cmd) + if cmd[:2] == ["helm", "version"]: + return MagicMock(returncode=0, stdout="v3.17.0\n", stderr="") return MagicMock(returncode=0, stdout="OK", stderr="") def mock_minikube_running() -> bool: @@ -211,6 +213,8 @@ def test_switch_context_minikube_skips_start_when_already_running( def mock_run_cmd(cmd: list[str], **kwargs: object) -> object: calls.append(cmd) + if cmd[:2] == ["helm", "version"]: + return MagicMock(returncode=0, stdout="v3.17.0\n", stderr="") return MagicMock(returncode=0, stdout="OK", stderr="") with ( @@ -241,6 +245,8 @@ def test_switch_context_other_cluster_does_not_start_minikube( def mock_run_cmd(cmd: list[str], **kwargs: object) -> object: calls.append(cmd) + if cmd[:2] == ["helm", "version"]: + return MagicMock(returncode=0, stdout="v3.17.0\n", stderr="") return MagicMock(returncode=0, stdout="OK", stderr="") with ( @@ -319,6 +325,8 @@ def test_switch_context_accepts_kubeconfig_names_and_rejects_injection( def mock_run_cmd(cmd: list[str], **kwargs: object) -> object: calls.append(cmd) + if cmd[:2] == ["helm", "version"]: + return MagicMock(returncode=0, stdout="v3.17.0\n", stderr="") return MagicMock(returncode=0, stdout="OK", stderr="") with ( @@ -376,6 +384,8 @@ def test_deploy_and_teardown_stack_use_effective_context( def mock_run_cmd(cmd: list[str], **kwargs: object) -> object: calls.append(cmd) + if cmd[:2] == ["helm", "version"]: + return MagicMock(returncode=0, stdout="v3.17.0\n", stderr="") return MagicMock(returncode=0, stdout="OK", stderr="") manifest_dir = tmp_path / "k8s" diff --git a/tests/test_k8s_gpu_placement.py b/tests/test_k8s_gpu_placement.py index d751fdaabe..7d755cc457 100644 --- a/tests/test_k8s_gpu_placement.py +++ b/tests/test_k8s_gpu_placement.py @@ -50,6 +50,8 @@ def cluster(cmd: list[str], **_kwargs: object) -> subprocess.CompletedProcess[st return subprocess.CompletedProcess( cmd, 1 if fail else 0, "" if fail else json.dumps({"items": nodes}), "" ) + if cmd[:2] == ["helm", "version"]: + return subprocess.CompletedProcess(cmd, 0, "v3.17.0\n", "") return subprocess.CompletedProcess(cmd, 0, "", "") with ( diff --git a/tests/test_k8s_logging_stack.py b/tests/test_k8s_logging_stack.py index c6cdd0fe2c..296fcd3102 100644 --- a/tests/test_k8s_logging_stack.py +++ b/tests/test_k8s_logging_stack.py @@ -117,12 +117,18 @@ def test_teardown_logging_stack_dry_run() -> None: def test_deploy_logging_stack_live() -> None: """Verify deploy-stack --stack logging execution.""" mock_proc = MagicMock(returncode=0, stdout="success", stderr="") + + def _fake_run(cmd: list[str], **kwargs: object) -> MagicMock: + if cmd[:2] == ["helm", "version"]: + return MagicMock(returncode=0, stdout="v3.17.0\n", stderr="") + return mock_proc + with ( patch("devops_cli.commands.k8s.shutil.which", return_value="/usr/local/bin/helm"), patch("devops_cli.commands.k8s._cluster_reachable", return_value=True), patch("devops_cli.commands.k8s._minikube_running", return_value=True), - patch("devops_cli.commands.k8s.run_subprocess", return_value=mock_proc), - patch("devops_cli.commands.k8s._run_cmd", return_value=mock_proc), + patch("devops_cli.commands.k8s.run_subprocess", side_effect=_fake_run), + patch("devops_cli.commands.k8s._run_cmd", side_effect=_fake_run), ): result = runner.invoke(app, ["deploy-stack", "--stack", "logging", "--no-push-secrets"]) assert result.exit_code == 0 diff --git a/tests/test_k8s_networking.py b/tests/test_k8s_networking.py index 12b6f0e0bf..8826744494 100644 --- a/tests/test_k8s_networking.py +++ b/tests/test_k8s_networking.py @@ -301,7 +301,7 @@ def test_deploy_stack_defaults_do_not_port_forward_or_configure_urls() -> None: patch( "devops_cli.commands.k8s.stack_lifecycle.runtime._cluster_reachable", return_value=True ), - patch("devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd"), + patch("devops_cli.commands.k8s.stack_lifecycle.runtime._run_cmd") as mock_run_cmd, patch("devops_cli.commands.k8s.stack_lifecycle.net.port_forward") as mock_pf, patch("devops_cli.commands.k8s.stack_lifecycle.net.configure_urls") as mock_conf, patch("devops_cli.k8s.credentials.sync_k8s_credentials", return_value={}), @@ -309,6 +309,13 @@ def test_deploy_stack_defaults_do_not_port_forward_or_configure_urls() -> None: patch("devops_cli.commands.k8s.stack_lifecycle.require_keyring_for_push"), patch("devops_cli.commands.k8s.stack_lifecycle.namespace_exists", return_value=False), ): + + def _fake_run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]: + if cmd[:2] == ["helm", "version"]: + return subprocess.CompletedProcess(cmd, 0, "v3.17.0\n", "") + return subprocess.CompletedProcess(cmd, 0, "", "") + + mock_run_cmd.side_effect = _fake_run deploy_stack(stack="infra") assert (mock_pf.called, mock_conf.called) == (False, False) diff --git a/tests/test_k8s_tempo.py b/tests/test_k8s_tempo.py index a75e7a8c26..8c6dcfbe56 100644 --- a/tests/test_k8s_tempo.py +++ b/tests/test_k8s_tempo.py @@ -191,7 +191,13 @@ def test_k8s_deploy_stack_shows_tempo_connection_info(runner: CliRunner) -> None mock_proc.returncode = 0 mock_proc.stdout = "" mock_proc.stderr = "" - mock_run.return_value = mock_proc + + def _fake_run(cmd: list[str], **kwargs: object) -> MagicMock: + if cmd[:2] == ["helm", "version"]: + return MagicMock(returncode=0, stdout="v3.17.0\n", stderr="") + return mock_proc + + mock_run.side_effect = _fake_run result = runner.invoke(k8s_app, ["deploy-stack", "--stack", "infra", "--no-push-secrets"]) assert ( From 023806d3bd46f34907a8478be59f2f464dac0647 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sun, 25 Oct 2026 22:27:43 +0000 Subject: [PATCH 2/2] chore(openspec): archive 1438-helm-status-take-ownership Archive completed OpenSpec change for issue 1438. --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/k8s-helm-deploy/spec.md | 0 .../tasks.md | 0 openspec/specs/k8s-helm-deploy/spec.md | 39 +++++++++++++++++++ 6 files changed, 39 insertions(+) rename openspec/changes/{1438-helm-status-take-ownership => archive/2026-10-25-1438-helm-status-take-ownership}/.openspec.yaml (100%) rename openspec/changes/{1438-helm-status-take-ownership => archive/2026-10-25-1438-helm-status-take-ownership}/design.md (100%) rename openspec/changes/{1438-helm-status-take-ownership => archive/2026-10-25-1438-helm-status-take-ownership}/proposal.md (100%) rename openspec/changes/{1438-helm-status-take-ownership => archive/2026-10-25-1438-helm-status-take-ownership}/specs/k8s-helm-deploy/spec.md (100%) rename openspec/changes/{1438-helm-status-take-ownership => archive/2026-10-25-1438-helm-status-take-ownership}/tasks.md (100%) create mode 100644 openspec/specs/k8s-helm-deploy/spec.md diff --git a/openspec/changes/1438-helm-status-take-ownership/.openspec.yaml b/openspec/changes/archive/2026-10-25-1438-helm-status-take-ownership/.openspec.yaml similarity index 100% rename from openspec/changes/1438-helm-status-take-ownership/.openspec.yaml rename to openspec/changes/archive/2026-10-25-1438-helm-status-take-ownership/.openspec.yaml diff --git a/openspec/changes/1438-helm-status-take-ownership/design.md b/openspec/changes/archive/2026-10-25-1438-helm-status-take-ownership/design.md similarity index 100% rename from openspec/changes/1438-helm-status-take-ownership/design.md rename to openspec/changes/archive/2026-10-25-1438-helm-status-take-ownership/design.md diff --git a/openspec/changes/1438-helm-status-take-ownership/proposal.md b/openspec/changes/archive/2026-10-25-1438-helm-status-take-ownership/proposal.md similarity index 100% rename from openspec/changes/1438-helm-status-take-ownership/proposal.md rename to openspec/changes/archive/2026-10-25-1438-helm-status-take-ownership/proposal.md diff --git a/openspec/changes/1438-helm-status-take-ownership/specs/k8s-helm-deploy/spec.md b/openspec/changes/archive/2026-10-25-1438-helm-status-take-ownership/specs/k8s-helm-deploy/spec.md similarity index 100% rename from openspec/changes/1438-helm-status-take-ownership/specs/k8s-helm-deploy/spec.md rename to openspec/changes/archive/2026-10-25-1438-helm-status-take-ownership/specs/k8s-helm-deploy/spec.md diff --git a/openspec/changes/1438-helm-status-take-ownership/tasks.md b/openspec/changes/archive/2026-10-25-1438-helm-status-take-ownership/tasks.md similarity index 100% rename from openspec/changes/1438-helm-status-take-ownership/tasks.md rename to openspec/changes/archive/2026-10-25-1438-helm-status-take-ownership/tasks.md diff --git a/openspec/specs/k8s-helm-deploy/spec.md b/openspec/specs/k8s-helm-deploy/spec.md new file mode 100644 index 0000000000..3ad822e3e9 --- /dev/null +++ b/openspec/specs/k8s-helm-deploy/spec.md @@ -0,0 +1,39 @@ +# k8s-helm-deploy Specification + +## Purpose +Automated Helm release deployment, version verification, state recovery, and resource ownership adoption for Kubernetes stacks. + +## Requirements + +### Requirement: Helm version requirement +The deployment process SHALL require Helm version 3.17 or later when deploying Helm releases. If the installed Helm version is older than 3.17, deployment SHALL abort with an error message naming the installed version. + +#### Scenario: Helm version meets minimum requirement +- **WHEN** the installed Helm version is 3.17.0 or later and `devops k8s deploy-stack` runs +- **THEN** the version check succeeds and deployment continues + +#### Scenario: Helm version is below minimum requirement +- **WHEN** the installed Helm version is 3.16.2 and `devops k8s deploy-stack` runs +- **THEN** deployment fails with an error stating that Helm 3.17 or later is required and naming version 3.16.2 + +### Requirement: Release status inspection and recovery +Before executing `helm upgrade --install`, the deployment process SHALL inspect the release status with `helm status -o json`. A release in `pending-install` status SHALL be uninstalled with `helm uninstall`. A release in `pending-upgrade` or `pending-rollback` status SHALL be rolled back with `helm rollback` before proceeding. + +#### Scenario: Pending install release is uninstalled +- **WHEN** `helm status -o json` reports release status `pending-install` +- **THEN** the system executes `helm uninstall` before running `helm upgrade --install` + +#### Scenario: Pending upgrade release is rolled back +- **WHEN** `helm status -o json` reports release status `pending-upgrade` +- **THEN** the system executes `helm rollback` before running `helm upgrade --install` + +#### Scenario: Pending rollback release is rolled back +- **WHEN** `helm status -o json` reports release status `pending-rollback` +- **THEN** the system executes `helm rollback` before running `helm upgrade --install` + +### Requirement: Helm ownership adoption +Every `helm upgrade --install` invocation SHALL include `--take-ownership` to adopt existing unmanaged Kubernetes resources without manual annotation or labeling. + +#### Scenario: Upgrade command includes take-ownership +- **WHEN** `devops k8s deploy-stack` executes a Helm release install or upgrade +- **THEN** the constructed `helm upgrade --install` command arguments include `--take-ownership`