diff --git a/app/config.py b/app/config.py index 9027010..1299db2 100644 --- a/app/config.py +++ b/app/config.py @@ -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( diff --git a/app/main.py b/app/main.py index 04c44fa..800a151 100644 --- a/app/main.py +++ b/app/main.py @@ -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(), } ) diff --git a/app/ollama_api.py b/app/ollama_api.py index 2372a29..a6d100f 100644 --- a/app/ollama_api.py +++ b/app/ollama_api.py @@ -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: diff --git a/app/upstream.py b/app/upstream.py index b33944b..55898a7 100644 --- a/app/upstream.py +++ b/app/upstream.py @@ -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