From e134914026f9ec190ae387ba8abfd042f455af33 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Mon, 31 Aug 2026 07:57:48 +0200 Subject: [PATCH] Coach: der Server waermt den Prefix-Cache selbst, und die Tipp-Blase glaubt dem letzten Lauf MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Der KV-Prefix-Cache eines lokalen Endpunkts stirbt mit dem Ollama-Prozess; der erste Job danach zahlte still den Kaltstart (~8 min statt ~1). Jetzt pingt der api-Prozess bei Boot und alle 30 Minuten die Review- und Debrief-Prefixe an den kompatiblen Endpunkt — warm kostet der Ping ein Token, kalt macht er die teure Lesung genau einmal, auf niemandes Uhr. Cloud-Provider werden nie gepingt. Und estimateMs nimmt min(Median, letzter Lauf): nach einer Beschleunigung schleppte der Median drei alte 8-Minuten-Laeufe mit. --- api/coach/warmup.js | 65 +++++++++++++++++++++++++++++++++++++++ api/server.js | 2 ++ api/test/warmup.test.js | 35 +++++++++++++++++++++ frontend/src/lib/coach.js | 15 ++++++--- 4 files changed, 113 insertions(+), 4 deletions(-) create mode 100644 api/coach/warmup.js create mode 100644 api/test/warmup.test.js diff --git a/api/coach/warmup.js b/api/coach/warmup.js new file mode 100644 index 0000000..3ca9e3c --- /dev/null +++ b/api/coach/warmup.js @@ -0,0 +1,65 @@ +/* Keeps a local model's prefix cache warm, so nobody pays the cold start. + * + * The rules ride as a byte-identical system message precisely so a llama.cpp/Ollama endpoint + * can reuse its KV prefix across jobs — but the cache only exists after something has sent + * that prefix once, and it dies with the ollama process. Without this, the first review after + * a reboot quietly costs ~8 minutes instead of ~1, and whoever asks it looks unlucky. + * + * So: when the configured provider is a compatible endpoint, send each chat prefix once at + * boot and then again every half hour. A warm ping is nearly free (the prefix is cached, one + * token comes back); a cold one does the expensive read exactly once, off anyone's clock. + * Cloud providers are never pinged — their caches are their problem, and requests cost money. + */ +import * as cfgStore from './config.js'; +import { adapterFor } from './adapters/index.js'; +import { buildPromptParts } from './core/prompt.js'; +import { fetchFor } from './node-fetch.js'; + +const INTERVAL_MS = 30 * 60000; +const TIMEOUT_MS = 10 * 60000; +// The two kinds a chat actually runs day to day; `create` happens once per user and may pay cold. +const KINDS = ['review', 'debrief']; + +let running = false; + +export async function warmOnce({ log = console, fetch: fetchImpl } = {}) { + const cfg = cfgStore.load(); + if (!cfgStore.isEnabled() || cfg.provider !== 'compatible') return { skipped: true }; + const adapter = adapterFor(cfg.provider); + if (!adapter || adapter.spawns !== false) return { skipped: true }; + if (running) return { skipped: true }; + running = true; + try { + for (const kind of KINDS) { + const parts = buildPromptParts(kind, {}); + const t0 = Date.now(); + const r = await adapter.invoke({ + cfg, + system: parts.system, + prompt: 'Reply with exactly {"coach_contract":1} and nothing else.', + model: cfgStore.modelFor(cfg), + timeoutMs: TIMEOUT_MS, + fetch: fetchImpl || fetchFor(TIMEOUT_MS) + }); + const ms = Date.now() - t0; + if (r.code !== 0) { + log.log(`coach warmup (${kind}): endpoint not reachable, will retry later`); + return { ok: false }; + } + // >5s means the prefix was actually (re)read — worth a line; a warm ping is noise. + if (ms > 5000) log.log(`coach warmup (${kind}): prefix cached in ${Math.round(ms / 1000)}s`); + } + return { ok: true }; + } finally { + running = false; + } +} + +/** Boot + every half hour. Never throws; a failed warmup is only a missed optimisation. */ +export function startWarmup(log = console) { + const tick = () => warmOnce({ log }).catch(() => {}); + setTimeout(tick, 5000); // let the container settle first + const timer = setInterval(tick, INTERVAL_MS); + timer.unref?.(); + return timer; +} diff --git a/api/server.js b/api/server.js index c700ca4..675a5d8 100644 --- a/api/server.js +++ b/api/server.js @@ -15,6 +15,7 @@ import * as coachConfig from './coach/config.js'; import * as coachJobs from './coach/jobs.js'; import { coachRoutes } from './coach/routes.js'; import { startCadence } from './coach/cadence.js'; +import { startWarmup } from './coach/warmup.js'; import { dayReminderPush, restTimerPush, testPush } from './push-messages.js'; import { verifyError } from './verify-error.js'; @@ -993,6 +994,7 @@ coachJobs.setProposalHook((uid, pending) => { }); }); startCadence({ users: () => db.users, userNow }); +startWarmup(); http.createServer(async (req, res) => { // Same-origin (the deployed nginx-proxied web app) never triggers CORS, so this only matters diff --git a/api/test/warmup.test.js b/api/test/warmup.test.js new file mode 100644 index 0000000..45e83c4 --- /dev/null +++ b/api/test/warmup.test.js @@ -0,0 +1,35 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-warmup-')); +process.env.DATA_DIR = DIR; +fs.writeFileSync(path.join(DIR, 'secret'), 'x'.repeat(64)); + +const cfgStore = await import('../coach/config.js'); +const { warmOnce } = await import('../coach/warmup.js'); +const { buildPromptParts } = await import('../coach/core/prompt.js'); + +test('warmup pings the compatible endpoint once per chat kind, with the real rules prefix', async t => { + cfgStore.reset(); + cfgStore.save({ enabled: true, provider: 'compatible', models: { compatible: 'm1' }, providerOptions: { compatible: { baseUrl: 'http://ollama.test:11434' } } }); + const seen = []; + const fakeFetch = async (url, init) => { + seen.push(JSON.parse(init.body)); + return new Response(JSON.stringify({ choices: [{ message: { content: '{"coach_contract":1}' }, finish_reason: 'stop' }] }), { status: 200 }); + }; + const quiet = { log: () => {} }; + t.after(() => cfgStore.reset()); + + const r = await warmOnce({ log: quiet, fetch: fakeFetch }); + assert.equal(r.ok, true); + assert.equal(seen.length, 2); + const reviewPrefix = buildPromptParts('review', {}).system; + assert.ok(seen[0].messages[0].content.endsWith(reviewPrefix), 'system message carries the byte-identical review rules'); + assert.equal(seen[0].model, 'm1'); + + cfgStore.save({ provider: 'anthropic' }); + assert.equal((await warmOnce({ log: quiet, fetch: fakeFetch })).skipped, true, 'cloud providers are never pinged'); +}); diff --git a/frontend/src/lib/coach.js b/frontend/src/lib/coach.js index f9e0e65..c3be361 100644 --- a/frontend/src/lib/coach.js +++ b/frontend/src/lib/coach.js @@ -327,11 +327,18 @@ export function recordTiming(s, ms) { const c = coachOf(s) c.timings = [...(c.timings || []), Math.round(ms)].slice(-TIMINGS_MAX) } -/** Median of the observed job durations, or null before any. */ +/** + * What to promise in the typing bubble. Median of the observed runs, but never slower than + * the most recent one: after a speed-up (a faster model, a warmed cache) the median drags + * three old 8-minute runs along, and telling someone "about 8 min" for a one-minute job is + * worse than being briefly optimistic. A slow outlier still cannot scare anyone — the median + * wins in that direction. + */ export function estimateMs(S) { - const arr = [...(S?.coach?.timings || [])].filter(n => n > 0).sort((a, b) => a - b) - if (!arr.length) return null - return arr[Math.floor(arr.length / 2)] + const raw = (S?.coach?.timings || []).filter(n => n > 0) + if (!raw.length) return null + const sorted = [...raw].sort((a, b) => a - b) + return Math.min(sorted[Math.floor(sorted.length / 2)], raw[raw.length - 1]) } /** The questionnaire, as the lines the chat shows back to the user. */