Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(account-fallback): add daily quota lockout for quota_exhausted errors (#1644)
diegosouzapw78b845b68c79
diff --git a/open-sse/services/accountFallback.ts b/open-sse/services/accountFallback.tsindex 74bc593f6c..19c8be2e43 100644--- a/open-sse/services/accountFallback.ts+++ b/open-sse/services/accountFallback.ts@@ -345,6 +345,12 @@ export function recordModelLockoutFailure(const now = Date.now();cleanupModelLockKey(key, now);+ // For daily quota exhaustion (quota_exhausted), set cooldown until tomorrow 00:00+ // Use exactCooldownMs to bypass exponential backoff, ensuring precise lock until midnight+ if (reason === "quota_exhausted" && typeof options.exactCooldownMs !== "number") {+ options = { ...options, exactCooldownMs: getMsUntilTomorrow() };+ }+const resetAfterMs = getFailureWindowMs(profile);const previous = modelFailureState.get(key);const withinWindow = previous && now - previous.lastFailureAt <= previous.resetAfterMs;@@ -770,11 +776,12 @@ export function classifyError(status, errorText) {* @returns {number} Milliseconds until tomorrow*/export function getMsUntilTomorrow(): number {- const now = new Date();- const tomorrow = new Date(now);+ const nowMs = Date.now();+ const now = new Date(nowMs);+ const tomorrow = new Date(nowMs);tomorrow.setDate(tomorrow.getDate() + 1);tomorrow.setHours(0, 0, 0, 0);- const ms = tomorrow.getTime() - now.getTime();+ const ms = tomorrow.getTime() - nowMs;// Guard against DST edge cases: if ms is negative (shouldn't happen) or// unreasonably large (>25h due to spring-forward), cap at 24 hours.return ms > 0 && ms <= 25 * 60 * 60 * 1000 ? ms : 24 * 60 * 60 * 1000;diff --git a/src/sse/handlers/chat.ts b/src/sse/handlers/chat.tsindex 6151a60706..d9bf0763e7 100644--- a/src/sse/handlers/chat.ts+++ b/src/sse/handlers/chat.ts@@ -9,6 +9,9 @@ import {getRuntimeProviderProfile,shouldMarkAccountExhaustedFrom429,clearModelLock,+ lockModel,+ recordModelLockoutFailure,+ isDailyQuotaExhausted,} from "@omniroute/open-sse/services/accountFallback.ts";import { getModelInfo, getComboForModel } from "../services/model";import { errorResponse } from "@omniroute/open-sse/utils/error.ts";@@ -827,18 +830,55 @@ async function handleSingleModelChat(}}- // 6. Mark account as quota-exhausted on 429 response+ // 6. Daily quota error check - must be executed before markAccountUnavailable+ // Check if it's a daily quota exhausted error (e.g., ModelScope/Kimi "today's quota for model")+ // Daily quota lockout overrides subsequent rate_limited lockout, ensuring lockout until tomorrow 0:00+ let dailyQuotaExhausted = false;+ const errorStr = String(result.error || "");+ if (result.status === 429 && isDailyQuotaExhausted(errorStr)) {+ // Parse which model is quota-limited+ const match = errorStr.match(/today's quota for model ([^,]+)/);+ const limitedModel = match ? match[1].trim() : model;++ // Lock this model on this connection until tomorrow 00:00+ const lockResult = recordModelLockoutFailure(+ provider,+ credentials.connectionId,+ limitedModel,+ "quota_exhausted",+ result.status,+ 0,+ providerProfile+ );++ log.info(+ "MODEL_DAILY_QUOTA",+ JSON.stringify({+ connection: credentials.connectionId.slice(0, 8),+ model: limitedModel,+ cooldownMs: lockResult.cooldownMs,+ failureCount: lockResult.failureCount,+ })+ );++ dailyQuotaExhausted = true;+ }++ // 7. Mark account as quota-exhausted on 429 response (non-daily-quota errors)// For providers that route quota/cooldown at model scope, a 429 on one model// does not mean the whole connection is exhausted.- const passthroughModels = credentials.providerSpecificData?.passthroughModels;- if (- result.status === 429 &&- shouldMarkAccountExhaustedFrom429(provider, model, passthroughModels)- ) {- markAccountExhaustedFrom429(credentials.connectionId, provider);+ // Daily quota errors are handled above; only process regular rate_limit here+ if (!dailyQuotaExhausted) {+ const passthroughModels = credentials.providerSpecificData?.passthroughModels;+ if (+ result.status === 429 &&+ shouldMarkAccountExhaustedFrom429(provider, model, passthroughModels)+ ) {+ markAccountExhaustedFrom429(credentials.connectionId, provider);+ }}- // 7. Fallback to next account+ // 8. Fallback to next accountconst { shouldFallback, cooldownMs } = await markAccountUnavailable(credentials.connectionId,result.status,diff --git a/tests/unit/account-fallback-service.test.ts b/tests/unit/account-fallback-service.test.tsindex 8e49cdd6d2..a72518e7ba 100644--- a/tests/unit/account-fallback-service.test.ts+++ b/tests/unit/account-fallback-service.test.ts@@ -613,3 +613,119 @@ test("checkFallbackError preserves OAuth 429 daily quota semantics", () => {assert.equal(result.dailyQuotaExhausted, true);assert.ok(result.cooldownMs > 0);});++// ModelScope daily quota lockout tests (commit 0456a1f5)+test("recordModelLockoutFailure sets cooldown until tomorrow 0:00 for quota_exhausted reason", () => {+ const originalNow = Date.now;+ // Use a fixed local time (noon) to ensure predictable results+ const testDate = new Date();+ testDate.setHours(12, 0, 0, 0); // Set to noon today+ const now = testDate.getTime();+ Date.now = () => now;++ try {+ const provider = "modelscope";+ const connectionId = "test-conn-modelscope-1";+ const model = "qwen/Qwen2.5-Coder-32B-Instruct";++ // Clear any existing state+ clearModelLock(provider, connectionId, model);++ const profile = {+ baseCooldownMs: 125,+ useUpstreamRetryHints: false,+ maxBackoffSteps: 3,+ failureThreshold: 60,+ resetTimeoutMs: 5000,+ };++ // Calculate milliseconds until tomorrow 00:00 local time+ const tomorrow = new Date(now);+ tomorrow.setDate(tomorrow.getDate() + 1);+ tomorrow.setHours(0, 0, 0, 0);+ const expectedMsUntilTomorrow = tomorrow.getTime() - now;++ // Account for timezone offset: function uses local time, test env may use UTC+ const timezoneOffset = new Date().getTimezoneOffset() * 60 * 1000;++ // Record failure with quota_exhausted reason+ const result = recordModelLockoutFailure(+ provider,+ connectionId,+ model,+ "quota_exhausted",+ 429,+ 0, // fallbackCooldownMs should be overridden to ms until tomorrow+ profile+ );++ // Verify the cooldown is set to ms until tomorrow 0:00 (with tolerance)+ // The cooldown should be close to expectedMsUntilTomorrow+ const tolerance = 60 * 1000; // 1 minute tolerance+ // Calculate difference between actual and expected values+ const diff = Math.abs(result.cooldownMs - expectedMsUntilTomorrow);++ // Allow ±5 minutes tolerance (300,000 ms)+ assert.ok(+ diff <= 300_000,+ `cooldown should be ms until tomorrow 0:00 (expected ${expectedMsUntilTomorrow}ms, got ${result.cooldownMs}ms, diff ${diff}ms)`+ );++ // Verify model is locked+ assert.equal(isModelLocked(provider, connectionId, model), true);++ const lockInfo = getModelLockoutInfo(provider, connectionId, model);+ assert.ok(lockInfo !== null, "lockInfo should not be null");+ assert.ok(lockInfo.remainingMs > 0, "remaining time should be positive");++ clearModelLock(provider, connectionId, model);+ } finally {+ Date.now = originalNow;+ clearModelLock("modelscope", "test-conn-modelscope-1", "qwen/Qwen2.5-Coder-32B-Instruct");+ }+});++test("recordModelLockoutFailure uses regular backoff for non-quota reasons", () => {+ const originalNow = Date.now;+ const now = 1_700_000_000_000;+ Date.now = () => now;++ try {+ const provider = "modelscope";+ const connectionId = "test-conn-modelscope-2";+ const model = "qwen/Qwen2.5-Coder-32B-Instruct";++ clearModelLock(provider, connectionId, model);++ const profile = {+ baseCooldownMs: 5000,+ useUpstreamRetryHints: false,+ maxBackoffSteps: 3,+ failureThreshold: 60,+ resetTimeoutMs: 5000,+ };++ // Record failure with rate_limited reason (not quota_exhausted)+ const result = recordModelLockoutFailure(+ provider,+ connectionId,+ model,+ "rate_limited",+ 429,+ 0,+ profile+ );++ // Verify the cooldown uses regular profile baseCooldownMs (5000ms)+ assert.ok(+ result.cooldownMs < 24 * 60 * 60 * 1000,+ "cooldown should be less than 24h for non-quota reasons"+ );+ assert.equal(result.cooldownMs, 5000, "cooldown should use profile baseCooldownMs");++ clearModelLock(provider, connectionId, model);+ } finally {+ Date.now = originalNow;+ clearModelLock("modelscope", "test-conn-modelscope-2", "qwen/Qwen2.5-Coder-32B-Instruct");+ }+});