From 83005f8110576991eb0f8aa5bf620563fce96079 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 23 Sep 2026 22:14:16 +0000 Subject: [PATCH 1/3] feat(k8s): give the gateway one deployment per Ollama node The gateway reached Ollama through the `ollama` Service. kube-proxy balances per connection and LiteLLM keeps its connections open, so all gateway traffic to Ollama went to one pod: in a full review one node served 15 requests and the other 0. With one deployment covering every node, LiteLLM could not match load to each node's single request slot or cool down a failing node on its own. - Ollama runs as a StatefulSet (k8s/llm/ollama.yaml) with per-pod DNS through the headless ollama-nodes Service, required anti-affinity for one pod per GPU node, and Parallel pod management so an offline node never blocks the others. Architecture affinity, hostPort, hostPath models and the `ollama` NodePort Service are unchanged. - The gateway lists every pod for devops-chat, devops-embedding, the Ollama tier of devops-review (max_parallel_requests 1, matching OLLAMA_NUM_PARALLEL) and the ollama/* pass-through. devops-chat moves to ollama_chat/, like the review tier. - Health checks probe embedding deployments as embeddings and the wildcard with a real model instead of a placeholder. - A test keeps the per-pod entries in step with the replica count. Closes #463 --- docs/ROADMAP.md | 5 + .../tasks/task-463-ollama-per-node-routing.md | 57 +++++++++ docs/cheatsheets/kubernetes.md | 2 +- docs/squid-failover-and-observability.md | 2 +- k8s/README.md | 4 +- k8s/llm/gateway/configmap.yaml | 52 +++++++-- k8s/llm/kustomization.yaml | 2 +- .../{ollama-daemonset.yaml => ollama.yaml} | 44 ++++++- k8s/llm/vllm-single/deployment.yaml | 2 +- k8s/llm/vllm/deployment.yaml | 2 +- .../devops_cli/tasks/k8s_stack_deployment.md | 2 +- .../knowledge_base/it_domains/tools/ollama.md | 2 +- .../commands/k8s/stack_lifecycle.py | 2 +- tests/test_k8s.py | 10 +- tests/test_k8s_llm_gateway.py | 110 ++++++++++++++++-- tests/test_k8s_squid.py | 14 +-- 16 files changed, 269 insertions(+), 43 deletions(-) create mode 100644 docs/agent/tasks/task-463-ollama-per-node-routing.md rename k8s/llm/{ollama-daemonset.yaml => ollama.yaml} (73%) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 8a0ce83aad..16d71f316d 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -314,6 +314,11 @@ High-density product roadmap, engineering milestones, and open-source integratio - *Context & Rationale*: `api_base_url` outranked `gateway_url` and every task inherited the global value. A task on `provider: gateway` under a global OpenAI setup sent its requests and the gateway master key to OpenAI. Any task switching provider sent its key to the global provider's endpoint, and the pydantic-ai bridge resolved `litellm:` models the same way. - *Delivered*: Provider `gateway` always sends to `gateway_url`, and a gateway task's own `api_base_url` becomes that task's gateway address. The global `api_base_url` carries over only to tasks that keep the global provider. The bridge's `litellm:`, `portkey:` and `lightllm:` prefixes use `gateway_url`, `portkey_url` and `lightllm_url`. +- [x] **One Gateway Deployment per Ollama Node (`#463`) (P2 - Medium)**: + - *Context & Rationale*: Through the `ollama` Service, LiteLLM's long-lived connections pinned all gateway traffic to one Ollama pod: in a full review, one node served 15 requests and the other 0. With one deployment covering every node, LiteLLM could neither match load to each node's single request slot nor cool down a failing node on its own. + - *Delivered*: Ollama runs as a StatefulSet (`k8s/llm/ollama.yaml`) with per-pod DNS through the headless `ollama-nodes` Service and one pod per GPU node. The gateway lists every pod for `devops-chat`, `devops-embedding`, the Ollama tier of `devops-review` and `ollama/*`. Embedding deployments are health-checked as embeddings, and the wildcard with a real model. + - *Remaining*: `replicas` and the gateway's per-pod entries are set by hand to match the number of Ollama GPU nodes; a test keeps them in step. + ### Reactive Workstation Command Center, Interactive TUI & Unified Operations Hub (v0.2.24 - Scheduled) - [ ] **Reactive Multi-Workspace Textual TUI Architecture & Master-Detail Navigation (`devops dashboard`, `devops tui`) (P0 - Critical)**: - *Context & Rationale*: Modernizes the basic Textual dashboard from static read-only tables into a reactive, multi-workspace workstation command center with non-blocking async workers (`work()`), real-time push events, and master-detail ergonomic split screens (navigation tree/list on left, contextual detail inspector with YAML/logs/markdown on right). diff --git a/docs/agent/tasks/task-463-ollama-per-node-routing.md b/docs/agent/tasks/task-463-ollama-per-node-routing.md new file mode 100644 index 0000000000..b1871ebf00 --- /dev/null +++ b/docs/agent/tasks/task-463-ollama-per-node-routing.md @@ -0,0 +1,57 @@ +# Task 463: One Gateway Deployment per Ollama Node + +**Issue**: [#463](https://github.com/dan-petty/devops-cli/issues/463) +**PR**: pending +**Status**: In Review +**Milestone**: `v0.2.23` +**Priority**: `priority/p2-medium` +**Scope**: `type/feature`, `scope/k8s`, `scope/ai`, `priority/p2-medium` + +--- + +## 1. Description & Objectives + +The gateway reached Ollama through the `ollama` Service. kube-proxy balances per TCP connection +and LiteLLM keeps its connections open, so all gateway traffic to Ollama went to whichever pod +the first connections landed on. In a full review, one Ollama node served 15 requests and the +other served 0. Because every Ollama node sat behind one gateway deployment, LiteLLM could not +match load to each node's single request slot (`OLLAMA_NUM_PARALLEL=1`), and it could not cool +down a failing node without cooling down all of them. + +The gateway's health report was also wrong. `devops-embedding` was reported unhealthy because it +was probed with a generate call, and the `ollama/*` wildcard was probed with a placeholder model. + +### Key Deliverables Completed: + +- [x] **Ollama StatefulSet** (`k8s/llm/ollama.yaml`, formerly `ollama-daemonset.yaml`): pods + get stable DNS names through the headless `ollama-nodes` Service. Required pod anti-affinity + keeps one pod per GPU node, and `podManagementPolicy: Parallel` stops an offline node from + blocking the others. Architecture affinity, `hostPort`, node-local `hostPath` models and the + `ollama` NodePort Service are unchanged. +- [x] **Per-Pod Gateway Deployments**: `devops-chat`, `devops-embedding`, the Ollama tier of + `devops-review` and the `ollama/*` pass-through each list every pod. Review entries take + `max_parallel_requests: 1`, matching `OLLAMA_NUM_PARALLEL`. `devops-chat` moves to + `ollama_chat/`, the same chat endpoint the review tier uses. +- [x] **Health Checks**: `mode: embedding` for embedding deployments, and a real + `health_check_model` for the wildcard. +- [x] **Automated Tests & Quality Gates**: + - `tests/test_k8s_llm_gateway.py`: per-pod deployments track the StatefulSet's replica count + and `OLLAMA_NUM_PARALLEL`; the headless Service, anti-affinity and shared Service; health + check modes; review windows per pod. + - `tests/test_k8s.py`, `tests/test_k8s_squid.py`: probes, storage and proxy settings on the + StatefulSet. + - 100% passing status across Gated CI validation suite (`uv run devops ci`). + +## 2. Rollout + +The DaemonSet holds host port 11434, so it must be deleted before the StatefulSet can start: + +```bash +kubectl -n llm delete daemonset ollama +kubectl apply -f k8s/llm/ollama.yaml +kubectl -n llm rollout status statefulset/ollama +kubectl apply -f k8s/llm/gateway/configmap.yaml +kubectl -n llm rollout restart deployment/llm-gateway +``` + +Models stay on each node's `hostPath`, so nothing is downloaded again. diff --git a/docs/cheatsheets/kubernetes.md b/docs/cheatsheets/kubernetes.md index f1eb78ef75..924363ae41 100644 --- a/docs/cheatsheets/kubernetes.md +++ b/docs/cheatsheets/kubernetes.md @@ -20,7 +20,7 @@ Compare standard `kubectl`, `helm`, and `kustomize` workflows with unified `devo | Action / Goal | Original Command (`kubectl`) | `devops-cli` Command | Key Enhancements in `devops-cli` | | :--- | :--- | :--- | :--- | | **List Stack Pods** | `kubectl get pods -A -l app.kubernetes.io/part-of=devops-cli-stack` | `devops k8s pods [-n ]` | Color-coded status tables highlighting crashloops, restart counts, and container resource limits. | -| **Check Stack Health** | Multiple `kubectl get svc,deploy,ds,statefulsets` | `devops k8s status [-c ]` | Complete health audit evaluating DaemonSets (Ollama GPUs), deployments, and ingress reachability. | +| **Check Stack Health** | Multiple `kubectl get svc,deploy,ds,statefulsets` | `devops k8s status [-c ]` | Complete health audit evaluating StatefulSets (Ollama GPUs), deployments, and ingress reachability. | | **Auto-Detect Service Endpoints** | `kubectl get svc -A -o jsonpath=...` | `devops k8s configure-urls [-c ]` | Discovers cluster IP/NodePort/hostPort targets and automatically updates local `devops config` settings. | --- diff --git a/docs/squid-failover-and-observability.md b/docs/squid-failover-and-observability.md index dc277167cf..2fcfbe978c 100644 --- a/docs/squid-failover-and-observability.md +++ b/docs/squid-failover-and-observability.md @@ -40,7 +40,7 @@ graph TD end subgraph "Client Workloads" - ollama["Ollama GPU DaemonSet
(llm namespace)"] + ollama["Ollama GPU StatefulSet
(llm namespace)"] end ollama -->|"HTTP_PROXY (port 3128)"| squid diff --git a/k8s/README.md b/k8s/README.md index f7a3cba24c..67ac74a2c4 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -107,9 +107,9 @@ Inference engines are placed by GPU architecture, using node labels from NVIDIA | :--- | :--- | :--- | :--- | :--- | | `vllm` Deployment | 2+ Ampere-or-newer GPUs | Qwen2.5-Coder-32B-Instruct-AWQ, tensor parallel 2, 64K context (YaRN) | `qwen2.5-coder-32b-instruct` | `devops-reasoning` | | `vllm-single` Deployment | 1 Ampere-or-newer GPU with 16 GiB+ | Qwen2.5-Coder-14B-Instruct-AWQ, FP8 KV cache, 16K context | `qwen2.5-coder-14b-instruct` | `devops-coder` | -| `ollama` DaemonSet | GPUs older than Ampere | Pulled on demand | Ollama model tags | `devops-chat`, `devops-embedding` | +| `ollama` StatefulSet, one pod per node | GPUs older than Ampere | Pulled on demand | Ollama model tags | `devops-chat`, `devops-embedding`, `ollama/*` | -Both vLLM Deployments keep weights on a PersistentVolumeClaim (`vllm-model-cache`, `vllm-single-model-cache`), download through the Squid proxy (trusting its CA, with Hugging Face Xet transfers disabled because they fail through SSL bumping), and are reachable only inside the cluster, through the gateway. A vLLM pod stays `Pending` until a node carries matching GPU labels. The first start downloads the weights, which can take hours on a home connection; the startup probe allows 3 hours before restarting the pod. The Ollama-backed aliases expect `qwen2.5-coder:7b` and `bge-m3` on every Ollama node, since the `ollama` Service balances across them (`ollama pull qwen2.5-coder:7b`). +Both vLLM Deployments keep weights on a PersistentVolumeClaim (`vllm-model-cache`, `vllm-single-model-cache`), download through the Squid proxy (trusting its CA, with Hugging Face Xet transfers disabled because they fail through SSL bumping), and are reachable only inside the cluster, through the gateway. A vLLM pod stays `Pending` until a node carries matching GPU labels. The first start downloads the weights, which can take hours on a home connection; the startup probe allows 3 hours before restarting the pod. The gateway lists each Ollama pod (`ollama-.ollama-nodes`) as its own deployment, so it balances load and cools down failures per node. Through the `ollama` Service, LiteLLM's long-lived connections would pin every request to one pod. The Ollama-backed aliases therefore expect `qwen2.5-coder:7b`, `bge-m3` and `gpt-oss:20b` on every Ollama node (`ollama pull qwen2.5-coder:7b`). Set `replicas` in `llm/ollama.yaml` to the number of GPU nodes Ollama may use, and keep one gateway entry per replica in `llm/gateway/configmap.yaml`. A replica with no node to run on stays `Pending`, and requests sent to it fail over to the other nodes. ## Port Forwarding & Automated Configuration diff --git a/k8s/llm/gateway/configmap.yaml b/k8s/llm/gateway/configmap.yaml index f4d75eebb0..fe94059e32 100644 --- a/k8s/llm/gateway/configmap.yaml +++ b/k8s/llm/gateway/configmap.yaml @@ -10,11 +10,19 @@ metadata: app.kubernetes.io/part-of: devops-cli-stack data: config.yaml: | + # Ollama-backed groups list every Ollama pod (ollama-.ollama-nodes, one per GPU node) as + # its own deployment, so LiteLLM balances load and cools down failures per node. Through the + # `ollama` Service its long-lived connections would pin all traffic to one pod. Keep one + # entry per replica of k8s/llm/ollama.yaml. model_list: - model_name: devops-chat litellm_params: - model: ollama/qwen2.5-coder:7b - api_base: http://ollama.llm.svc.cluster.local:11434 + model: ollama_chat/qwen2.5-coder:7b + api_base: http://ollama-0.ollama-nodes.llm.svc.cluster.local:11434 + - model_name: devops-chat + litellm_params: + model: ollama_chat/qwen2.5-coder:7b + api_base: http://ollama-1.ollama-nodes.llm.svc.cluster.local:11434 - model_name: devops-coder litellm_params: model: openai/qwen2.5-coder-14b-instruct @@ -31,10 +39,19 @@ data: # Prompt budget inside the 64K vLLM window, leaving 4K tokens for the reply. model_info: max_input_tokens: 61440 + # mode: embedding makes health checks embed rather than generate, which bge-m3 rejects. + - model_name: devops-embedding + litellm_params: + model: ollama/bge-m3 + api_base: http://ollama-0.ollama-nodes.llm.svc.cluster.local:11434 + model_info: + mode: embedding - model_name: devops-embedding litellm_params: model: ollama/bge-m3 - api_base: http://ollama.llm.svc.cluster.local:11434 + api_base: http://ollama-1.ollama-nodes.llm.svc.cluster.local:11434 + model_info: + mode: embedding # devops-review: one virtual model spread over every inference server, so a review's # parallel persona and verification calls use all of them. least-busy routing plus @@ -58,23 +75,42 @@ data: max_parallel_requests: 2 model_info: max_input_tokens: 12288 + # One request at a time per Ollama node (OLLAMA_NUM_PARALLEL=1). max_input_tokens is + # OLLAMA_CONTEXT_LENGTH (48000) minus 4K tokens for the reply. - model_name: devops-review litellm_params: model: ollama_chat/gpt-oss:20b - api_base: http://ollama.llm.svc.cluster.local:11434 - # One request per Ollama node (OLLAMA_NUM_PARALLEL=1); raise with the node count. - max_parallel_requests: 2 - # OLLAMA_CONTEXT_LENGTH (48000) minus 4K tokens for the reply. + api_base: http://ollama-0.ollama-nodes.llm.svc.cluster.local:11434 + max_parallel_requests: 1 + model_info: + max_input_tokens: 43904 + - model_name: devops-review + litellm_params: + model: ollama_chat/gpt-oss:20b + api_base: http://ollama-1.ollama-nodes.llm.svc.cluster.local:11434 + max_parallel_requests: 1 model_info: max_input_tokens: 43904 # Pass-through: any model on the Ollama nodes by name, e.g. `ollama/gpt-oss:20b`. Ollama's # OpenAI-compatible API serves both chat (with the model's own template) and embeddings. + # A model pulled on only some nodes still answers: a node without it fails, and the retry + # moves to another node. Health checks need a concrete model; without one LiteLLM probes a + # placeholder that no node has. - model_name: ollama/* litellm_params: model: openai/* - api_base: http://ollama.llm.svc.cluster.local:11434/v1 + api_base: http://ollama-0.ollama-nodes.llm.svc.cluster.local:11434/v1 api_key: none + model_info: + health_check_model: openai/qwen2.5-coder:7b + - model_name: ollama/* + litellm_params: + model: openai/* + api_base: http://ollama-1.ollama-nodes.llm.svc.cluster.local:11434/v1 + api_key: none + model_info: + health_check_model: openai/qwen2.5-coder:7b router_settings: routing_strategy: least-busy diff --git a/k8s/llm/kustomization.yaml b/k8s/llm/kustomization.yaml index 1d16650d45..3debb1a361 100644 --- a/k8s/llm/kustomization.yaml +++ b/k8s/llm/kustomization.yaml @@ -6,7 +6,7 @@ resources: - networkpolicy.yaml - ca-configmap.yaml - valkey.yaml - - ollama-daemonset.yaml + - ollama.yaml - gateway/configmap.yaml - gateway/deployment.yaml - gateway/service.yaml diff --git a/k8s/llm/ollama-daemonset.yaml b/k8s/llm/ollama.yaml similarity index 73% rename from k8s/llm/ollama-daemonset.yaml rename to k8s/llm/ollama.yaml index f362063f06..72cc002e63 100644 --- a/k8s/llm/ollama-daemonset.yaml +++ b/k8s/llm/ollama.yaml @@ -1,5 +1,9 @@ +# Ollama serves GPUs older than Ampere, one pod per GPU node. A StatefulSet rather than a +# DaemonSet gives each pod a stable DNS name (ollama-.ollama-nodes), so the gateway can list +# every node as its own deployment: through the `ollama` Service, LiteLLM's long-lived +# connections pin all gateway traffic to one pod. apiVersion: apps/v1 -kind: DaemonSet +kind: StatefulSet metadata: name: ollama namespace: llm @@ -8,6 +12,12 @@ metadata: app.kubernetes.io/instance: ollama app.kubernetes.io/part-of: devops-cli-stack spec: + # One per GPU node that Ollama may use. Keep one gateway deployment per replica in + # gateway/configmap.yaml (devops-chat, devops-embedding and the Ollama tier of devops-review). + replicas: 2 + serviceName: ollama-nodes + # Start and replace pods independently, so a node that is offline never holds up the others. + podManagementPolicy: Parallel selector: matchLabels: app.kubernetes.io/name: ollama @@ -35,6 +45,14 @@ spec: - key: nvidia.com/gpu.architecture operator: NotIn values: [ampere, ada-lovelace, hopper, blackwell] + # One pod per node: each owns the node's GPUs, host port and model directory. + podAntiAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - topologyKey: kubernetes.io/hostname + labelSelector: + matchLabels: + app.kubernetes.io/name: ollama + app.kubernetes.io/instance: ollama containers: - name: ollama image: ollama/ollama:0.32.14 @@ -122,6 +140,30 @@ spec: name: squid-ca-cert optional: false --- +# Per-pod DNS for the gateway: ollama-.ollama-nodes.llm.svc.cluster.local. Only ready pods +# resolve, so the gateway's retries skip a pod that is down. +apiVersion: v1 +kind: Service +metadata: + name: ollama-nodes + namespace: llm + labels: + app.kubernetes.io/name: ollama + app.kubernetes.io/instance: ollama + app.kubernetes.io/part-of: devops-cli-stack +spec: + clusterIP: None + selector: + app.kubernetes.io/name: ollama + app.kubernetes.io/instance: ollama + ports: + - name: http + port: 11434 + targetPort: 11434 + protocol: TCP +--- +# Any Ollama node, for clients that need no particular one (Open WebUI, port-forwards, the +# gateway's ollama/* pass-through). apiVersion: v1 kind: Service metadata: diff --git a/k8s/llm/vllm-single/deployment.yaml b/k8s/llm/vllm-single/deployment.yaml index 51529ac2e4..e1c3f49405 100644 --- a/k8s/llm/vllm-single/deployment.yaml +++ b/k8s/llm/vllm-single/deployment.yaml @@ -1,5 +1,5 @@ # vLLM single-GPU continuous batching inference engine for nodes with one Ampere-or-newer GPU -# (16 GiB or more). Older architectures run the Ollama DaemonSet instead. +# (16 GiB or more). Older architectures run Ollama (../ollama.yaml) instead. --- apiVersion: apps/v1 kind: Deployment diff --git a/k8s/llm/vllm/deployment.yaml b/k8s/llm/vllm/deployment.yaml index 4a3175eff0..f539e7139f 100644 --- a/k8s/llm/vllm/deployment.yaml +++ b/k8s/llm/vllm/deployment.yaml @@ -1,5 +1,5 @@ # vLLM Tensor-Parallel (TP=2) continuous batching inference engine for nodes with two or more -# Ampere-or-newer GPUs. Older architectures run the Ollama DaemonSet instead. +# Ampere-or-newer GPUs. Older architectures run Ollama (../ollama.yaml) instead. --- apiVersion: apps/v1 kind: Deployment diff --git a/src/devops_cli/ai/knowledge_base/devops_cli/tasks/k8s_stack_deployment.md b/src/devops_cli/ai/knowledge_base/devops_cli/tasks/k8s_stack_deployment.md index 54e3ace528..d9b0facfd7 100644 --- a/src/devops_cli/ai/knowledge_base/devops_cli/tasks/k8s_stack_deployment.md +++ b/src/devops_cli/ai/knowledge_base/devops_cli/tasks/k8s_stack_deployment.md @@ -24,7 +24,7 @@ graph TD - `gitops`: ArgoCD server, controller, and repo server in `argocd` namespace. - `tracing`: Jaeger distributed tracing query & collector in `otel` namespace. - `otel`: OpenTelemetry Collector DaemonSet/Deployment and Jaeger in `otel` namespace. - - `llm`: Local LLM stack (Ollama DaemonSet, Open-WebUI, Qdrant Vector DB, Valkey Cache) in `llm` namespace. + - `llm`: Local LLM stack (Ollama StatefulSet, Open-WebUI, Qdrant Vector DB, Valkey Cache) in `llm` namespace. - `all`: Bootstraps all stacks (`monitoring`, `gitops`, `otel`, `llm`) with automatic port-forwarding and service URL target detection. --- diff --git a/src/devops_cli/ai/knowledge_base/it_domains/tools/ollama.md b/src/devops_cli/ai/knowledge_base/it_domains/tools/ollama.md index 573ff48665..b4965208c6 100644 --- a/src/devops_cli/ai/knowledge_base/it_domains/tools/ollama.md +++ b/src/devops_cli/ai/knowledge_base/it_domains/tools/ollama.md @@ -79,7 +79,7 @@ curl http://localhost:11434/api/embeddings -d '{ ## 4. Best Practice Guidance & Performance Tuning 1. **Optimize Concurrency in Kubernetes / Host Daemons**: - - When deploying Ollama via Kubernetes ([`k8s/llm/ollama-daemonset.yaml`](../../../../../../k8s/llm/ollama-daemonset.yaml)), configure: + - When deploying Ollama via Kubernetes ([`k8s/llm/ollama.yaml`](../../../../../../k8s/llm/ollama.yaml)), configure: ```yaml env: - name: OLLAMA_NUM_PARALLEL diff --git a/src/devops_cli/commands/k8s/stack_lifecycle.py b/src/devops_cli/commands/k8s/stack_lifecycle.py index e1a32a70a2..fe72296d92 100644 --- a/src/devops_cli/commands/k8s/stack_lifecycle.py +++ b/src/devops_cli/commands/k8s/stack_lifecycle.py @@ -111,7 +111,7 @@ ], "llm": [ DEFAULT_K8S_DIR / "llm" / "valkey.yaml", - DEFAULT_K8S_DIR / "llm" / "ollama-daemonset.yaml", + DEFAULT_K8S_DIR / "llm" / "ollama.yaml", ], "logging": [ DEFAULT_K8S_DIR / "logging" / "networkpolicy.yaml", diff --git a/tests/test_k8s.py b/tests/test_k8s.py index 7bcf91ef34..5f5cb355fb 100644 --- a/tests/test_k8s.py +++ b/tests/test_k8s.py @@ -809,12 +809,12 @@ def test_k8s_workload_resource_limits_and_probes() -> None: """Verify workload resource limits, relaxed memory constraints, and resilient probes.""" repo_root = Path(__file__).resolve().parent.parent - # 1. Ollama DaemonSet: unconstrained memory limits for node-adaptive scaling, requests 8Gi, robust startup and liveness probes - ollama_path = repo_root / "k8s" / "llm" / "ollama-daemonset.yaml" + # 1. Ollama StatefulSet: unconstrained memory limits for node-adaptive scaling, requests 8Gi, robust startup and liveness probes + ollama_path = repo_root / "k8s" / "llm" / "ollama.yaml" assert ollama_path.is_file() ollama_docs = list(yaml.safe_load_all(ollama_path.read_text(encoding="utf-8"))) - daemonset = next(d for d in ollama_docs if d and d.get("kind") == "DaemonSet") - container = daemonset["spec"]["template"]["spec"]["containers"][0] + statefulset = next(d for d in ollama_docs if d and d.get("kind") == "StatefulSet") + container = statefulset["spec"]["template"]["spec"]["containers"][0] resources = container.get("resources", {}) assert "limits" not in resources or "memory" not in resources.get("limits", {}) assert resources["requests"]["memory"] == "8Gi" @@ -828,7 +828,7 @@ def test_k8s_workload_resource_limits_and_probes() -> None: assert container["startupProbe"]["failureThreshold"] == 60 # Storage: verify hostPath contract for node-local model persistence - volumes = daemonset["spec"]["template"]["spec"]["volumes"] + volumes = statefulset["spec"]["template"]["spec"]["volumes"] ollama_vol = next(v for v in volumes if v["name"] == "ollama-data") assert ollama_vol["hostPath"]["path"] == "/var/lib/ollama" assert ollama_vol["hostPath"]["type"] == "DirectoryOrCreate" diff --git a/tests/test_k8s_llm_gateway.py b/tests/test_k8s_llm_gateway.py index 4a3a7508c4..c37e9fe268 100644 --- a/tests/test_k8s_llm_gateway.py +++ b/tests/test_k8s_llm_gateway.py @@ -23,7 +23,7 @@ GATEWAY_DIR = Path("k8s/llm/gateway") VLLM_DIR = Path("k8s/llm/vllm") VLLM_SINGLE_DIR = Path("k8s/llm/vllm-single") -OLLAMA_DAEMONSET = Path("k8s/llm/ollama-daemonset.yaml") +OLLAMA_MANIFEST = Path("k8s/llm/ollama.yaml") LLM_KUSTOMIZATION = Path("k8s/llm/kustomization.yaml") OPEN_WEBUI_VALUES = Path("k8s/llm/values-open-webui.yaml") @@ -36,7 +36,6 @@ GPU_ARCHITECTURE_LABELS = ["nvidia.com/gpu.architecture", "nvidia.com/gpu.family"] CA_BUNDLE = "/etc/ssl/bundle/ca-certificates.crt" SQUID_PROXY = "http://squid.squid.svc.cluster.local:3128" -OLLAMA_CLUSTER_URL = "http://ollama.llm.svc.cluster.local:11434" def _load_kind(path: Path, kind: str) -> dict[str, Any]: @@ -55,6 +54,23 @@ def _vllm_container(dep: dict[str, Any]) -> dict[str, Any]: return next(c for c in dep["spec"]["template"]["spec"]["containers"] if c["name"] == "vllm") +def _ollama_pod_urls() -> list[str]: + """Return the per-pod URL of every Ollama StatefulSet replica, via its headless Service.""" + sts = _load_kind(OLLAMA_MANIFEST, "StatefulSet") + service = sts["spec"]["serviceName"] + return [ + f"http://ollama-{n}.{service}.llm.svc.cluster.local:11434" + for n in range(sts["spec"]["replicas"]) + ] + + +def _deployments(group: str) -> list[dict[str, Any]]: + """Return the gateway deployments of one model group, in configuration order.""" + cm = _load_kind(GATEWAY_DIR / "configmap.yaml", "ConfigMap") + cfg = yaml.safe_load(cm["data"]["config.yaml"]) + return [m for m in cfg["model_list"] if m["model_name"] == group] + + def _node_selector_terms(pod_spec: dict[str, Any]) -> list[dict[str, Any]]: """Return required node affinity terms of a pod spec.""" affinity = pod_spec["affinity"]["nodeAffinity"] @@ -187,10 +203,11 @@ def test_gateway_review_pool_spans_every_inference_backend(self) -> None: } ollama_env = { e["name"]: e.get("value") - for e in _load_kind(OLLAMA_DAEMONSET, "DaemonSet")["spec"]["template"]["spec"][ + for e in _load_kind(OLLAMA_MANIFEST, "StatefulSet")["spec"]["template"]["spec"][ "containers" ][0]["env"] } + ollama_window = int(ollama_env["OLLAMA_CONTEXT_LENGTH"] or 0) windows = { DEFAULT_VLLM_CLUSTER_URL: int( _flag( @@ -208,20 +225,65 @@ def test_gateway_review_pool_spans_every_inference_backend(self) -> None: ) or 0 ), - OLLAMA_CLUSTER_URL: int(ollama_env["OLLAMA_CONTEXT_LENGTH"] or 0), + **dict.fromkeys(_ollama_pod_urls(), ollama_window), } - passthrough = next(m for m in cfg["model_list"] if m["model_name"] == "ollama/*") assert ( sorted(pool), all(m["litellm_params"]["max_parallel_requests"] >= 1 for m in pool.values()), all(m["model_info"]["max_input_tokens"] < windows[base] for base, m in pool.items()), - passthrough["litellm_params"]["api_base"], ) == ( sorted(windows), True, True, - f"{OLLAMA_CLUSTER_URL}/v1", + ) + + def test_gateway_lists_one_deployment_per_ollama_pod(self) -> None: + """Verify each Ollama-backed group has one deployment per StatefulSet pod. + + The `ollama` Service would pin all gateway traffic to one pod, because LiteLLM keeps its + connections open; per-pod deployments let LiteLLM balance and cool down each node. + """ + ollama_env = { + e["name"]: e.get("value") + for e in _load_kind(OLLAMA_MANIFEST, "StatefulSet")["spec"]["template"]["spec"][ + "containers" + ][0]["env"] + } + review_ollama = [ + m for m in _deployments("devops-review") if "ollama" in m["litellm_params"]["model"] + ] + + assert ( + [m["litellm_params"]["api_base"] for m in _deployments("devops-chat")], + [m["litellm_params"]["api_base"] for m in _deployments("devops-embedding")], + [m["litellm_params"]["api_base"] for m in review_ollama], + [m["litellm_params"]["api_base"] for m in _deployments("ollama/*")], + {m["litellm_params"]["max_parallel_requests"] for m in review_ollama}, + ) == ( + _ollama_pod_urls(), + _ollama_pod_urls(), + _ollama_pod_urls(), + [f"{url}/v1" for url in _ollama_pod_urls()], + {int(ollama_env["OLLAMA_NUM_PARALLEL"] or 0)}, + ) + + def test_gateway_health_checks_probe_each_deployment_the_way_it_is_called(self) -> None: + """Verify embedding deployments are probed as embeddings and the wildcard with a real model. + + LiteLLM probes with a chat completion by default, which embedding-only models reject, and + probes a wildcard with a placeholder model name that no Ollama node has. + """ + passthrough = _deployments("ollama/*")[0] + health_model = passthrough["model_info"]["health_check_model"] + chat_model = _deployments("devops-chat")[0]["litellm_params"]["model"].split("/", 1)[1] + + assert ( + {m.get("model_info", {}).get("mode") for m in _deployments("devops-embedding")}, + health_model, + ) == ( + {"embedding"}, + f"openai/{chat_model}", ) def test_gateway_service_and_network_policy(self) -> None: @@ -417,10 +479,10 @@ def test_vllm_profiles_select_gpu_count_and_architecture( for label in GPU_ARCHITECTURE_LABELS ] - def test_ollama_daemonset_leaves_vllm_architectures_to_vllm(self) -> None: + def test_ollama_leaves_vllm_architectures_to_vllm(self) -> None: """Verify Ollama runs only on GPU nodes whose architecture is not reserved for vLLM.""" - ds = _load_kind(OLLAMA_DAEMONSET, "DaemonSet") - spec = ds["spec"]["template"]["spec"] + sts = _load_kind(OLLAMA_MANIFEST, "StatefulSet") + spec = sts["spec"]["template"]["spec"] terms = _node_selector_terms(spec) expressions = sorted( (e["key"], e["operator"], sorted(e["values"])) @@ -438,6 +500,32 @@ def test_ollama_daemonset_leaves_vllm_architectures_to_vllm(self) -> None: [(label, "NotIn", VLLM_ARCHITECTURES) for label in GPU_ARCHITECTURE_LABELS], ) + def test_ollama_pods_have_stable_names_one_per_gpu_node(self) -> None: + """Verify Ollama pods get per-pod DNS, one pod per node, and keep the shared Service.""" + docs = [d for d in yaml.safe_load_all(OLLAMA_MANIFEST.read_text(encoding="utf-8")) if d] + sts = next(d for d in docs if d["kind"] == "StatefulSet") + services = {d["metadata"]["name"]: d["spec"] for d in docs if d["kind"] == "Service"} + pod_labels = sts["spec"]["template"]["metadata"]["labels"] + anti_affinity = sts["spec"]["template"]["spec"]["affinity"]["podAntiAffinity"][ + "requiredDuringSchedulingIgnoredDuringExecution" + ] + headless = services[sts["spec"]["serviceName"]] + + assert ( + sts["spec"]["podManagementPolicy"], + [(t["topologyKey"], t["labelSelector"]["matchLabels"]) for t in anti_affinity], + headless["clusterIP"], + headless["selector"], + services["ollama"]["selector"], + ) == ( + "Parallel", + [("kubernetes.io/hostname", sts["spec"]["selector"]["matchLabels"])], + "None", + sts["spec"]["selector"]["matchLabels"], + sts["spec"]["selector"]["matchLabels"], + ) + assert sts["spec"]["selector"]["matchLabels"].items() <= pod_labels.items() + @pytest.mark.parametrize("profile_dir", [VLLM_DIR, VLLM_SINGLE_DIR]) def test_vllm_profiles_trust_squid_ca_and_persist_model_cache(self, profile_dir: Path) -> None: """Verify vLLM downloads through the SSL-bumping proxy, keeps weights, and tolerates long loads.""" @@ -560,7 +648,7 @@ def test_zero_homelab_ip_or_hostname_leakage(self) -> None: *GATEWAY_DIR.glob("*.yaml"), *VLLM_DIR.glob("*.yaml"), *VLLM_SINGLE_DIR.glob("*.yaml"), - OLLAMA_DAEMONSET, + OLLAMA_MANIFEST, ] private_ip_pattern = re.compile( r"\b(192\.168\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})\b" diff --git a/tests/test_k8s_squid.py b/tests/test_k8s_squid.py index 06faee2a18..57ccefd39b 100644 --- a/tests/test_k8s_squid.py +++ b/tests/test_k8s_squid.py @@ -169,13 +169,11 @@ def test_squid_pvc_and_service_spec() -> None: assert ports.get("metrics") == 9301 -def test_ollama_daemonset_proxy_integration() -> None: - """Verify ollama-daemonset.yaml configures HTTP_PROXY, HTTPS_PROXY, and squid-ca mount.""" - docs = list( - yaml.safe_load_all((K8S_DIR / "llm" / "ollama-daemonset.yaml").read_text(encoding="utf-8")) - ) - daemonset_doc = next(d for d in docs if d and d.get("kind") == "DaemonSet") - containers = daemonset_doc["spec"]["template"]["spec"]["containers"] +def test_ollama_proxy_integration() -> None: + """Verify ollama.yaml configures HTTP_PROXY, HTTPS_PROXY, and squid-ca mount.""" + docs = list(yaml.safe_load_all((K8S_DIR / "llm" / "ollama.yaml").read_text(encoding="utf-8"))) + statefulset_doc = next(d for d in docs if d and d.get("kind") == "StatefulSet") + containers = statefulset_doc["spec"]["template"]["spec"]["containers"] ollama_c = next(c for c in containers if c["name"] == "ollama") env_map = {e["name"]: e["value"] for e in ollama_c.get("env", []) if "value" in e} @@ -187,7 +185,7 @@ def test_ollama_daemonset_proxy_integration() -> None: volume_mounts = {vm["name"]: vm["mountPath"] for vm in ollama_c.get("volumeMounts", [])} assert volume_mounts.get("squid-ca-cert") == "/etc/ssl/squid-ca" - volumes = {v["name"]: v for v in daemonset_doc["spec"]["template"]["spec"]["volumes"]} + volumes = {v["name"]: v for v in statefulset_doc["spec"]["template"]["spec"]["volumes"]} assert "squid-ca-cert" in volumes assert volumes["squid-ca-cert"].get("configMap", {}).get("optional") is False From 9195f8ee368c1e9360b2b0339d7b4a0f75225a96 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 23 Sep 2026 22:15:16 +0000 Subject: [PATCH 2/3] docs(agent): link task 463 to its PR --- docs/agent/tasks/task-463-ollama-per-node-routing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/agent/tasks/task-463-ollama-per-node-routing.md b/docs/agent/tasks/task-463-ollama-per-node-routing.md index b1871ebf00..859364dee4 100644 --- a/docs/agent/tasks/task-463-ollama-per-node-routing.md +++ b/docs/agent/tasks/task-463-ollama-per-node-routing.md @@ -1,7 +1,7 @@ # Task 463: One Gateway Deployment per Ollama Node **Issue**: [#463](https://github.com/dan-petty/devops-cli/issues/463) -**PR**: pending +**PR**: [#464](https://github.com/dan-petty/devops-cli/pull/464) **Status**: In Review **Milestone**: `v0.2.23` **Priority**: `priority/p2-medium` From 5ad4d1a3086e1fd07de0287acedd66a2614d181f Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Wed, 23 Sep 2026 22:45:14 +0000 Subject: [PATCH 3/3] docs(agent): record live verification for task 463 --- docs/agent/tasks/task-463-ollama-per-node-routing.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/agent/tasks/task-463-ollama-per-node-routing.md b/docs/agent/tasks/task-463-ollama-per-node-routing.md index 859364dee4..8e4b3f6cdf 100644 --- a/docs/agent/tasks/task-463-ollama-per-node-routing.md +++ b/docs/agent/tasks/task-463-ollama-per-node-routing.md @@ -55,3 +55,11 @@ kubectl -n llm rollout restart deployment/llm-gateway ``` Models stay on each node's `hostPath`, so nothing is downloaded again. + +## 3. Verification on a Live Cluster + +After the rollout, one pod ran on each Ollama node, and both still had their models. Gateway +`/health` reported all 12 deployments healthy and none unhealthy. Before, `devops-embedding` and +the wildcard were reported unhealthy. Of eight concurrent `devops-chat` requests, one node served +five and the other three. Before the change, a full review sent 15 requests to one node and 0 to +the other.