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
feat(budget): soft budget alerts at 80%/100% of a key's monthly caps (#1158) (#1665)
tashdroid6fbad9a4ddf6
diff --git a/.env.example b/.env.exampleindex 4319dc04..99e43494 100644--- a/.env.example+++ b/.env.example@@ -162,6 +162,13 @@ PORT=3001# which costs quota where a provider's key check is metered. Read at startup.# HEALTH_CHECK_INTERVAL_MS=300000+# Optional destination for soft budget alerts: when a provider key crosses 80%+# or 100% of its monthly request/token cap, the alert is POSTed to this URL as+# JSON (type: freellmapi.key_budget_threshold) in addition to the Logs page+# event. http(s) only; delivery is fire-and-forget with a 10s timeout. Works+# with Slack/Discord via a workflow webhook. Read when an alert fires.+# BUDGET_ALERT_WEBHOOK_URL=https://hooks.example.test/abc+# Opt-in background model probes (#1438): every 30 minutes, send a tiny# "Reply with OK" chat to up to MODEL_PROBE_MAX_PER_PASS (default 3) model+key# pairs and record whether each model answers. Off by default because everydiff --git a/docs/en/api/01-rest-api.md b/docs/en/api/01-rest-api.mdindex 8de6db2a..81453927 100644--- a/docs/en/api/01-rest-api.md+++ b/docs/en/api/01-rest-api.md@@ -510,6 +510,16 @@ pointing to the next UTC month. OpenAI-compatible endpoints also returnerror format. Fusion subcalls obey the caps but retain Fusion's aggregate errorformat. If another key has capacity, normal fallback can use it.+Crossing 80% and again 100% of either cap logs a soft budget alert — a+structured `key_budget_threshold` event in the dashboard's Logs page (the same+viewer as provider logs), naming the key, the cap kind, the usage and the reset+time. Each threshold fires once per key per UTC month, so a key cannot flood the+log. This mirrors LiteLLM's budget alerts and OpenRouter's per-key spend-limit+alert: the warning arrives while requests still flow, before the hard `429`.+Set `BUDGET_ALERT_WEBHOOK_URL` to also POST each alert as JSON+(`type: freellmapi.key_budget_threshold`) to a webhook, such as a Slack or+Discord workflow.+Embeddings additionally relay the upstream providers' own back-off. A providerthat answers `429` is simply skipped for the next one in the family; only whenevery provider in the family was rate limited and each stated a `Retry-After`diff --git a/server/src/__tests__/services/budget-alerts.test.ts b/server/src/__tests__/services/budget-alerts.test.tsnew file mode 100644index 00000000..7fdd16fb--- /dev/null+++ b/server/src/__tests__/services/budget-alerts.test.ts@@ -0,0 +1,146 @@+import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';+import { initDb, getDb } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { logRequest } from '../../lib/request-log.js';+import { ringSnapshot, clearLogs } from '../../lib/server-logs.js';+import { setMonthlyBudgetCaps } from '../../services/key-budget.js';+import {+ budgetAlertWebhookUrl,+ budgetThresholdCrossings,+ budgetWebhookPayload,+ firedBudgetAlerts,+ noteBudgetAlerts,+} from '../../services/budget-alerts.js';++// Soft budget alerts: 80% and 100% of a key's monthly request/token caps log+// a `key_budget_threshold` event exactly once per threshold per UTC month,+// mirroring LiteLLM budget_alerts / OpenRouter's per-key spend-limit alert.++let keyId = 0;++function insertKey() {+ const { encrypted, iv, authTag } = encrypt('sk-test');+ const result = getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled, monthly_request_cap, monthly_token_cap)+ VALUES ('groq', 'alert-test', ?, ?, ?, 'healthy', 1, 0, 0)+ `).run(encrypted, iv, authTag);+ keyId = Number(result.lastInsertRowid);+}++function alertEntries() {+ return ringSnapshot().filter(e => e.event === 'key_budget_threshold');+}++describe('budgetThresholdCrossings (pure)', () => {+ it('never crosses for unlimited caps', () => {+ expect(budgetThresholdCrossings({ requestCap: 0, tokenCap: 0 }, { requests: 10_000, tokens: 10_000_000 })).toEqual([]);+ });+ it('crosses 80% then 100% as usage grows', () => {+ const caps = { requestCap: 100, tokenCap: 0 };+ expect(budgetThresholdCrossings(caps, { requests: 79, tokens: 0 }).map(c => c.threshold)).toEqual([]);+ expect(budgetThresholdCrossings(caps, { requests: 80, tokens: 0 }).map(c => c.threshold)).toEqual([0.8]);+ const at = budgetThresholdCrossings(caps, { requests: 100, tokens: 0 });+ expect(at.map(c => c.threshold)).toEqual([0.8, 1.0]);+ expect(at.every(c => c.kind === 'requests')).toBe(true);+ });+ it('evaluates request and token caps independently', () => {+ const crossings = budgetThresholdCrossings(+ { requestCap: 1000, tokenCap: 100 },+ { requests: 10, tokens: 90 },+ );+ expect(crossings).toHaveLength(1);+ expect(crossings[0]).toMatchObject({ kind: 'tokens', threshold: 0.8, used: 90, cap: 100 });+ });+});++describe('budget alerts (end to end through the request log)', () => {+ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ });++ beforeEach(() => {+ clearLogs();+ getDb().prepare('DELETE FROM api_keys').run();+ getDb().prepare('DELETE FROM requests').run();+ getDb().prepare('DELETE FROM key_monthly_usage').run();+ getDb().prepare("DELETE FROM settings WHERE key LIKE 'budget_alerts_fired%'").run();+ insertKey();+ });++ it('logs nothing below 80% and once at/above 80%', () => {+ setMonthlyBudgetCaps(keyId, { requestCap: 10, tokenCap: 0 });+ for (let i = 0; i < 7; i++) logRequest('groq', 'llama', keyId, 'success', 10, 0, 5, null);+ expect(alertEntries()).toHaveLength(0);++ logRequest('groq', 'llama', keyId, 'success', 10, 0, 5, null); // 8th → 80%+ const first = alertEntries();+ expect(first).toHaveLength(1);+ expect(first[0].message).toMatch(/80% of its monthly requests cap \(8\/10\)/);+ expect(firedBudgetAlerts(keyId)).toEqual(['requests:0.8']);++ logRequest('groq', 'llama', keyId, 'success', 10, 0, 5, null); // 9th → still 80% band+ expect(alertEntries()).toHaveLength(1); // deduped+ });++ it('logs a hard "AT CAP" warn once at 100% and keeps the 80% alert distinct', () => {+ setMonthlyBudgetCaps(keyId, { requestCap: 5, tokenCap: 0 });+ for (let i = 0; i < 5; i++) logRequest('groq', 'llama', keyId, 'success', 10, 0, 5, null);+ const entries = alertEntries();+ expect(entries).toHaveLength(2); // 80% + 100%+ const hard = entries.find(e => e.message.includes('KEY AT CAP'));+ expect(hard).toBeDefined();+ expect(hard!.level).toBe('warn');+ expect(hard!.message).toMatch(/100% of its monthly requests cap \(5\/5\)/);+ expect(firedBudgetAlerts(keyId).sort()).toEqual(['requests:0.8', 'requests:1']);++ logRequest('groq', 'llama', keyId, 'success', 10, 0, 5, null); // over cap: no new alerts+ expect(alertEntries()).toHaveLength(2);+ });++ it('meters token caps from the same ledger the block enforces', () => {+ setMonthlyBudgetCaps(keyId, { requestCap: 0, tokenCap: 1000 });+ logRequest('groq', 'llama', keyId, 'success', 850, 0, 5, null);+ const entries = alertEntries();+ expect(entries).toHaveLength(1);+ expect(entries[0].message).toMatch(/85% of its monthly tokens cap \(850\/1000\)/);+ });++ it('stays silent for uncapped keys (the hot path pays one indexed read)', () => {+ logRequest('groq', 'llama', keyId, 'success', 1_000_000, 0, 5, null);+ expect(alertEntries()).toHaveLength(0);+ });++ it('noteBudgetAlerts never throws on a bogus key id', () => {+ expect(() => noteBudgetAlerts(999_999)).not.toThrow();+ });+});++describe('budget alert webhook', () => {+ const saved = process.env.BUDGET_ALERT_WEBHOOK_URL;+ afterEach(() => {+ if (saved === undefined) delete process.env.BUDGET_ALERT_WEBHOOK_URL;+ else process.env.BUDGET_ALERT_WEBHOOK_URL = saved;+ });++ it('accepts only http(s) URLs', () => {+ delete process.env.BUDGET_ALERT_WEBHOOK_URL;+ expect(budgetAlertWebhookUrl()).toBeNull();+ process.env.BUDGET_ALERT_WEBHOOK_URL = 'file:///etc/passwd';+ expect(budgetAlertWebhookUrl()).toBeNull();+ process.env.BUDGET_ALERT_WEBHOOK_URL = ' https://hooks.example.test/abc ';+ expect(budgetAlertWebhookUrl()).toBe('https://hooks.example.test/abc');+ });++ it('payload marks the hard threshold as blocked', () => {+ const payload = budgetWebhookPayload(3, 'prod', 'groq', [+ { threshold: 0.8, kind: 'requests', used: 80, cap: 100 },+ { threshold: 1.0, kind: 'tokens', used: 1000, cap: 1000 },+ ]);+ expect(payload.type).toBe('freellmapi.key_budget_threshold');+ expect(payload.thresholds).toEqual([+ { kind: 'requests', threshold: 0.8, used: 80, cap: 100, blocked: false },+ { kind: 'tokens', threshold: 1, used: 1000, cap: 1000, blocked: true },+ ]);+ });+});diff --git a/server/src/__tests__/services/decision-spend-ledger.test.ts b/server/src/__tests__/services/decision-spend-ledger.test.tsindex 50e980e9..b72d037a 100644--- a/server/src/__tests__/services/decision-spend-ledger.test.ts+++ b/server/src/__tests__/services/decision-spend-ledger.test.ts@@ -5,6 +5,7 @@ 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';+import { ringSnapshot, clearLogs } from '../../lib/server-logs.js';// POST /v1/decisions spends real provider quota on every routing turn, but// logDecision only wrote decision_requests. The per-key monthly caps (#1158)@@ -98,6 +99,19 @@ describe('decision spend lands in the monthly ledger (#1158)', () => {expect(err.code).toBe('quota_exceeded');});+ it('a decision that crosses 80% of the cap logs the budget alert', async () => {+ clearLogs();+ const key = addKey('cloudflare', 5);+ spendRequests(key, 3);+ globalThis.fetch = vi.fn(async () => okResponse()) as unknown as typeof fetch;++ await runDecision(REQUEST);++ const alerts = ringSnapshot().filter(e => e.event === 'key_budget_threshold');+ expect(alerts).toHaveLength(1);+ expect(alerts[0]!.message).toContain('80% of its monthly requests cap (4/5)');+ });+it('a key at its cap is skipped without touching upstream', async () => {const key = addKey('cloudflare', 1);spendRequests(key, 1);diff --git a/server/src/lib/request-log.ts b/server/src/lib/request-log.tsindex 029db673..d7055549 100644--- a/server/src/lib/request-log.ts+++ b/server/src/lib/request-log.ts@@ -1,5 +1,6 @@import { getDb } from '../db/index.js';import { pruneRequestAnalytics } from '../services/request-retention.js';+import { noteBudgetAlerts } from '../services/budget-alerts.js';import { getClientContext } from './client-context.js';import { noteRequestRowId, type RequestTrace } from './attempt-trace.js';@@ -154,6 +155,11 @@ export function logRequest(tx();pruneRequestAnalytics({ db });++ // Soft budget alerts (#1158 follow-on): after the ledger trigger committed,+ // compare this key's month usage to its caps and log a threshold event+ // (80%/100%, once each per month). Never throws.+ if (status === 'success' && keyId != null) noteBudgetAlerts(keyId);} catch (e) {console.error('Failed to log request:', e);}diff --git a/server/src/services/budget-alerts.ts b/server/src/services/budget-alerts.tsnew file mode 100644index 00000000..70594e09--- /dev/null+++ b/server/src/services/budget-alerts.ts@@ -0,0 +1,208 @@+/**+ * Soft budget alerts for per-key monthly caps (#1158).+ *+ * A cap that only speaks at 100% is a hard stop with no warning: an agent+ * fleet just starts seeing 429s and the operator learns about it from the+ * outage. Every comparable router grew an early-warning layer on top of its+ * caps — LiteLLM's budget_alerts / soft-budget notifications and OpenRouter's+ * per-key spend-limit alert (80% then 100% of the limit by default) are the+ * reference designs. This is the same shape on our own ledger:+ *+ * - Thresholds: 80% and 100% of monthly_request_cap and monthly_token_cap,+ * checked against the durable key_monthly_usage ledger the caps enforce+ * against, so the alert and the block can never disagree.+ * - Dedup: each (key, month, threshold, cap) fires exactly once. State lives+ * in the settings table keyed by month, so a new UTC month re-arms the+ * alerts for free and no pruning job is needed (one small row per capped+ * key per month).+ * - Destinations: a structured event in the dashboard's server-log store+ * (Logs page, event=key_budget_threshold), which the operator already+ * watches, plus an optional BUDGET_ALERT_WEBHOOK_URL POST (below).+ *+ * The check runs wherever a success settles into the ledger (the request-log+ * commit hook, the embedding/media/moderation/rerank/search loggers and the+ * decision logger), so it sees every served surface once per request. It is deliberately cheap on the hot path:+ * one indexed cap read, and the usage read + state write only happen once a+ * key is actually capped; the settings dedup read only after a threshold is+ * already crossed.+ */+import { getDb, getSetting, setSetting } from '../db/index.js';+import { providerLog } from '../lib/server-logs.js';+import { getMonthlyBudgetCaps, getMonthlyUsage, nextMonthResetAt } from './key-budget.js';++/** Fraction-of-cap points that produce an alert. 1.0 is the hard block; the+ * whole point is that 0.8 fires while there is still room to act. */+export const BUDGET_ALERT_THRESHOLDS = [0.8, 1.0] as const;+export type BudgetAlertThreshold = (typeof BUDGET_ALERT_THRESHOLDS)[number];++export type BudgetCapKind = 'requests' | 'tokens';++export interface BudgetCrossing {+ threshold: BudgetAlertThreshold;+ kind: BudgetCapKind;+ /** Ledger usage at check time (requests or tokens). */+ used: number;+ /** The configured cap. */+ cap: number;+}++/**+ * Pure crossing decision: given a key's caps and current usage, which alert+ * thresholds are at or over? A cap of 0 means unlimited and never crosses.+ * Kept pure so the arithmetic is testable without a DB.+ */+export function budgetThresholdCrossings(+ caps: { requestCap: number; tokenCap: number },+ usage: { requests: number; tokens: number },+): BudgetCrossing[] {+ const crossings: BudgetCrossing[] = [];+ const consider = (kind: BudgetCapKind, used: number, cap: number) => {+ if (cap <= 0) return;+ for (const threshold of BUDGET_ALERT_THRESHOLDS) {+ if (used >= threshold * cap) crossings.push({ threshold, kind, used, cap });+ }+ };+ consider('requests', usage.requests, caps.requestCap);+ consider('tokens', usage.tokens, caps.tokenCap);+ return crossings;+}++function stateKey(keyId: number, month: string): string {+ return `budget_alerts_fired:${keyId}:${month}`;+}++function firedList(raw: string | undefined): string[] {+ if (!raw) return [];+ try {+ const parsed = JSON.parse(raw);+ return Array.isArray(parsed) ? parsed.filter((v): v is string => typeof v === 'string') : [];+ } catch {+ return [];+ }+}++function pct(used: number, cap: number): string {+ return `${Math.floor((used / cap) * 100)}%`;+}++/**+ * Check one key against its alert thresholds and emit any alert not already+ * fired this month. Never throws: budget alerting must not break the request+ * path it observes.+ */+export function noteBudgetAlerts(keyId: number, now = Date.now()): void {+ try {+ const caps = getMonthlyBudgetCaps(keyId);+ if (caps.requestCap <= 0 && caps.tokenCap <= 0) return;++ const usage = getMonthlyUsage(keyId, now);+ const crossings = budgetThresholdCrossings(caps, usage);+ if (crossings.length === 0) return;++ const month = new Date(now).toISOString().slice(0, 7);+ const skey = stateKey(keyId, month);+ const fired = firedList(getSetting(skey));+ const fresh = crossings.filter(c => !fired.includes(`${c.kind}:${c.threshold}`));+ if (fresh.length === 0) return;++ const row = getDb()+ .prepare('SELECT label, platform FROM api_keys WHERE id = ?')+ .get(keyId) as { label: string | null; platform: string } | undefined;+ const label = row?.label ?? `key ${keyId}`;++ for (const c of fresh) {+ const hard = c.threshold >= 1;+ providerLog(+ hard ? 'warn' : 'info',+ `[budget] ${hard ? 'KEY AT CAP' : 'budget alert'}: key ${keyId} '${label}' (${row?.platform ?? '?'}) ` ++ `reached ${pct(c.used, c.cap)} of its monthly ${c.kind} cap (${c.used}/${c.cap}); ` ++ `requests ${hard ? 'are now rejected' : 'still flow'} until the reset at ${nextMonthResetAt(now)}.`,+ { event: 'key_budget_threshold', provider: row?.platform ?? undefined },+ );+ }+ setSetting(skey, JSON.stringify([...fired, ...fresh.map(c => `${c.kind}:${c.threshold}`)]));+ dispatchBudgetWebhook(keyId, label, row?.platform ?? null, fresh, now);+ } catch {+ // Alerting is observational; a failure here must never fail a request.+ }+}++// ── Webhook destination ────────────────────────────────────────────────────+//+// BUDGET_ALERT_WEBHOOK_URL (optional, read each time an alert fires): a POST+// target for the same alerts the Logs page shows — the LiteLLM+// `budget_alerts` webhook shape (Slack/Discord work via a workflow). One+// JSON body per firing batch; fire-and-forget with a short timeout; failures+// are logged once and swallowed. The URL is operator configuration, not+// caller input, so no SSRF surface is added beyond what the proxy already+// trusts (upstream provider endpoints).++export function budgetAlertWebhookUrl(): string | null {+ const raw = process.env.BUDGET_ALERT_WEBHOOK_URL?.trim();+ if (!raw) return null;+ try {+ const u = new URL(raw);+ return u.protocol === 'https:' || u.protocol === 'http:' ? raw : null;+ } catch {+ return null;+ }+}++/** Build the webhook payload for one firing batch. Pure so it is testable. */+export function budgetWebhookPayload(+ keyId: number,+ label: string,+ platform: string | null,+ crossings: BudgetCrossing[],+ now = Date.now(),+) {+ return {+ type: 'freellmapi.key_budget_threshold',+ key_id: keyId,+ label,+ platform,+ month: new Date(now).toISOString().slice(0, 7),+ resets_at: nextMonthResetAt(now),+ thresholds: crossings.map(c => ({+ kind: c.kind,+ threshold: c.threshold,+ used: c.used,+ cap: c.cap,+ blocked: c.threshold >= 1,+ })),+ };+}++function dispatchBudgetWebhook(+ keyId: number,+ label: string,+ platform: string | null,+ crossings: BudgetCrossing[],+ now: number,+): void {+ const url = budgetAlertWebhookUrl();+ if (!url) return;+ // proxyFetch honours the same outbound proxy the rest of the server uses;+ // import lazily so unit tests without a DB/proxy config stay cheap.+ void import('../lib/proxy.js')+ .then(({ proxyFetch }) =>+ proxyFetch(url, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(budgetWebhookPayload(keyId, label, platform, crossings, now)),+ signal: AbortSignal.timeout(10_000),+ }),+ )+ .then(res => {+ if (!res.ok) providerLog('warn', `[budget] alert webhook answered ${res.status}`, { event: 'key_budget_webhook' });+ })+ .catch(() => {+ providerLog('warn', '[budget] alert webhook delivery failed', { event: 'key_budget_webhook' });+ });+}++/** Test/admin helper: alerts fired for a key in a month (for assertions). */+export function firedBudgetAlerts(keyId: number, now = Date.now()): string[] {+ const month = new Date(now).toISOString().slice(0, 7);+ return firedList(getSetting(stateKey(keyId, month)));+}diff --git a/server/src/services/decision.ts b/server/src/services/decision.tsindex d6e8630f..e593e980 100644--- a/server/src/services/decision.ts+++ b/server/src/services/decision.ts@@ -6,6 +6,7 @@ import { RetryHintTracker } from '../lib/retry-hint.js';import { getClientContext } from '../lib/client-context.js';import { proxyFetch } from '../lib/proxy.js';import { recordMonthlyUsage, secondsUntilNextMonth } from './key-budget.js';+import { noteBudgetAlerts } from './budget-alerts.js';import { reserveProviderCredential, type ReservedProviderCredential } from './provider-credential.js';import { isOnCooldown, setCooldown } from './ratelimit.js';import { markKeyHealthyFromRequest } from './health.js';@@ -293,6 +294,7 @@ function logDecision(row: DecisionModelRow, keyId: number | null, status: 'ok' |if (status === 'ok' && keyId != null) {try {recordMonthlyUsage(keyId, inputTokens);+ noteBudgetAlerts(keyId);} catch (e) {console.error('Failed to settle decision spend:', e);}diff --git a/server/src/services/embeddings.ts b/server/src/services/embeddings.tsindex d43799dc..ff7cb674 100644--- a/server/src/services/embeddings.ts+++ b/server/src/services/embeddings.ts@@ -9,6 +9,7 @@// cross-provider redundancy for free.import { getDb, getSetting } from '../db/index.js';import { secondsUntilNextMonth } from './key-budget.js';+import { noteBudgetAlerts } from './budget-alerts.js';import { parseRetryAfterMs } from '../providers/base.js';import { RetryHintTracker, retryAfterSeconds } from '../lib/retry-hint.js';import { getClientContext } from '../lib/client-context.js';@@ -359,6 +360,9 @@ function logEmbeddingRequest(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, ?, ?, 'embedding', ?, ?, ?)`).run(row.platform, row.model_id, keyId, status, inputTokens, latencyMs, error, client.ip, client.userAgent, client.agent);+ // Soft budget alert (#1158 follow-on): the ledger trigger fired with this+ // row, so compare the caps once. No-op for uncapped keys.+ if (status === 'success' && keyId != null) noteBudgetAlerts(keyId);} catch (e) {console.error('Failed to log embedding request:', e);}diff --git a/server/src/services/media.ts b/server/src/services/media.tsindex a032fe0a..2cf2a303 100644--- a/server/src/services/media.ts+++ b/server/src/services/media.ts@@ -11,6 +11,7 @@ import { getDb } from '../db/index.js';import { parseRetryAfterMs } from '../providers/base.js';import { RetryHintTracker } from '../lib/retry-hint.js';import { secondsUntilNextMonth } from './key-budget.js';+import { noteBudgetAlerts } from './budget-alerts.js';import { getClientContext } from '../lib/client-context.js';import { reserveProviderCredential } from './provider-credential.js';import { proxyFetch } from '../lib/proxy.js';@@ -823,6 +824,8 @@ function logMedia(row: Pick<MediaModelRow, 'platform' | 'model_id' | 'modality'>// 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);+ // Soft budget alert (#1158 follow-on), same hook as the chat path.+ if (status === 'success' && keyId != null) noteBudgetAlerts(keyId);} catch (e) {console.error('Failed to log media request:', e);}diff --git a/server/src/services/moderation.ts b/server/src/services/moderation.tsindex 400a0f71..dc1afb59 100644--- a/server/src/services/moderation.ts+++ b/server/src/services/moderation.ts@@ -16,6 +16,7 @@ import { getClientContext } from '../lib/client-context.js';import { decrypt } from '../lib/crypto.js';import { proxyFetch } from '../lib/proxy.js';import { checkMonthlyBudget, secondsUntilNextMonth } from './key-budget.js';+import { noteBudgetAlerts } from './budget-alerts.js';import { markKeyHealthyFromRequest } from './health.js';/* ------------------------------------------------------------------ */@@ -161,6 +162,9 @@ function logModerationRequest(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, ?, ?, 'moderation', ?, ?, ?)`).run(row.platform, row.modelId, row.keyId, status, latencyMs, error, client.ip, client.userAgent, client.agent);+ // Soft budget alert (#1158 follow-on): the ledger trigger fired with this+ // row, so compare the caps once. No-op for uncapped keys.+ if (status === 'success' && row.keyId != null) noteBudgetAlerts(row.keyId);} catch (e) {console.error('Failed to log moderation request:', e);}diff --git a/server/src/services/rerank.ts b/server/src/services/rerank.tsindex fff755d0..cf4018f5 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 { checkMonthlyBudget, reserveMonthlyBudget, secondsUntilNextMonth } from './key-budget.js';+import { noteBudgetAlerts } from './budget-alerts.js';import { markKeyHealthyFromRequest } from './health.js';import { getClientContext } from '../lib/client-context.js';@@ -74,6 +75,9 @@ function logRerankRequest(cand: { platform: string }, keyId: number, modelId: stINSERT 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, ?, ?, 'rerank', ?, ?, ?)`).run(cand.platform, modelId, keyId, status, inputTokens, latencyMs, error, client.ip, client.userAgent, client.agent);+ // Soft budget alert (#1158 follow-on): the ledger trigger fired with this+ // row, so compare the caps once. No-op for uncapped keys.+ if (status === 'success' && keyId != null) noteBudgetAlerts(keyId);} catch (e) {console.error('Failed to log rerank request:', e);}diff --git a/server/src/services/search.ts b/server/src/services/search.tsindex 5c3a971f..1591c7d7 100644--- a/server/src/services/search.ts+++ b/server/src/services/search.ts@@ -14,6 +14,7 @@ import { KEENABLE_APP_TITLE, KEENABLE_BASE_URL } from '../providers/keenable.js'import { isAnonymousCredential } from '../lib/credential.js';import { randomUUID } from 'node:crypto';import { secondsUntilNextMonth } from './key-budget.js';+import { noteBudgetAlerts } from './budget-alerts.js';import { reserveProviderCredential, type ReservedProviderCredential } from './provider-credential.js';import { isOnCooldown, setCooldown } from './ratelimit.js';import { markKeyHealthyFromRequest } from './health.js';@@ -460,6 +461,9 @@ function logSearch(row: SearchEngineRow, keyId: number | null, status: 'ok' | 'eINSERT 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);+ // Soft budget alert (#1158 follow-on): the ledger trigger fired with this+ // row, so compare the caps once. No-op for uncapped keys.+ if (status === 'ok' && keyId != null) noteBudgetAlerts(keyId);} catch (e) {console.error('Failed to log search request to requests table:', e);}