Coach: der Server waermt den Prefix-Cache selbst, und die Tipp-Blase glaubt dem letzten Lauf

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.
This commit is contained in:
Duarte Santos committed 2026-08-31 07:57:48 +02:00
1 parent 5116f8770d
commit e134914026
4 files changed
+113 -4

No files matched your search

+65
View File
@@ -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;
}
+2
View File
@@ -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
+35
View File
@@ -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');
});