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(health): a served embedding/rerank/decision/media request marks its key working (#1620)

tashdroidec9123886630
diff --git a/server/src/__tests__/services/served-nonchat-marks-key-healthy.test.ts b/server/src/__tests__/services/served-nonchat-marks-key-healthy.test.ts
new file mode 100644
index 00000000..0a25aa9a
--- /dev/null
+++ b/server/src/__tests__/services/served-nonchat-marks-key-healthy.test.ts
@@ -0,0 +1,130 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { initDb, getDb } from '../../db/index.js';
+import { encrypt } from '../../lib/crypto.js';
+import { clearAllCooldowns } from '../../services/ratelimit.js';
+import { clearLastHealthyStampState } from '../../services/health.js';
+import { runEmbeddings } from '../../services/embeddings.js';
+import { runRerank } from '../../services/rerank.js';
+import { runDecision } from '../../services/decision.js';
+import { runImageGeneration } from '../../services/media.js';
+import { seedDecisionModels } from '../helpers/decision-models.js';
+
+// A served request is the strongest "this key works" evidence there is, and
+// every surface that spends a key from the 'healthy'/'unknown' pool must act
+// on it: the chat fallback loop (#1493) and a served search (#1612) already
+// do. Embeddings, rerank, decisions and media draw from the SAME pool via
+// reserveProviderCredential / the rerank candidates query, yet a success there
+// left the key frozen at 'unknown' — and for a provider whose keys never get
+// polled (#1599/#1459) or a key demoted by an earlier blip, there was no way
+// back to 'healthy' short of a manual "Check now".
+
+const realFetch = globalThis.fetch;
+
+function addKey(platform: string, status: 'healthy' | 'unknown', baseUrl?: string, raw = `${platform}-test-key`): number {
+ const { encrypted, iv, authTag } = encrypt(raw);
+ const row = baseUrl
+ ? getDb().prepare(`
+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled, base_url)
+ VALUES (?, 'test', ?, ?, ?, ?, 1, ?)
+ `).run(platform, encrypted, iv, authTag, status, baseUrl)
+ : getDb().prepare(`
+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)
+ VALUES (?, 'test', ?, ?, ?, ?, 1)
+ `).run(platform, encrypted, iv, authTag, status);
+ return Number(row.lastInsertRowid);
+}
+
+function keyState(id: number) {
+ return getDb().prepare('SELECT status, last_healthy_at FROM api_keys WHERE id = ?').get(id) as
+ { status: string; last_healthy_at: string | null };
+}
+
+function mockFetch(handler: (url: string, init: RequestInit) => Response) {
+ const fn = vi.fn((url: string, init: RequestInit) => Promise.resolve(handler(String(url), init)));
+ globalThis.fetch = fn as unknown as typeof fetch;
+ return fn;
+}
+
+describe('a served non-chat request marks its key as working (#1493, #1612)', () => {
+ beforeEach(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ clearAllCooldowns(Number.MAX_SAFE_INTEGER);
+ clearLastHealthyStampState();
+ });
+
+ afterEach(() => {
+ globalThis.fetch = realFetch;
+ vi.restoreAllMocks();
+ });
+
+ it('embeddings: a served embedding promotes an unknown key', async () => {
+ const keyId = addKey('custom', 'unknown', 'https://embeddings.example/v1');
+ getDb().prepare(`INSERT INTO embedding_models (family, platform, model_id, display_name, dimensions, priority, enabled, quota_label, key_id)
+ VALUES ('probe-embed', 'custom', 'probe-embed', 'Probe embedding', 2, 1, 1, '', ?)`).run(keyId);
+ mockFetch(() => new Response(JSON.stringify({
+ data: [{ index: 0, embedding: [0.1, 0.2] }],
+ usage: { prompt_tokens: 3 },
+ }), { status: 200, headers: { 'content-type': 'application/json' } }));
+
+ await expect(runEmbeddings('probe-embed', ['hello'])).resolves.toMatchObject({ platform: 'custom' });
+ expect(keyState(keyId)).toMatchObject({ status: 'healthy', last_healthy_at: expect.any(String) });
+ });
+
+ it('embeddings: a failed embedding does not', async () => {
+ const keyId = addKey('custom', 'unknown', 'https://embeddings.example/v1');
+ getDb().prepare(`INSERT INTO embedding_models (family, platform, model_id, display_name, dimensions, priority, enabled, quota_label, key_id)
+ VALUES ('probe-embed', 'custom', 'probe-embed', 'Probe embedding', 2, 1, 1, '', ?)`).run(keyId);
+ mockFetch(() => new Response('boom', { status: 500 }));
+
+ await expect(runEmbeddings('probe-embed', ['hello'])).rejects.toThrow();
+ expect(keyState(keyId)).toEqual({ status: 'unknown', last_healthy_at: null });
+ });
+
+ it('rerank: a served rerank promotes an unknown key', async () => {
+ const keyId = addKey('cohere', 'unknown');
+ mockFetch(() => new Response(JSON.stringify({ results: [{ index: 0, relevance_score: 0.9 }] }), { status: 200 }));
+
+ await expect(runRerank(undefined, 'q', ['a', 'b'], 1)).resolves.toMatchObject({ platform: 'cohere' });
+ expect(keyState(keyId)).toMatchObject({ status: 'healthy', last_healthy_at: expect.any(String) });
+ });
+
+ it('decision: a served decision promotes an unknown key', async () => {
+ seedDecisionModels();
+ const keyId = addKey('cloudflare', 'unknown', undefined, 'acct123:cf-token');
+ mockFetch(() => new Response(JSON.stringify({
+ success: true,
+ result: {
+ model: 'clef-flash',
+ answers: { tier: { type: 'choice', choice: 'code', probabilities: { light: 0.02, code: 0.98 } } },
+ usage: { input_tokens: 10, output_tokens: 0 },
+ },
+ }), { status: 200, headers: { 'content-type': 'application/json' } }));
+
+ await runDecision(
+ { state: 'x', questions: { tier: { type: 'choice', instructions: 'i', criteria: { light: 'a', code: 'b' } } } },
+ { model: '@cf/cloudflare/clef-flash', clientAgent: null },
+ );
+ expect(keyState(keyId)).toMatchObject({ status: 'healthy', last_healthy_at: expect.any(String) });
+ });
+
+ it('media: a served image generation promotes an unknown key', async () => {
+ const keyId = addKey('nvidia', 'unknown');
+ getDb().prepare(`INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label, key_id, meta_json)
+ VALUES ('nvidia', 'black-forest-labs/flux.1-schnell', 'flux', 'image', 1, 1, '', ?, NULL)`).run(keyId);
+ mockFetch(() => new Response(JSON.stringify({ artifacts: [{ base64: 'AAAA' }] }), { status: 200, headers: { 'content-type': 'application/json' } }));
+
+ await expect(runImageGeneration('auto', { prompt: 'a cat' })).resolves.toMatchObject({ platform: 'nvidia' });
+ expect(keyState(keyId)).toMatchObject({ status: 'healthy', last_healthy_at: expect.any(String) });
+ });
+
+ it('media: a failed image generation does not', async () => {
+ const keyId = addKey('nvidia', 'unknown');
+ getDb().prepare(`INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label, key_id, meta_json)
+ VALUES ('nvidia', 'black-forest-labs/flux.1-schnell', 'flux', 'image', 1, 1, '', ?, NULL)`).run(keyId);
+ mockFetch(() => new Response('unavailable', { status: 503 }));
+
+ await expect(runImageGeneration('auto', { prompt: 'a cat' })).rejects.toThrow();
+ expect(keyState(keyId)).toEqual({ status: 'unknown', last_healthy_at: null });
+ });
+});
diff --git a/server/src/services/decision.ts b/server/src/services/decision.ts
index cf1ba447..ec860015 100644
--- a/server/src/services/decision.ts
+++ b/server/src/services/decision.ts
@@ -8,6 +8,7 @@ import { proxyFetch } from '../lib/proxy.js';
import { secondsUntilNextMonth } from './key-budget.js';
import { reserveProviderCredential, type ReservedProviderCredential } from './provider-credential.js';
import { isOnCooldown, setCooldown } from './ratelimit.js';
+import { markKeyHealthyFromRequest } from './health.js';
// Decision models over the key pool.
//
@@ -352,6 +353,11 @@ export async function runDecision(body: DecisionRequest, opts: DecisionOptions =
try {
const out = await ADAPTERS[row.platform]!(credential, row.model_id, body, opts.signal);
logDecision(row, credential.id, 'ok', Date.now() - started, questionCount, out.usage.input_tokens, clientAgent, null);
+ // A served decision is evidence the key works, the same as a served
+ // chat request (#1493) or search (#1612). Decision routing fires every
+ // turn, so a decision key that serves fine but once got demoted to
+ // 'error' by a blip had no way back into the pool.
+ markKeyHealthyFromRequest(credential.id);
return { model: row.model_id, provider: row.platform, answers: out.answers, usage: out.usage };
} catch (err: any) {
const e = err instanceof DecisionError ? err : new DecisionError(String(err?.message ?? err), 502);
diff --git a/server/src/services/embeddings.ts b/server/src/services/embeddings.ts
index 63f6d203..d43799dc 100644
--- a/server/src/services/embeddings.ts
+++ b/server/src/services/embeddings.ts
@@ -15,6 +15,7 @@ import { getClientContext } from '../lib/client-context.js';
import { reserveProviderCredential } from './provider-credential.js';
import { proxyFetch } from '../lib/proxy.js';
import { bearerAuthHeader } from '../lib/credential.js';
+import { markKeyHealthyFromRequest } from './health.js';
import { customEndpointKeyIds } from './custom-endpoint.js';
import type { Db } from '../db/types.js';
import { SPEKA_BASE_URL } from '../providers/speka.js';
@@ -408,6 +409,11 @@ export async function runEmbeddings(model: string | undefined, inputs: string[],
}
const tokens = out.inputTokens ?? estimateTokens(inputs);
logEmbeddingRequest(row, credential.id, 'success', tokens, Date.now() - started, null);
+ // A served embedding is evidence the key works, the same as a served
+ // chat request (#1493) or a served search (#1612): stamp last_healthy_at
+ // and lift an 'unknown'/'error' key. Embedding-only keys (and #1459-era
+ // providers that refuse probes) had no success signal at all otherwise.
+ markKeyHealthyFromRequest(credential.id);
return {
family,
platform: row.platform,
diff --git a/server/src/services/media.ts b/server/src/services/media.ts
index 34dac773..a032fe0a 100644
--- a/server/src/services/media.ts
+++ b/server/src/services/media.ts
@@ -17,6 +17,7 @@ import { proxyFetch } from '../lib/proxy.js';
import { bearerAuthHeader } from '../lib/credential.js';
import { assessProviderUrl } from '../lib/url-guard.js';
import { isOnCooldown, setCooldown } from './ratelimit.js';
+import { markKeyHealthyFromRequest } from './health.js';
import { SPEECHIFY_BASE_URL, SPEECHIFY_VERSION } from '../providers/speechify.js';
import { TYPHOON_BASE_URL } from '../providers/typhoon.js';
import { ELECTRONHUB_BASE_URL } from '../providers/electronhub.js';
@@ -818,6 +819,10 @@ function logMedia(row: Pick<MediaModelRow, 'platform' | 'model_id' | 'modality'>
.prepare(`INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms, error, request_type, client_ip, client_user_agent, client_agent)
VALUES (?, ?, ?, ?, 0, 0, ?, ?, ?, ?, ?, ?)`)
.run(row.platform, row.model_id, keyId, status, latencyMs, error, row.modality, client.ip, client.userAgent, client.agent);
+ // A served media request is evidence the key works, the same as a served
+ // chat request (#1493) or a served search (#1612): stamp last_healthy_at
+ // and lift an 'unknown'/'error' key out of the pool's cold corner.
+ if (status === 'success' && keyId != null) markKeyHealthyFromRequest(keyId);
} catch (e) {
console.error('Failed to log media request:', e);
}
diff --git a/server/src/services/rerank.ts b/server/src/services/rerank.ts
index bb3d5cdb..89565c8b 100644
--- a/server/src/services/rerank.ts
+++ b/server/src/services/rerank.ts
@@ -2,6 +2,7 @@ import { getDb } from '../db/index.js';
import { decrypt } from '../lib/crypto.js';
import { parseRetryAfterMs } from '../providers/base.js';
import { secondsUntilNextMonth } from './key-budget.js';
+import { markKeyHealthyFromRequest } from './health.js';
// Cohere-style rerank over the existing free-tier key pool (#1029). Deliberately
// narrow first slice: platform='cohere' keys and custom OpenAI-compatible
@@ -101,6 +102,11 @@ export async function runRerank(model: string | undefined, query: string, docume
for (const cand of chain) {
try {
const out = await callProvider(cand, model, query, documents, n);
+ // A served rerank is evidence the key works, the same as a served chat
+ // request (#1493) or a served search (#1612). Rerank candidates come
+ // from the same 'healthy'/'unknown' pool, so a key that only ever
+ // serves reranks had no success signal to lift it out of 'error'.
+ markKeyHealthyFromRequest(cand.id);
return { platform: cand.platform, modelId: out.modelId, results: out.results };
} catch (err: any) {
lastError = err instanceof RerankError ? err : new RerankError(String(err?.message ?? err), 502);