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

fix(router): warn when MODEL_ROUTING_OVERRIDES will never apply (#738) (#857)

OhOkThisIsFine48591a8e983d
diff --git a/.env.example b/.env.example
index 9d3c4321..8120f200 100644
--- a/.env.example
+++ b/.env.example
@@ -267,8 +267,11 @@ REQUEST_ANALYTICS_MAX_ROWS=100000
# Per-model routing score multipliers (#738), JSON object of model id → 0..2.
# 1.0 leaves a model unchanged, below 1 demotes it, above 1 promotes it, and 0
# means the automatic router never picks it (Manual priority still can).
-# Matching is by model id alone, across all platforms serving that id.
-# MODEL_ROUTING_OVERRIDES={"gpt-4o": 0.2, "deepseek-v3": 1.5}
+# Matching is by model id alone, across all platforms serving that id, and the
+# match is exact and case-sensitive. Copy ids from the dashboard Models page:
+# an id that matches nothing is silently ignored (the boot log flags it once the
+# catalog has synced).
+# MODEL_ROUTING_OVERRIDES={"gpt-4o": 0.2, "gpt-oss-120b": 1.5}
# --- Advanced / embedding ---------------------------------------------------
# Path to a prebuilt client `dist` directory to serve. Defaults to the bundled
diff --git a/server/src/__tests__/services/model-weight-overrides.test.ts b/server/src/__tests__/services/model-weight-overrides.test.ts
index dc97619f..85bfef10 100644
--- a/server/src/__tests__/services/model-weight-overrides.test.ts
+++ b/server/src/__tests__/services/model-weight-overrides.test.ts
@@ -4,7 +4,9 @@ import {
applyModelWeightOverride,
getModelWeightOverrides,
resetModelWeightOverrides,
+ warnOnRoutingOverrideDrift,
} from '../../services/model-weight-overrides.js';
+import { initDb, getDb, setSetting } from '../../db/index.js';
const ORIGINAL_ENV = process.env.MODEL_ROUTING_OVERRIDES;
@@ -75,4 +77,89 @@ describe('model weight overrides', () => {
resetModelWeightOverrides();
expect(getModelWeightOverrides().get('other')).toBe(0.9);
});
+
+ // Every rejection path above is silent by design so a bad variable cannot
+ // break boot. That is the right call for routing and the wrong one for the
+ // operator who just wrote the variable: a typo'd model id, an out-of-range
+ // multiplier and a stray comma are all indistinguishable from not setting it.
+ describe('warnOnRoutingOverrideDrift', () => {
+ const warnings: string[] = [];
+ const logger = { warn: (m: string) => { warnings.push(m); } };
+
+ beforeEach(() => {
+ warnings.length = 0;
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ });
+
+ it('says nothing when the variable is unset or empty', () => {
+ delete process.env.MODEL_ROUTING_OVERRIDES;
+ expect(warnOnRoutingOverrideDrift(logger)).toBeNull();
+ process.env.MODEL_ROUTING_OVERRIDES = ' ';
+ expect(warnOnRoutingOverrideDrift(logger)).toBeNull();
+ expect(warnings).toEqual([]);
+ });
+
+ it('reports unparsable JSON instead of ignoring it silently', () => {
+ process.env.MODEL_ROUTING_OVERRIDES = '{"gpt-4o": 0.2,}';
+ const drift = warnOnRoutingOverrideDrift(logger)!;
+ expect(drift.malformed).toBe(true);
+ expect(warnings.join()).toContain('not valid JSON');
+ });
+
+ it('reports a non-object value', () => {
+ process.env.MODEL_ROUTING_OVERRIDES = '["gpt-4o"]';
+ const drift = warnOnRoutingOverrideDrift(logger)!;
+ expect(drift.malformed).toBe(true);
+ expect(warnings.join()).toContain('must be a JSON object');
+ });
+
+ it('names entries dropped for an out-of-range or non-numeric multiplier', () => {
+ const real = (getDb().prepare('SELECT model_id FROM models LIMIT 1').get() as { model_id: string }).model_id;
+ process.env.MODEL_ROUTING_OVERRIDES = JSON.stringify({ [real]: 5, ['x-' + real]: 'fast' });
+ const drift = warnOnRoutingOverrideDrift(logger)!;
+ expect(drift.rejectedValues).toContain(real);
+ expect(drift.rejectedValues).toContain('x-' + real);
+ expect(warnings.join()).toContain('not a finite multiplier');
+ });
+
+ it('names an override that matches no model in the catalog', () => {
+ setSetting('catalog_last_sync_ms', String(Date.now()));
+ process.env.MODEL_ROUTING_OVERRIDES = '{"gpt-4o-typo-not-real": 0.2}';
+ const drift = warnOnRoutingOverrideDrift(logger)!;
+ expect(drift.unknownModels).toEqual(['gpt-4o-typo-not-real']);
+ expect(warnings.join()).toContain("not a model id in this install's catalog");
+ });
+
+ // This runs at boot, BEFORE startCatalogSync, so on a first run the models
+ // table holds only the migration seed (110 rows) against a real catalog of
+ // ~460. Without this gate every override naming one of the ~350 unseeded
+ // models is reported as bogus on exactly the boot someone is watching, and
+ // a warning that cries wolf first time out gets ignored forever after.
+ it('stays silent about unknown models until the catalog has synced once', () => {
+ // No catalog_last_sync_ms: a fresh install that has never synced.
+ process.env.MODEL_ROUTING_OVERRIDES = '{"a-real-model-not-yet-synced": 0.2}';
+ const drift = warnOnRoutingOverrideDrift(logger)!;
+ expect(drift.unknownModels).toEqual([]);
+ expect(warnings).toEqual([]);
+ });
+
+ it('still reports malformed JSON before the catalog has synced', () => {
+ // The value halves need no catalog, so the gate must not silence them.
+ process.env.MODEL_ROUTING_OVERRIDES = '{"gpt-4o": 0.2,}';
+ expect(warnOnRoutingOverrideDrift(logger)!.malformed).toBe(true);
+ warnings.length = 0;
+ process.env.MODEL_ROUTING_OVERRIDES = '{"gpt-4o": 5}';
+ expect(warnOnRoutingOverrideDrift(logger)!.rejectedValues).toEqual(['gpt-4o']);
+ expect(warnings.join()).toContain('not a finite multiplier');
+ });
+
+ it('stays quiet for a well-formed override naming a real model', () => {
+ const real = (getDb().prepare('SELECT model_id FROM models LIMIT 1').get() as { model_id: string }).model_id;
+ process.env.MODEL_ROUTING_OVERRIDES = JSON.stringify({ [real]: 0.2 });
+ const drift = warnOnRoutingOverrideDrift(logger)!;
+ expect(drift).toEqual({ malformed: false, rejectedValues: [], unknownModels: [] });
+ expect(warnings).toEqual([]);
+ });
+ });
});
diff --git a/server/src/index.ts b/server/src/index.ts
index 4403b8ea..093dba17 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -14,6 +14,7 @@ import { restoreDbBackupIfNeeded, startDbBackupPump } from './lib/db-backup.js';
import { userCount } from './services/auth.js';
import { generateSetupCode } from './lib/setup-code.js';
import { warnOnEnvDrift } from './lib/env-drift.js';
+import { warnOnRoutingOverrideDrift } from './services/model-weight-overrides.js';
import { installLogRedaction } from './lib/log-redaction.js';
// Before any other statement runs, so no provider key can reach stdout — users
@@ -39,6 +40,8 @@ async function main() {
}
initDb(config.dbPath ?? undefined);
applyDeclarativeConfigFromEnv();
+ // After initDb: the unknown-model half of this check reads the catalog.
+ warnOnRoutingOverrideDrift();
// First-run hardening: when the dashboard is still unclaimed, mint a one-time
// setup code and log it. A loopback browser can finish setup without it; a
diff --git a/server/src/services/model-weight-overrides.ts b/server/src/services/model-weight-overrides.ts
index 4d8ceeeb..d537efd0 100644
--- a/server/src/services/model-weight-overrides.ts
+++ b/server/src/services/model-weight-overrides.ts
@@ -1,3 +1,10 @@
+import { getDb, getSetting } from '../db/index.js';
+
+// Written by catalog-sync on every completed run (services/catalog-sync.ts).
+// Its presence is the only "the catalog is real, not just the migration seed"
+// signal available at boot.
+const CATALOG_LAST_SYNC_SETTING = 'catalog_last_sync_ms';
+
// ── Per-model routing weight overrides (#738) ────────────────────────────────
//
// Operators who run a relay with several models sometimes want to keep a model
@@ -74,3 +81,105 @@ export function applyModelWeightOverride(
const override = overrides.get(modelId);
return override === undefined ? score : score * override;
}
+
+/** What `warnOnRoutingOverrideDrift` found. Returned for tests; the caller at
+ * boot only wants the log lines. */
+export interface RoutingOverrideDrift {
+ /** The variable is set but did not parse into a usable object. */
+ malformed: boolean;
+ /** Keys present in the JSON but dropped: not a finite number in [0, 2]. */
+ rejectedValues: string[];
+ /** Keys that parsed fine but match no model_id in the catalog. Always empty
+ * when the catalog has not synced yet — see `warnOnRoutingOverrideDrift`. */
+ unknownModels: string[];
+}
+
+/**
+ * Report `MODEL_ROUTING_OVERRIDES` entries that will never do anything.
+ *
+ * Every rejection path in this module is deliberately silent so a bad variable
+ * can never break boot — but silence is the wrong answer for an operator who
+ * has just written one. A typo in a model id, a value of 5, or a stray trailing
+ * comma all produce exactly the same observable result as not setting the
+ * variable at all: the model keeps its normal score and nothing says why.
+ *
+ * Log-only, and never throws: an unreadable catalog just skips the model-id
+ * check rather than failing a boot over a diagnostic.
+ *
+ * The unknown-model half is SKIPPED until the catalog has synced at least once.
+ * This runs at boot, before startCatalogSync, so on a first run the models table
+ * holds only what the migrations seeded (110 rows) against a real catalog of
+ * ~460: every override naming one of the ~350 not in the seed would be reported
+ * as bogus on exactly the boot an operator is most likely to be reading. A
+ * warning that cries wolf on its first outing teaches people to skip the line
+ * that would have caught the real typo, so it stays quiet until it can be
+ * right. The malformed-JSON and bad-multiplier halves need no catalog and
+ * always run.
+ */
+export function warnOnRoutingOverrideDrift(
+ logger: Pick<Console, 'warn'> = console,
+): RoutingOverrideDrift | null {
+ const raw = process.env.MODEL_ROUTING_OVERRIDES;
+ if (raw === undefined || raw.trim() === '') return null;
+
+ const drift: RoutingOverrideDrift = { malformed: false, rejectedValues: [], unknownModels: [] };
+
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (err: any) {
+ drift.malformed = true;
+ logger.warn(
+ `[config] MODEL_ROUTING_OVERRIDES is not valid JSON and is being ignored entirely `
+ + `(${err?.message ?? err}). Expected an object like {"gpt-4o": 0.2}.`,
+ );
+ return drift;
+ }
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
+ drift.malformed = true;
+ logger.warn(
+ '[config] MODEL_ROUTING_OVERRIDES must be a JSON object mapping model ids to multipliers, '
+ + 'e.g. {"gpt-4o": 0.2} — the current value is being ignored entirely.',
+ );
+ return drift;
+ }
+
+ const accepted = parseModelWeightOverrides(raw);
+ for (const [modelId, value] of Object.entries(parsed)) {
+ if (!modelId.trim() || accepted.has(modelId)) continue;
+ drift.rejectedValues.push(modelId);
+ logger.warn(
+ `[config] MODEL_ROUTING_OVERRIDES entry "${modelId}" was dropped: `
+ + `${JSON.stringify(value)} is not a finite multiplier in [0, 2].`,
+ );
+ }
+
+ if (accepted.size > 0) {
+ try {
+ // Read-only, and gated on a completed sync: before the first one the
+ // models table is just the migration seed, so "unknown" would mean
+ // "not seeded yet" rather than "wrong".
+ if (getSetting(CATALOG_LAST_SYNC_SETTING)) {
+ const known = new Set(
+ (getDb().prepare('SELECT DISTINCT model_id FROM models').all() as { model_id: string }[])
+ .map(r => r.model_id),
+ );
+ for (const modelId of accepted.keys()) {
+ if (known.has(modelId)) continue;
+ drift.unknownModels.push(modelId);
+ logger.warn(
+ `[config] MODEL_ROUTING_OVERRIDES names "${modelId}", which is not a model id in this `
+ + "install's catalog, so the override is not applying. Overrides match model_id alone, "
+ + 'unqualified by platform, and the match is exact and case-sensitive. A model gated '
+ + 'behind a provider you have no key for appears once that key is added.',
+ );
+ }
+ }
+ } catch {
+ // Catalog unreadable (DB not ready, mid-migration). The value half of the
+ // report is still useful; skip the existence check rather than throw.
+ }
+ }
+
+ return drift;
+}