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(decisions): a served decision spends its key's monthly budget (#1158) (#1664)
tashdroid5b0d3cca84bb
diff --git a/server/src/__tests__/services/decision-spend-ledger.test.ts b/server/src/__tests__/services/decision-spend-ledger.test.tsnew file mode 100644index 00000000..50e980e9--- /dev/null+++ b/server/src/__tests__/services/decision-spend-ledger.test.ts@@ -0,0 +1,113 @@+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 { runDecision, DecisionError } from '../../services/decision.js';+import { getMonthlyUsage } from '../../services/key-budget.js';+import { seedDecisionModels } from '../helpers/decision-models.js';++// POST /v1/decisions spends real provider quota on every routing turn, but+// logDecision only wrote decision_requests. The per-key monthly caps (#1158)+// and GET /v1/usage read key_monthly_usage, which other surfaces feed through+// their `requests` rows — so a capped key never accrued decision spend and+// served decisions forever past its cap. Decisions now settle into the ledger+// directly, without a `requests` row that would double-count chat turns in+// the dashboard's request analytics.++const realFetch = globalThis.fetch;++function addKey(platform: string, monthlyRequestCap = 0): number {+ const raw = platform === 'cloudflare' ? 'acct123:cf-token' : `${platform}-test-key`;+ const { encrypted, iv, authTag } = encrypt(raw);+ 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 ANSWERS = { tier: { type: 'choice', choice: 'code', probabilities: { light: 0.02, code: 0.98 }, confidence: 0.96 } };+const REQUEST = {+ state: 'Write a Python function that merges two sorted lists.',+ questions: {+ tier: { type: 'choice' as const, instructions: 'Which tier should answer?', criteria: { light: 'chat', code: 'coding' } },+ },+};++const okResponse = () => new Response(JSON.stringify({+ success: true,+ result: { model: 'clef-flash', answers: ANSWERS, usage: { input_tokens: 219, output_tokens: 0 } },+}), { status: 200 });++describe('decision spend lands in the monthly ledger (#1158)', () => {+ beforeEach(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ seedDecisionModels();+ clearAllCooldowns(Number.MAX_SAFE_INTEGER);+ });+ afterEach(() => {+ globalThis.fetch = realFetch;+ vi.restoreAllMocks();+ });++ it('a served decision counts toward the monthly ledger without a requests row', async () => {+ const key = addKey('cloudflare');+ globalThis.fetch = vi.fn(async () => okResponse()) as unknown as typeof fetch;++ const out = await runDecision(REQUEST);+ expect(out.provider).toBe('cloudflare');++ // key_monthly_usage is what the caps and /v1/usage read.+ const usage = getMonthlyUsage(key);+ expect(usage.requests).toBe(1);+ expect(usage.tokens).toBeGreaterThan(0);+ // The decision stays out of the request analytics (decision_requests+ // already backs the Decisions page).+ const rows = getDb().prepare('SELECT COUNT(*) AS n FROM requests WHERE key_id = ?').get(key) as { n: number };+ expect(rows.n).toBe(0);+ });++ it('a failed attempt does NOT count toward usage', async () => {+ const key = addKey('cloudflare');+ globalThis.fetch = vi.fn(async () => new Response(JSON.stringify({ error: { message: 'boom' } }), { status: 500 })) as unknown as typeof fetch;++ await expect(runDecision(REQUEST)).rejects.toBeInstanceOf(DecisionError);++ const row = getDb().prepare('SELECT status FROM decision_requests WHERE key_id = ?').get(key) as any;+ expect(row).toMatchObject({ status: 'error' });+ expect(getMonthlyUsage(key)).toEqual({ requests: 0, tokens: 0 });+ });++ it('spend accumulates until the cap bites (end-to-end cap enforcement)', async () => {+ const key = addKey('cloudflare', 2);+ globalThis.fetch = vi.fn(async () => okResponse()) as unknown as typeof fetch;++ await runDecision(REQUEST);+ await runDecision(REQUEST);+ expect(getMonthlyUsage(key).requests).toBe(2);++ const err = await runDecision(REQUEST).catch(e => e) as DecisionError;+ expect(err.status).toBe(429);+ expect(err.code).toBe('quota_exceeded');+ });++ it('a key at its cap is skipped without touching upstream', async () => {+ const key = addKey('cloudflare', 1);+ spendRequests(key, 1);+ const fetch = vi.fn(async () => okResponse());+ globalThis.fetch = fetch as unknown as typeof fetch;++ const err = await runDecision(REQUEST).catch(e => e) as DecisionError;+ expect(err).toBeInstanceOf(DecisionError);+ expect(err.status).toBe(429);+ expect(err.code).toBe('quota_exceeded');+ expect(fetch).not.toHaveBeenCalled();+ });+});diff --git a/server/src/services/decision.ts b/server/src/services/decision.tsindex ec860015..d6e8630f 100644--- a/server/src/services/decision.ts+++ b/server/src/services/decision.ts@@ -5,7 +5,7 @@ import { parseRetryAfterMs, parseStatedRetryMs } from '../providers/base.js';import { RetryHintTracker } from '../lib/retry-hint.js';import { getClientContext } from '../lib/client-context.js';import { proxyFetch } from '../lib/proxy.js';-import { secondsUntilNextMonth } from './key-budget.js';+import { recordMonthlyUsage, secondsUntilNextMonth } from './key-budget.js';import { reserveProviderCredential, type ReservedProviderCredential } from './provider-credential.js';import { isOnCooldown, setCooldown } from './ratelimit.js';import { markKeyHealthyFromRequest } from './health.js';@@ -284,6 +284,19 @@ function logDecision(row: DecisionModelRow, keyId: number | null, status: 'ok' |} catch (e) {console.error('Failed to log decision request:', e);}+ // The per-key monthly caps (#1158) and GET /v1/usage read the+ // key_monthly_usage ledger. Chat, embeddings, media, rerank, moderation and+ // search settle into it through their `requests` rows; decisions log to+ // decision_requests, so a served decision settles its spend directly here.+ // Not a `requests` row: decisions fire every routing turn, and one there+ // would double every chat turn in the dashboard's request analytics.+ if (status === 'ok' && keyId != null) {+ try {+ recordMonthlyUsage(keyId, inputTokens);+ } catch (e) {+ console.error('Failed to settle decision spend:', e);+ }+ }}function coolDown(row: DecisionModelRow, keyId: number, e: DecisionError): void {diff --git a/server/src/services/key-budget.ts b/server/src/services/key-budget.tsindex 3b5854fb..6048ff6e 100644--- a/server/src/services/key-budget.ts+++ b/server/src/services/key-budget.ts@@ -84,6 +84,22 @@ export function getMonthlyUsage(keyId: number, now = Date.now()): MonthlyUsage {return { requests: Number(row?.requests ?? 0), tokens: Number(row?.tokens ?? 0) };}+/**+ * Settle one successful request straight into the ledger, for surfaces that+ * log to their own table instead of `requests` (decisions). Same arithmetic+ * as the requests_key_monthly_usage trigger, so caps and /v1/usage see it+ * without the request also counting in the dashboard's request analytics.+ */+export function recordMonthlyUsage(keyId: number, tokens: number, now = Date.now()): void {+ getDb().prepare(`+ INSERT INTO key_monthly_usage (key_id, month, requests, tokens)+ VALUES (?, ?, 1, ?)+ ON CONFLICT(key_id, month) DO UPDATE SET+ requests = requests + 1,+ tokens = tokens + excluded.tokens+ `).run(keyId, new Date(now).toISOString().slice(0, 7), Math.max(0, Math.floor(tokens)));+}+/*** Check a key against its monthly caps, taking the current month's successful* usage plus the tokens THIS request would add. Returns allowed when both caps