0.2.3: keep the model resident — pin keep_alive on the native dialect

A cold load of gpt-oss:120b is 21-66 s and lands entirely in front of the
caller, so every idle spell put that pause on Rick's next Home Assistant turn.
The 0.3-0.6 s figures from 2026-09-18 were warm-model numbers.

Measured on Ollama 0.34.0, and NOT symmetrical with the num_ctx pin:

  native /api/chat, keep_alive:-1     -> Forever
  native /api/chat, explicit finite   -> that duration, and it BEATS the
                                         server-side OLLAMA_KEEP_ALIVE default
  native /api/chat, absent            -> does NOT reset an existing value;
                                         the duration is fixed AT LOAD TIME
  /v1/chat/completions, keep_alive    -> IGNORED, like options.num_ctx
                                         (confirmed in openai/openai.go: the
                                         request struct has no such field)

So the router alone can never carry residency: an OpenAI-dialect caller cannot
set it, and whichever request happens to trigger the cold load fixes the
duration. forge therefore also gets OLLAMA_KEEP_ALIVE=-1 in
/etc/systemd/system/ollama.service.d/30-keepalive.conf. The two are
complementary rather than redundant — the server default covers dialects and
callers we never proxy, this pin defeats a native caller that sends a short
keep_alive of its own.

The health probe asserts residency rather than inheriting it: it runs before
every proxied request, so it is the most frequent caller forge has and the one
most likely to be what triggers a cold load.

/status gains keep_alive_pin, runner_resident and runner_expires_at, and the
locator logs a WARNING if forge's runner stops being permanently resident —
the same visibility pattern as num_ctx_pin vs runner_context.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Dolon (Agent)
2026-09-18 20:02:03 +00:00
co-authored by Claude Opus 5
parent 2d3c548542
commit f7cd9b6690
4 changed files with 74 additions and 8 deletions
+19
View File
@@ -69,6 +69,25 @@ class Config:
# model default; the pin must equal that default, and /status + a WARNING
# flag it if the runner's context is ever observed to differ.
num_ctx: int = field(default_factory=lambda: _env_int("FORGEWAY_NUM_CTX", 131072))
# Residency. A cold load of gpt-oss:120b costs 21-66 s, so an evicted model puts
# that whole pause in front of the next Home Assistant turn. -1 means "stay loaded
# forever"; 0 disables the pin and leaves the caller's value alone.
#
# MEASURED on Ollama 0.34.0, 2026-09-18. The semantics are NOT symmetrical with
# num_ctx, and the asymmetry is the part that surprises:
# * native /api/chat, keep_alive:-1 -> Forever
# * native /api/chat, explicit finite -> that duration, and it BEATS the server
# default — which is why we override it
# * native /api/chat, absent -> does NOT reset an existing value; the
# duration is fixed AT LOAD TIME
# * /v1/chat/completions, keep_alive -> IGNORED, exactly like options.num_ctx
# So this pin can only carry residency on the NATIVE dialect. OpenAI-dialect
# callers are covered instead by OLLAMA_KEEP_ALIVE=-1 on forge itself (drop-in
# /etc/systemd/system/ollama.service.d/30-keepalive.conf), which sets the load-time
# default for every caller and every path. The two are complementary: the server
# default covers dialects and callers we never see, this pin defeats a native
# caller that sends a short keep_alive of its own.
keep_alive: int = field(default_factory=lambda: _env_int("FORGEWAY_KEEP_ALIVE", -1))
# --- cloud fallback (local-optimistic only) -------------------------
cloud_base_url: str = field(
+5
View File
@@ -235,6 +235,11 @@ async def status() -> JSONResponse:
# and the context the loaded runner was last seen with (must match)
"num_ctx_pin": CONFIG.num_ctx or None,
"runner_context": app.state.locator.runner_context,
# residency: the pin we send, and whether forge's runner is actually
# permanently loaded. False means the next idle spell costs a cold load.
"keep_alive_pin": CONFIG.keep_alive or None,
"runner_resident": app.state.locator.runner_resident,
"runner_expires_at": app.state.locator.runner_expires_at,
"health": health.as_dict(),
}
)
+9
View File
@@ -399,6 +399,15 @@ async def _route(request: Request, mode: str, path: str, body: dict[str, Any], s
log.info("pinning num_ctx %s -> %s on %s (one runner config, no reload)", sent, CONFIG.num_ctx, path)
opts["num_ctx"] = CONFIG.num_ctx
payload["options"] = opts
if CONFIG.keep_alive != 0:
# Residency: a cold load is 21-66 s and lands entirely in front of the
# caller. An explicit finite keep_alive from a caller BEATS forge's
# OLLAMA_KEEP_ALIVE default, so overriding it here is the only thing that
# stops one such caller evicting the model for everyone else.
sent = payload.get("keep_alive")
if sent is not None and sent != CONFIG.keep_alive:
log.info("pinning keep_alive %s -> %s on %s (stay resident)", sent, CONFIG.keep_alive, path)
payload["keep_alive"] = CONFIG.keep_alive
try:
return await _forge_raw(request, health.upstream, path, payload, mode, stream)
except UpstreamError as exc:
+41 -8
View File
@@ -6,6 +6,7 @@ import asyncio
import logging
import time
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
import httpx
@@ -67,6 +68,8 @@ class ForgeLocator:
self._health: Health | None = None
self._lock = asyncio.Lock()
self.runner_context: int | None = None # last observed loaded context on forge
self.runner_expires_at: str | None = None # last observed residency deadline
self.runner_resident: bool | None = None # True once it is "forever"
@property
def sticky(self) -> str | None:
@@ -192,10 +195,10 @@ class ForgeLocator:
async def _completion(self, base: str) -> dict:
"""One real, minimal completion. Not a ping — that is the whole point.
Uses Ollama's native /api/chat so the probe can carry the pinned num_ctx:
the OpenAI-compatible /v1 endpoint ignores `options`, and an unpinned
probe was half of the runner-reload thrash. Falls back to /v1 for a
non-Ollama upstream (404 on /api/chat).
Uses Ollama's native /api/chat so the probe can carry the pinned num_ctx
and keep_alive: the OpenAI-compatible /v1 endpoint ignores both, and an
unpinned probe was half of the runner-reload thrash. Falls back to /v1 for
a non-Ollama upstream (404 on /api/chat).
"""
options: dict = {"num_predict": 1}
if CONFIG.num_ctx > 0:
@@ -206,6 +209,12 @@ class ForgeLocator:
"stream": False,
"options": options,
}
if CONFIG.keep_alive != 0:
# This probe runs before every proxied request, so it is the most frequent
# caller forge has. It must ASSERT residency rather than inherit it: Ollama
# fixes keep_alive at LOAD time, so if the probe is what triggers a cold
# load, the duration the probe carries is the one the model then keeps.
native["keep_alive"] = CONFIG.keep_alive
try:
resp = await self._client.post(f"{base}/api/chat", json=native, timeout=CONFIG.health_timeout)
if resp.status_code == 404:
@@ -235,12 +244,13 @@ class ForgeLocator:
raise UpstreamError("upstream returned non-JSON") from exc
if not (data.get("done") or data.get("choices")):
raise UpstreamError("upstream returned no completion")
await self._observe_runner_context(base)
await self._observe_runner(base)
return data
async def _observe_runner_context(self, base: str) -> None:
"""Record the loaded runner's context so a pin/default mismatch is visible
(in /status and as a WARNING) instead of silently reloading forever."""
async def _observe_runner(self, base: str) -> None:
"""Record the loaded runner's context and residency, so a pin/default mismatch
or a lost keep_alive is visible (in /status and as a WARNING) instead of
silently reloading forever."""
try:
resp = await self._client.get(f"{base}/api/ps", timeout=CONFIG.discovery_timeout)
if resp.status_code != 200:
@@ -256,6 +266,29 @@ class ForgeLocator:
ctx, CONFIG.num_ctx,
)
self.runner_context = ctx
self._observe_residency(m.get("expires_at"))
return
except (httpx.HTTPError, ValueError):
return
def _observe_residency(self, expires_at: str | None) -> None:
"""A cold load costs 21-66 s and lands in front of the caller, so residency is
a property worth watching, not assuming. Ollama renders "forever" as a year-2318
timestamp, so "more than a year out" is the portable test for it."""
resident = None
if expires_at:
try:
delta = datetime.fromisoformat(expires_at.replace("Z", "+00:00")) - datetime.now(timezone.utc)
resident = delta > timedelta(days=365)
except ValueError:
resident = None
if resident is not None and resident != self.runner_resident:
if not resident and CONFIG.keep_alive != 0:
log.warning(
"forge's runner is no longer permanently resident (expires_at %s) despite a "
"keep_alive pin of %s — a caller sending its own finite keep_alive, or forge's "
"OLLAMA_KEEP_ALIVE default, is winning; the next idle spell will cost a cold load",
expires_at, CONFIG.keep_alive,
)
self.runner_resident = resident
self.runner_expires_at = expires_at