Skip to content

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

Make the headroom guardrail thresholds tunable (#989)

suantea (asuan_suan)547692a86f27
diff --git a/server/src/__tests__/routes/settings-headroom.test.ts b/server/src/__tests__/routes/settings-headroom.test.ts
new file mode 100644
index 00000000..017cada0
--- /dev/null
+++ b/server/src/__tests__/routes/settings-headroom.test.ts
@@ -0,0 +1,86 @@
+import { describe, it, expect, beforeAll } from 'vitest';
+import type { Express } from 'express';
+import { createApp } from '../../app.js';
+import { initDb, getSetting } from '../../db/index.js';
+import { mintDashboardToken } from '../helpers/auth.js';
+import { HEADROOM_RAMP_START_KEY, HEADROOM_FLOOR_KEY } from '../../services/router.js';
+
+async function request(app: Express, method: string, path: string, body: any, token: string) {
+ const server = app.listen(0, '127.0.0.1');
+ if (!server.listening) await new Promise<void>(resolve => server.once('listening', () => resolve()));
+ const addr = server.address() as any;
+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {
+ method,
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ const raw = await res.text();
+ server.close();
+ let json: any = null;
+ try { json = JSON.parse(raw); } catch {}
+ return { status: res.status, body: json };
+}
+
+// GET/PUT /api/settings/headroom (#899): tunable proactive-demotion thresholds
+// for the free-quota headroom guardrail.
+describe('/api/settings/headroom', () => {
+ let app: Express;
+ let token: string;
+
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ app = createApp();
+ token = mintDashboardToken();
+ });
+
+ it('reports nulls (scoring.ts defaults) before anything is configured', async () => {
+ const { status, body } = await request(app, 'GET', '/api/settings/headroom', undefined, token);
+ expect(status).toBe(200);
+ expect(body).toEqual({ rampStart: null, floor: null });
+ });
+
+ it('stores and returns the configured thresholds', async () => {
+ const put = await request(app, 'PUT', '/api/settings/headroom', { rampStart: 0.5, floor: 0.3 }, token);
+ expect(put.status).toBe(200);
+ expect(put.body).toEqual({ rampStart: 0.5, floor: 0.3 });
+ expect(getSetting(HEADROOM_RAMP_START_KEY)).toBe('0.5');
+ expect(getSetting(HEADROOM_FLOOR_KEY)).toBe('0.3');
+
+ const get = await request(app, 'GET', '/api/settings/headroom', undefined, token);
+ expect(get.body).toEqual(put.body);
+ });
+
+ it('supports partial updates, leaving the other threshold untouched', async () => {
+ await request(app, 'PUT', '/api/settings/headroom', { rampStart: 0.5, floor: 0.3 }, token);
+ const put = await request(app, 'PUT', '/api/settings/headroom', { rampStart: 0.6 }, token);
+ expect(put.status).toBe(200);
+ expect(put.body).toEqual({ rampStart: 0.6, floor: 0.3 });
+ });
+
+ it('null clears a threshold back to the default', async () => {
+ await request(app, 'PUT', '/api/settings/headroom', { rampStart: 0.5, floor: 0.3 }, token);
+ const put = await request(app, 'PUT', '/api/settings/headroom', { floor: null }, token);
+ expect(put.status).toBe(200);
+ expect(put.body).toEqual({ rampStart: 0.5, floor: null });
+ expect(getSetting(HEADROOM_FLOOR_KEY)).toBeUndefined();
+ });
+
+ const rejected: Array<[string, any]> = [
+ ['an out-of-range rampStart', { rampStart: 1.5 }],
+ ['a negative rampStart', { rampStart: -0.1 }],
+ ['an out-of-range floor', { floor: 2 }],
+ ['a string instead of a number', { rampStart: '0.5' }],
+ ];
+
+ for (const [label, payload] of rejected) {
+ it(`rejects ${label} with a 400 and leaves the settings untouched`, async () => {
+ await request(app, 'PUT', '/api/settings/headroom', { rampStart: 0.5, floor: 0.3 }, token);
+ const { status, body } = await request(app, 'PUT', '/api/settings/headroom', payload, token);
+ expect(status).toBe(400);
+ expect(body.error.type).toBe('invalid_request_error');
+ expect(getSetting(HEADROOM_RAMP_START_KEY)).toBe('0.5');
+ expect(getSetting(HEADROOM_FLOOR_KEY)).toBe('0.3');
+ });
+ }
+});
diff --git a/server/src/__tests__/services/scoring.test.ts b/server/src/__tests__/services/scoring.test.ts
index 2c0f06a4..63d1ebf7 100644
--- a/server/src/__tests__/services/scoring.test.ts
+++ b/server/src/__tests__/services/scoring.test.ts
@@ -127,6 +127,24 @@ describe('scoring: guardrails', () => {
expect(headroomFactor(900_000, 1_000_000)).toBeLessThan(1); // 10% left → protecting
});
+ it('honors tunable rampStart/floor thresholds (#899)', () => {
+ // Aggressive operator: start protecting at 50% remaining, floor at 0.3.
+ const opts = { rampStart: 0.5, floor: 0.3 };
+ expect(headroomFactor(400_000, 1_000_000, opts)).toBe(1); // 60% left ≥ rampStart → no opinion
+ expect(headroomFactor(500_000, 1_000_000, opts)).toBe(1); // exactly at rampStart → not yet demoting
+ // 40% left → demoting: floor + (1-floor)·(remaining/rampStart)
+ // = 0.3 + 0.7·(0.4/0.5) = 0.86
+ expect(headroomFactor(600_000, 1_000_000, opts)).toBeCloseTo(0.86, 5);
+ expect(headroomFactor(1_000_000, 1_000_000, opts)).toBeCloseTo(0.3, 5); // fully used → floor
+ });
+
+ it('clamps out-of-range thresholds to defaults (#899)', () => {
+ expect(headroomFactor(500_000, 1_000_000, { rampStart: 2, floor: -1 }))
+ .toBe(headroomFactor(500_000, 1_000_000)); // same as default behavior
+ expect(headroomFactor(500_000, 1_000_000, { rampStart: NaN }))
+ .toBe(headroomFactor(500_000, 1_000_000));
+ });
+
it('unknown budget yields no opinion (factor 1)', () => {
expect(headroomFactor(123, 0)).toBe(1);
});
diff --git a/server/src/routes/settings.ts b/server/src/routes/settings.ts
index 7515c9af..1ebd10cf 100644
--- a/server/src/routes/settings.ts
+++ b/server/src/routes/settings.ts
@@ -22,6 +22,7 @@ import {
getCompressionConfig,
setCompressionConfig,
} from '../services/compression/config.js';
+import { getHeadroomThresholds, setHeadroomThresholds } from '../services/router.js';
import { z } from 'zod';
import { getAppVersion } from '../lib/app-version.js';
import {
@@ -280,6 +281,40 @@ const guardrailsPutSchema = z.object({
maxConsecutiveUpstreamFails: z.number().int().min(0).optional(),
});
+// Get the headroom guardrail thresholds (#899): the remaining-budget fraction
+// at which proactive demotion begins and the score floor at 0 remaining. Both
+// are decimals (0.2 = 20%). null = the scoring.ts default is in effect.
+settingsRouter.get('/headroom', (_req: Request, res: Response) => {
+ const { rampStart, floor } = getHeadroomThresholds();
+ res.json({ rampStart: rampStart ?? null, floor: floor ?? null });
+});
+
+const headroomPutSchema = z.object({
+ rampStart: z.number().min(0).max(1).nullable().optional(),
+ floor: z.number().min(0).max(1).nullable().optional(),
+});
+
+// Update the headroom guardrail thresholds. null clears a threshold back to the
+// scoring.ts default. Takes effect on the next request — no restart needed.
+settingsRouter.put('/headroom', (req: Request, res: Response) => {
+ const parsed = headroomPutSchema.safeParse(req.body);
+ if (!parsed.success) {
+ const detail = parsed.error.errors
+ .map(e => (e.path.length ? `${e.path.join('.')}: ${e.message}` : e.message))
+ .slice(0, 5)
+ .join(', ');
+ res.status(400).json({ error: { message: `Invalid headroom thresholds: ${detail}`, type: 'invalid_request_error' } });
+ return;
+ }
+ try {
+ setHeadroomThresholds(parsed.data.rampStart, parsed.data.floor);
+ const { rampStart, floor } = getHeadroomThresholds();
+ res.json({ rampStart: rampStart ?? null, floor: floor ?? null });
+ } catch (err: any) {
+ res.status(400).json({ error: { message: `Invalid headroom thresholds: ${err.message}`, type: 'invalid_request_error' } });
+ }
+});
+
// Update the guardrails. Partial: send just the knob you want to change.
// Takes effect on the next request — no restart needed. 0 disables a knob.
settingsRouter.put('/guardrails', (req: Request, res: Response) => {
diff --git a/server/src/services/router.ts b/server/src/services/router.ts
index 7cb811f0..c263fd9d 100644
--- a/server/src/services/router.ts
+++ b/server/src/services/router.ts
@@ -22,6 +22,7 @@ import {
peakAdjustedWeights, isValidPeakHour, isValidTimezone,
DEFAULT_PEAK_HOURS, type PeakHoursConfig,
observedSpeedRank, TIMEOUT_LATENCY_CAP_MS,
+ type HeadroomThresholds,
} from './scoring.js';
import { TIMEOUT_ERROR_MARKERS } from '../lib/error-classify.js';
import { applyModelWeightOverride, getModelWeightOverrides } from './model-weight-overrides.js';
@@ -338,6 +339,40 @@ const PEAK_END_KEY = 'routing_peak_end_hour';
const PEAK_TZ_KEY = 'routing_peak_timezone';
const COMMUNITY_PRIOR_KEY = 'routing_community_prior';
const COMMUNITY_PRIOR_ENABLED_KEY = 'routing_community_prior_enabled';
+// Headroom guardrail thresholds (#899): the remaining-budget fraction at which
+// demotion begins and the score floor at 0 remaining. Stored as decimals
+// (0.2 = 20%). Absent/invalid values fall back to the scoring.ts constants so
+// existing installs are untouched.
+export const HEADROOM_RAMP_START_KEY = 'routing_headroom_ramp_start';
+export const HEADROOM_FLOOR_KEY = 'routing_headroom_floor';
+
+export function getHeadroomThresholds(): { rampStart: number | undefined; floor: number | undefined } {
+ const read = (key: string): number | undefined => {
+ const raw = getSetting(key);
+ if (raw === undefined || raw.trim() === '') return undefined;
+ const n = Number(raw);
+ return Number.isFinite(n) && n >= 0 && n <= 1 ? n : undefined;
+ };
+ return { rampStart: read(HEADROOM_RAMP_START_KEY), floor: read(HEADROOM_FLOOR_KEY) };
+}
+
+// null clears a threshold back to the default; undefined leaves it untouched.
+export function setHeadroomThresholds(rampStart?: number | null, floor?: number | null): void {
+ const db = getDb();
+ const apply = (key: string, value: number | null | undefined): void => {
+ if (value === undefined) return;
+ if (value === null) {
+ db.prepare('DELETE FROM settings WHERE key = ?').run(key); // back to default
+ return;
+ }
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
+ throw new Error(`Invalid value ${value} for ${key} (must be 0..1)`);
+ }
+ setSetting(key, String(value));
+ };
+ apply(HEADROOM_RAMP_START_KEY, rampStart);
+ apply(HEADROOM_FLOOR_KEY, floor);
+}
/** Chance per request that an unmeasured model gets tried first when the
* exploration toggle is on. The bandit's Thompson sampling already explores
@@ -902,6 +937,7 @@ function scoreChainEntry(
intelMax: number,
sampled: boolean,
keyCounts: Map<string, number>,
+ headroomCfg: HeadroomThresholds,
): ScoredEntry {
const stats = statsCache?.get(modelStatsKey(entry.platform, entry.model_id, entry.endpoint_scope));
const successes = stats?.successes ?? 0;
@@ -925,7 +961,12 @@ function scoreChainEntry(
// matching the pooled `monthlyUsedTokens` aggregate (#456). Math.max(1, …) so a
// model whose platform currently has no usable key isn't handed a 0 budget.
const budget = parseBudget(entry.monthly_token_budget) * Math.max(1, keyCounts.get(entry.platform) ?? 1);
- const headroom = headroomFactor(stats?.monthlyUsedTokens ?? 0, budget);
+ // Tunable headroom thresholds (#899): persisted overrides for when demotion
+ // starts and its floor; absent settings keep the scoring.ts defaults. Read
+ // ONCE per chain by the caller, not per entry — getSetting is an uncached
+ // SELECT, so reading it here cost two extra SQLite round-trips per model per
+ // request, the same reason `weights` and `keyCounts` are hoisted.
+ const headroom = headroomFactor(stats?.monthlyUsedTokens ?? 0, budget, headroomCfg);
const rl = rateLimitFactor(getPenalty(entry.model_db_id));
// Per-model env overrides (#738) scale the final score so a slow or
@@ -997,9 +1038,10 @@ function orderChain(chain: ChainRow[], strategy: RoutingStrategy, sampled = true
const intelMin = composites.length ? Math.min(...composites) : 0;
const intelMax = composites.length ? Math.max(...composites) : 0;
const keyCounts = usableKeyCountsByPlatform(getDb());
+ const headroomCfg = getHeadroomThresholds();
return chain
- .map(e => ({ e, s: scoreChainEntry(e, weights, intelMin, intelMax, sampled, keyCounts).score }))
+ .map(e => ({ e, s: scoreChainEntry(e, weights, intelMin, intelMax, sampled, keyCounts, headroomCfg).score }))
// Higher score first WITHIN a tier; manual priority breaks ties so the chain
// still matters.
.sort((a, b) => tier(a.e) - tier(b.e) || b.s - a.s || a.e.priority - b.e.priority)
@@ -1985,9 +2027,10 @@ export function getRoutingScores(): { strategy: RoutingStrategy; keySelectionStr
const intelMin = composites.length ? Math.min(...composites) : 0;
const intelMax = composites.length ? Math.max(...composites) : 0;
const keyCounts = usableKeyCountsByPlatform(db);
+ const headroomCfg = getHeadroomThresholds();
const scores: RoutingScore[] = chain.map(entry => {
- const scored = scoreChainEntry(entry, weights, intelMin, intelMax, false, keyCounts);
+ const scored = scoreChainEntry(entry, weights, intelMin, intelMax, false, keyCounts, headroomCfg);
const stats = statsCache?.get(modelStatsKey(entry.platform, entry.model_id, entry.endpoint_scope));
return {
modelDbId: entry.model_db_id,
diff --git a/server/src/services/scoring.ts b/server/src/services/scoring.ts
index 58383169..7cbaecb2 100644
--- a/server/src/services/scoring.ts
+++ b/server/src/services/scoring.ts
@@ -349,15 +349,35 @@ export function intelligenceScore(composite: number, min: number, max: number):
// Multiplier that stays at 1 while a model has comfortable monthly headroom and
// ramps down to a floor as it approaches its free-tier cap, so we stop steering
// traffic at a model we're about to burn out. Unknown budget (0) → no opinion.
+// Thresholds are tunable per-instance (#899): callers may pass explicit
+// rampStart/floor, and the defaults below are the historical behavior (start
+// protecting at 20% remaining, floor at 10% of the score). Router wires these
+// to persisted settings so operators can tune without a code change.
export const HEADROOM_FLOOR = 0.1;
export const HEADROOM_RAMP_START = 0.2; // start protecting at 20% remaining
-export function headroomFactor(usedTokens: number, budgetTokens: number): number {
+export interface HeadroomThresholds {
+ /** Remaining-budget fraction at which demotion begins (0..1). */
+ rampStart?: number;
+ /** Score floor while a model is at 0 remaining budget (0..1). */
+ floor?: number;
+}
+
+export function headroomFactor(usedTokens: number, budgetTokens: number, opts?: HeadroomThresholds): number {
if (!budgetTokens || budgetTokens <= 0) return 1; // unknown budget → no opinion
+ const rampStart = clampUnit(opts?.rampStart, HEADROOM_RAMP_START);
+ const floor = clampUnit(opts?.floor, HEADROOM_FLOOR);
const remaining = Math.max(0, 1 - usedTokens / budgetTokens);
- if (remaining >= HEADROOM_RAMP_START) return 1;
- // Linear from (0 remaining → floor) to (RAMP_START remaining → 1).
- return HEADROOM_FLOOR + (1 - HEADROOM_FLOOR) * (remaining / HEADROOM_RAMP_START);
+ if (remaining >= rampStart) return 1;
+ // Linear from (0 remaining → floor) to (rampStart remaining → 1).
+ return floor + (1 - floor) * (remaining / rampStart);
+}
+
+// Out-of-range / non-finite operator input falls back to the default rather
+// than silently clamping to a legal-but-unintended value (#899).
+function clampUnit(n: number | undefined, fallback: number): number {
+ if (n === undefined || !Number.isFinite(n) || n < 0 || n > 1) return fallback;
+ return n;
}
// ── Guardrail: live rate-limit penalty ──────────────────────────────────────