7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
feat(cache): persist response cache to SQLite — survive restarts for the daily quota-reset re-run pattern (#1096) (#1097)
suantea (asuan_suan)32b2ea6206a1
diff --git a/.env.example b/.env.exampleindex 80e71a11..3dd79ae4 100644--- a/.env.example+++ b/.env.example@@ -196,8 +196,15 @@ PORT=3001# any provider quota. Exact match only (no fuzzy matching), so a near-miss never# returns a different prompt's answer. Off by default; set to true to enable.# Can also be toggled at runtime via the dashboard (PUT /api/cache/config), and-# per-request with the `X-FreeLLM-Cache: on|off` header. A restart flushes it.+# per-request with the `X-FreeLLM-Cache: on|off` header.# RESPONSE_CACHE=false+# Persist cached answers to SQLite so they survive a restart (the daily+# quota-reset re-run pattern). Only applies when the cache above is on. Note+# this writes PLAINTEXT model responses to the database file, which the+# memory-only cache never did; set it to false to keep caching but hold+# everything in memory, as before. Entries are removed from disk the moment+# they leave the in-memory cache (TTL expiry, eviction, DELETE /api/cache).+# RESPONSE_CACHE_PERSIST=true# How long a cached answer stays fresh, in seconds (default: 3600 = 1 hour).# RESPONSE_CACHE_TTL_SECONDS=3600# Only cache requests at/below this temperature; higher temperatures want freshdiff --git a/desktop/src/__tests__/server-host-boot.test.ts b/desktop/src/__tests__/server-host-boot.test.tsindex 9eb30f75..5f035399 100644--- a/desktop/src/__tests__/server-host-boot.test.ts+++ b/desktop/src/__tests__/server-host-boot.test.ts@@ -52,6 +52,12 @@ vi.mock('../../../server/src/services/ratelimit.js', () => ({}),}));+vi.mock('../../../server/src/services/cache.js', () => ({+ loadCacheFromDb: vi.fn(() => {+ calls.push('loadCacheFromDb');+ }),+}));+vi.mock('../../../server/src/services/cooldown-probe.js', () => ({startCooldownProbe: vi.fn(() => {calls.push('startCooldownProbe');@@ -155,6 +161,7 @@ describe('desktop server boot sequence (#949)', () => {'initDb','cleanupExpiredCooldowns','restoreProxySettings',+ 'loadCacheFromDb','createApp','listen','startHealthChecker',@@ -180,11 +187,13 @@ describe('desktop server boot sequence (#949)', () => {.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');const steps = new Set(- [...withoutComments.matchAll(/\b((?:install|start|cleanup|restore)[A-Z]\w*)\(/g)].map((m) => m[1]),+ [...withoutComments.matchAll(/\b((?:install|start|cleanup|restore|load)[A-Z]\w*)\(/g)].map((m) => m[1]),);// Env-gated (FREEAPI_DB_BACKUP_*): a GUI-launched packaged app inherits no- // shell environment, so these can never activate on desktop.- const SKIPPED = new Set(['restoreDbBackupIfNeeded', 'startDbBackupPump']);+ // shell environment, so these can never activate on desktop. loadConfig()+ // is the same story: port/host/dbPath arrive as StartOptions here, not from+ // the environment it would read.+ const SKIPPED = new Set(['restoreDbBackupIfNeeded', 'startDbBackupPump', 'loadConfig']);// Regex sanity floor — an index.ts restructure must not blank this test.expect(steps.size).toBeGreaterThanOrEqual(10);diff --git a/desktop/src/server-host.ts b/desktop/src/server-host.tsindex 00a00109..3ade752c 100644--- a/desktop/src/server-host.ts+++ b/desktop/src/server-host.ts@@ -18,6 +18,7 @@ import { startCooldownProbe } from '../../server/src/services/cooldown-probe.js'import { startCustomModelSync } from '../../server/src/services/custom-model-sync.js';import { startBackupScheduler } from '../../server/src/services/backups.js';import { cleanupExpiredCooldowns } from '../../server/src/services/ratelimit.js';+import { loadCacheFromDb } from '../../server/src/services/cache.js';import { startWakeDetect } from '../../server/src/lib/wake-detect.js';import { installProcessSafetyNet } from '../../server/src/lib/process-safety-net.js';import { installLogRedaction } from '../../server/src/lib/log-redaction.js';@@ -96,6 +97,10 @@ export async function startServer(opts: StartOptions): Promise<ServerHandle> {// the URL saved in the settings table is ignored on every restart and the// outbound proxy fields appear empty until re-saved.restoreProxySettings();+ // Rehydrate the persisted response cache, same as server/src/index.ts. The+ // desktop app is restarted far more often than a server (every quit, every+ // update), so without this the cache is effectively never warm here.+ loadCacheFromDb();const app = createApp();const { server, port } = await listenWithScan(app, opts.host, opts.preferredPort);// Background timers need a Scheduler since the abstraction landed (4cbb571);diff --git a/docs/env/01-variables.md b/docs/env/01-variables.mdindex cdce0ecf..821b933a 100644--- a/docs/env/01-variables.md+++ b/docs/env/01-variables.md@@ -91,7 +91,8 @@ In Docker, `127.0.0.1` is the container, not your machine — see [03-outbound-p| Variable | Default | Purpose || --- | --- | --- |-| `RESPONSE_CACHE` | `false` | Opt-in response cache. When on, a successful non-streaming `/v1/chat/completions` answer is stored in a bounded in-memory LRU keyed by a canonical hash of the request, so an IDENTICAL later request is served from memory without spending provider quota. Exact match only — a near-miss never returns a different prompt's answer. Toggled at runtime via the dashboard (`PUT /api/cache/config`) and per-request with the `X-FreeLLM-Cache: on\|off` header. A restart flushes it. |+| `RESPONSE_CACHE` | `false` | Opt-in response cache. When on, a successful non-streaming `/v1/chat/completions` answer is stored in a bounded in-memory LRU keyed by a canonical hash of the request, so an IDENTICAL later request is served from memory without spending provider quota. Exact match only — a near-miss never returns a different prompt's answer. Toggled at runtime via the dashboard (`PUT /api/cache/config`) and per-request with the `X-FreeLLM-Cache: on\|off` header. |+| `RESPONSE_CACHE_PERSIST` | `true` | Persist cached answers to SQLite so they survive a restart. Only applies when `RESPONSE_CACHE` is on, so it is inert on a default install. Note this writes **plaintext model responses** to the database file, which the memory-only cache never did; set it to `false` to keep caching in memory only. Rows are deleted as soon as the entry leaves the in-memory cache (TTL expiry, LRU eviction, `DELETE /api/cache`), plus a sweep at startup. || `RESPONSE_CACHE_TTL_SECONDS` | `3600` (1 hour) | How long a cached answer stays fresh, in seconds. || `RESPONSE_CACHE_MAX_TEMPERATURE` | `1.0` | Only cache requests at/below this temperature; higher temperatures want fresh variety. Default caches everything when enabled; lower it (e.g. `0.2`) to cache only near-deterministic calls. || `RESPONSE_CACHE_MAX_ENTRIES` | `5000` | Hard cap on stored entries; least-recently-used entries are evicted past this. |diff --git a/docs/i18n/zh-CN/docs/env/01-variables.md b/docs/i18n/zh-CN/docs/env/01-variables.mdindex 1e451930..30c4df10 100644--- a/docs/i18n/zh-CN/docs/env/01-variables.md+++ b/docs/i18n/zh-CN/docs/env/01-variables.md@@ -93,7 +93,8 @@ FreeLLMAPI 从 `.env` 读取的全部变量,按主题分组。默认值和说| 变量 | 默认值 | 用途 || --- | --- | --- |-| `RESPONSE_CACHE` | `false` | 可选开启的响应缓存。开启后,一次成功的非流式 `/v1/chat/completions` 回答会存进一个有界的内存 LRU(以整个请求的规范化哈希为键),因此完全相同的后续请求直接由内存应答,不再消耗提供方额度。只做精确匹配——近似请求绝不会返回另一个提示词的答案。可在运行时通过仪表盘切换(`PUT /api/cache/config`),也可按请求用 `X-FreeLLM-Cache: on\|off` 头控制。重启即清空。 |+| `RESPONSE_CACHE` | `false` | 可选开启的响应缓存。开启后,一次成功的非流式 `/v1/chat/completions` 回答会存进一个有界的内存 LRU(以整个请求的规范化哈希为键),因此完全相同的后续请求直接由内存应答,不再消耗提供方额度。只做精确匹配——近似请求绝不会返回另一个提示词的答案。可在运行时通过仪表盘切换(`PUT /api/cache/config`),也可按请求用 `X-FreeLLM-Cache: on\|off` 头控制。 |+| `RESPONSE_CACHE_PERSIST` | `true` | 将缓存的回答持久化到 SQLite,使其在重启后依然可用(对应每日额度重置后重跑相同任务的场景)。仅在 `RESPONSE_CACHE` 开启时生效,因此默认安装下完全不起作用。请注意:这会把**明文的模型响应**写入数据库文件,纯内存缓存从不这样做;设为 `false` 可继续使用缓存但只保留在内存中。条目一旦离开内存缓存(TTL 过期、LRU 逐出、`DELETE /api/cache`)对应的行会立即删除,启动时还会再清扫一次。 || `RESPONSE_CACHE_TTL_SECONDS` | `3600`(1 小时) | 缓存的回答保持新鲜多久,单位秒。 || `RESPONSE_CACHE_MAX_TEMPERATURE` | `1.0` | 只缓存温度不高于该值的请求;更高的温度需要新鲜多样的输出。默认在开启时全部缓存;调低它(如 `0.2`)则只缓存接近确定性的调用。 || `RESPONSE_CACHE_MAX_ENTRIES` | `5000` | 存储条目的硬上限;超过后按最近最少使用逐出。 |diff --git a/server/src/__tests__/db/migrate/roundtrip.test.ts b/server/src/__tests__/db/migrate/roundtrip.test.tsindex 2c9d2245..ab01aefd 100644--- a/server/src/__tests__/db/migrate/roundtrip.test.ts+++ b/server/src/__tests__/db/migrate/roundtrip.test.ts@@ -36,6 +36,7 @@ const IDEMPOTENCY_CLAIMS_FILENAME = '20260901_000001_idempotency_claims.ts';const QUOTA_OBSERVATION_LOOKUP_FILENAME = '20260901_000002_quota_observation_lookup.ts';const ANALYTICS_LATENCY_PERCENTILE_INDEX_FILENAME = '20260902_000001_analytics_latency_percentile_index.ts';const MCP_ENABLED_DEFAULT_FILENAME = '20260903_000001_mcp_enabled_default.ts';+const RESPONSE_CACHE_FILENAME = '20260903_000002_response_cache.ts';interface SchemaRow {type: string;@@ -118,6 +119,7 @@ describe('migration round trip', () => {QUOTA_OBSERVATION_LOOKUP_FILENAME,ANALYTICS_LATENCY_PERCENTILE_INDEX_FILENAME,MCP_ENABLED_DEFAULT_FILENAME,+ RESPONSE_CACHE_FILENAME,]);} finally {db.close();diff --git a/server/src/__tests__/services/cache.test.ts b/server/src/__tests__/services/cache.test.tsindex d9d6abc6..1cf53285 100644--- a/server/src/__tests__/services/cache.test.ts+++ b/server/src/__tests__/services/cache.test.ts@@ -1,11 +1,14 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest';-import { initDb, setSetting } from '../../db/index.js';+import { initDb, setSetting, getDb } from '../../db/index.js';import {computeCacheKey,getCachedResponse,storeCachedResponse,getCacheStats,clearCache,+ loadCacheFromDb,+ __flushPersistenceForTests,+ __resetMemoryForTests,isCacheableTemperature,parseCacheDirective,cacheActive,@@ -16,6 +19,7 @@ import type { ChatMessage } from '@freellmapi/shared/types.js';const CACHE_ENV = ['RESPONSE_CACHE',+ 'RESPONSE_CACHE_PERSIST','RESPONSE_CACHE_TTL_SECONDS','RESPONSE_CACHE_MAX_TEMPERATURE','RESPONSE_CACHE_MAX_ENTRIES',@@ -370,4 +374,141 @@ describe('response cache', () => {expect(isCacheEnabled()).toBe(true);});});++ // Persistence is tied to the cache master switch, so these have to turn it on.+ // "Restart" means __resetMemoryForTests(): it drops the in-memory LRU and+ // leaves the table alone, which is what a process restart does. clearCache()+ // is the user-facing flush and now wipes SQLite too, so it cannot stand in.+ describe('SQLite persistence', () => {+ beforeEach(() => {+ process.env.RESPONSE_CACHE = 'true';+ });++ const rowCount = (): number =>+ (getDb().prepare('SELECT COUNT(*) AS n FROM response_cache').get() as { n: number }).n;++ it('survives a restart: store -> reload from DB -> hit', () => {+ const key = computeCacheKey({ model: 'auto', messages: [msg('user', 'persisted')] });+ store(key, 'persisted answer');+ expect(getCacheStats().entries).toBe(1);++ __resetMemoryForTests();+ expect(getCacheStats().entries).toBe(0);+ loadCacheFromDb();++ const hit = getCachedResponse(key);+ expect(hit).not.toBeNull();+ expect((hit!.body as any).choices[0].message.content).toBe('persisted answer');+ expect(hit!.platform).toBe('groq');+ expect(hit!.promptTokens).toBe(10);+ });++ it('persists nothing while the cache is off', () => {+ process.env.RESPONSE_CACHE = 'false';+ const key = computeCacheKey({ model: 'auto', messages: [msg('user', 'unpersisted')] });+ store(key, 'answer');+ __flushPersistenceForTests();+ expect(rowCount()).toBe(0);+ });++ it('persists nothing when RESPONSE_CACHE_PERSIST is off', () => {+ process.env.RESPONSE_CACHE_PERSIST = 'false';+ const key = computeCacheKey({ model: 'auto', messages: [msg('user', 'memory-only')] });+ store(key, 'answer');+ __flushPersistenceForTests();+ expect(rowCount()).toBe(0);+ // Still cached in memory: only the disk half is disabled.+ expect(getCachedResponse(key)).not.toBeNull();+ });++ it('carries the rolling hit count across a restart', () => {+ const key = computeCacheKey({ model: 'auto', messages: [msg('user', 'counted')] });+ store(key, 'answer');+ getCachedResponse(key);+ getCachedResponse(key);+ expect(getCacheStats().totalHits).toBe(2);++ __resetMemoryForTests();+ loadCacheFromDb();+ // The hits reached the row, so the savings numbers do not reset to zero.+ expect(getCacheStats().totalHits).toBe(2);+ getCachedResponse(key);+ expect(getCacheStats().totalHits).toBe(3);+ });++ it('does not reload entries expired before startup', () => {+ process.env.RESPONSE_CACHE_TTL_SECONDS = '60';+ const key = computeCacheKey({ model: 'auto', messages: [msg('user', 'stale-persisted')] });+ const t0 = 1_000_000;+ store(key, 'stale', t0);++ __resetMemoryForTests();+ // 10 minutes later (past the 60s TTL): startup purge drops the row.+ loadCacheFromDb(t0 + 600_000);+ expect(getCachedResponse(key, t0 + 600_000)).toBeNull();+ expect(getCacheStats().entries).toBe(0);+ expect(rowCount()).toBe(0);+ });++ it('respects RESPONSE_CACHE_MAX_ENTRIES when reloading', () => {+ process.env.RESPONSE_CACHE_MAX_ENTRIES = '2';+ const base = 1_700_000_000_000;+ const keys = ['p1', 'p2', 'p3'].map(t =>+ computeCacheKey({ model: 'auto', messages: [msg('user', t)] }));+ // Stored with the cap raised so all three reach the table, then reloaded+ // under the cap — the load path has its own bound, separate from the LRU.+ process.env.RESPONSE_CACHE_MAX_ENTRIES = '10';+ keys.forEach((k, i) => store(k, `v${i}`, base + i));+ __flushPersistenceForTests();+ process.env.RESPONSE_CACHE_MAX_ENTRIES = '2';++ __resetMemoryForTests();+ loadCacheFromDb(base + 10);+ // Newest two win; the oldest row is dropped past the cap.+ expect(getCacheStats().entries).toBe(2);+ expect(getCachedResponse(keys[0]!, base + 10)).toBeNull();+ expect(getCachedResponse(keys[2]!, base + 10)).not.toBeNull();+ });++ it('drops the row when the LRU evicts the entry', () => {+ process.env.RESPONSE_CACHE_MAX_ENTRIES = '1';+ const first = computeCacheKey({ model: 'auto', messages: [msg('user', 'evicted')] });+ const second = computeCacheKey({ model: 'auto', messages: [msg('user', 'survivor')] });+ store(first, 'gone');+ store(second, 'kept');+ __flushPersistenceForTests();++ expect(rowCount()).toBe(1);+ __resetMemoryForTests();+ loadCacheFromDb();+ // The evicted entry must not come back from disk.+ expect(getCachedResponse(first)).toBeNull();+ expect(getCachedResponse(second)).not.toBeNull();+ });++ it('drops the row when a read finds the entry expired', () => {+ process.env.RESPONSE_CACHE_TTL_SECONDS = '60';+ const key = computeCacheKey({ model: 'auto', messages: [msg('user', 'ttl-row')] });+ const t0 = 2_000_000;+ store(key, 'stale', t0);+ __flushPersistenceForTests();+ expect(rowCount()).toBe(1);++ expect(getCachedResponse(key, t0 + 120_000)).toBeNull();+ __flushPersistenceForTests();+ expect(rowCount()).toBe(0);+ });++ it('clearCache() purges SQLite too, so a restart does not resurrect entries', () => {+ const key = computeCacheKey({ model: 'auto', messages: [msg('user', 'flushed')] });+ store(key, 'answer');+ __flushPersistenceForTests();+ expect(rowCount()).toBe(1);++ expect(clearCache()).toBe(1);+ expect(rowCount()).toBe(0);+ loadCacheFromDb();+ expect(getCachedResponse(key)).toBeNull();+ });+ });});diff --git a/server/src/db/migrate/defaults.ts b/server/src/db/migrate/defaults.tsindex b3d9cdc9..4a284c01 100644--- a/server/src/db/migrate/defaults.ts+++ b/server/src/db/migrate/defaults.ts@@ -31,6 +31,7 @@ import * as idempotencyClaims from '../migrations/20260901_000001_idempotency_climport * as quotaObservationLookup from '../migrations/20260901_000002_quota_observation_lookup.js';import * as analyticsLatencyPercentileIndex from '../migrations/20260902_000001_analytics_latency_percentile_index.js';import * as mcpEnabledDefault from '../migrations/20260903_000001_mcp_enabled_default.js';+import * as responseCache from '../migrations/20260903_000002_response_cache.js';export interface MigrationModule {up(db: Db): void;@@ -74,6 +75,7 @@ export const IDEMPOTENCY_CLAIMS_FILENAME = '20260901_000001_idempotency_claims.texport const QUOTA_OBSERVATION_LOOKUP_FILENAME = '20260901_000002_quota_observation_lookup.ts';export const ANALYTICS_LATENCY_PERCENTILE_INDEX_FILENAME = '20260902_000001_analytics_latency_percentile_index.ts';export const MCP_ENABLED_DEFAULT_FILENAME = '20260903_000001_mcp_enabled_default.ts';+export const RESPONSE_CACHE_FILENAME = '20260903_000002_response_cache.ts';export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: LEGACY_BASELINE_FILENAME, module: legacyBaseline },@@ -108,4 +110,5 @@ export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: QUOTA_OBSERVATION_LOOKUP_FILENAME, module: quotaObservationLookup },{ filename: ANALYTICS_LATENCY_PERCENTILE_INDEX_FILENAME, module: analyticsLatencyPercentileIndex },{ filename: MCP_ENABLED_DEFAULT_FILENAME, module: mcpEnabledDefault },+ { filename: RESPONSE_CACHE_FILENAME, module: responseCache },];diff --git a/server/src/db/migrations/20260903_000002_response_cache.ts b/server/src/db/migrations/20260903_000002_response_cache.tsnew file mode 100644index 00000000..593bc27d--- /dev/null+++ b/server/src/db/migrations/20260903_000002_response_cache.ts@@ -0,0 +1,56 @@+// Migration: persistent response cache+// Created: 2026-09-03+//+// DOWN: reversible+//+// The response cache (services/cache.ts) is a pure in-memory LRU today: a+// restart drops every entry, so the daily quota-reset re-run pattern (same+// tasks re-executed after UTC midnight) never benefits. This table gives the+// cache a durable backing store while keeping the in-memory LRU as the hot+// path: storeCachedResponse writes through, startup reloads unexpired rows.+//+// Note this puts PLAINTEXT model responses on disk, which the memory-only cache+// never did. It is therefore tied to the cache master switch (off by default)+// and separately disableable with RESPONSE_CACHE_PERSIST=false.+//+// cache_key is the canonical SHA-256 from computeCacheKey (PK).+// body_json is the full OpenAI-shaped completion, replayed verbatim on a hit.+// hit_count / last_hit_at_ms carry the savings stats: a store writes them and+// every hit updates the row, so the dashboard numbers survive a restart. Both+// writes are queued off the proxy hot path (services/cache.ts drains them on+// the next tick) because better-sqlite3 is synchronous.+// created_at_ms anchors TTL checks; expires_at_ms is a denormalized+// created_at_ms + TTL for cheap startup purges and index scans.+// Rows are dropped whenever their memory entry goes (TTL expiry, LRU eviction,+// DELETE /api/cache) plus a startup sweep, so the table stays LRU-bounded.++import type { Db } from '../types.js';++export function up(db: Db): void {+ db.exec(`+ CREATE TABLE IF NOT EXISTS response_cache (+ cache_key TEXT PRIMARY KEY,+ body_json TEXT NOT NULL,+ platform TEXT NOT NULL,+ model_id TEXT NOT NULL,+ key_id INTEGER,+ prompt_tokens INTEGER NOT NULL,+ completion_tokens INTEGER NOT NULL,+ hit_count INTEGER NOT NULL DEFAULT 0,+ created_at_ms INTEGER NOT NULL,+ last_hit_at_ms INTEGER,+ expires_at_ms INTEGER NOT NULL+ );++ -- Startup purge and expiry sweeps scan by TTL.+ CREATE INDEX IF NOT EXISTS idx_response_cache_expires+ ON response_cache(expires_at_ms);+ `);+}++export function down(db: Db): void {+ db.exec(`+ DROP INDEX IF EXISTS idx_response_cache_expires;+ DROP TABLE IF EXISTS response_cache;+ `);+}diff --git a/server/src/index.ts b/server/src/index.tsindex 70c31e0a..4b4f85eb 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -19,6 +19,7 @@ import { warnOnEnvDrift } from './lib/env-drift.js';import { warnOnRoutingOverrideDrift } from './services/model-weight-overrides.js';import { installLogRedaction } from './lib/log-redaction.js';import { cleanupExpiredCooldowns } from './services/ratelimit.js';+import { loadCacheFromDb } from './services/cache.js';// Before any other statement runs, so no provider key can reach stdout — users// paste server output into bug reports. Module scope, not inside main(), so it@@ -46,6 +47,11 @@ async function main() {// After initDb: the unknown-model half of this check reads the catalog.warnOnRoutingOverrideDrift();+ // Reload the persisted response cache into the in-memory LRU so entries+ // survive a restart (the daily quota-reset re-run pattern). Best-effort:+ // a DB failure leaves the cache empty (memory-only), exactly as before.+ loadCacheFromDb();+// Cooldowns persist across restarts on purpose, but their expiry is collected// lazily (isOnCooldown, per model+key). Rows for routes nothing asks about// again — retired models, deleted keys, a shutdown taken while everything wasdiff --git a/server/src/services/cache.ts b/server/src/services/cache.tsindex 2d2e62fd..cf2d7933 100644--- a/server/src/services/cache.ts+++ b/server/src/services/cache.ts@@ -22,14 +22,21 @@// replaying one frozen answer would defeat that. Cached only when the// temperature is omitted or at/below RESPONSE_CACHE_MAX_TEMPERATURE.// - In-memory and bounded. Entries live in a size-capped LRU map (oldest use-// evicted first), so the cache can never grow without bound and a restart-// simply flushes it. No schema, no migration, no persisted response blobs.+// evicted first), so the cache can never grow without bound.+// - Optionally durable. When the cache is ON, the same entries are written+// through to the response_cache table so a restart does not throw the day's+// savings away (the daily quota-reset re-run pattern). This means PLAINTEXT+// model responses land on disk, which is a privacy posture change, so it is+// tied to the cache master switch and can be turned off on its own with+// RESPONSE_CACHE_PERSIST=false (memory-only, the pre-0.9.5 behaviour). The+// SQLite row is dropped whenever the memory entry goes: TTL expiry, LRU+// eviction, an explicit flush, or the startup purge.// - Fail-safe reads. The settings lookup that decides the master switch is// wrapped, so a not-yet-initialized DB disables the cache rather than// throwing in the proxy hot path (mirrors services/ratelimit.ts).import crypto from 'crypto';-import { getSetting } from '../db/index.js';+import { getSetting, getDb } from '../db/index.js';import type { ChatMessage } from '@freellmapi/shared/types.js';// ── Config (read on each call so tests and the dashboard can toggle live) ──@@ -73,6 +80,16 @@ export function isCacheEnabled(): boolean {return envFlag('RESPONSE_CACHE', false);}+/**+ * Write-through to SQLite. Only meaningful when the cache itself is on, so an+ * install that never enabled caching persists nothing and the feature is inert.+ * Separately switchable because persisting plaintext model responses to disk is+ * a privacy decision an operator may want to decline while still caching.+ */+export function cachePersistenceEnabled(): boolean {+ return isCacheEnabled() && envFlag('RESPONSE_CACHE_PERSIST', true);+}+/** Entry lifetime. Default 1h: long enough to absorb retries and agent re-runs,* short enough that a refreshed catalog or key changes answers soon after. */export function cacheTtlMs(): number {@@ -263,10 +280,65 @@ interface CacheEntry {// at the end (delete + set), so eviction from the front drops the coldest entry.const store = new Map<string, CacheEntry>();+// ── Deferred SQLite write-through ──+// better-sqlite3 is synchronous, so a store/hit write would sit on the request+// path (a large completion body is a multi-KB write with an fsync behind it).+// Every persistence write is therefore queued and drained on the next tick: the+// in-memory map is already correct by then, and a crash in the gap only costs+// a cache entry. Individually wrapped so one bad write cannot take down the+// drain, and skipped entirely when persistence is off.+const pendingWrites: Array<() => void> = [];+let drainScheduled = false;++function schedulePersist(op: () => void): void {+ if (!cachePersistenceEnabled()) return;+ pendingWrites.push(op);+ if (drainScheduled) return;+ drainScheduled = true;+ setImmediate(drainPendingWrites);+}++function drainPendingWrites(): void {+ drainScheduled = false;+ const ops = pendingWrites.splice(0, pendingWrites.length);+ for (const op of ops) {+ try {+ op();+ } catch {+ // best-effort: a DB failure degrades to memory-only, never to a 500+ }+ }+}++function scheduleRowDelete(cacheKey: string): void {+ schedulePersist(() => {+ getDb().prepare('DELETE FROM response_cache WHERE cache_key = ?').run(cacheKey);+ });+}++/**+ * Test-only: run the queued write-through immediately instead of on the next+ * tick, so a synchronous test can assert on what actually reached SQLite.+ */+export function __flushPersistenceForTests(): void {+ drainPendingWrites();+}++/**+ * Test-only: drop the in-memory LRU while leaving the SQLite table intact, the+ * way a process restart does. (clearCache() is the user-facing flush and wipes+ * both, so it cannot stand in for a restart.) Pending write-through is drained+ * first, since a real restart's writes had already landed.+ */+export function __resetMemoryForTests(): void {+ drainPendingWrites();+ store.clear();+}+/*** Look up a cached completion. Returns null on a miss or when the entry has aged- * past the TTL (expired entries are deleted lazily on read). A hit bumps the- * entry's hit_count and moves it to most-recently-used.+ * past the TTL (expired entries are deleted lazily on read, in memory and on+ * disk). A hit bumps the entry's hit_count and moves it to most-recently-used.*/export function getCachedResponse(cacheKey: string, now = Date.now()): CachedResponse | null {const entry = store.get(cacheKey);@@ -274,6 +346,8 @@ export function getCachedResponse(cacheKey: string, now = Date.now()): CachedResif (now - entry.createdAtMs > cacheTtlMs()) {store.delete(cacheKey);+ // The row would otherwise outlive its memory entry until the next restart.+ scheduleRowDelete(cacheKey);return null;}@@ -283,6 +357,15 @@ export function getCachedResponse(cacheKey: string, now = Date.now()): CachedResstore.delete(cacheKey);store.set(cacheKey, entry);+ // Keep the persisted counters in step so the savings numbers survive a+ // restart instead of resetting to whatever the last store wrote.+ const hitCount = entry.hitCount;+ schedulePersist(() => {+ getDb()+ .prepare('UPDATE response_cache SET hit_count = ?, last_hit_at_ms = ? WHERE cache_key = ?')+ .run(hitCount, now, cacheKey);+ });+return {body: entry.body,platform: entry.platform,@@ -299,11 +382,18 @@ export function getCachedResponse(cacheKey: string, now = Date.now()): CachedRes* Enforces the entry cap by evicting the least-recently-used entries. Best-* effort: an unserializable body is skipped so caching can never break a* request that already succeeded.+ *+ * SQLite persistence: when the cache is on, the entry is also written through+ * to the response_cache table so it survives a restart (the daily quota-reset+ * re-run pattern). The write is deferred to the next tick and best-effort, so+ * it never sits on — or throws into — the proxy hot path; a DB failure degrades+ * to in-memory-only, exactly as before.*/export function storeCachedResponse(cacheKey: string, input: StoreInput, now = Date.now()): void {// Reject bodies that can't be JSON-serialized; a hit must be replayable.+ let bodyJson: string;try {- JSON.stringify(input.body);+ bodyJson = JSON.stringify(input.body);} catch {return;}@@ -329,6 +419,105 @@ export function storeCachedResponse(cacheKey: string, input: StoreInput, now = Dconst oldest = store.keys().next().value as string | undefined;if (oldest === undefined) break;store.delete(oldest);+ // Evicting in memory but not on disk would let the table grow without+ // bound and let a restart resurrect entries the LRU already gave up on.+ scheduleRowDelete(oldest);+ }++ // Write-through to SQLite. hit_count is stored at its current in-memory value+ // (0 for a fresh store, since an overwrite resets the rolling stat with the+ // answer it counts); subsequent hits update the row in getCachedResponse.+ const entry = store.get(cacheKey);+ if (!entry) return; // cap of 0: the entry was evicted by the loop above+ const expiresAtMs = now + cacheTtlMs();+ schedulePersist(() => {+ getDb().prepare(+ `INSERT INTO response_cache+ (cache_key, body_json, platform, model_id, key_id, prompt_tokens, completion_tokens, hit_count, created_at_ms, last_hit_at_ms, expires_at_ms)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(cache_key) DO UPDATE SET+ body_json = excluded.body_json,+ platform = excluded.platform,+ model_id = excluded.model_id,+ key_id = excluded.key_id,+ prompt_tokens = excluded.prompt_tokens,+ completion_tokens = excluded.completion_tokens,+ hit_count = excluded.hit_count,+ created_at_ms = excluded.created_at_ms,+ last_hit_at_ms = excluded.last_hit_at_ms,+ expires_at_ms = excluded.expires_at_ms`,+ ).run(+ cacheKey,+ bodyJson,+ input.platform,+ input.modelId,+ input.keyId,+ input.promptTokens,+ input.completionTokens,+ entry.hitCount,+ now,+ entry.lastHitAtMs,+ expiresAtMs,+ );+ });+}++/**+ * Reload unexpired entries from SQLite into the in-memory LRU, bounded by+ * RESPONSE_CACHE_MAX_ENTRIES. Called once at startup (after initDb) from both+ * boot paths, server/src/index.ts and desktop/src/server-host.ts; expired rows+ * are purged opportunistically. Best-effort: any DB error leaves the cache+ * empty (memory-only), matching the pre-persistence behavior.+ */+export function loadCacheFromDb(now = Date.now()): void {+ try {+ const db = getDb();+ // Purge expired rows lazily on startup so the table doesn't accumulate+ // dead entries between restarts. Unconditional: rows written while the+ // cache was on must still age out after it is switched off.+ db.prepare('DELETE FROM response_cache WHERE expires_at_ms <= ?').run(now);+ // Hydration only when the operator actually wants the cache (and its+ // on-disk half). Off by default, so this is inert on an untouched install.+ if (!cachePersistenceEnabled()) return;+ const rows = db.prepare(+ `SELECT cache_key, body_json, platform, model_id, key_id, prompt_tokens, completion_tokens, hit_count, created_at_ms, last_hit_at_ms+ FROM response_cache+ ORDER BY created_at_ms ASC`,+ ).all() as Array<{+ cache_key: string;+ body_json: string;+ platform: string;+ model_id: string;+ key_id: number | null;+ prompt_tokens: number;+ completion_tokens: number;+ hit_count: number;+ created_at_ms: number;+ last_hit_at_ms: number | null;+ }>;+ const cap = cacheMaxEntries();+ // Newest wins: drop rows past the cap from the FRONT (oldest first).+ const keep = rows.length > cap ? rows.slice(rows.length - cap) : rows;+ for (const row of keep) {+ if (now - row.created_at_ms > cacheTtlMs()) continue; // aged between purge and read+ try {+ store.set(row.cache_key, {+ body: JSON.parse(row.body_json),+ platform: row.platform,+ modelId: row.model_id,+ keyId: row.key_id,+ promptTokens: row.prompt_tokens,+ completionTokens: row.completion_tokens,+ hitCount: row.hit_count,+ createdAtMs: row.created_at_ms,+ lastHitAtMs: row.last_hit_at_ms,+ });+ } catch {+ // corrupt body — skip; it will be overwritten on the next store+ }+ }+ } catch {+ // best-effort: DB unavailable at startup → memory-only cache}}@@ -358,9 +547,22 @@ export function getCacheStats(): CacheStats {return { entries: store.size, totalHits, savedPromptTokens, savedCompletionTokens };}-/** Drop every cached entry. Returns the number removed. */+/**+ * Drop every cached entry, in memory AND on disk. Returns the number removed.+ * The persisted table has to go too: DELETE /api/cache is how an operator+ * forces fresh answers (changed keys, a bad reply, a privacy request), and a+ * flush that left the rows behind would resurrect all of it on the next+ * restart. Queued write-through is discarded for the same reason. Runs inline+ * rather than deferred: this is an admin route, not the proxy hot path.+ */export function clearCache(): number {const removed = store.size;store.clear();+ pendingWrites.length = 0;+ try {+ getDb().prepare('DELETE FROM response_cache').run();+ } catch {+ // best-effort: no DB (or no table yet) means there is nothing persisted+ }return removed;}