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(search): a served search spends its key's monthly budget (#1158) (#1648)
tashdroid24748539c651
diff --git a/server/src/__tests__/services/search-spend-ledger.test.ts b/server/src/__tests__/services/search-spend-ledger.test.tsnew file mode 100644index 00000000..755bd885--- /dev/null+++ b/server/src/__tests__/services/search-spend-ledger.test.ts@@ -0,0 +1,106 @@+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 { runSearch, SearchError } from '../../services/search.js';+import { getMonthlyUsage } from '../../services/key-budget.js';+import { seedSearchEngines } from '../helpers/search-engines.js';++// POST /v1/search spends real provider quota (credits per query on Tavily,+// credits on Exa et al.), but logSearch only wrote search_requests. The+// per-key monthly caps (#1158) and GET /v1/usage read key_monthly_usage,+// which the requests_key_monthly_usage trigger feeds from `requests` — so a+// capped key never accrued search spend and served searches forever past its+// cap. This is the rerank gap (#1621/#1627) on the search surface.++const realFetch = globalThis.fetch;++function addKey(platform: string, monthlyRequestCap = 0): number {+ const { encrypted, iv, authTag } = encrypt(`${platform}-test-key`);+ const row = getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled, monthly_request_cap)+ VALUES (?, 'test', ?, ?, ?, 'healthy', 1, ?)+ `).run(platform, encrypted, iv, authTag, monthlyRequestCap);+ return Number(row.lastInsertRowid);+}++function spendRequests(keyId: number, requests: number) {+ getDb().prepare(+ 'INSERT INTO key_monthly_usage (key_id, month, requests, tokens) VALUES (?, ?, ?, 10)',+ ).run(keyId, new Date().toISOString().slice(0, 7), requests);+}++const hits = () => new Response(JSON.stringify({+ results: [{ title: 'A', url: 'https://a', text: 'alpha' }],+}), { status: 200 });++describe('search spend lands in the requests ledger (#1158)', () => {+ beforeEach(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ seedSearchEngines();+ clearAllCooldowns(Number.MAX_SAFE_INTEGER);+ });+ afterEach(() => {+ globalThis.fetch = realFetch;+ vi.restoreAllMocks();+ });++ it('a served search writes a success row and counts toward the monthly ledger', async () => {+ const key = addKey('exa');+ globalThis.fetch = vi.fn(async () => hits()) as unknown as typeof fetch;++ const out = await runSearch('what is the weather');+ expect(out.provider).toBe('exa');++ const row = getDb().prepare(+ "SELECT platform, model_id, status, request_type, input_tokens FROM requests WHERE key_id = ?",+ ).get(key) as any;+ expect(row).toMatchObject({+ platform: 'exa', model_id: 'exa-search', status: 'success',+ request_type: 'search', input_tokens: Math.ceil('what is the weather'.length / 4),+ });+ // The trigger on requests feeds key_monthly_usage, which the caps and+ // /v1/usage read: the search is now visible to both.+ expect(getMonthlyUsage(key).requests).toBe(1);+ });++ it('a failed attempt logs an error row that does NOT count toward usage', async () => {+ const key = addKey('exa');+ globalThis.fetch = vi.fn(async () => new Response(JSON.stringify({ error: 'boom' }), { status: 500 })) as unknown as typeof fetch;++ await expect(runSearch('q')).rejects.toBeInstanceOf(SearchError);++ const row = getDb().prepare(+ "SELECT status, request_type FROM requests WHERE key_id = ?",+ ).get(key) as any;+ expect(row).toMatchObject({ status: 'error', request_type: 'search' });+ expect(getMonthlyUsage(key)).toEqual({ requests: 0, tokens: 0 });+ });++ it('a key at its monthly request cap is skipped; a capped-only chain 429s without touching upstream', async () => {+ const key = addKey('exa', 1);+ spendRequests(key, 1);+ const fetch = vi.fn(async () => hits());+ globalThis.fetch = fetch as unknown as typeof fetch;++ const err = await runSearch('q').catch(e => e) as SearchError;+ expect(err).toBeInstanceOf(SearchError);+ expect(err.status).toBe(429);+ expect(err.code).toBe('quota_exceeded');+ expect(fetch).not.toHaveBeenCalled();+ });++ it('spend accumulates until the cap bites (end-to-end cap enforcement)', async () => {+ const key = addKey('exa', 2);+ globalThis.fetch = vi.fn(async () => hits()) as unknown as typeof fetch;++ await runSearch('q1');+ await runSearch('q2');+ expect(getMonthlyUsage(key).requests).toBe(2);++ const err = await runSearch('q3').catch(e => e) as SearchError;+ expect(err.status).toBe(429);+ expect(err.code).toBe('quota_exceeded');+ });+});diff --git a/server/src/services/search.ts b/server/src/services/search.tsindex 3193f33b..7539146e 100644--- a/server/src/services/search.ts+++ b/server/src/services/search.ts@@ -416,7 +416,7 @@ export const SEARCH_ENGINE_PLATFORMS = new Set(Object.keys(ADAPTERS).filter(p =>// ── Routing ─────────────────────────────────────────────────────────────────-function logSearch(row: SearchEngineRow, keyId: number | null, status: 'ok' | 'error', latencyMs: number, resultCount: number, clientAgent: string | null, error: string | null): void {+function logSearch(row: SearchEngineRow, keyId: number | null, status: 'ok' | 'error', latencyMs: number, resultCount: number, clientAgent: string | null, error: string | null, estimatedTokens: number): void {try {getDb().prepare(`INSERT INTO search_requests (engine_id, platform, key_id, status, latency_ms, result_count, client_agent, error)@@ -425,6 +425,21 @@ function logSearch(row: SearchEngineRow, keyId: number | null, status: 'ok' | 'e} catch (e) {console.error('Failed to log search request:', e);}+ // The per-key monthly caps (#1158) and GET /v1/usage read the+ // key_monthly_usage ledger, which the requests_key_monthly_usage trigger+ // feeds from `requests`. Search only wrote search_requests, so a served+ // search spent provider quota the cap never saw — the exact rerank gap+ // (#1621/#1627). request_type='search' follows the rerank/embeddings+ // precedent; the dashboard's Search page keeps reading search_requests.+ try {+ const client = getClientContext();+ getDb().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, ?, ?, 'search', ?, ?, ?)+ `).run(row.platform, row.model_id, keyId, status === 'ok' ? 'success' : 'error', estimatedTokens, latencyMs, error, client.ip, client.userAgent, client.agent ?? clientAgent);+ } catch (e) {+ console.error('Failed to log search request to requests table:', e);+ }}/** Bench this key for this engine according to what the upstream said. */@@ -485,6 +500,10 @@ export async function runSearch(query: string, opts: SearchOptions = {}): Promisconst chain = searchChain(opts.engine);const maxResults = Math.min(Math.max(1, Math.floor(opts.maxResults ?? DEFAULT_RESULTS)), MAX_RESULTS);const clientAgent = opts.clientAgent !== undefined ? opts.clientAgent : getClientContext().agent;+ // Rough token estimate for the ledger row (~4 chars/token), the same+ // heuristic rerank uses. It sizes the requests-table row so the monthly+ // caps (#1158) and /v1/usage see search spend.+ const estTokens = Math.ceil(query.length / 4);let lastError: SearchError | null = null;let attempted = 0;@@ -513,7 +532,7 @@ export async function runSearch(query: string, opts: SearchOptions = {}): Promistry {const out = await ADAPTERS[row.platform]!(credential, query, opts, maxResults);if (out.results.length === 0) throw new SearchError('upstream returned no valid search hits', 502);- logSearch(row, credential.id, 'ok', Date.now() - started, out.results.length, clientAgent, null);+ logSearch(row, credential.id, 'ok', Date.now() - started, out.results.length, clientAgent, null, estTokens);// A served search is the evidence the key works, the same as a served// chat request: it stamps last_healthy_at and lifts an 'unknown' or// 'error' key. For SerpSearch, Exa and Parallel it is the only evidence@@ -528,7 +547,7 @@ export async function runSearch(query: string, opts: SearchOptions = {}): Promis};} catch (err: any) {const e = err instanceof SearchError ? err : new SearchError(String(err?.message ?? err), 502);- logSearch(row, credential.id, 'error', Date.now() - started, 0, clientAgent, e.message.slice(0, 300));+ logSearch(row, credential.id, 'error', Date.now() - started, 0, clientAgent, e.message.slice(0, 300), estTokens);coolDown(row, credential.id, e);lastError = e;hints.record(e.status, e.retryAfterMs);