trouteai 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/.build/next/BUILD_ID +1 -1
  2. package/.build/next/build-manifest.json +3 -3
  3. package/.build/next/fallback-build-manifest.json +3 -3
  4. package/.build/next/prerender-manifest.json +3 -3
  5. package/.build/next/server/app/(dashboard)/dashboard/activity/page_client-reference-manifest.js +1 -1
  6. package/.build/next/server/app/(dashboard)/dashboard/analytics/combo-health/page_client-reference-manifest.js +1 -1
  7. package/.build/next/server/app/(dashboard)/dashboard/analytics/page_client-reference-manifest.js +1 -1
  8. package/.build/next/server/app/(dashboard)/dashboard/analytics/utilization/page_client-reference-manifest.js +1 -1
  9. package/.build/next/server/app/(dashboard)/dashboard/api-manager/page_client-reference-manifest.js +1 -1
  10. package/.build/next/server/app/(dashboard)/dashboard/audit/page_client-reference-manifest.js +1 -1
  11. package/.build/next/server/app/(dashboard)/dashboard/auto-combo/page_client-reference-manifest.js +1 -1
  12. package/.build/next/server/app/(dashboard)/dashboard/cache/page_client-reference-manifest.js +1 -1
  13. package/.build/next/server/app/(dashboard)/dashboard/combos/[id]/page_client-reference-manifest.js +1 -1
  14. package/.build/next/server/app/(dashboard)/dashboard/combos/live/page_client-reference-manifest.js +1 -1
  15. package/.build/next/server/app/(dashboard)/dashboard/combos/page_client-reference-manifest.js +1 -1
  16. package/.build/next/server/app/(dashboard)/dashboard/combos/playground/page_client-reference-manifest.js +1 -1
  17. package/.build/next/server/app/(dashboard)/dashboard/costs/budget/page_client-reference-manifest.js +1 -1
  18. package/.build/next/server/app/(dashboard)/dashboard/costs/page_client-reference-manifest.js +1 -1
  19. package/.build/next/server/app/(dashboard)/dashboard/costs/pricing/page_client-reference-manifest.js +1 -1
  20. package/.build/next/server/app/(dashboard)/dashboard/costs/quota-share/page_client-reference-manifest.js +1 -1
  21. package/.build/next/server/app/(dashboard)/dashboard/endpoint/page_client-reference-manifest.js +1 -1
  22. package/.build/next/server/app/(dashboard)/dashboard/health/page_client-reference-manifest.js +1 -1
  23. package/.build/next/server/app/(dashboard)/dashboard/limits/page_client-reference-manifest.js +1 -1
  24. package/.build/next/server/app/(dashboard)/dashboard/logs/activity/page_client-reference-manifest.js +1 -1
  25. package/.build/next/server/app/(dashboard)/dashboard/logs/console/page_client-reference-manifest.js +1 -1
  26. package/.build/next/server/app/(dashboard)/dashboard/logs/page_client-reference-manifest.js +1 -1
  27. package/.build/next/server/app/(dashboard)/dashboard/logs/proxy/page_client-reference-manifest.js +1 -1
  28. package/.build/next/server/app/(dashboard)/dashboard/logs/timeline/page_client-reference-manifest.js +1 -1
  29. package/.build/next/server/app/(dashboard)/dashboard/media-providers/[kind]/[id]/page_client-reference-manifest.js +1 -1
  30. package/.build/next/server/app/(dashboard)/dashboard/media-providers/[kind]/page_client-reference-manifest.js +1 -1
  31. package/.build/next/server/app/(dashboard)/dashboard/media-providers/page_client-reference-manifest.js +1 -1
  32. package/.build/next/server/app/(dashboard)/dashboard/more/page_client-reference-manifest.js +1 -1
  33. package/.build/next/server/app/(dashboard)/dashboard/onboarding/page_client-reference-manifest.js +1 -1
  34. package/.build/next/server/app/(dashboard)/dashboard/page_client-reference-manifest.js +1 -1
  35. package/.build/next/server/app/(dashboard)/dashboard/playground/page_client-reference-manifest.js +1 -1
  36. package/.build/next/server/app/(dashboard)/dashboard/provider-stats/page_client-reference-manifest.js +1 -1
  37. package/.build/next/server/app/(dashboard)/dashboard/providers/[id]/page_client-reference-manifest.js +1 -1
  38. package/.build/next/server/app/(dashboard)/dashboard/providers/new/page_client-reference-manifest.js +1 -1
  39. package/.build/next/server/app/(dashboard)/dashboard/providers/page_client-reference-manifest.js +1 -1
  40. package/.build/next/server/app/(dashboard)/dashboard/quota/page_client-reference-manifest.js +1 -1
  41. package/.build/next/server/app/(dashboard)/dashboard/runtime/page_client-reference-manifest.js +1 -1
  42. package/.build/next/server/app/(dashboard)/dashboard/settings/advanced/page_client-reference-manifest.js +1 -1
  43. package/.build/next/server/app/(dashboard)/dashboard/settings/ai/page_client-reference-manifest.js +1 -1
  44. package/.build/next/server/app/(dashboard)/dashboard/settings/appearance/page_client-reference-manifest.js +1 -1
  45. package/.build/next/server/app/(dashboard)/dashboard/settings/cache/page_client-reference-manifest.js +1 -1
  46. package/.build/next/server/app/(dashboard)/dashboard/settings/feature-flags/page_client-reference-manifest.js +1 -1
  47. package/.build/next/server/app/(dashboard)/dashboard/settings/general/page_client-reference-manifest.js +1 -1
  48. package/.build/next/server/app/(dashboard)/dashboard/settings/page_client-reference-manifest.js +1 -1
  49. package/.build/next/server/app/(dashboard)/dashboard/settings/pricing/page_client-reference-manifest.js +1 -1
  50. package/.build/next/server/app/(dashboard)/dashboard/settings/resilience/page_client-reference-manifest.js +1 -1
  51. package/.build/next/server/app/(dashboard)/dashboard/settings/routing/page_client-reference-manifest.js +1 -1
  52. package/.build/next/server/app/(dashboard)/dashboard/settings/security/page_client-reference-manifest.js +1 -1
  53. package/.build/next/server/app/(dashboard)/dashboard/settings/sidebar/page_client-reference-manifest.js +1 -1
  54. package/.build/next/server/app/(dashboard)/dashboard/system/page_client-reference-manifest.js +1 -1
  55. package/.build/next/server/app/(dashboard)/dashboard/system/proxy/page_client-reference-manifest.js +1 -1
  56. package/.build/next/server/app/(dashboard)/dashboard/usage/page_client-reference-manifest.js +1 -1
  57. package/.build/next/server/app/(dashboard)/home/page_client-reference-manifest.js +1 -1
  58. package/.build/next/server/app/400/page_client-reference-manifest.js +1 -1
  59. package/.build/next/server/app/401/page_client-reference-manifest.js +1 -1
  60. package/.build/next/server/app/403/page_client-reference-manifest.js +1 -1
  61. package/.build/next/server/app/408/page_client-reference-manifest.js +1 -1
  62. package/.build/next/server/app/429/page_client-reference-manifest.js +1 -1
  63. package/.build/next/server/app/500/page_client-reference-manifest.js +1 -1
  64. package/.build/next/server/app/502/page_client-reference-manifest.js +1 -1
  65. package/.build/next/server/app/503/page_client-reference-manifest.js +1 -1
  66. package/.build/next/server/app/_global-error.html +1 -1
  67. package/.build/next/server/app/_global-error.rsc +1 -1
  68. package/.build/next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  69. package/.build/next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  70. package/.build/next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  71. package/.build/next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  72. package/.build/next/server/app/auth/callback/page_client-reference-manifest.js +1 -1
  73. package/.build/next/server/app/callback/page_client-reference-manifest.js +1 -1
  74. package/.build/next/server/app/connect/codex/[token]/page_client-reference-manifest.js +1 -1
  75. package/.build/next/server/app/forbidden/page_client-reference-manifest.js +1 -1
  76. package/.build/next/server/app/forgot-password/page_client-reference-manifest.js +1 -1
  77. package/.build/next/server/app/login/page_client-reference-manifest.js +1 -1
  78. package/.build/next/server/app/maintenance/page_client-reference-manifest.js +1 -1
  79. package/.build/next/server/app/offline/page_client-reference-manifest.js +1 -1
  80. package/.build/next/server/app/page_client-reference-manifest.js +1 -1
  81. package/.build/next/server/chunks/[root-of-the-server]__1tjo4bqh377hk._.js +1 -1
  82. package/.build/next/server/chunks/_03o-fzwa-kvl7._.js +1 -1
  83. package/.build/next/server/chunks/_11hbt4c_vm6y3._.js +4 -4
  84. package/.build/next/server/chunks/_11hiw0cib9wo0._.js +4 -4
  85. package/.build/next/server/chunks/_1a403tptlxihn._.js +4 -4
  86. package/.build/next/server/chunks/_1po50cfv-3hj5._.js +4 -4
  87. package/.build/next/server/chunks/open-sse_services_tokenLimitCounter_ts_0emf9-_8k5yyi._.js +6 -6
  88. package/.build/next/server/chunks/open-sse_services_tokenLimitCounter_ts_1q5py6p7qq4tu._.js +6 -6
  89. package/.build/next/server/chunks/src_064vs8lffx0-_._.js +1 -1
  90. package/.build/next/server/chunks/src_0iy-rc7g3glpq._.js +1 -1
  91. package/.build/next/server/chunks/src_0jsr5vm5qt_kk._.js +1 -1
  92. package/.build/next/server/chunks/src_0y4bmsr2hv9j5._.js +1 -1
  93. package/.build/next/server/chunks/src_10n1nyrglck1k._.js +1 -1
  94. package/.build/next/server/chunks/src_1i8b9-47vidnt._.js +1 -1
  95. package/.build/next/server/chunks/src_1o27utniltpds._.js +1 -1
  96. package/.build/next/server/chunks/src_1o2lwcb4hqni1._.js +8 -8
  97. package/.build/next/server/chunks/src_1q9w1tlfhqoii._.js +1 -1
  98. package/.build/next/server/chunks/src_1rn4cjxtp_6u7._.js +1 -1
  99. package/.build/next/server/chunks/src_1u700kbcxsmm_._.js +1 -1
  100. package/.build/next/server/chunks/src_lib_db_adapters_driverFactory_ts_0155orwyetkch._.js +1 -1
  101. package/.build/next/server/chunks/src_lib_db_adapters_driverFactory_ts_0f06i971sgzty._.js +1 -1
  102. package/.build/next/server/chunks/src_lib_db_adapters_driverFactory_ts_0zrsxgp-znp4w._.js +1 -1
  103. package/.build/next/server/chunks/src_lib_usage_01bz69aaadtw-._.js +7 -6
  104. package/.build/next/server/chunks/src_lib_usage_1u13rm3b-466-._.js +6 -5
  105. package/.build/next/server/chunks/src_shared_constants_appConfig_ts_1rww0w9vzhopb._.js +1 -1
  106. package/.build/next/server/chunks/src_sse_handlers_rejectedRequestUsage_ts_1b55t-ib_tcom._.js +1 -1
  107. package/.build/next/server/chunks/ssr/src_1th8ewh11ev61._.js +1 -1
  108. package/.build/next/server/chunks/ssr/src_lib_db_adapters_driverFactory_ts_0h9nksnfqd24o._.js +1 -1
  109. package/.build/next/server/chunks/ssr/src_shared_constants_appConfig_ts_06ksyl9fe46j1._.js +1 -1
  110. package/.build/next/server/middleware-build-manifest.js +3 -3
  111. package/.build/next/server/pages/500.html +1 -1
  112. package/.build/next/server/preview-props.json +3 -3
  113. package/.build/next/server/server-reference-manifest.js +1 -1
  114. package/.build/next/server/server-reference-manifest.json +1 -1
  115. package/.build/next/static/chunks/{3ww_hz6yicjrg.js → 2il0d_6tjiinn.js} +1 -1
  116. package/bin/cli/sqlite.mjs +4 -0
  117. package/open-sse/handlers/chatCore/failureUsage.ts +2 -0
  118. package/open-sse/handlers/chatCore/nonStreamingUsageStats.ts +3 -0
  119. package/open-sse/handlers/chatCore/streamingUsageStats.ts +3 -0
  120. package/open-sse/handlers/chatCore.ts +3 -0
  121. package/open-sse/services/tokenLimitCounter.ts +41 -36
  122. package/package.json +1 -1
  123. package/src/lib/db/adapters/nodeSqliteShared.ts +21 -1
  124. package/src/lib/db/schemaColumns.ts +5 -0
  125. package/src/lib/usage/usageHistory.ts +23 -8
  126. package/src/sse/handlers/rejectedRequestUsage.ts +4 -0
  127. /package/.build/next/static/{prVY4oDcIYhYIAmKKETw_ → TV3h5vHYH5dOZKDHmwyuM}/_buildManifest.js +0 -0
  128. /package/.build/next/static/{prVY4oDcIYhYIAmKKETw_ → TV3h5vHYH5dOZKDHmwyuM}/_clientMiddlewareManifest.js +0 -0
  129. /package/.build/next/static/{prVY4oDcIYhYIAmKKETw_ → TV3h5vHYH5dOZKDHmwyuM}/_ssgManifest.js +0 -0
@@ -590,6 +590,7 @@ export async function handleChatCore({
590
590
  errorCode,
591
591
  latencyMs: Date.now() - startTime,
592
592
  endpoint: endpointPath,
593
+ requestId: traceId,
593
594
  })
594
595
  ).catch(() => {});
595
596
  };
@@ -4429,6 +4430,7 @@ export async function handleChatCore({
4429
4430
  isCombo,
4430
4431
  comboStrategy,
4431
4432
  endpoint: endpointPath,
4433
+ requestId: traceId,
4432
4434
  });
4433
4435
 
4434
4436
  // Translate response to client's expected format (usually OpenAI)
@@ -4993,6 +4995,7 @@ export async function handleChatCore({
4993
4995
  isCombo,
4994
4996
  comboStrategy,
4995
4997
  endpoint: endpointPath,
4998
+ requestId: traceId,
4996
4999
  });
4997
5000
 
4998
5001
  persistAttemptLogs({
@@ -274,48 +274,53 @@ export function recordTokenUsage(
274
274
  const db = getDbInstance();
275
275
  const applied: Array<{ limitId: string; windowStart: string; total: number }> = [];
276
276
 
277
- const tx = db.transaction(() => {
278
- for (const limit of limits) {
279
- if (limit.enabled === false) continue;
280
-
281
- const { windowStart } = resetWindowIfElapsed(limit, now);
282
-
283
- const currentRow = db
284
- .prepare(
285
- "SELECT tokens_used FROM api_key_token_counters WHERE limit_id = ? AND window_start = ?"
286
- )
287
- .get(limit.id, windowStart) as { tokens_used?: number } | undefined;
288
-
289
- // First write to a new window? Detect rollover from the prior window.
290
- if (!currentRow) {
291
- const priorRow = db
277
+ // IMMEDIATE: the write lock is taken before the counter row is read, so another process's
278
+ // write waits busy_timeout. In a deferred transaction this read-then-write failed at once
279
+ // with SQLITE_BUSY when another process wrote in between, and the tokens were never counted
280
+ // (a key could then go past its limit); two processes could also both seed a cold window.
281
+ const tx = () =>
282
+ db.immediate(() => {
283
+ for (const limit of limits) {
284
+ if (limit.enabled === false) continue;
285
+
286
+ const { windowStart } = resetWindowIfElapsed(limit, now);
287
+
288
+ const currentRow = db
292
289
  .prepare(
293
- `SELECT window_start, tokens_used FROM api_key_token_counters
290
+ "SELECT tokens_used FROM api_key_token_counters WHERE limit_id = ? AND window_start = ?"
291
+ )
292
+ .get(limit.id, windowStart) as { tokens_used?: number } | undefined;
293
+
294
+ // First write to a new window? Detect rollover from the prior window.
295
+ if (!currentRow) {
296
+ const priorRow = db
297
+ .prepare(
298
+ `SELECT window_start, tokens_used FROM api_key_token_counters
294
299
  WHERE limit_id = ? AND window_start < ?
295
300
  ORDER BY window_start DESC LIMIT 1`
296
- )
297
- .get(limit.id, windowStart) as
298
- { window_start?: string; tokens_used?: number } | undefined;
299
- const prevTokens =
300
- priorRow && typeof priorRow.tokens_used === "number" ? priorRow.tokens_used : 0;
301
- if (prevTokens > 0) {
302
- logTokenLimitReset(limit.id, prevTokens, windowStart);
301
+ )
302
+ .get(limit.id, windowStart) as
303
+ { window_start?: string; tokens_used?: number } | undefined;
304
+ const prevTokens =
305
+ priorRow && typeof priorRow.tokens_used === "number" ? priorRow.tokens_used : 0;
306
+ if (prevTokens > 0) {
307
+ logTokenLimitReset(limit.id, prevTokens, windowStart);
308
+ }
309
+
310
+ // Cold window with no counter row: seed from usage_history so the
311
+ // running total reflects prior usage already recorded in this window
312
+ // before applying the new delta. Synchronous (better-sqlite3) — safe
313
+ // inside this transaction. Mirrors getCurrentWindowUsage seed-on-miss.
314
+ const seeded = seedWindowUsageFromHistory(limit, now);
315
+ if (seeded > 0) {
316
+ incrementWindowTokens(limit.id, windowStart, seeded);
317
+ }
303
318
  }
304
319
 
305
- // Cold window with no counter row: seed from usage_history so the
306
- // running total reflects prior usage already recorded in this window
307
- // before applying the new delta. Synchronous (better-sqlite3) — safe
308
- // inside this transaction. Mirrors getCurrentWindowUsage seed-on-miss.
309
- const seeded = seedWindowUsageFromHistory(limit, now);
310
- if (seeded > 0) {
311
- incrementWindowTokens(limit.id, windowStart, seeded);
312
- }
320
+ const total = incrementWindowTokens(limit.id, windowStart, delta);
321
+ applied.push({ limitId: limit.id, windowStart, total });
313
322
  }
314
-
315
- const total = incrementWindowTokens(limit.id, windowStart, delta);
316
- applied.push({ limitId: limit.id, windowStart, total });
317
- }
318
- });
323
+ });
319
324
 
320
325
  try {
321
326
  tx();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trouteai",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "Your AI. Your Models. Your Rules. An open-source, self-hosted AI gateway to route, manage, and optimize multiple LLM providers through a single OpenAI- and Anthropic-compatible API.",
5
5
  "keywords": [
6
6
  "ai",
@@ -19,6 +19,7 @@ export function createNodeSqliteAdapterFromDatabase(
19
19
  onClose?: () => void
20
20
  ): SqliteAdapter {
21
21
  let _isOpen = true;
22
+ let immediateDepth = 0;
22
23
  type NodeSqliteStatement = ReturnType<NodeSqliteDatabaseLike["prepare"]>;
23
24
  interface CachedStatement {
24
25
  stmt: NodeSqliteStatement;
@@ -127,7 +128,26 @@ export function createNodeSqliteAdapterFromDatabase(
127
128
  return (...args: unknown[]) => runSavepoint(fn, ...args);
128
129
  },
129
130
  immediate(fn: () => void): void {
130
- runSavepoint(() => fn());
131
+ // Outside a transaction a SAVEPOINT begins a DEFERRED one: a read-then-write in it fails at
132
+ // once with "database is locked" when another process wrote in between (busy_timeout does
133
+ // not apply to that upgrade). BEGIN IMMEDIATE takes the write lock first and waits for it.
134
+ if (immediateDepth > 0 || (db as { isTransaction?: boolean }).isTransaction === true) {
135
+ runSavepoint(() => fn());
136
+ return;
137
+ }
138
+ db.exec("BEGIN IMMEDIATE");
139
+ immediateDepth++;
140
+ try {
141
+ fn();
142
+ db.exec("COMMIT");
143
+ } catch (err) {
144
+ try {
145
+ db.exec("ROLLBACK");
146
+ } catch {}
147
+ throw err;
148
+ } finally {
149
+ immediateDepth--;
150
+ }
131
151
  },
132
152
  async backup(destination: string): Promise<void> {
133
153
  try {
@@ -164,6 +164,11 @@ export function ensureUsageHistoryColumns(db: SqliteDatabase) {
164
164
  tokens_output
165
165
  )`
166
166
  );
167
+ // Last: when two processes start at once, the one that loses this race skips nothing else.
168
+ if (!columnNames.has("request_id")) {
169
+ db.exec("ALTER TABLE usage_history ADD COLUMN request_id TEXT DEFAULT NULL");
170
+ console.log("[DB] Added usage_history.request_id column");
171
+ }
167
172
  } catch (error: unknown) {
168
173
  const message = error instanceof Error ? error.message : String(error);
169
174
  console.warn("[DB] Failed to verify usage_history schema:", message);
@@ -610,6 +610,11 @@ export interface UsageEntry {
610
610
  /** @deprecated legacy snake_case fallback, read only if `comboStrategy` is unset. */
611
611
  combo_strategy?: string | null;
612
612
  endpoint?: string | null;
613
+ /**
614
+ * The request's own id. Part of the de-dup key below, so two requests that end in the same
615
+ * millisecond with the same tokens are two rows while one request recorded twice is one.
616
+ */
617
+ requestId?: string | null;
613
618
  }
614
619
 
615
620
  /**
@@ -638,11 +643,18 @@ export async function saveRequestUsage(entry: UsageEntry) {
638
643
  // than once (e.g. combo routing calling the callback from both the
639
644
  // streaming and non-streaming paths for the same underlying request).
640
645
  // Keyed on the natural identity of a request: timestamp + provider + model
641
- // + connectionId + apiKeyId + token counts. If only the endpoint is missing
642
- // on the existing row, fill it in rather than inserting a duplicate.
646
+ // + connectionId + apiKeyId + token counts + request id. Without the request id two
647
+ // different requests that end in the same millisecond with the same counts (common with
648
+ // several worker processes) were taken for one and a row was lost. A row without an id (an
649
+ // older version, a writer that has none) is only matched by a record without one. If only
650
+ // the endpoint is missing on the existing row, fill it in rather than inserting a duplicate.
651
+ const requestId = entry.requestId || null;
643
652
  let inserted = false;
644
653
 
645
- db.transaction(() => {
654
+ // IMMEDIATE: the write lock is taken before the read, so a write of another process waits
655
+ // busy_timeout. In a deferred transaction the read-then-insert failed at once with
656
+ // SQLITE_BUSY when another process wrote in between, and the row was lost.
657
+ db.immediate(() => {
646
658
  const existing = db
647
659
  .prepare(
648
660
  `SELECT id, endpoint FROM usage_history
@@ -653,6 +665,7 @@ export async function saveRequestUsage(entry: UsageEntry) {
653
665
  AND COALESCE(api_key_id, '') = COALESCE(?, '')
654
666
  AND tokens_input = ?
655
667
  AND tokens_output = ?
668
+ AND request_id IS ?
656
669
  ORDER BY id DESC LIMIT 1`
657
670
  )
658
671
  .get(
@@ -662,7 +675,8 @@ export async function saveRequestUsage(entry: UsageEntry) {
662
675
  entry.connectionId || null,
663
676
  entry.apiKeyId || null,
664
677
  tokensInput,
665
- tokensOutput
678
+ tokensOutput,
679
+ requestId
666
680
  ) as { id: number; endpoint: string | null } | undefined;
667
681
 
668
682
  if (existing) {
@@ -681,8 +695,8 @@ export async function saveRequestUsage(entry: UsageEntry) {
681
695
  INSERT INTO usage_history (provider, model, connection_id, account_key, account_label,
682
696
  account_label_priority, api_key_id, api_key_name, tokens_input, tokens_output,
683
697
  tokens_cache_read, tokens_cache_creation, tokens_reasoning, service_tier, status, success,
684
- latency_ms, ttft_ms, error_code, combo_strategy, endpoint, timestamp)
685
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
698
+ latency_ms, ttft_ms, error_code, combo_strategy, endpoint, timestamp, request_id)
699
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
686
700
  `
687
701
  ).run(
688
702
  entry.provider || null,
@@ -710,11 +724,12 @@ export async function saveRequestUsage(entry: UsageEntry) {
710
724
  entry.errorCode || null,
711
725
  entry.comboStrategy || entry.combo_strategy || null,
712
726
  entry.endpoint || null,
713
- timestamp
727
+ timestamp,
728
+ requestId
714
729
  );
715
730
 
716
731
  inserted = true;
717
- })();
732
+ });
718
733
 
719
734
  // Decoupled via the event bus so usageHistory never imports providerLimits
720
735
  // (which would pull the executors/translator graph into the type-check surface).
@@ -17,6 +17,8 @@
17
17
  * Best-effort: both writes swallow their own errors — logging a rejection must
18
18
  * never turn into a second failure on the response path.
19
19
  */
20
+ import { randomUUID } from "node:crypto";
21
+
20
22
  import { saveCallLog, saveRequestUsage } from "@/lib/usageDb";
21
23
 
22
24
  export interface RejectedRequestUsageInput {
@@ -103,6 +105,8 @@ export async function recordRejectedRequestUsage(input: RejectedRequestUsageInpu
103
105
  latencyMs: duration,
104
106
  comboStrategy: comboName || null,
105
107
  endpoint: endpoint || "/v1/chat/completions",
108
+ // One call is one rejected request: two rejected in the same millisecond are two rows.
109
+ requestId: randomUUID(),
106
110
  }).catch(() => {});
107
111
  }
108
112