Skip to content

fix(k8s): free the root disk of the control-plane node #3654

Closed

Description

@dan-petty

Problem

The root disk of the control-plane node stays too full after #2147. On 2026-11-05 the node exporter shows 30.7 GiB free of about 220 GiB, about 86% used. The warning LocalPathNodeDiskHigh fires for this node. k8s/README.md says that the kubelet starts to delete unused images at 85% and evicts pods under DiskPressure.

What holds the space, on 2026-11-05:

So #2147 frees about 2% of the disk, and only after a person deletes the old volumes.

Expected

The root disk of the control-plane node stays under the 85% threshold, with a margin for model updates and for the growth of the volumes that stay on it.

Acceptance criteria

  • The root filesystem of the control-plane node is under 75% used.
  • LocalPathNodeDiskHigh does not fire for this node for 7 days.
  • Each model that the tiers of this node need stays available, and the fix writes down which models the node keeps.

Existing tool considered

ollama rm removes a model that no tier of this node uses. If the node needs all its models, a person extends the disk or moves the model store to another disk with the tools of the host. That is a host change, so a person does it.

Related

#1634, #2147

Proposed design

Problem statement

The root disk of the control-plane node is about 86% used, above the 85% where the kubelet starts to delete images. The Ollama model store on the node holds 128 GiB of the about 220 GiB. Most of those models serve no tier of the node, because Ollama keeps every model that a person pulled. The fix removes the models that no tier of a node serves, through the Ollama API, and writes down the models that each node keeps. #2147 frees about 2% and does not solve this.

Acceptance criteria

Requirement: The prune keeps the models of the node

The prune command SHALL remove only a model that no tier on the node serves.

Scenario: One extra model on a node with two tiers

  • WHEN a node runs the tiers ollama-16gib and ollama-24gib-embed-gpu0, and its store holds a Gemma model that neither tier serves
  • THEN the plan names the Gemma model for that node and names no other model.

Requirement: The plan names each node and each model once

The plan SHALL name each model to remove once for each node, also when two tiers of the node serve the same model.

Scenario: A model that two tiers of one node serve

  • WHEN the tiers ollama-48gib and ollama-64gib run on one node and both serve qwen3.8:27b
  • THEN the keep set of the node holds one qwen3.8:27b, and the plan names the node once.

Requirement: A dry run makes no request

--dry-run MUST make no request to the cluster and MUST print each kubectl exec and ollama rm command that it would run.

Scenario: Dry run of the prune

  • WHEN a person runs devops k8s ollama prune --dry-run
  • THEN the output holds the kubectl exec command of each node, and no request leaves the workstation.

Requirement: The written keep set matches the gateway config

k8s/README.md MUST name each model that each serving tier keeps, and a test MUST fail when a name differs from llm/gateway/config.yaml.

Scenario: A model added to the gateway config

  • WHEN llm/gateway/config.yaml names a model that the table of k8s/README.md does not
  • THEN tests/test_k8s_ollama_models.py fails and names the model and the tier.

Requirement: An unreadable model list stops the node

The prune MUST remove no model on a node whose ollama list fails, and MUST name that node.

Scenario: ollama list fails on one node

  • WHEN the ollama list of a node exits non-zero
  • THEN the command removes no model on that node, names the node, and exits non-zero.

Existing Tool Considered

No alternatives check has run on this item. The open, maintained tool is Ollama itself: its CLI (ollama list, ollama ps) and its API (DELETE /api/delete, ollama rm) list and remove a model, and its FAQ names the model store. It lacks the keep set: it does not know which models the tiers of a node serve, so it cannot choose the models to remove, and it has no plan mode. The change builds a thin command around it: about 250 lines of Python and one test file, about 25,000 tokens to build, about 5,000 tokens a year to keep and fix, and about half a day of elapsed time.

Key questions

  • Which models does a node keep?: The models that the gateway routes to the tiers with a pod on that node, written in the GPU Placement table of k8s/README.md. [sources: k8s/README.md]
  • Is the model store of a node one directory that its tiers share?: Yes. The hostPath /var/lib/ollama is on the node, each tier mounts it at /home/ollama/.ollama, and the tiers of a node set OLLAMA_NOPRUNE because they share the model directory. [sources: k8s/README.md]
  • How does the prune remove a model?: It calls ollama rm for each model that no tier of the node serves, through the Ollama API of a tier pod on that node. (best practice) [sources: k8s/README.md]
    • Chosen: ollama rm through the Ollama API. Ollama removes the manifest and the blobs together, so the store stays consistent, and its API documents the call.
    • Rejected: Delete the files of /var/lib/ollama/models from a pod. It leaves a manifest that names a missing blob, and the next load of that model fails.
    • Rejected: Move the store to another disk. It is a host change, and it is deferred to its own issue.
  • Does the fix change the LocalPathNodeDiskHigh rule?: No. The rule stays at 85%, because that is where the kubelet starts to delete images, and the fix lowers the usage of the disk. (best practice) [sources: k8s/monitoring/prometheus-values.yaml:291, k8s/README.md:360, tests/prometheus/test_k8s_monitoring_alerting.py]
    • Chosen: Keep the rule at 85%. 85% is the limit at which the kubelet acts, so the rule reports the real limit of the node.
    • Rejected: Lower the threshold to 75%. It fires on a node where the kubelet does nothing, and it hides the cause of the usage.
    • Rejected: Silence the node. A silence hides the DiskPressure that evicts a pod from a local-path volume.
  • Where does the fix write down the keep set?: In the GPU Placement section of k8s/README.md, next to the tier table, with a test that keeps it equal to llm/gateway/config.yaml. (best practice) [sources: k8s/README.md]
    • Chosen: The GPU Placement section of k8s/README.md, with a test. A person reads it where the tiers are described, and the test keeps it equal to the gateway config.
    • Rejected: A new file under llm/profiles/. It is a second source of truth for what the gateway config already states.
    • Rejected: The annotations of the DaemonSets only. It is no record that a person reads.
  • When does the prune run?: On demand, after a plan that a person reads, like devops k8s volume move. (best practice) [sources: k8s/README.md]
    • Chosen: On demand, after a plan that a person reads. A removal is destructive, and the keep set depends on the pods that run now, so a person reads the plan first.
    • Rejected: A CronJob every night. It removes a model that a person pulled on purpose within one day, and it needs a token and RBAC in namespace llm.
    • Rejected: An initContainer of each tier. It runs before Ollama serves, so it cannot call the API, and a failed removal stops the pod.

Fit

Fits in one pull request.

Suspected block

None.

Dependencies

None.

Activity

  1. added
    source/agent
    type/bug
    scope/k8s
    status/new
    value/high
    effort/medium
    on Nov 5, 2026
  2. dan-petty commented on Nov 5, 2026

    @dan-petty
    OwnerAuthor

    Intake placed this item to the backlog: intake puts every new item in the backlog. A person plans the milestones.

    • Type: type/bug. The fix prefix of the title gives the type.
    • Scope: scope/k8s. The (k8s) scope of the title gives the scope.
    • Priority: P1-High. The node is at 86% disk usage, past the 85% threshold where kubelet deletes images and evicts pods.
    • Value: High. Pod eviction and image deletion on the control-plane node would disrupt the entire cluster.
    • Effort: Medium. It requires identifying removable models, running ollama rm, documenting kept models, and verifying disk usage over 7 days.
    • Related: fix(k8s): the volumes of grafana, the prometheus server and loki move off the control-plane node, and their placement exemptions go #2147, which asks for a different change. Both address the control-plane node disk, but #2147 moves specific monitoring volumes while the candidate manages overall disk usage including the 128 GiB Ollama model store.
  3. added
    priority/p1-high
    on Nov 5, 2026
  4. added
    status/ready
    and removed
    status/new
    on Nov 5, 2026
  5. devops-cli-service commented on Nov 5, 2026

    @devops-cli-service
    Contributor

    Status set to Ready at f6d57ec (see proposed design in issue body).

    Moved to new items: #3659, #3660.

  6. dan-petty commented on Nov 6, 2026

    @dan-petty
    OwnerAuthor

    Evidence on 2026-11-07 for the acceptance criteria (node exporter and alert history in Grafana):

    • The root filesystem of the control-plane node is 30.5% used. The criterion asks for under 75%. It was 86% on 2026-11-05. The cause of the change: the Ollama model store moved to the new NVMe disk (the homelab pull requests for the NVMe mount and the Ollama move), and the local-path provisioner now places the volumes of this node on that disk.
    • LocalPathNodeDiskHigh last fired for this node on 2026-11-06 at about 07:00Z. It has stayed quiet since. The 7-day window ends on about 2026-11-13.
    • The criterion about the models that the node keeps is open: the list of kept models is not written down in k8s/README.md yet.

    This item can close on or after 2026-11-13, if the alert stays quiet and the model list is written down. The old Released volumes still hold some space until a person deletes them (the commands are in the #2147 comment).

  7. devops-cli-service commented on Nov 7, 2026

    @devops-cli-service
    Contributor

    Staged: branch fix/3654-free-the-root-disk-of-the, draft pull request #3954. The pull request plans the item and closes no issue.

    The task groups, with the tokens of the inputs of each step, for a budget of 64000 tokens:

    1. Write the keep set of each gateway target in the README: 25548 tokens
    2. Plan the prune of the models that no tier serves: 26389 tokens
    3. Add the ollama prune command: 53891 tokens

    The runs of the planner and the review made 26 model request(s), and used 1488691 input tokens and 63622 output tokens. The tool calls, in order:

    1. references({"name":"LocalPathNodeDiskHigh"})
    2. list_files({"directory":"k8s/llm/gateway"})
    3. search_code({"text":"LocalPathNodeDiskHigh"})
    4. list_files({"directory":"src/devops_cli/commands/k8s"})
    5. file_symbols({"path":"src/devops_cli/commands/k8s/volume.py"})
    6. read_file({"path":"k8s/llm/gateway/config.yaml","end_line":120})
    7. read_file({"path":"k8s/README.md","start_line":330,"end_line":400})
    8. read_file({"path":"src/devops_cli/commands/k8s/__init__.py"})
    9. list_files({"directory":"tests/invariants"})
    10. list_files({"directory":"tests/k8s"})
    11. search_code({"text":"gateway/config.yaml"})
    12. repo_map({"directory":"src/devops_cli/k8s"})
    13. read_file({"path":"src/devops_cli/commands/k8s/volume.py","start_line":1,"end_line":60})
    14. read_issue({"number":2147})
    15. read_issue({"number":1634})
    16. read_file({"path":"src/devops_cli/commands/k8s/volume.py","start_line":58,"end_line":110})
    17. file_symbols({"path":"src/devops_cli/dry_run/requests.py"})
    18. search_code({"text":"volume_app"})
    19. find_issues({"terms":"ollama prune"})
    20. read_issue({"number":3660})
    21. search_code({"text":"ollama"})
    22. search_code({"text":"llm.devops.io/vram-gib"})
    23. search_code({"text":"ollama-48gib-fast"})
    24. list_files({"directory":"tests/commands/k8s"})
    25. list_files({"directory":"src/devops_cli/lang/en"})
    26. read_file({"path":"src/devops_cli/ai/gateway_render.py","start_line":1,"end_line":100})
    27. read_file({"path":"k8s/llm/profiles/services.yaml","start_line":240,"end_line":330})
    28. read_spec({"capability":"docker-prune"})
    29. read_spec({"capability":"local-path-volume-placement"})
    30. list_files({"directory":"src/devops_cli/commands"})
    31. file_symbols({"path":"src/devops_cli/commands/ci.py"})
    32. file_symbols({"path":"tests/commands/k8s/test_k8s.py"})
    33. read_file({"path":"tests/invariants/test_dry_run_class_ratchet.py","end_line":60})
    34. search_code({"text":"model_list"})
    35. search_code({"text":"llm/gateway"})
    36. read_file({"end_line":330,"path":"src/devops_cli/k8s/gpu_thresholds.py","start_line":270})
    37. read_file({"end_line":30,"path":"tests/k8s/test_gpu_thresholds.py","start_line":1})
    38. search_code({"text":"DEFAULT_LLM_GATEWAY_CONFIG_PATH"})
    39. search_code({"text":"kubelet starts to delete"})
    40. search_code({"text":"DEFAULT_LLM_GATEWAY_CONFIG_PATH"})
    41. list_files({"directory":"k8s/llm"})
    42. list_files({"directory":"tests/k8s"})
    43. read_file({"path":"src/devops_cli/commands/k8s/__init__.py"})
    44. read_file({"path":"k8s/llm/gateway/config.yaml","start_line":1,"end_line":70})
    45. read_file({"path":"src/devops_cli/commands/k8s/volume.py","start_line":1,"end_line":80})
    46. search_code({"text":"llm.devops.io/provider"})
    47. list_files({"directory":"src/devops_cli/dry_run"})
    48. read_file({"path":"k8s/llm/profiles/services.yaml","start_line":1,"end_line":30})
    49. read_file({"path":"k8s/llm/profiles/services.yaml","start_line":245,"end_line":280})
    50. file_symbols({"path":"src/devops_cli/k8s/gpu_thresholds.py"})
    51. search_code({"text":"ollama prune"})
    52. search_code({"text":"volume_reclaim"})
    53. find_issues({"terms":"ollama prune model store"})
    54. read_issue({"number":3660})
    55. list_files({"directory":"src/devops_cli/lang"})
    56. list_files({"directory":"src/devops_cli/k8s"})
    57. list_files({"directory":"src/devops_cli/lang/en"})
    58. list_files({"directory":"src/devops_cli/k8s"})
    59. list_files({"directory":"tests/k8s"})
    60. list_files({"directory":"src/devops_cli/commands/k8s"})
    61. search_code({"text":"LocalPathNodeDiskHigh"})
    62. search_code({"text":"ollama prune"})
    63. search_code({"text":"_refuse_chat_routes"})
    64. read_file({"path":"src/devops_cli/commands/k8s/__init__.py","start_line":120,"end_line":160})
    65. read_file({"path":"src/devops_cli/commands/k8s/volume.py","start_line":1,"end_line":100})
    66. read_file({"path":"k8s/monitoring/prometheus-values.yaml","start_line":280,"end_line":330})
    67. read_file({"path":"src/devops_cli/config/defaults.py","start_line":980,"end_line":1020})
    68. read_file({"path":"src/devops_cli/config/constants.py","start_line":1060,"end_line":1100})

    Tool calls: file_symbols=5 (empty=0), find_issues=2 (empty=0), list_files=16 (empty=0), read_file=20 (empty=0), read_issue=4 (empty=0), read_spec=2 (empty=0), references=1 (empty=0), repo_map=1 (empty=0), search_code=17 (empty=2)

    The stage job read the open pull requests and their files in 1 GraphQL request(s).

  8. added
    owner/service
    and removed
    status/ready
    on Nov 7, 2026
  9. 3 remaining items

  10. devops-cli-service commented on Nov 7, 2026

    @devops-cli-service
    Contributor

    Stopped at group 3.

    Failure class: limit_reached.
    Action taken: none.
    Action left: raise_limit: raise the limit that the run went over.

    Step Status Attempts Tokens in/out Last failing command
    group 1 done 1 2702735/16049 -
    group 2 done 2 3505164/33518 pytest on base: tests/k8s/test_k8s_ollama_prune.py
    group 3 stopped 1 8057210/32155 -

    Reason:

    LimitReached: The step spent its budget `roadmap.implement.step_token_budget=8000000`.
    Refused commands: git 1, other:f29942ea1104 1. Other retries: 0.
    

    Last message of the agent (a claim that no check verified): Now I'll write the failing test first.

    The job discarded this work. The diff is cut to 20000 characters. Read it before you retry:

    diff --git a/README.md b/README.md
    index 14adfde4..89fe4f2c 100644
    --- a/README.md
    +++ b/README.md
    @@ -243,6 +243,7 @@ read. The CI job `image-pins` runs the check on a pull request that changes k8s/
     |  | `devops k8s doctor [OPTIONS]` | Diagnose Kubernetes cluster deployment health, correlate failures, and recommend remediations. |
     |  | `devops k8s tunnel COMMAND [ARGS]...` | Keep the local end of the Kubernetes API route at k8s.\<domain\> running: one 'cloudflared access tcp' forward, for the tunnel kubeconfig context off the home network. |
     |  | `devops k8s volume COMMAND [ARGS]...` | Move a local-path claim to a volume on another node, and reclaim orphaned PersistentVolumes. |
    +|  | `devops k8s ollama COMMAND [ARGS]...` | Prune the Ollama models that no tier of a node serves. |
     | [**kustomize**](docs/commands/kustomize.md) | `devops kustomize build [OPTIONS] <path>` | Build kustomize overlays (delegates to kustomize build). |
     |  | `devops kustomize diff [OPTIONS] <path>` | Show a diff of pending changes (delegates to kubectl diff -k). |
     |  | `devops kustomize apply [OPTIONS] <path>` | Apply a kustomization (delegates to kubectl apply -k). |
    diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md
    index 5b0d212d..1081e769 100644
    --- a/docs/CLI_REFERENCE.md
    +++ b/docs/CLI_REFERENCE.md
    @@ -1629,6 +1629,30 @@ devops k8s volume move [OPTIONS] <claim>
     | `--dry-run` | `boolean` | - | Make no request, reads included: print the requests a move would make, in order, with placeholders for each value that a read gives. Wins over --plan. |
     | `--context`, `-c` | `string` | - | Kubernetes cluster context name. |
     
    +### `devops k8s ollama`
    +
    +**Prune the Ollama models that no tier of a node serves.**
    +
    +```bash
    +devops k8s ollama COMMAND [ARGS]...
    +```
    +
    +#### `devops k8s ollama prune`
    +
    +**Remove each model that no tier of a node serves from the Ollama store of that node, through the Ollama API in one pod of the node. The keep set of a node is the set of models that the gateway config sends to the tier Services whose selector the Ollama pods of the node hold. A node whose ollama list fails keeps every model, is named, and makes the command exit 1.**
    +
    +```bash
    +devops k8s ollama prune [OPTIONS]
    +```
    +
    +**Options:**
    +
    +| Option / Flag | Type | Default | Description |
    +|---|---|---|---|
    +| `--plan` | `boolean` | - | Read the gateway routes, the tier Services, the Ollama pods and the model list of each node, print the models that each node keeps and removes, and remove nothing. |
    +| `--dry-run` | `boolean` | - | Make no request: print the kubectl exec commands that list and remove the models of each gateway target, with placeholders for the pod and the models. Wins over --plan. |
    +| `--context`, `-c` | `string` | - | Kubernetes cluster context name. |
    +
     ---
     
     ## devops kustomize
    diff --git a/docs/commands/k8s.md b/docs/commands/k8s.md
    index 2620db7f..fbec5315 100644
    --- a/docs/commands/k8s.md
    +++ b/docs/commands/k8s.md
    @@ -907,3 +907,29 @@ devops k8s volume move [OPTIONS] <claim>
     | `--context`, `-c` | `string` | - | Kubernetes cluster context name. |
     
     ---
    +
    +## `devops k8s ollama`
    +
    +**Prune the Ollama models that no tier of a node serves.**
    +
    +```bash
    +devops k8s ollama COMMAND [ARGS]...
    +```
    +
    +### `devops k8s ollama prune`
    +
    +**Remove each model that no tier of a node serves from the Ollama store of that node, through the Ollama API in one pod of the node. The keep set of a node is the set of models that the gateway config sends to the tier Services whose selector the Ollama pods of the node hold. A node whose ollama list fails keeps every model, is named, and makes the command exit 1.**
    +
    +```bash
    +devops k8s ollama prune [OPTIONS]
    +```
    +
    +**Options:**
    +
    +| Option / Flag | Type | Default | Description |
    +|---|---|---|---|
    +| `--plan` | `boolean` | - | Read the gateway routes, the tier Services, the Ollama pods and the model list of each node, print the models that each node keeps and removes, and remove nothing. |
    +| `--dry-run` | `boolean` | - | Make no request: print the kubectl exec commands that list and remove the models of each gateway target, with placeholders for the pod and the models. Wins over --plan. |
    +| `--context`, `-c` | `string` | - | Kubernetes cluster context name. |
    +
    +---
    diff --git a/k8s/README.md b/k8s/README.md
    index 57ef890d..882d53a2 100644
    --- a/k8s/README.md
    +++ b/k8s/README.md
    @@ -182,6 +182,8 @@ Ollama runs as one DaemonSet per total-VRAM tier (`ollama-16gib` … `ollama-128
     | `ollama-48gib-fast` | `qwen3.8:27b` |
     | `ollama-64gib-standard` | `qwen3.8:27b` |
     
    +**Prune the models that no tier serves.** `devops k8s ollama prune` removes each model that no tier of a node serves from the Ollama store of that node. It reads the gateway routes and the tier Services of the checkout, lists the Ollama pods of namespace `llm`, and runs `ollama list` in one pod of each node. The keep set of a node is the set of models that the gateway config sends to the tier Services whose selector the pods of the node hold, so two tiers of a node keep one copy of a shared model. The command then runs `ollama rm` for each model that the node does not keep. Ollama deletes the manifest and the blobs together, so the store stays consistent. A node whose `ollama list` fails keeps every model, is named, and makes the command exit 1. `--plan` prints the models that each node keeps and removes, and removes nothing. `--dry-run` makes no request: it prints the `kubectl exec` commands of each gateway target, with placeholders for the pod and the models. Read the plan before the prune, because the keep set follows the pods that run now. The prune lowers the used fraction of the root disk, and it leaves the alert rule at 85%, where the kubelet starts to delete unused images.
    +
     **GPU thresholds.** `llm/profiles/gpu-thresholds.yaml` holds two values of `nvidia.com/gpu.architecture`, both `pascal`. Argo CD tracks `main`, so the values are in git and not in `config.yaml`. A tier in `llm/profiles/tier-templates/` is at or below a threshold when the newest architecture that it accepts is that architecture or an older one:
     
     - At or below `embedding_only`: the tier serves embedding models alone, keeps one model loaded and sets `LLAMA_ARG_THREADS: "1"`, because the model runs on the GPU. Each of its gateway deployments has order 1. Otherwise the tier runs as its template says: it is a chat tier, it loads one model, and the gateway sends it no embedding batch.
    diff --git a/src/devops_cli/commands/k8s/__init__.py b/src/devops_cli/commands/k8s/__init__.py
    index 83ee6df0..788ec2fb 100644
    --- a/src/devops_cli/commands/k8s/__init__.py
    +++ b/src/devops_cli/commands/k8s/__init__.py
    @@ -66,6 +66,7 @@ from devops_cli.commands.k8s.networking import (
         port_forward_stop,
         service_url,
     )
    +from devops_cli.commands.k8s.ollama import app as ollama_app
     from devops_cli.commands.k8s.security_audit import (
         k8s_audit,
         k8s_check_deprecated,
    @@ -138,6 +139,7 @@ app.command(name="gpu-matrix")(gpu_matrix_cmd)
     app.command(name="doctor")(doctor_cmd)
     app.add_typer(tunnel_app, name="tunnel", help=HELP.k8s.tunnel_app)
     app.add_typer(volume_app, name="volume", help=HELP.k8s.volume_app)
    +app.add_typer(ollama_app, name="ollama", help=HELP.k8s.ollama_app)
     
     
     __all__ = [
    @@ -183,6 +185,7 @@ __all__ = [
         "k8s_lint",
         "k8s_validate",
         "logs",
    +    "ollama_app",
         "pods_cmd",
         "port_forward",
         "push_secrets",
    diff --git a/src/devops_cli/commands/k8s/ollama.py b/src/devops_cli/commands/k8s/ollama.py
    new file mode 100644
    index 00000000..96f84b04
    --- /dev/null
    +++ b/src/devops_cli/commands/k8s/ollama.py
    @@ -0,0 +1,248 @@
    +"""Ollama commands: prune the models that no tier of a node serves (#3654).
    +
    +`devops k8s ollama prune` reads the gateway routes and the tier Services of the checkout, lists the
    +Ollama pods of namespace llm, runs `ollama list` in one pod of each node, and removes each model
    +that no tier of that node serves with `ollama rm`. A node whose list fails keeps every model, is
    +named, and makes the command exit 1. `--plan` prints the plan and removes nothing, and `--dry-run`
    +prints the kubectl exec commands of each gateway target and makes no request.
    +"""
    +
    +from __future__ import annotations
    +
    +import subprocess
    +from collections.abc import Sequence
    +from pathlib import Path
    +from typing import Annotated
    +
    +import typer
    +
    +from devops_cli.config.commands import build_kubectl_cmd
    +from devops_cli.config.constants import (
    +    CONST_K8S_OLLAMA_PROVIDER_LABEL,
    +    CONST_K8S_OLLAMA_PRUNE_HEADING,
    +)
    +from devops_cli.config.defaults import (
    +    DEFAULT_LLM_GATEWAY_CONFIG_PATH,
    +    DEFAULT_LLM_NAMESPACE,
    +    DEFAULT_LLM_SERVICES_PATH,
    +)
    +from devops_cli.core.cli import new_typer
    +from devops_cli.core.process import run_subprocess
    +from devops_cli.dry_run import dry_run_class, is_dry_run
    +from devops_cli.dry_run.requests import PlannedRequest, render_request_plan
    +from devops_cli.k8s.doctor import get_k8s_client
    +from devops_cli.k8s.ollama_prune import (
    +    NodePrune,
    +    OllamaPod,
    +    gateway_targets,
    +    plan_ollama_prune,
    +)
    +from devops_cli.lang import HELP, MESSAGES
    +from devops_cli.output import print_error, print_info, print_success
    +
    +app = new_typer(help=HELP.k8s.ollama_app, no_args_is_help=True)
    +
    +
    +def _say(message: str) -> None:
    +    print_info(message, prefix=False, safe=True)
    +
    +
    +def _label_selector() -> str:
    +    """The label selector that finds the Ollama pods of the stack."""
    +    return "=".join(CONST_K8S_OLLAMA_PROVIDER_LABEL)
    +
    +
    +def read_ollama_pods(context: str | None = None) -> list[OllamaPod]:
    +    """The Ollama pods of namespace llm, each with the node it runs on and its labels.
    +
    +    A pod that no node holds serves no tier yet, so it is left out.
    +    """
    +    core = get_k8s_client(context=context)
    +    pods = core.list_namespaced_pod(DEFAULT_LLM_NAMESPACE, label_selector=_label_selector())
    +    return [
    +        OllamaPod(
    +            name=item.metadata.name,
    +            node=item.spec.node_name,
    +            labels=dict(item.metadata.labels or {}),
    +        )
    +        for item in pods.items
    +        if item.spec.node_name
    +    ]
    +
    +
    +def _pod_by_node(pods: Sequence[OllamaPod]) -> dict[str, str]:
    +    """The pod to run Ollama in for each node: the first of its pods by name."""
    +    return {
    +        node: min(pod.name for pod in pods if pod.node == node)
    +        for node in sorted({pod.node for pod in pods})
    +    }
    +
    +
    +def _ollama_argv(pod: str, args: Sequence[str], context: str | None) -> tuple[str, ...]:
    +    """The kubectl exec that runs `ollama` with `args` in `pod`."""
    +    command = ["exec", "-n", DEFAULT_LLM_NAMESPACE, pod, "--", "ollama", *args]
    +    return tuple(build_kubectl_cmd(command, context))
    +
    +
    +def _run_ollama(
    +    pod: str, args: Sequence[str], context: str | None
    +) -> subprocess.CompletedProcess[str] | None:
    +    """Run `ollama` in `pod`, or None when kubectl could not be started or did not answer."""
    +    try:
    +        return run_subprocess(_ollama_argv(pod, args, context))
    +    except OSError, subprocess.TimeoutExpired:
    +        return None
    +
    +
    +def _list_node(pod: str, context: str | None) -> str | None:
    +    """The `ollama list` of the node that `pod` runs on, or None when the call failed."""
    +    result = _run_ollama(pod, ("list",), context)
    +    if result is None or result.returncode != 0:
    +        return None
    +    return result.stdout
    +
    +
    +def _read_manifest(path: Path) -> str | None:
    +    """The text of `path`, or None with the error printed when it cannot be read."""
    +    try:
    +        return path.read_text(encoding="utf-8")
    +    except OSError as exc:
    +        print_error(
    +            MESSAGES.k8s.ollama_prune_manifest_missing.format(path=path, reason=exc),
    +            prefix=False,
    +            safe=True,
    +        )
    +        return None
    +
    +
    +def plan_ollama_prune_requests(
    +    gateway: str, context: str | None = None
    +) -> list[PlannedRequest]:
    +    """The requests of a prune, in order: the list and the removals of each gateway target.
    +
    +    A dry run makes no request, so it cannot read the pod of a node or the models of its store:
    +    the pod and each model to remove are placeholders.
    +    """
    +    requests: list[PlannedRequest] = []
    +    for target, models in sorted(gateway_targets(gateway).items()):
    +        pod = f"<{target}-pod>"
    +        requests.append(_request(pod, ("list",), context))
    +        requests.extend(_request(pod, ("rm", model), context) for model in sorted(models))
    +    return requests
    +
    +
    +def _request(pod: str, args: Sequence[str], context: str | None) -> PlannedRequest:
    +    return PlannedRequest(
    +        method="kubectl", target=f"exec/{pod}", argv=_ollama_argv(pod, args, context)
    +    )
    +
    +
    +def _print_node(entry: NodePrune) -> None:
    +    """One line for a node: its keep set and the models that the prune removes."""
    +    m = MESSAGES.k8s
    +    if entry.list_failed:
    +        _say(m.ollama_prune_list_failed.format(node=entry.node))
    +        return
    +    keep = ", ".join(entry.keep) or m.ollama_prune_no_keep
    +    if not entry.remove:
    +        _say(m.ollama_prune_node_keeps_all.format(node=entry.node, keep=keep))
    +        return
    +    _say(m.ollama_prune_node.format(node=entry.node, keep=keep, remove=", ".join(entry.remove)))
    +
    +
    +def _remove_models(
    +    entries: Sequence[NodePrune], pod_by_node: dict[str, str], context: str | None
    +) -> bool:
    +    """Remove each model of the plan, and report each failure. True when a removal failed."""
    +    failed = False
    +    removed = 0
    +    for entry in entries:
    +        for model in entry.remove:
    +            result = _run_ollama(pod_by_node[entry.node], ("rm", model), context)
    +            if result is None or result.returncode != 0:
    +                print_error(
    +                    MESSAGES.k8s.ollama_prune_remove_failed.format(model=model, node=entry.node),
    +                    prefix=False,
    +                    safe=True,
    +                )
    +                failed = True
    +                continue
    +            removed += 1
    +            _say(MESSAGES.k8s.ollama_prune_removed.format(model=model, node=entry.node))
    +    if removed:
    +        print_success(MESSAGES.k8s.ollama_prune_done.format(count=removed), prefix=False, safe=True)
    +    return failed
    +
    +
    +def _read_pods_or_exit(context: str | None) -> list[OllamaPod]:
    +    """The Ollama pods of the cluster, or exit 1 with the reason that the list failed."""
    +    try:
    +        return read_ollama_pods(context)
    +    except Exception as exc:
    +        print_error(
    +            MESSAGES.k8s.ollama_prune_pods_failed.format(
    +                namespace=DEFAULT_LLM_NAMESPACE, reason=exc
    +            ),
    +            prefix=False,
    +            safe=True,
    +        )
    +        raise typer.Exit(1) from exc
    +
    +
    +@app.command(name="prune", help=HELP.k8s.ollama_prune)
    +@dry_run_class("request-plan")
    +def ollama_prune_cmd(
    +    plan: Annotated[bool, typer.Option("--plan", help=HELP.k8s.ollama_prune_plan)] = False,
    +    dry_run: Annotated[bool, typer.Option("--dry-run", help=HELP.k8s.ollama_prune_dry_run)] = False,
    +    context: Annotated[
    +        str | None, typer.Option("--context", "-c", help=HELP.options.context)
    +    ] = None,
    +) -> None:
    +    """Remove each Ollama model that no tier of a node serves."""
    +    from devops_cli.commands.k8s.cluster_runtime import resolve_effective_context
    +    from devops_cli.core.validation import validate_k8s_context_name
    +
    +    effective_context = resolve_effective_context(context)
    +    if effective_context:
    +        validate_k8s_context_name(effective_context, "context")
    +    gateway = _read_manifest(DEFAULT_LLM_GATEWAY_CONFIG_PATH)
    +    if gateway is None:
    +        raise typer.Exit(1)
    +    if dry_run or is_dry_run():
    +        render_request_plan(
    +            CONST_K8S_OLLAMA_PRUNE_HEADING,
    +            plan_ollama_prune_requests(gateway, effective_context),
    +            (MESSAGES.dry_run.placeholders_note,),
    +        )
    +        return
    +    services = _read_manifest(DEFAULT_LLM_SERVICES_PATH)
    +    if services is None:
    +        raise typer.Exit(1)
    +    pods = _read_pods_or_exit(effective_context)
    +    if not pods:
    +        _say(
    +            MESSAGES.k8s.ollama_prune_no_pods.format(
    +                namespace=DEFAULT_LLM_NAMESPACE, label=_label_selector()
    +            )
    +        )
    +        return
    +    pod_by_node = _pod_by_node(pods)
    +    listed = {node: _list_node(pod, effective_context) for node, pod in pod_by_node.items()}
    +    entries = plan_ollama_prune(gateway, services, pods, listed)
    +    _say(MESSAGES.k8s.ollama_prune_heading.format(namespace=DEFAULT_LLM_NAMESPACE))
    +    for entry in entries:
    +        _print_node(entry)
    +    if plan:
    +        _say(MESSAGES.k8s.ollama_prune_plan_only)
    +        return
    +    failed = _remove_models(entries, pod_by_node, effective_context)
    +    if failed or any(entry.list_failed for entry in entries):
    +        raise typer.Exit(1)
    +
    +
    +__all__ = [
    +    "app",
    +    "ollama_prune_cmd",
    +    "plan_ollama_prune_requests",
    +    "read_ollama_pods",
    +]
    diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py
    index aa4679b1..3ae3a5f9 100644
    --- a/src/devops_cli/config/constants.py
    +++ b/src/devops_cli/config/constants.py
    @@ -3796,6 +3796,7 @@ CONST_K8S_ORPHAN_VOLUME_PHASES: Final[frozenset[str]] = frozenset(
         {CONST_K8S_PV_PHASE_RELEASED, CONST_K8S_PV_PHASE_FAILED}
     )
     CONST_K8S_VOLUME_RECLAIM_HEADING: Final[str] = "Planned Kubernetes Volume Reclaim API Requests:"
    +CONST_K8S_OLLAMA_PRUNE_HEADING: Final[str] = "Planned Kubernetes Ollama Prune Requests:"
     CONST_K8S_PV_API_PATH_TEMPLATE: Final[str] = "/api/v1/persistentvolumes/{name}"
     
     # ── Local-Path Volume Move (#2186) ─────────────────────────────────────────
    diff --git a/src/devops_cli/lang/en/help.py b/src/devops_cli/lang/en/help.py
    index c43134de..7ef91921 100644
    --- a/src/devops_cli/lang/en/help.py
    +++ b/src/devops_cli/lang/en/help.py
    @@ -536,6 +536,22 @@ class K8sCommandHelp:
             "Make no request, reads included: print the requests a move would make, in order, with "
             "placeholders for each value that a read gives. Wins over --plan."
         )
    +    ollama_app: str = "Prune the Ollama models that no tier of a node serves."
    +    ollama_prune: str = (
    +        "Remove each model that no tier of a node serves from the Ollama store of that node, "
    +        "through the Ollama API in one pod of the node. The keep set of a node is the set of "
    +        "models that the gateway config sends to the tier Services whose selector the Ollama pods "
    +        "of the node hold. A node whose ollama list fails keeps every model, is named, and makes "
    +        "the command exit 1."
    +    )
    +    ollama_prune_plan: str = (
    +        "Read the gateway routes, the tier Services, the Ollama pods and the model list of each "
    +        "node, print the models that each node keeps and removes, and remove nothing."
    +    )
    +    ollama_prune_dry_run: str = (
    +        "Make no request: print the kubectl exec commands that list and remove the models of each "
    +        "gateway target, with placeholders for the pod and the models. Wins over --plan."
    +    )
     
     
     @dataclass(frozen=True)
    diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py
    index a057b7f1..d1df1e8e 100644
    --- a/src/devops_cli/lang/en/messages.py
    +++ b/src/devops_cli/lang/en/messages.py
    @@ -992,6 +992,30 @@ class K8sMessages:
             "it deletes the copy pods and claim {claim}, scales the workloads back, sets the reclaim "
             "policies back and resumes Argo CD."
         )
    +    ollama_prune_heading: str = (
    +        "Ollama model prune of namespace {namespace}. Each node keeps the models that the gateway "
    +        "sends to the tiers that run on it."
    +    )
    +    ollama_prune_node: str = "Node {node}: keeps {keep}; removes {remove}."
    +    ollama_prune_node_keeps_all: str = "Node {node}: keeps {keep}; removes no model."
    +    ollama_prune_no_keep: str = "no model"
    +    ollama_prune_list_failed: str = (
    +        

    The item is Blocked, and the job will not run it. Fix the cause. Then comment implement: retry. The Service clears the stop on its own when a new runner image rolls out, but only if a retry can fix the class of the stop and the limits of roadmap.implement.digest_clears_per_class and roadmap.implement.digest_clears_per_item allow it.

  11. added
    status/blocked
    and removed
    status/in-progress
    on Nov 7, 2026
  12. devops-cli-service commented on Nov 7, 2026

    @devops-cli-service
    Contributor

    The runner Job devops-cli-runner-20261107-080202-c77f ended: succeeded.
    Image digest: sha256:a12d8a3601a2f9803ba6a7f77fe19fdcc27a4de30944a1e65fc19d08808e9eff

    The last lines of its log:

    Tool call: shell, started: uv run devops ci test tests/commands/k8s/test_k8s_ollama_prune.py
    Tool call: shell, program uv, ok.
    Tool call: shell, started: uv run ruff check src/devops_cli/commands/k8s/ollama.py src/devops_cli/commands/k8s/__init__.py ...
    Tool call: shell, started: uv run mypy --strict src/devops_cli/commands/k8s/ollama.py src/devops_cli/commands/k8s/__init__.py
    Tool call: shell, program uv, ok.
    Tool call: shell, program uv, ok.
    Tool call: edit_file, ok.
    Tool call: shell, started: uv run ruff check src/devops_cli/commands/k8s/ollama.py src/devops_cli/commands/k8s/__init__.py ...
    Tool call: shell, started: uv run devops ci test tests/k8s/test_k8s_ollama_prune.py
    Tool call: shell, program uv, ok.
    Tool call: shell, program uv, ok.
    Tool call: edit_file, ok.
    Tool call: shell, started: uv run devops docs generate --sync-readme
    Tool call: shell, program uv, ok.
    Tool call: shell, started: git status --short
    Tool call: shell, program git, ok.
    Tool call: shell, started: uv run devops ci docs
    Tool call: shell, program uv, ok.
    Tool call: shell, started: grep -rln HELP.k8s\\|help.py tests --include=<masked> | ...
    Tool call: shell, started: grep -rln MESSAGES.k8s\\|messages.py tests --include=<masked> | ...
    Tool call: shell, program grep, ok.
    Tool call: shell, program grep, ok.
    Tool call: shell, started: uv run devops ci test tests/k8s/test_k8s_ollama_models.py
    Tool call: shell, started: uv run devops ci test tests/commands/k8s/test_k8s.py
    Tool call: shell, program uv, ok.
    Tool call: shell, program uv, ok.
    Tool call: shell, started: uv run pytest tests/commands/k8s/test_k8s.py -k test_deploy_stack_infra_on_argo_cd_sets_only_the_ingress_hosts ...
    Tool call: shell, program uv, ok.
    Tool call: shell, started: grep -n <masked> -A 12 tests/commands/k8s/test_k8s.py ...
    Tool call: shell, program grep, ok.
    Tool call: shell, started: uv run python -c __import__("pathlib").Path(".data/agent/scratch").mkdir(parents=<masked>
    Tool call: shell, program uv, ok.
    Tool call: write_file, ok.
    Tool call: shell, started: other
    Tool call: shell, program other:f29942ea1104, refused.
    Tool call: read_file, ok.
    Tool call: read_file, ok.
    Failure class limit_reached. Action left: raise_limit.
    ✓ Took 0 item(s) to a ready pull request, stopped 1.
    Elapsed: 22m 56s
    
  13. removed
    owner/service
    on Nov 7, 2026
  14. added
    status/in-review
    and removed
    status/blocked
    on Nov 7, 2026
  15. removed
    status/in-review
    on Nov 7, 2026
  16. devops-cli-service commented on Nov 7, 2026

    @devops-cli-service
    Contributor

    Live since 2026-11-07 15:48 UTC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    effort/mediumpriority/p1-highscope/k8ssource/agenttype/bugvalue/high

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions