Skip to content

feat(ai): ollama model residency per-pod model budget, keep-alive, ms/token #598

Closed

Description

@dan-petty

Context & Rationale

Ollama slot leases (src/devops_cli/ai/client/network.py:169) and pydantic-ai limiters (src/devops_cli/ai/concurrency.py:31) count per process; GitHub pacing is already cross-process (src/devops_cli/github/rate_limiter.py:243). devops ai prewarm sends keep_alive: 1h (src/devops_cli/ai/client/ollama.py:60). Chat and stream bodies omit it (ollama.py:287, :463), devops ai chat then calls through pydantic-ai (src/devops_cli/commands/ai.py:1046), and no manifest sets OLLAMA_KEEP_ALIVE. A request without it resets expiry to the server default, so the lease is probably cut short; unchecked on a live server. Each of the 2 Ollama pods is routed 3 named models against OLLAMA_MAX_LOADED_MODELS 2 (k8s/llm/ollama.yaml:66-67); the direct embedding task adds another (#481). No ms/token metric exists, only a tokens/s span attribute on direct non-streaming Ollama calls (src/devops_cli/ai/client/unified.py:69), and nothing reads /api/ps. vibes observations/systems/06 reports 45 to over 2,500 ms/token under eviction cycles, with no method; its claim that prewarm pins VRAM is contradicted above.

Scope & Deliverables

  • Context & Rationale*: Ollama slot leases (src/devops_cli/ai/client/network.py:169) and pydantic-ai limiters (src/devops_cli/ai/concurrency.py:31) count per process; GitHub pacing is already cross-process (src/devops_cli/github/rate_limiter.py:243). devops ai prewarm sends keep_alive: 1h (src/devops_cli/ai/client/ollama.py:60). Chat and stream bodies omit it (ollama.py:287, :463), devops ai chat then calls through pydantic-ai (src/devops_cli/commands/ai.py:1046), and no manifest sets OLLAMA_KEEP_ALIVE. A request without it resets expiry to the server default, so the lease is probably cut short; unchecked on a live server. Each of the 2 Ollama pods is routed 3 named models against OLLAMA_MAX_LOADED_MODELS 2 (k8s/llm/ollama.yaml:66-67); the direct embedding task adds another (feat(ai): embeddings through the llm gateway, with embedding model evaluation #481). No ms/token metric exists, only a tokens/s span attribute on direct non-streaming Ollama calls (src/devops_cli/ai/client/unified.py:69), and nothing reads /api/ps. vibes observations/systems/06 reports 45 to over 2,500 ms/token under eviction cycles, with no method; its claim that prewarm pins VRAM is contradicted above.
  • Deliverable*: Measure first. Add a time-per-output-token histogram to src/devops_cli/telemetry/instruments.py, emitted beside the AI token counters (src/devops_cli/ai/spend/ledger.py:485) with the same backend labels, and unit and meaning taken from semconv gen_ai.server.time_per_output_token; add p50/p95 to feat(ai): llm gateway calls record their serving backend in the spend ledger #474's devops ai cost report --by backend. Wire or delete the unused record_llm_metrics (src/devops_cli/telemetry/tracer.py:436). Report /api/ps per pod (loaded models, expires_at, VRAM) from devops ai gateway status. Then check with expires_at whether a chat shortens a prewarm lease; if it does, send the configured keep-alive on direct Ollama bodies and the pydantic-ai path, and set OLLAMA_KEEP_ALIVE on the StatefulSet. Last, learn why the loaded-model limit is 2, then fit models per pod to it, with feat(ai): embeddings through the llm gateway, with embedding model evaluation #481 choosing the embedding model. Document that acquire_ollama_slot is per-process by design.
  • Constraint*: keep_alive is an idle timer; it does not stop eviction once the loaded-model limit is reached, so it cannot fix eviction cycles alone. A client-side cross-process semaphore adds a hidden queue ahead of Ollama's own (OLLAMA_NUM_PARALLEL 1), repeating fix(k8s): devops-review routing throttles the largest server to the smallest server's request limit #467, and host processes reach the pods directly (hostPort, k8s/llm/ollama.yaml:95) besides the gateway. ValkeyTokenBucketRateLimiter limits rate, not concurrency, and fails open (src/devops_cli/valkey/rate_limiter.py:106); wiring it in would report arbitration that is not happening.
  • Measured*: .venv/bin/python probe/xproc_slot.py process (scratch probe, not in repo): 3 processes leasing one URL at max_parallel=1 held it 3 at once; thread mode, 1. .venv/bin/python probe/chat_payload.py (scratch): chat body has no keep_alive. awk '/model: ollama/{m=$2; getline; print $2, m}' k8s/llm/gateway/configmap.yaml | sort -u: each of 2 Ollama backends routed 3 named models.
  • Source*: vibes patterns/multi-agent-codebase-concurrency.md; vibes observations/systems/06-multi-agent-concurrency-shared-workspace-hazards-and-swarm-coordination.md

Update 2026-10-08: refinement

Proposed design

Problem statement

The Ollama model residency and performance in the devops-cli system is suboptimal due to incorrect keep-alive handling, lack of time-per-token metrics, and inefficient model loading strategies that lead to eviction cycles and inconsistent performance.

Acceptance criteria

  • Criterion 1: A time-per-output-token histogram is added to telemetry instruments and emitted alongside AI token counters with the same backend labels
    Verification: Verify that devops_cli/telemetry/instruments.py contains a new histogram instrument for time-per-output-token and that it's emitted in src/devops_cli/ai/spend/ledger.py with backend labels
  • Criterion 2: The ms/token metric is properly measured and reported in cost reports
    Verification: Run devops ai cost report --by backend and confirm p50/p95 values are present for time-per-output-token
  • Criterion 3: Ollama requests sent through the direct client path include the configured keep-alive value
    Verification: Check that calls to ollama.py (lines 287, 463) now include keep_alive parameter from configuration
  • Criterion 4: The pydantic-ai path also sends the configured keep-alive value for Ollama requests
    Verification: Confirm that src/devops_cli/commands/ai.py:1046 correctly passes keep-alive through to Ollama clients
  • Criterion 5: The StatefulSet is updated with OLLAMA_KEEP_ALIVE configuration
    Verification: Validate that Kubernetes manifest in k8s/llm/ollama.yaml includes OLLAMA_KEEP_ALIVE environment variable set appropriately

Key questions

  • What is the current behavior of Ollama slot leases and pydantic-ai limiters?: Ollama slot leases (src/devops_cli/ai/client/network.py:169) and pydantic-ai limiters (src/devops_cli/ai/concurrency.py:31) count per process; GitHub pacing is already cross-process (src/devops_cli/github/rate_limiter.py:243). [sources: src/devops_cli/ai/client/network.py, src/devops_cli/ai/concurrency.py, src/devops_cli/github/rate_limiter.py]
  • How is keep-alive currently handled in Ollama requests?: devops ai prewarm sends keep_alive: 1h (src/devops_cli/ai/client/ollama.py:60). Chat and stream bodies omit it (ollama.py:287, :463), devops ai chat then calls through pydantic-ai (src/devops_cli/commands/ai.py:1046) and no manifest sets OLLAMA_KEEP_ALIVE. [sources: src/devops_cli/ai/client/ollama.py, src/devops_cli/commands/ai.py]
  • What is the current approach for measuring time-per-output-token?: No ms/token metric exists, only a tokens/s span attribute on direct non-streaming Ollama calls (src/devops_cli/ai/client/unified.py:69), and nothing reads /api/ps. [sources: src/devops_cli/ai/client/unified.py]
  • Should the Ollama keep-alive feature be used to address eviction cycles?: Keep-alive is an idle timer that does not stop eviction once the loaded-model limit is reached, so it cannot fix eviction cycles alone. The approach should focus on measuring and optimizing model residency strategies. [sources: docs/agent/tasks/task-598-ollama-model-residency-per-pod-model-budget-keep-alive-ms-to.md]
  • Should the system measure time-per-output-token metric?: Yes, a time-per-output-token histogram should be added to src/devops_cli/telemetry/instruments.py, emitted beside the AI token counters with the same backend labels, and unit and meaning taken from semconv gen_ai.server.time_per_output_token. (proposed) [sources: src/devops_cli/telemetry/instruments.py]
  • Should the unused record_llm_metrics be deleted?: Yes, as mentioned in the update, record_llm_metrics was deleted in v0.2.25. [sources: docs/agent/tasks/task-598-ollama-model-residency-per-pod-model-budget-keep-alive-ms-to.md]

Open questions

  • What is the current limit for loaded models per Ollama pod? (missing verified source)

Fit

Needs splitting into 5 items:

  1. Add time-per-output-token histogram to telemetry instruments
  2. Implement ms/token metric reporting in cost reports
  3. Send configured keep-alive on direct Ollama bodies and pydantic-ai path
  4. Set OLLAMA_KEEP_ALIVE on StatefulSet manifest
  5. Document that acquire_ollama_slot is per-process by design

Suspected block

None.

Dependencies

None.

Activity

  1. added this to the v0.2.23 milestone on Sep 25, 2026
  2. added
    type/feature
    scope/ai
    priority/p2-medium
    on Sep 25, 2026
  3. modified the milestones: v0.2.23, v0.2.24 on Sep 28, 2026
  4. removed this from the v0.2.23 milestone on Oct 1, 2026
  5. dan-petty commented on Oct 1, 2026

    @dan-petty
    OwnerAuthor

    Moved from the shipped v0.2.23 to the backlog. It is still valid (checked 2026-10-01), and P2 items don't displace P1 work in the planned releases.

  6. dan-petty commented on Oct 3, 2026

    @dan-petty
    OwnerAuthor

    Hog's residency is decided in #1064 (2026-10-03). Source: the slow-tier plan (.data/slow-tier-plan-20261003.md, section 3) and its verification pass. Ollama logs were read with kubectl logs, read-only.

    The decision.

    Why the count cap alone failed.

    • From 06:15:34 to 06:19:47, hog loaded a runner 10 times, alternating bge-m3 and qwen3-coder, with loaded runners count=1 after each load.
    • Six embeddings waited 31–40 s, past the client's 30 s timeout, and embeddings stopped at 06:19:37 while chat continued.

    What Ollama does (v0.34.4).

    • It counts embedding runners toward the cap. processPending compares len(s.loaded) with maxRunners.
    • A second gate evicts on predicted VRAM. When another runner is resident and the new model's predicted size is over 80% of free VRAM, Ollama evicts anyway (sched.go).
      • qwen3.8:27b was predicted at 42.1 GiB and evicted bge-m3 at 04:11:03, even under MAX_LOADED=2.
      • qwen3-coder is predicted at about 25 GiB and should fit beside the embedder. Measured at one slot: 29,040 MiB projected for qwen3-coder at 128k, 833 MiB for bge-m3, and 48,535 MiB free.
    • How keep-alive behaves.
      • KEEP_ALIVE below 0 means forever (envconfig).
      • A request's own keep_alive overrides it, and the gateway path sends none.
      • A reload costs 6.4–7.4 s warm and 26.9 s cold.
      • With every runner kept forever, a third model evicts by blob-path order: qwen3-coder (sha256-1194…) goes before bge-m3 (sha256-daec…). The feat(ai): embeddings through the llm gateway, with embedding model evaluation #481 switch therefore stops a model first.

    What stays here.

    • This item's premise is out of date. It describes 2 pods in k8s/llm/ollama.yaml with MAX_LOADED 2. There are now nine DaemonSets in k8s/llm/profiles/ollama-profiles.yaml, at MAX_LOADED 1 (fix(k8s): every ollama tier keeps one model loaded and serves one request at a time, so its kv cache holds one context #1061).
    • The rest of the scope stays: the time-per-output-token histogram, /api/ps per pod in gateway status, keep-alive on direct Ollama bodies, and fitting models per pod on the other tiers. Gemini (64gib-standard) serves four generation models, so its residency is still open.
    • Measured single-slot decode for qwen3-coder: 46.6–48.2 tok/s on hog, about 120 on condor and about 88 on gemini.
  7. added this to the v0.2.39 milestone on Oct 17, 2026
  8. dan-petty commented on Oct 17, 2026

    @dan-petty
    OwnerAuthor

    Proposal needs splitting into 5 items at 3dd7fa6 (see proposed design in issue body).

  9. modified the milestones: v0.2.39, on Oct 20, 2026
  10. dan-petty commented on Oct 24, 2026

    @dan-petty
    OwnerAuthor

    The item premise is invalid against the current repository state. First, k8s/llm/ollama.yaml does not exist. Ollama runs as nine DaemonSets in k8s/llm/profiles/ollama-profiles.yaml under issue #1061. The ollama-48gib-slow tier already configures OLLAMA_KEEP_ALIVE as -1 under issue #1064. Second, record_llm_metrics was removed in version 0.2.25. Third, the scope contains five distinct changes and requires splitting into five items.

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

    priority/p2-mediumscope/aitype/feature

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions