From f558ef4c886794f34bb5d7086c4763813b0462e5 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Wed, 4 Nov 2026 20:25:51 +0000 Subject: [PATCH 1/3] fix(engine): handle Content-Length mismatch, socket drops, and stream failover resilience --- package.json | 2 +- src/revolverEngine.ts | 212 ++++++++++++----- src/routes.ts | 8 + test-content-length-resilience.ts | 365 ++++++++++++++++++++++++++++++ 4 files changed, 526 insertions(+), 61 deletions(-) create mode 100644 test-content-length-resilience.ts diff --git a/package.json b/package.json index 8127935..c84018c 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "start": "node dist/index.js", "dev": "ts-node src/index.ts", "watch": "tsc --watch", - "test": "API_PASSWORD=test_password ts-node test-revolver.ts && API_PASSWORD=test_password ts-node test-integration.ts && API_PASSWORD=test_password ts-node test-timeout-keepalive.ts && API_PASSWORD=test_password ts-node test-live-watcher.ts && API_PASSWORD=test_password ts-node test-telemetry-fallback.ts" + "test": "API_PASSWORD=test_password ts-node test-revolver.ts && API_PASSWORD=test_password ts-node test-integration.ts && API_PASSWORD=test_password ts-node test-timeout-keepalive.ts && API_PASSWORD=test_password ts-node test-live-watcher.ts && API_PASSWORD=test_password ts-node test-telemetry-fallback.ts && API_PASSWORD=test_password ts-node test-content-length-resilience.ts" }, "keywords": ["openai", "gemini", "api", "rotation"], "author": "", diff --git a/src/revolverEngine.ts b/src/revolverEngine.ts index ad93eb4..2af74c6 100644 --- a/src/revolverEngine.ts +++ b/src/revolverEngine.ts @@ -197,14 +197,47 @@ export class RevolverEngine { } private isServerError(error: any): boolean { + if (!error) return false; + const status = error?.status || error?.statusCode || error?.code; + if (typeof status === 'number' && status >= 500 && status < 600) { + return true; + } + + const networkCodes = [ + 'ECONNRESET', + 'ETIMEDOUT', + 'ECONNREFUSED', + 'EPIPE', + 'ENOTFOUND', + 'EAI_AGAIN', + 'UND_ERR_SOCKET', + 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH', + 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH', + 'UND_ERR_BODY_TIMEOUT', + 'UND_ERR_HEADERS_TIMEOUT', + 'UND_ERR_CONNECT_TIMEOUT' + ]; + + const errCode = error?.code || error?.cause?.code; + if (errCode && networkCodes.includes(errCode)) { + return true; + } + + const errName = error?.name || error?.cause?.name; + if (errName === 'ResponseContentLengthMismatchError' || errName === 'SocketError') { + return true; + } + + const msg = `${error?.message || ''} ${error?.cause?.message || ''}`.toLowerCase(); return ( - status === 500 || - status === 502 || - status === 503 || - status === 504 || - status === 'ECONNRESET' || - status === 'ETIMEDOUT' + msg.includes('content-length') || + msg.includes('fetch failed') || + msg.includes('terminated') || + msg.includes('other side closed') || + msg.includes('socket hung up') || + msg.includes('premature close') || + msg.includes('network error') ); } @@ -485,13 +518,15 @@ export class RevolverEngine { res.write(JSON.stringify(responseData)); res.end(); } else { + res.setHeader('Cache-Control', 'no-cache, no-transform'); res.json(responseData); } return; } } catch (err: any) { lastError = err; - console.error(`[REVOLVER] Candidate failed (Provider: '${candidate.provider.name}', Model: '${candidate.target.model}'):`, err.message); + const detailedErrorMessage = err.cause?.message ? `${err.message}: ${err.cause.message}` : (err.message || 'Unknown candidate error'); + console.error(`[REVOLVER] Candidate failed (Provider: '${candidate.provider.name}', Model: '${candidate.target.model}'):`, detailedErrorMessage); const stepDuration = Date.now() - candidateStart; const isRateLimit = this.isRateLimitOrQuotaError(err); @@ -521,8 +556,8 @@ export class RevolverEngine { maskedKey: this.store.maskKey(candidate.keyConfig.key), durationMs: stepDuration, status: statusType, - statusCode: err.status || (isRateLimit ? 429 : 500), - errorMessage: err.message, + statusCode: err.status || (isRateLimit ? 429 : (isServerErr ? 502 : 500)), + errorMessage: detailedErrorMessage, rateLimitedUntil: cooldown ? Date.now() + cooldown : null, cooldownSeconds: cooldown ? Math.ceil(cooldown / 1000) : undefined, nextAction @@ -557,7 +592,7 @@ export class RevolverEngine { if (!res.destroyed && !res.writableEnded) { res.write(`data: ${JSON.stringify({ error: { - message: err.message || 'Stream interrupted', + message: detailedErrorMessage, type: 'server_error', code: 'stream_interrupted' } @@ -756,14 +791,20 @@ export class RevolverEngine { method: 'POST', headers: { 'Content-Type': 'application/json', - 'Authorization': `Bearer ${candidate.keyConfig.key}` + 'Authorization': `Bearer ${candidate.keyConfig.key}`, + 'Accept-Encoding': 'identity' }, body: JSON.stringify(forwardedBody), signal: AbortSignal.timeout(config.candidateTimeoutMs) }); if (!response.ok) { - const errBody = await response.text(); + let errBody = ''; + try { + errBody = await response.text(); + } catch (readErr: any) { + errBody = readErr.message || 'Failed to read error response'; + } let errorDetails = errBody; try { const parsed = JSON.parse(errBody); @@ -774,7 +815,46 @@ export class RevolverEngine { throw err; } - const json = (await response.json()) as OpenAIChatResponse; + if (!response.body) { + throw new Error('Response body is null from provider.'); + } + + // Safely consume response stream to handle premature connection termination or Content-Length mismatches gracefully + let rawText = ''; + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let streamReadError: any = null; + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (value) { + rawText += decoder.decode(value, { stream: true }); + } + } + rawText += decoder.decode(); + } catch (readErr: any) { + streamReadError = readErr; + } + + let json: OpenAIChatResponse | null = null; + if (rawText.trim()) { + try { + json = JSON.parse(rawText.trim()) as OpenAIChatResponse; + } catch (parseErr) { + // If JSON parsing fails and stream had a read error, re-throw the stream read error + if (streamReadError) { + throw streamReadError; + } + throw new Error(`Invalid JSON received from provider: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`); + } + } else if (streamReadError) { + throw streamReadError; + } else { + throw new Error('Empty response body received from provider.'); + } + // Overwrite returned model with requestedModelName for client fidelity json.model = requestedModelName; if (!json.id) { @@ -963,14 +1043,20 @@ export class RevolverEngine { method: 'POST', headers: { 'Content-Type': 'application/json', - 'Authorization': `Bearer ${candidate.keyConfig.key}` + 'Authorization': `Bearer ${candidate.keyConfig.key}`, + 'Accept-Encoding': 'identity' }, body: JSON.stringify(forwardedBody), signal: AbortSignal.timeout(config.candidateTimeoutMs) }); if (!response.ok) { - const errBody = await response.text(); + let errBody = ''; + try { + errBody = await response.text(); + } catch (readErr: any) { + errBody = readErr.message || 'Failed to read error response'; + } let errorDetails = errBody; try { const parsed = JSON.parse(errBody); @@ -1001,54 +1087,52 @@ export class RevolverEngine { let buffer = ''; let totalOutputChars = 0; - try { - while (true) { - if (res.destroyed) break; - const { done, value } = await reader.read(); - if (done) break; + while (true) { + if (res.destroyed) break; + const { done, value } = await reader.read(); + if (done) break; - const text = decoder.decode(value, { stream: true }); - buffer += text; + const text = decoder.decode(value, { stream: true }); + buffer += text; - const lines = buffer.split('\n'); - buffer = lines.pop() || ''; + const lines = buffer.split('\n'); + buffer = lines.pop() || ''; - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed) { - res.write('\n'); + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed) { + res.write('\n'); + continue; + } + + if (trimmed.startsWith('data: ')) { + const dataStr = trimmed.slice(6); + if (dataStr === '[DONE]') { + res.write('data: [DONE]\n\n'); continue; } - if (trimmed.startsWith('data: ')) { - const dataStr = trimmed.slice(6); - if (dataStr === '[DONE]') { - res.write('data: [DONE]\n\n'); - continue; + try { + const parsed = JSON.parse(dataStr); + parsed.model = requestedModelName; + if (parsed.choices?.[0]?.delta?.content) { + onStreamStart(); + const delta = parsed.choices[0].delta.content; + totalOutputChars += delta.length; + liveWatcher.appendStreamChunk(requestId, delta); } - - try { - const parsed = JSON.parse(dataStr); - parsed.model = requestedModelName; - if (parsed.choices?.[0]?.delta?.content) { - onStreamStart(); - const delta = parsed.choices[0].delta.content; - totalOutputChars += delta.length; - liveWatcher.appendStreamChunk(requestId, delta); - } - res.write(`data: ${JSON.stringify(parsed)}\n\n`); - } catch { - res.write(`${line}\n`); - } - } else { + res.write(`data: ${JSON.stringify(parsed)}\n\n`); + } catch { res.write(`${line}\n`); } + } else { + res.write(`${line}\n`); } } - } finally { - if (!res.destroyed) { - res.end(); - } + } + + if (!res.destroyed && !res.writableEnded) { + res.end(); } const estimatedInput = Math.ceil(JSON.stringify(requestBody.messages).length / 4); @@ -1145,9 +1229,10 @@ export class RevolverEngine { } catch (err: any) { lastError = err; const isRateLimit = this.isRateLimitOrQuotaError(err); - if (isRateLimit) { + const isServerErr = this.isServerError(err); + if (isRateLimit || isServerErr) { this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { - rateLimitedUntil: Date.now() + config.rateLimitDurationMs, + rateLimitedUntil: Date.now() + (isRateLimit ? config.rateLimitDurationMs : 15000), incrementError: true }); } @@ -1190,7 +1275,8 @@ export class RevolverEngine { method: 'POST', headers: { 'Content-Type': 'application/json', - 'Authorization': `Bearer ${params.key}` + 'Authorization': `Bearer ${params.key}`, + 'Accept-Encoding': 'identity' }, body: JSON.stringify({ model, @@ -1200,11 +1286,16 @@ export class RevolverEngine { }); if (!res.ok) { - const body = await res.text(); - let errText = body; + let errBody = ''; try { - const parsed = JSON.parse(body); - errText = parsed.error?.message || body; + errBody = await res.text(); + } catch (readErr: any) { + errBody = readErr.message || 'Failed to read error response'; + } + let errText = errBody; + try { + const parsed = JSON.parse(errBody); + errText = parsed.error?.message || errBody; } catch {} return { success: false, @@ -1222,10 +1313,11 @@ export class RevolverEngine { }; } } catch (err: any) { + const detailedMsg = err.cause?.message ? `${err.message}: ${err.cause.message}` : (err.message || 'Connection failed'); return { success: false, latencyMs: Date.now() - start, - message: err.message || 'Connection failed' + message: detailedMsg }; } } diff --git a/src/routes.ts b/src/routes.ts index 97de756..1ae5cbd 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -136,6 +136,7 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { }); if (!res.headersSent) { + res.setHeader('Cache-Control', 'no-cache, no-transform'); res.status(error.status || 500).json({ error: { message: error.message || 'Internal server error', @@ -144,6 +145,13 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { } }); } else if (!res.writableEnded) { + res.write(JSON.stringify({ + error: { + message: error.message || 'Internal server error', + type: 'server_error', + code: 'internal_error' + } + })); res.end(); } } diff --git a/test-content-length-resilience.ts b/test-content-length-resilience.ts new file mode 100644 index 0000000..01c8c47 --- /dev/null +++ b/test-content-length-resilience.ts @@ -0,0 +1,365 @@ +import http from 'http'; +import assert from 'assert'; +import app from './src/index'; +import { revolverEngine } from './src/revolverEngine'; +import { configStore } from './src/configStore'; +import { telemetryTracker } from './src/telemetryTracker'; + +const PORT = 3999; +const API_KEY = 'test_password'; + +console.log('๐Ÿงช Starting Content-Length Resilience & Upstream Failover Test Suite...\n'); + +async function runTests() { + const server = http.createServer(app); + await new Promise((resolve) => server.listen(PORT, resolve)); + + const createdModelIds: string[] = []; + const createdProviderIds: string[] = []; + + try { + // ========================================================================= + // Test 1: Unit Test isServerError() logic via revolverEngine private access + // ========================================================================= + console.log('1. Testing isServerError detection across all Content-Length and socket error variants...'); + + const isServerErrorFn = (revolverEngine as any).isServerError.bind(revolverEngine); + + // 1.1 HTTP 5xx codes + assert.strictEqual(isServerErrorFn({ status: 500 }), true, '500 should be server error'); + assert.strictEqual(isServerErrorFn({ status: 502 }), true, '502 should be server error'); + assert.strictEqual(isServerErrorFn({ status: 503 }), true, '503 should be server error'); + assert.strictEqual(isServerErrorFn({ statusCode: 504 }), true, '504 should be server error'); + + // 1.2 Undici Content-Length Mismatch Errors + const undiciContentLengthErr = new TypeError('fetch failed'); + (undiciContentLengthErr as any).cause = { + name: 'ResponseContentLengthMismatchError', + code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH', + message: 'Response body length does not match content-length header' + }; + assert.strictEqual(isServerErrorFn(undiciContentLengthErr), true, 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH must be server error'); + + // 1.3 Exact string from prompt: Content-Length header of network response exceeds response Body. + const exactPromptErr = new TypeError('fetch failed'); + (exactPromptErr as any).cause = new Error('Content-Length header of network response exceeds response Body.'); + assert.strictEqual(isServerErrorFn(exactPromptErr), true, 'Exact Content-Length mismatch string must be server error'); + + // 1.4 Socket closed prematurely (UND_ERR_SOCKET / other side closed) + const undiciSocketErr = new TypeError('fetch failed'); + (undiciSocketErr as any).cause = { + name: 'SocketError', + code: 'UND_ERR_SOCKET', + message: 'other side closed' + }; + assert.strictEqual(isServerErrorFn(undiciSocketErr), true, 'UND_ERR_SOCKET other side closed must be server error'); + + // 1.5 Node standard network errors + assert.strictEqual(isServerErrorFn({ code: 'ECONNRESET' }), true, 'ECONNRESET must be server error'); + assert.strictEqual(isServerErrorFn({ code: 'ETIMEDOUT' }), true, 'ETIMEDOUT must be server error'); + assert.strictEqual(isServerErrorFn({ code: 'ECONNREFUSED' }), true, 'ECONNREFUSED must be server error'); + + // 1.6 Client errors that should NOT be server error + assert.strictEqual(isServerErrorFn({ status: 400 }), false, '400 must NOT be server error'); + assert.strictEqual(isServerErrorFn({ status: 401 }), false, '401 must NOT be server error'); + assert.strictEqual(isServerErrorFn({ status: 404 }), false, '404 must NOT be server error'); + assert.strictEqual(isServerErrorFn({ status: 429 }), false, '429 must NOT be server error (handled as rate limit)'); + + console.log(' โœ“ isServerError accurately identifies undici/network/Content-Length mismatch errors.\n'); + + // ========================================================================= + // Test 2: Non-Streaming: Recovery of valid JSON when upstream claims inflated Content-Length + // ========================================================================= + console.log('2. Testing Non-Streaming recovery when upstream returns valid JSON but terminates with Content-Length mismatch...'); + + const validJsonPayload = { + id: 'chatcmpl-recovered-123', + object: 'chat.completion', + created: Math.floor(Date.now() / 1000), + model: 'resilient-model', + choices: [ + { + index: 0, + message: { role: 'assistant', content: 'Successfully parsed even with Content-Length header mismatch!' }, + finish_reason: 'stop' + } + ], + usage: { prompt_tokens: 10, completion_tokens: 12, total_tokens: 22 } + }; + const validJsonStr = JSON.stringify(validJsonPayload); + + // Mock server returns Content-Length: 5000, writes only ~250 bytes, then abruptly closes + const mockMismatchedServer = http.createServer((req, res) => { + res.writeHead(200, { + 'Content-Type': 'application/json', + 'Content-Length': '5000' // Inflated Content-Length + }); + res.write(validJsonStr); + // Abruptly destroy socket to trigger Content-Length mismatch on standard client + setTimeout(() => { + res.destroy(); + }, 50); + }); + await new Promise((resolve) => mockMismatchedServer.listen(0, resolve)); + const mismatchPort = (mockMismatchedServer.address() as any).port; + + // Create provider with the mock server URL + const p1 = configStore.saveProvider({ + name: 'Mismatched Content-Length Provider', + type: 'custom', + baseUrl: `http://localhost:${mismatchPort}`, + keys: ['mock-key-1'] + }); + createdProviderIds.push(p1.id); + + const m1 = configStore.saveCustomModel({ + name: 'model-mismatch-recovery', + tiers: [ + { + tierIndex: 0, + name: 'Tier 0', + targets: [{ providerId: p1.id, model: 'mismatch-model' }] + } + ] + }); + createdModelIds.push(m1.id); + + // Make non-streaming request to Revolver + const req1 = await fetch(`http://localhost:${PORT}/v1/chat/completions`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${API_KEY}` + }, + body: JSON.stringify({ + model: 'model-mismatch-recovery', + messages: [{ role: 'user', content: 'Test prompt' }], + stream: false + }) + }); + + assert.strictEqual(req1.status, 200, `Expected 200 OK, got ${req1.status}`); + const data1 = (await req1.json()) as any; + assert.strictEqual(data1.choices[0].message.content, 'Successfully parsed even with Content-Length header mismatch!'); + console.log(' โœ“ Revolver recovered full valid JSON payload despite upstream Content-Length mismatch.\n'); + + mockMismatchedServer.close(); + + // ========================================================================= + // Test 3: Non-Streaming: Failover to Candidate 2 when upstream terminates with truly corrupted/truncated JSON + // ========================================================================= + console.log('3. Testing Non-Streaming failover to Candidate 2 when Candidate 1 drops with truncated broken JSON...'); + + // Server 1 returns truncated broken JSON and closes socket + const mockCorruptedServer = http.createServer((req, res) => { + res.writeHead(200, { + 'Content-Type': 'application/json', + 'Content-Length': '500' + }); + res.write('{"choices": [{"message": {"content": "Truncated cut-off'); + setTimeout(() => { + res.destroy(); + }, 30); + }); + await new Promise((resolve) => mockCorruptedServer.listen(0, resolve)); + const corruptPort = (mockCorruptedServer.address() as any).port; + + // Server 2 returns valid 200 response + const mockHealthyServer = http.createServer((req, res) => { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ + id: 'chatcmpl-healthy-candidate', + object: 'chat.completion', + created: Math.floor(Date.now() / 1000), + model: 'healthy-model', + choices: [ + { + index: 0, + message: { role: 'assistant', content: 'Candidate 2 saved the day!' }, + finish_reason: 'stop' + } + ], + usage: { prompt_tokens: 5, completion_tokens: 8, total_tokens: 13 } + })); + }); + await new Promise((resolve) => mockHealthyServer.listen(0, resolve)); + const healthyPort = (mockHealthyServer.address() as any).port; + + const pCorrupt = configStore.saveProvider({ + name: 'Corrupted Provider', + type: 'custom', + baseUrl: `http://localhost:${corruptPort}`, + keys: ['corrupt-key'] + }); + createdProviderIds.push(pCorrupt.id); + + const pHealthy = configStore.saveProvider({ + name: 'Healthy Provider', + type: 'custom', + baseUrl: `http://localhost:${healthyPort}`, + keys: ['healthy-key'] + }); + createdProviderIds.push(pHealthy.id); + + const mFailover = configStore.saveCustomModel({ + name: 'model-failover-test', + tiers: [ + { + tierIndex: 0, + name: 'Tier 0', + targets: [ + { providerId: pCorrupt.id, model: 'corrupt-model' }, + { providerId: pHealthy.id, model: 'healthy-model' } + ] + } + ] + }); + createdModelIds.push(mFailover.id); + + const req2 = await fetch(`http://localhost:${PORT}/v1/chat/completions`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${API_KEY}` + }, + body: JSON.stringify({ + model: 'model-failover-test', + messages: [{ role: 'user', content: 'Failover please' }], + stream: false + }) + }); + + assert.strictEqual(req2.status, 200, `Expected 200 OK after failover, got ${req2.status}`); + const data2 = (await req2.json()) as any; + assert.strictEqual(data2.choices[0].message.content, 'Candidate 2 saved the day!'); + + // Verify Telemetry Tracker recorded candidate 1 failure and candidate 2 success + const latestJourneys = telemetryTracker.getRecentJourneys(1); + assert.strictEqual(latestJourneys.length, 1); + const j = latestJourneys[0]; + assert.strictEqual(j.finalStatus, 'success_fallback'); + assert.strictEqual(j.steps.length, 2); + assert.strictEqual(j.steps[0].status, 'server_error'); + assert.strictEqual(j.steps[1].status, 'success'); + console.log(' โœ“ Revolver detected socket truncation, marked candidate 1 with server_error, and served via candidate 2.\n'); + + mockCorruptedServer.close(); + mockHealthyServer.close(); + + // ========================================================================= + // Test 4: Streaming: Failover to Candidate 2 when Candidate 1 drops stream before first token + // ========================================================================= + console.log('4. Testing Streaming failover to Candidate 2 when Candidate 1 terminates stream prematurely...'); + + // Stream Server 1: Sends SSE 200 OK headers, but immediately destroys socket before data + const mockStreamCorrupt = http.createServer((req, res) => { + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + 'Connection': 'keep-alive' + }); + setTimeout(() => { + res.destroy(); + }, 30); + }); + await new Promise((resolve) => mockStreamCorrupt.listen(0, resolve)); + const streamCorruptPort = (mockStreamCorrupt.address() as any).port; + + // Stream Server 2: Sends proper SSE chunks and [DONE] + const mockStreamHealthy = http.createServer((req, res) => { + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + 'Connection': 'keep-alive' + }); + res.write(`data: ${JSON.stringify({ + id: 'chatcmpl-stream-healthy', + object: 'chat.completion.chunk', + created: Math.floor(Date.now() / 1000), + model: 'healthy-stream-model', + choices: [{ index: 0, delta: { content: 'Streaming seamless failover succeeded!' }, finish_reason: null }] + })}\n\n`); + res.write('data: [DONE]\n\n'); + res.end(); + }); + await new Promise((resolve) => mockStreamHealthy.listen(0, resolve)); + const streamHealthyPort = (mockStreamHealthy.address() as any).port; + + const pStreamCorrupt = configStore.saveProvider({ + name: 'Stream Corrupt Provider', + type: 'custom', + baseUrl: `http://localhost:${streamCorruptPort}`, + keys: ['stream-key-1'] + }); + createdProviderIds.push(pStreamCorrupt.id); + + const pStreamHealthy = configStore.saveProvider({ + name: 'Stream Healthy Provider', + type: 'custom', + baseUrl: `http://localhost:${streamHealthyPort}`, + keys: ['stream-key-2'] + }); + createdProviderIds.push(pStreamHealthy.id); + + const mStreamFailover = configStore.saveCustomModel({ + name: 'model-stream-failover-test', + tiers: [ + { + tierIndex: 0, + name: 'Tier 0', + targets: [ + { providerId: pStreamCorrupt.id, model: 'corrupt-stream' }, + { providerId: pStreamHealthy.id, model: 'healthy-stream' } + ] + } + ] + }); + createdModelIds.push(mStreamFailover.id); + + const req3 = await fetch(`http://localhost:${PORT}/v1/chat/completions`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${API_KEY}` + }, + body: JSON.stringify({ + model: 'model-stream-failover-test', + messages: [{ role: 'user', content: 'Stream failover please' }], + stream: true + }) + }); + + assert.strictEqual(req3.status, 200, `Expected 200 OK for stream, got ${req3.status}`); + const streamBody = await req3.text(); + assert.ok(streamBody.includes('Streaming seamless failover succeeded!'), 'Stream body must contain content from Candidate 2'); + assert.ok(streamBody.includes('[DONE]'), 'Stream body must end with [DONE]'); + console.log(' โœ“ Revolver caught stream drop on candidate 1 and cleanly streamed candidate 2 to client.\n'); + + mockStreamCorrupt.close(); + mockStreamHealthy.close(); + + // ========================================================================= + // Test 5: Verify Cache-Control: no-cache, no-transform header is sent downstream + // ========================================================================= + console.log('5. Testing downstream Cache-Control: no-cache, no-transform headers...'); + const cacheHeader = req1.headers.get('cache-control'); + assert.ok(cacheHeader && cacheHeader.includes('no-transform'), 'Downstream response must include no-transform to prevent proxy compression mismatches'); + console.log(' โœ“ Cache-Control: no-cache, no-transform verified on downstream responses.\n'); + + console.log('๐ŸŽ‰ ALL CONTENT-LENGTH RESILIENCE & FAILOVER TESTS PASSED SUCCESSFULLY!\n'); + + } finally { + for (const mId of createdModelIds) { + try { configStore.deleteCustomModel(mId); } catch {} + } + for (const pId of createdProviderIds) { + try { configStore.deleteProvider(pId); } catch {} + } + server.close(); + } +} + +runTests().catch((err) => { + console.error('โŒ Test suite failed:', err); + process.exit(1); +}); From 680c080c78d0817df3f4b39cdc595722bbae0c6b Mon Sep 17 00:00:00 2001 From: tyuXX Date: Wed, 4 Nov 2026 20:33:13 +0000 Subject: [PATCH 2/3] fix(liveWatcher): ensure idempotency on cancelRequest and detailed error reporting --- src/liveWatcher.ts | 4 ++-- src/revolverEngine.ts | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/liveWatcher.ts b/src/liveWatcher.ts index c3f6619..3139731 100644 --- a/src/liveWatcher.ts +++ b/src/liveWatcher.ts @@ -391,7 +391,7 @@ export class LiveWatcher { }): void { if (!this.isWatcherActive) return; const entry = this.buffer.find(e => e.id === params.requestId); - if (!entry) return; + if (!entry || (entry.endTime !== undefined && entry.status === 'completed')) return; entry.endTime = Date.now(); entry.durationMs = entry.endTime - entry.startTime; @@ -426,7 +426,7 @@ export class LiveWatcher { public cancelRequest(requestId: string): void { if (!this.isWatcherActive) return; const entry = this.buffer.find(e => e.id === requestId); - if (!entry) return; + if (!entry || entry.endTime !== undefined) return; entry.endTime = Date.now(); entry.durationMs = entry.endTime - entry.startTime; diff --git a/src/revolverEngine.ts b/src/revolverEngine.ts index 2af74c6..ddc9525 100644 --- a/src/revolverEngine.ts +++ b/src/revolverEngine.ts @@ -627,7 +627,9 @@ export class RevolverEngine { // If we reached here, all tiers and all candidates failed cleanupTimers(); if (onFailure) onFailure('all_tiers_exhausted'); - const finalErrorMessage = lastError ? lastError.message : 'All model tiers and provider keys are exhausted or rate-limited.'; + const finalErrorMessage = lastError?.cause?.message + ? `${lastError.message}: ${lastError.cause.message}` + : (lastError ? lastError.message : 'All model tiers and provider keys are exhausted or rate-limited.'); const journey: RequestFallbackJourney = { requestId, @@ -673,6 +675,7 @@ export class RevolverEngine { })); res.end(); } else { + res.setHeader('Cache-Control', 'no-cache, no-transform'); res.status(503).json({ error: { message: `[Revolver Fallback Error]: ${finalErrorMessage}`, From 4434d308d65faa8cf2de05d5350c5ddbbe574931 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Wed, 4 Nov 2026 20:44:57 +0000 Subject: [PATCH 3/3] feat(revolver): add model circuit breaker and zero-tolerance 503 fast-failover - Implement ModelCircuitBreaker to track (provider, model) overload states independently of API keys - Skip remaining keys in active tier immediately on 503 Service Unavailable / High Demand - Protect key quotas by preventing 503 errors from marking keys as rate-limited - Add 15s streaming TTFT timeout and reduce candidate timeout to 20s - Add Model Circuit Breaker live telemetry and manual reset in Admin Console - Add comprehensive automated test suite for circuit breaker and failover cascades --- .env.example | 13 +- package.json | 2 +- src/adminRoutes.ts | 23 +- src/adminView.ts | 55 ++++- src/config.ts | 6 +- src/modelCircuitBreaker.ts | 238 ++++++++++++++++++++ src/revolverEngine.ts | 301 +++++++++++++++++++------ src/telemetryTracker.ts | 3 + test-circuit-breaker-fallback.ts | 362 +++++++++++++++++++++++++++++++ 9 files changed, 931 insertions(+), 72 deletions(-) create mode 100644 src/modelCircuitBreaker.ts create mode 100644 test-circuit-breaker-fallback.ts diff --git a/.env.example b/.env.example index 9e081e3..675f9cd 100644 --- a/.env.example +++ b/.env.example @@ -24,8 +24,17 @@ RATE_LIMIT_DURATION_MS=60000 # ENABLE_NON_STREAMING_KEEPALIVE=true # NON_STREAMING_KEEPALIVE_DELAY_MS=20000 -# Candidate timeout per provider attempt before rotating (in ms) -# CANDIDATE_TIMEOUT_MS=60000 +# Candidate timeout per provider attempt before rotating (in ms, default 20s) +# CANDIDATE_TIMEOUT_MS=20000 + +# Streaming Time-To-First-Token (TTFT) timeout before failover (in ms, default 15s) +# STREAM_FIRST_TOKEN_TIMEOUT_MS=15000 + +# Model circuit breaker cooldown duration on 503 / high demand (in ms, default 60s) +# MODEL_COOLDOWN_MS=60000 + +# Max consecutive timeouts per model target before tripping circuit breaker (default 0 when fallback tier exists) +# MAX_TARGET_TIMEOUT_RETRIES=0 # Cloudflare Tunnel configuration (for Docker deployment) # Get your tunnel token from: https://dash.cloudflare.com/ diff --git a/package.json b/package.json index 8127935..a2ca005 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "start": "node dist/index.js", "dev": "ts-node src/index.ts", "watch": "tsc --watch", - "test": "API_PASSWORD=test_password ts-node test-revolver.ts && API_PASSWORD=test_password ts-node test-integration.ts && API_PASSWORD=test_password ts-node test-timeout-keepalive.ts && API_PASSWORD=test_password ts-node test-live-watcher.ts && API_PASSWORD=test_password ts-node test-telemetry-fallback.ts" + "test": "API_PASSWORD=test_password ts-node test-revolver.ts && API_PASSWORD=test_password ts-node test-integration.ts && API_PASSWORD=test_password ts-node test-timeout-keepalive.ts && API_PASSWORD=test_password ts-node test-live-watcher.ts && API_PASSWORD=test_password ts-node test-telemetry-fallback.ts && API_PASSWORD=test_password ts-node test-circuit-breaker-fallback.ts" }, "keywords": ["openai", "gemini", "api", "rotation"], "author": "", diff --git a/src/adminRoutes.ts b/src/adminRoutes.ts index 4096ff2..464d7d6 100644 --- a/src/adminRoutes.ts +++ b/src/adminRoutes.ts @@ -4,6 +4,7 @@ import { revolverEngine } from './revolverEngine'; import { ProviderType } from './revolverTypes'; import { liveWatcher } from './liveWatcher'; import { telemetryTracker } from './telemetryTracker'; +import { modelCircuitBreaker } from './modelCircuitBreaker'; const router = Router(); @@ -186,7 +187,11 @@ router.get('/keys-status', (req: Request, res: Response) => { }) })); - res.json({ providers: status, timestamp: new Date().toISOString() }); + res.json({ + providers: status, + circuitBreakers: modelCircuitBreaker.getStatuses(), + timestamp: new Date().toISOString() + }); }); // GET /api/admin/live-logs/state @@ -230,7 +235,21 @@ router.get('/telemetry/fallback-traces', (req: Request, res: Response) => { const limit = req.query.limit ? parseInt(req.query.limit as string, 10) : 50; res.json({ journeys: telemetryTracker.getRecentJourneys(limit), - keys: telemetryTracker.getKeyTelemetry() + keys: telemetryTracker.getKeyTelemetry(), + circuitBreakers: modelCircuitBreaker.getStatuses() + }); +}); + +// POST /api/admin/circuit-breaker/reset +router.post('/circuit-breaker/reset', (req: Request, res: Response) => { + const { providerId, model } = req.body || {}; + modelCircuitBreaker.reset(providerId, model); + telemetryTracker.broadcastKeyStatus(); + res.json({ + success: true, + message: providerId && model + ? `Circuit breaker for ${providerId} / ${model} reset successfully.` + : 'All model circuit breakers reset successfully.' }); }); diff --git a/src/adminView.ts b/src/adminView.ts index f1f1569..891f09a 100644 --- a/src/adminView.ts +++ b/src/adminView.ts @@ -2017,7 +2017,7 @@ export function renderAdminHtml(): string { const data = await res.json(); cachedKeys = data.keys || []; cachedJourneys = data.journeys || []; - renderTelemetryKeys(cachedKeys); + renderTelemetryKeys(cachedKeys, data.circuitBreakers); renderTelemetryJourneys(cachedJourneys); } catch (err) { showToast('Telemetry load failed: ' + err.message, 'error'); @@ -2043,11 +2043,11 @@ export function renderAdminHtml(): string { if (msg.type === 'snapshot') { cachedKeys = msg.keys || []; cachedJourneys = msg.journeys || []; - renderTelemetryKeys(cachedKeys); + renderTelemetryKeys(cachedKeys, msg.circuitBreakers); renderTelemetryJourneys(cachedJourneys); } else if (msg.type === 'key_status_update') { cachedKeys = msg.keys || []; - renderTelemetryKeys(cachedKeys); + renderTelemetryKeys(cachedKeys, msg.circuitBreakers); } else if (msg.type === 'fallback_journey') { cachedJourneys.unshift(msg.data); if (cachedJourneys.length > 50) cachedJourneys.length = 50; @@ -2070,11 +2070,58 @@ export function renderAdminHtml(): string { } } - function renderTelemetryKeys(keys) { + function renderTelemetryKeys(keys, circuitBreakers) { const container = document.getElementById('telemetry-list'); if (!container) return; container.innerHTML = ''; + if (circuitBreakers && circuitBreakers.length > 0) { + const cbCard = document.createElement('div'); + cbCard.className = 'card'; + cbCard.style.borderColor = 'rgba(255, 183, 77, 0.4)'; + + let cbRows = ''; + circuitBreakers.forEach(cb => { + const inCooldown = cb.status === 'cooldown'; + const badge = inCooldown + ? ' Cooldown (' + cb.cooldownRemainingSeconds + 's remaining)' + : (cb.status === 'half_open' + ? ' Probing (Half-Open)' + : ' Healthy'); + + cbRows += '
' + + '
' + + '' + escapeHtml(cb.model) + ' (' + escapeHtml(cb.providerId) + ')' + + (cb.lastError ? '
' + escapeHtml(cb.lastError) + '
' : '') + + '
' + + '
' + badge + '
' + + '
'; + }); + + cbCard.innerHTML = '
' + + ' Model Circuit Breakers (Overload Protection)' + + '' + + '
' + + '
' + cbRows + '
'; + + container.appendChild(cbCard); + + const resetBtn = cbCard.querySelector('#reset-cb-btn'); + if (resetBtn) { + resetBtn.onclick = async function() { + try { + const res = await apiRequest('/api/admin/circuit-breaker/reset', { method: 'POST' }); + if (res.ok) { + showToast('Circuit breakers reset successfully.', 'success'); + loadTelemetry(); + } + } catch (err) { + showToast('Failed to reset circuit breakers: ' + err.message, 'error'); + } + }; + } + } + if (!keys || keys.length === 0) { container.innerHTML = '

No provider keys configured.

'; return; diff --git a/src/config.ts b/src/config.ts index 95f9c3b..9d3f766 100644 --- a/src/config.ts +++ b/src/config.ts @@ -15,7 +15,11 @@ export const config = { keepAliveIntervalMs: parseInt(process.env.KEEPALIVE_INTERVAL_MS || '15000', 10), enableNonStreamingKeepAlive: process.env.ENABLE_NON_STREAMING_KEEPALIVE !== 'false', nonStreamingKeepAliveDelayMs: parseInt(process.env.NON_STREAMING_KEEPALIVE_DELAY_MS || '20000', 10), - candidateTimeoutMs: parseInt(process.env.CANDIDATE_TIMEOUT_MS || '60000', 10) + candidateTimeoutMs: parseInt(process.env.CANDIDATE_TIMEOUT_MS || '20000', 10), + // Model Overload & Fast-Failover Circuit Breaker settings + streamFirstTokenTimeoutMs: parseInt(process.env.STREAM_FIRST_TOKEN_TIMEOUT_MS || '15000', 10), + modelCooldownDurationMs: parseInt(process.env.MODEL_COOLDOWN_MS || '60000', 10), + maxTargetTimeoutRetries: parseInt(process.env.MAX_TARGET_TIMEOUT_RETRIES || '0', 10) }; if (!config.apiPassword) { diff --git a/src/modelCircuitBreaker.ts b/src/modelCircuitBreaker.ts new file mode 100644 index 0000000..dc183a8 --- /dev/null +++ b/src/modelCircuitBreaker.ts @@ -0,0 +1,238 @@ +import { config } from './config'; + +export interface ModelTargetHealthStatus { + targetKey: string; // `${providerId}:::${model}` + providerId: string; + model: string; + status: 'healthy' | 'cooldown' | 'half_open'; + consecutiveFailures: number; + cooldownUntil: number | null; + cooldownRemainingSeconds: number; + lastError: string | null; + lastFailedAt: string | null; + lastSuccessAt: string | null; +} + +interface TargetHealthInternal { + providerId: string; + model: string; + status: 'healthy' | 'cooldown' | 'half_open'; + consecutiveFailures: number; + consecutiveTimeouts: number; + cooldownUntil: number | null; + lastError: string | null; + lastFailedAt: number | null; + lastSuccessAt: number | null; + probeInFlight: boolean; + probeStartedAt: number | null; +} + +export class ModelCircuitBreaker { + private targets: Map = new Map(); + + private getTargetKey(providerId: string, model: string): string { + return `${providerId}:::${model}`; + } + + private getOrCreate(providerId: string, model: string): TargetHealthInternal { + const key = this.getTargetKey(providerId, model); + let target = this.targets.get(key); + if (!target) { + target = { + providerId, + model, + status: 'healthy', + consecutiveFailures: 0, + consecutiveTimeouts: 0, + cooldownUntil: null, + lastError: null, + lastFailedAt: null, + lastSuccessAt: null, + probeInFlight: false, + probeStartedAt: null + }; + this.targets.set(key, target); + } + return target; + } + + /** + * Checks if a target is eligible to receive candidate traffic. + * If in cooldown and the cooldown period has expired, transitions to half_open for a probe attempt. + */ + public isTargetAvailable(providerId: string, model: string): boolean { + const target = this.getOrCreate(providerId, model); + const now = Date.now(); + + if (target.status === 'healthy') { + return true; + } + + if (target.status === 'cooldown') { + if (target.cooldownUntil && now >= target.cooldownUntil) { + // Cooldown has expired: allow 1 half_open probe request + target.status = 'half_open'; + target.probeInFlight = true; + target.probeStartedAt = now; + return true; + } + return false; + } + + if (target.status === 'half_open') { + // In half_open state, allow 1 probe through (auto-expire stale probes after candidateTimeoutMs) + if (!target.probeInFlight || (target.probeStartedAt && now - target.probeStartedAt > config.candidateTimeoutMs)) { + target.probeInFlight = true; + target.probeStartedAt = now; + return true; + } + return false; + } + + return true; + } + + /** + * Determines if an error represents model-level overload, service unavailable, + * capacity limits, or non-existent model (as opposed to an API key quota exhaustion). + */ + public isModelOverloadOrUnavailable(error: any): boolean { + if (!error) return false; + const status = error?.status || error?.statusCode || error?.code; + const msg = (error?.message || '').toLowerCase(); + + // 503 Service Unavailable / Model High Demand + if (status === 503 || status === '503') return true; + + // 404 Model Not Found + if (status === 404 || status === '404') return true; + + // Check message markers + if ( + msg.includes('high demand') || + msg.includes('is overloaded') || + msg.includes('model overloaded') || + msg.includes('service unavailable') || + msg.includes('capacity') || + msg.includes('resource temporarily unavailable') || + msg.includes('model not found') || + msg.includes('does not exist') + ) { + return true; + } + + return false; + } + + /** + * Record a model target failure. + * If error is 503 or model overload, trips immediately into cooldown. + * If timeout, increments consecutive timeouts and trips if threshold reached. + */ + public recordFailure( + providerId: string, + model: string, + error: any, + isTimeout = false + ): { tripped: boolean; cooldownSeconds: number; reason: string } { + const target = this.getOrCreate(providerId, model); + const now = Date.now(); + target.consecutiveFailures++; + target.lastFailedAt = now; + target.probeInFlight = false; + target.lastError = error?.message || (isTimeout ? 'Timeout / Aborted' : 'Unknown error'); + + if (isTimeout) { + target.consecutiveTimeouts++; + } + + const isOverload = this.isModelOverloadOrUnavailable(error); + const timeoutThreshold = config.maxTargetTimeoutRetries === 0 ? 1 : config.maxTargetTimeoutRetries + 1; + const isConsecutiveTimeoutTrip = isTimeout && target.consecutiveTimeouts >= timeoutThreshold; + + if (isOverload || isConsecutiveTimeoutTrip || target.status === 'half_open') { + const cooldownMs = config.modelCooldownDurationMs; + target.status = 'cooldown'; + target.cooldownUntil = now + cooldownMs; + + const reason = isOverload + ? `Model overload/unavailable (${error?.status || 503}): ${error?.message || 'High demand'}` + : `Target exceeded timeout threshold (${target.consecutiveTimeouts} timeouts)`; + + console.warn(`[CIRCUIT_BREAKER] Tripped cooldown for ${providerId} / ${model} for ${Math.ceil(cooldownMs / 1000)}s: ${reason}`); + + return { + tripped: true, + cooldownSeconds: Math.ceil(cooldownMs / 1000), + reason + }; + } + + return { + tripped: false, + cooldownSeconds: 0, + reason: '' + }; + } + + /** + * Record a model target success. + * Closes circuit breaker and restores healthy status. + */ + public recordSuccess(providerId: string, model: string): void { + const target = this.getOrCreate(providerId, model); + target.status = 'healthy'; + target.consecutiveFailures = 0; + target.consecutiveTimeouts = 0; + target.cooldownUntil = null; + target.lastError = null; + target.lastSuccessAt = Date.now(); + target.probeInFlight = false; + } + + /** + * Return telemetry status of all monitored model targets. + */ + public getStatuses(): ModelTargetHealthStatus[] { + const now = Date.now(); + const result: ModelTargetHealthStatus[] = []; + + this.targets.forEach((target, key) => { + let cooldownRemainingSeconds = 0; + if (target.status === 'cooldown' && target.cooldownUntil) { + if (now < target.cooldownUntil) { + cooldownRemainingSeconds = Math.ceil((target.cooldownUntil - now) / 1000); + } + } + + result.push({ + targetKey: key, + providerId: target.providerId, + model: target.model, + status: target.status, + consecutiveFailures: target.consecutiveFailures, + cooldownUntil: target.cooldownUntil, + cooldownRemainingSeconds, + lastError: target.lastError, + lastFailedAt: target.lastFailedAt ? new Date(target.lastFailedAt).toISOString() : null, + lastSuccessAt: target.lastSuccessAt ? new Date(target.lastSuccessAt).toISOString() : null + }); + }); + + return result; + } + + /** + * Reset target circuit breaker (or all targets if omitted). + */ + public reset(providerId?: string, model?: string): void { + if (providerId && model) { + const key = this.getTargetKey(providerId, model); + this.targets.delete(key); + } else { + this.targets.clear(); + } + } +} + +export const modelCircuitBreaker = new ModelCircuitBreaker(); diff --git a/src/revolverEngine.ts b/src/revolverEngine.ts index ad93eb4..59f0f41 100644 --- a/src/revolverEngine.ts +++ b/src/revolverEngine.ts @@ -13,6 +13,7 @@ import { import { OpenAIChatRequest, OpenAIChatResponse } from './openaiTypes'; import { telemetryTracker, FallbackStep, RequestFallbackJourney } from './telemetryTracker'; import { liveWatcher } from './liveWatcher'; +import { modelCircuitBreaker } from './modelCircuitBreaker'; interface CandidateExecution { tier: FallbackTier; @@ -79,10 +80,15 @@ export class RevolverEngine { return Date.now() < keyConfig.rateLimitedUntil; } - private getCandidatesForTier(tier: FallbackTier, modelId: string): CandidateExecution[] { + public getCandidatesForTier(tier: FallbackTier, modelId: string, allowCooldownProbes = false): CandidateExecution[] { const candidates: CandidateExecution[] = []; for (const target of tier.targets) { + if (!allowCooldownProbes && !modelCircuitBreaker.isTargetAvailable(target.providerId, target.model)) { + console.warn(`[REVOLVER] Target '${target.providerId}' / '${target.model}' is in circuit-breaker cooldown. Skipping.`); + continue; + } + const provider = this.store.getProviderById(target.providerId); if (!provider || provider.keys.length === 0) continue; @@ -208,6 +214,22 @@ export class RevolverEngine { ); } + private isTimeoutError(error: any): boolean { + if (!error) return false; + const msg = (error?.message || '').toLowerCase(); + const name = error?.name || ''; + const code = error?.code || ''; + return ( + name === 'AbortError' || + name === 'TimeoutError' || + code === 'ETIMEDOUT' || + code === 'ESOCKETTIMEDOUT' || + msg.includes('aborted') || + msg.includes('timed out') || + msg.includes('timeout') + ); + } + public async executeChatCompletion(params: { requestBody: OpenAIChatRequest; requestId: string; @@ -303,9 +325,20 @@ export class RevolverEngine { let totalHops = 0; let lastError: any = null; + // Check if any healthy candidates exist across all tiers (or if all targets are in cooldown) + let hasAvailableCandidateAcrossTiers = false; + for (const t of sortedTiers) { + if (this.getCandidatesForTier(t, customModel.id, false).length > 0) { + hasAvailableCandidateAcrossTiers = true; + break; + } + } + const allowProbes = !hasAvailableCandidateAcrossTiers; + // Traverse tiers: Tier 0 -> Tier 1 -> Tier 2... - for (const tier of sortedTiers) { - const candidates = this.getCandidatesForTier(tier, customModel.id); + for (let tIdx = 0; tIdx < sortedTiers.length; tIdx++) { + const tier = sortedTiers[tIdx]; + let candidates = this.getCandidatesForTier(tier, customModel.id, allowProbes); if (candidates.length === 0) { console.warn(`[REVOLVER] No candidates found in Tier ${tier.tierIndex} ('${tier.name || 'Tier ' + tier.tierIndex}') for model '${customModel.name}'. Skipping tier.`); continue; @@ -314,7 +347,8 @@ export class RevolverEngine { console.log(`[REVOLVER] Attempting Tier ${tier.tierIndex} ('${tier.name || 'Tier ' + tier.tierIndex}') with ${candidates.length} candidate(s)...`); // Try candidates in this tier - for (const candidate of candidates) { + for (let cIdx = 0; cIdx < candidates.length; cIdx++) { + const candidate = candidates[cIdx]; if (isCancelled || res.destroyed) { cleanupTimers(); return; @@ -322,8 +356,7 @@ export class RevolverEngine { const candidateStart = Date.now(); totalHops++; - const isLastCandidateInTier = candidate === candidates[candidates.length - 1]; - const isLastTier = tier === sortedTiers[sortedTiers.length - 1]; + const isLastTier = tIdx === sortedTiers.length - 1; try { console.log(`[REVOLVER] Routing to Provider '${candidate.provider.name}' (${candidate.provider.type}) with model '${candidate.target.model}' [Key ${candidate.keyIndex + 1}/${candidate.provider.keys.length}]`); @@ -342,6 +375,9 @@ export class RevolverEngine { }); cleanupTimers(); + // Record success on circuit breaker to keep target marked healthy + modelCircuitBreaker.recordSuccess(candidate.provider.id, candidate.target.model); + const stepDuration = Date.now() - candidateStart; const successStep: FallbackStep = { stepIndex: totalHops, @@ -411,7 +447,8 @@ export class RevolverEngine { cleanupTimers(); if (isCancelled || res.destroyed) return; - // Success! Update stats + // Success! Update stats and reset model circuit breaker + modelCircuitBreaker.recordSuccess(candidate.provider.id, candidate.target.model); this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { incrementCount: true, rateLimitedUntil: null @@ -496,18 +533,62 @@ export class RevolverEngine { const stepDuration = Date.now() - candidateStart; const isRateLimit = this.isRateLimitOrQuotaError(err); const isServerErr = this.isServerError(err); - const cooldown = isRateLimit ? config.rateLimitDurationMs : (isServerErr ? 15000 : undefined); - const statusType = isRateLimit ? 'rate_limited' : (isServerErr ? 'server_error' : 'failed'); + const isTimeout = this.isTimeoutError(err); + const isModelOverload = modelCircuitBreaker.isModelOverloadOrUnavailable(err); + + let tripResult = { tripped: false, cooldownSeconds: 0, reason: '' }; + if (isModelOverload || isTimeout) { + tripResult = modelCircuitBreaker.recordFailure(candidate.provider.id, candidate.target.model, err, isTimeout); + } + + // Zero-tolerance policy: skip remaining keys for this target immediately on 503/overload or timeout + const shouldFastFailTarget = isModelOverload || (isTimeout && config.maxTargetTimeoutRetries === 0) || tripResult.tripped; + + let skippedRemainingCount = 0; + if (shouldFastFailTarget) { + skippedRemainingCount = candidates.slice(cIdx + 1).filter(c => + c.target.providerId === candidate.target.providerId && c.target.model === candidate.target.model + ).length; + + if (skippedRemainingCount > 0) { + console.warn(`[REVOLVER] Fast-failover on '${candidate.target.model}'. Skipping ${skippedRemainingCount} remaining key(s) for this target in Tier ${tier.tierIndex}.`); + candidates = candidates.filter((c, idx) => + idx <= cIdx || c.target.providerId !== candidate.target.providerId || c.target.model !== candidate.target.model + ); + } + } + + const isLastCandidateInTier = cIdx >= candidates.length - 1; + const nextTier = !isLastTier ? sortedTiers[tIdx + 1] : null; let nextAction = ''; - if (!isLastCandidateInTier) { - nextAction = `Rotating to next key in Tier ${tier.tierIndex}`; - } else if (!isLastTier) { - nextAction = `Tier ${tier.tierIndex} exhausted. Cascading to Fallback Tier ${sortedTiers[sortedTiers.indexOf(tier) + 1]?.tierIndex ?? 'next'}`; + if (shouldFastFailTarget) { + const skipNote = skippedRemainingCount > 0 + ? `skipped ${skippedRemainingCount} remaining key(s) for ${candidate.target.model}` + : `for ${candidate.target.model}`; + if (!isLastCandidateInTier) { + const nextTargetName = candidates[cIdx + 1]?.target.model || 'next target'; + nextAction = `${isModelOverload ? 'Model overloaded (503)' : 'Target timeout'} โ€” ${skipNote}. Trying alternative target in Tier ${tier.tierIndex} (${nextTargetName})`; + } else if (nextTier) { + nextAction = `${isModelOverload ? 'Model overloaded (503)' : 'Target timeout'} โ€” ${skipNote}. Cascading to Fallback Tier ${nextTier.tierIndex} (${nextTier.name || 'Tier ' + nextTier.tierIndex})`; + } else { + nextAction = `${isModelOverload ? 'Model overloaded (503)' : 'Target timeout'} โ€” all tiers and candidates exhausted`; + } } else { - nextAction = 'All tiers and candidates exhausted'; + if (!isLastCandidateInTier) { + nextAction = `Rotating to next key in Tier ${tier.tierIndex}`; + } else if (nextTier) { + nextAction = `Tier ${tier.tierIndex} exhausted. Cascading to Fallback Tier ${nextTier.tierIndex} (${nextTier.name || 'Tier ' + nextTier.tierIndex})`; + } else { + nextAction = 'All tiers and candidates exhausted'; + } } + const statusType = isRateLimit ? 'rate_limited' : (isTimeout ? 'timeout' : (isServerErr ? 'server_error' : 'failed')); + const cooldownSecs = tripResult.tripped + ? tripResult.cooldownSeconds + : (isRateLimit ? Math.ceil(config.rateLimitDurationMs / 1000) : undefined); + const failedStep: FallbackStep = { stepIndex: totalHops, timestamp: new Date().toISOString(), @@ -521,10 +602,10 @@ export class RevolverEngine { maskedKey: this.store.maskKey(candidate.keyConfig.key), durationMs: stepDuration, status: statusType, - statusCode: err.status || (isRateLimit ? 429 : 500), + statusCode: err.status || (isRateLimit ? 429 : (isTimeout ? 504 : 500)), errorMessage: err.message, - rateLimitedUntil: cooldown ? Date.now() + cooldown : null, - cooldownSeconds: cooldown ? Math.ceil(cooldown / 1000) : undefined, + rateLimitedUntil: isRateLimit ? Date.now() + config.rateLimitDurationMs : null, + cooldownSeconds: cooldownSecs, nextAction }; fallbackSteps.push(failedStep); @@ -568,11 +649,12 @@ export class RevolverEngine { throw err; } - // Mark key rate limited or increment error - if (isRateLimit || isServerErr) { - console.warn(`[REVOLVER] Marking key ${this.store.maskKey(candidate.keyConfig.key)} rate-limited for ${cooldown! / 1000}s`); + // Update Key Stats: ONLY mark rateLimitedUntil if isRateLimit is true (429)! + // Model-level overloads/timeouts do NOT penalize individual key quota. + if (isRateLimit) { + console.warn(`[REVOLVER] Marking key ${this.store.maskKey(candidate.keyConfig.key)} rate-limited for ${config.rateLimitDurationMs / 1000}s`); this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { - rateLimitedUntil: Date.now() + cooldown!, + rateLimitedUntil: Date.now() + config.rateLimitDurationMs, incrementError: true }); } else { @@ -853,6 +935,35 @@ export class RevolverEngine { // Start streaming from Gemini const result = await chat.sendMessageStream(lastMessage.parts[0].text); + let fullContent = ''; + let promptTokens = 0; + let completionTokens = 0; + + const streamIterator = result.stream[Symbol.asyncIterator](); + + // TTFT Timeout: Wait for first chunk within streamFirstTokenTimeoutMs + let firstResult: IteratorResult; + let ttftTimer: NodeJS.Timeout | null = null; + const ttftPromise = new Promise((_, reject) => { + ttftTimer = setTimeout(() => { + const timeoutErr = new Error(`Streaming TTFT timeout: no tokens received within ${config.streamFirstTokenTimeoutMs}ms`); + (timeoutErr as any).name = 'TimeoutError'; + reject(timeoutErr); + }, config.streamFirstTokenTimeoutMs); + }); + + try { + firstResult = await Promise.race([ + streamIterator.next(), + ttftPromise + ]); + } finally { + if (ttftTimer) { + clearTimeout(ttftTimer); + ttftTimer = null; + } + } + // If headers haven't been committed, commit them now if (!res.headersSent) { res.setHeader('Content-Type', 'text/event-stream; charset=utf-8'); @@ -864,13 +975,35 @@ export class RevolverEngine { } } - let fullContent = ''; - let promptTokens = 0; - let completionTokens = 0; + if (!firstResult.done && firstResult.value) { + const text = firstResult.value.text(); + fullContent += text; + liveWatcher.appendStreamChunk(requestId, text); + onStreamStart(); - for await (const chunk of result.stream) { + const chunkResponse = { + id: `chatcmpl-${requestId}`, + object: 'chat.completion.chunk', + created: Math.floor(Date.now() / 1000), + model: requestedModelName, + choices: [ + { + index: 0, + delta: { content: text }, + finish_reason: null + } + ] + }; + + res.write(`data: ${JSON.stringify(chunkResponse)}\n\n`); + } + + while (true) { if (res.destroyed) break; - const text = chunk.text(); + const { done, value } = await streamIterator.next(); + if (done) break; + + const text = value.text(); fullContent += text; liveWatcher.appendStreamChunk(requestId, text); onStreamStart(); @@ -1000,57 +1133,89 @@ export class RevolverEngine { const decoder = new TextDecoder(); let buffer = ''; let totalOutputChars = 0; + let streamHasStarted = false; - try { - while (true) { - if (res.destroyed) break; - const { done, value } = await reader.read(); - if (done) break; + const processText = (textChunk: string) => { + buffer += textChunk; + const lines = buffer.split('\n'); + buffer = lines.pop() || ''; - const text = decoder.decode(value, { stream: true }); - buffer += text; + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed) { + res.write('\n'); + continue; + } - const lines = buffer.split('\n'); - buffer = lines.pop() || ''; - - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed) { - res.write('\n'); + if (trimmed.startsWith('data: ')) { + const dataStr = trimmed.slice(6); + if (dataStr === '[DONE]') { + res.write('data: [DONE]\n\n'); continue; } - if (trimmed.startsWith('data: ')) { - const dataStr = trimmed.slice(6); - if (dataStr === '[DONE]') { - res.write('data: [DONE]\n\n'); - continue; + try { + const parsed = JSON.parse(dataStr); + parsed.model = requestedModelName; + if (parsed.choices?.[0]?.delta?.content) { + onStreamStart(); + streamHasStarted = true; + const delta = parsed.choices[0].delta.content; + totalOutputChars += delta.length; + liveWatcher.appendStreamChunk(requestId, delta); } - - try { - const parsed = JSON.parse(dataStr); - parsed.model = requestedModelName; - if (parsed.choices?.[0]?.delta?.content) { - onStreamStart(); - const delta = parsed.choices[0].delta.content; - totalOutputChars += delta.length; - liveWatcher.appendStreamChunk(requestId, delta); - } - res.write(`data: ${JSON.stringify(parsed)}\n\n`); - } catch { - res.write(`${line}\n`); - } - } else { + res.write(`data: ${JSON.stringify(parsed)}\n\n`); + } catch { res.write(`${line}\n`); } + } else { + res.write(`${line}\n`); } } + }; + + // TTFT Timeout: Wait for first chunk within streamFirstTokenTimeoutMs + let ttftTimer: NodeJS.Timeout | null = null; + const ttftPromise = new Promise((_, reject) => { + ttftTimer = setTimeout(() => { + try { reader.cancel(); } catch {} + const timeoutErr = new Error(`Streaming TTFT timeout: no tokens received within ${config.streamFirstTokenTimeoutMs}ms`); + (timeoutErr as any).name = 'TimeoutError'; + reject(timeoutErr); + }, config.streamFirstTokenTimeoutMs); + }); + + let firstReadResult: { done?: boolean; value?: Uint8Array }; + try { + firstReadResult = await Promise.race([ + reader.read(), + ttftPromise + ]); } finally { - if (!res.destroyed) { - res.end(); + if (ttftTimer) { + clearTimeout(ttftTimer); + ttftTimer = null; } } + if (!firstReadResult.done && firstReadResult.value) { + const text = decoder.decode(firstReadResult.value, { stream: true }); + processText(text); + } + + while (true) { + if (res.destroyed) break; + const { done, value } = await reader.read(); + if (done) break; + + const text = decoder.decode(value, { stream: true }); + processText(text); + } + + if (!res.destroyed) { + res.end(); + } + const estimatedInput = Math.ceil(JSON.stringify(requestBody.messages).length / 4); const estimatedOutput = Math.ceil(totalOutputChars / 4); @@ -1119,6 +1284,7 @@ export class RevolverEngine { const content = resp.choices?.[0]?.message?.content || ''; const duration = Date.now() - candidateStart; + modelCircuitBreaker.recordSuccess(candidate.provider.id, candidate.target.model); this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { incrementCount: true, rateLimitedUntil: null @@ -1145,11 +1311,22 @@ export class RevolverEngine { } catch (err: any) { lastError = err; const isRateLimit = this.isRateLimitOrQuotaError(err); + const isOverload = modelCircuitBreaker.isModelOverloadOrUnavailable(err); + const isTimeout = this.isTimeoutError(err); + + if (isOverload || isTimeout) { + modelCircuitBreaker.recordFailure(candidate.provider.id, candidate.target.model, err, isTimeout); + } + if (isRateLimit) { this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { rateLimitedUntil: Date.now() + config.rateLimitDurationMs, incrementError: true }); + } else { + this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { + incrementError: true + }); } } } diff --git a/src/telemetryTracker.ts b/src/telemetryTracker.ts index 209f72c..c4f3659 100644 --- a/src/telemetryTracker.ts +++ b/src/telemetryTracker.ts @@ -1,6 +1,7 @@ import { Response } from 'express'; import { ProviderType } from './revolverTypes'; import { configStore } from './configStore'; +import { modelCircuitBreaker, ModelTargetHealthStatus } from './modelCircuitBreaker'; export interface FallbackStep { stepIndex: number; @@ -136,6 +137,7 @@ export class TelemetryTracker { type: 'snapshot', journeys: this.getRecentJourneys(20), keys: this.getKeyTelemetry(), + circuitBreakers: modelCircuitBreaker.getStatuses(), timestamp: new Date().toISOString() }; res.write(`data: ${JSON.stringify(initialData)}\n\n`); @@ -151,6 +153,7 @@ export class TelemetryTracker { this.broadcast({ type: 'key_status_update', keys: this.getKeyTelemetry(), + circuitBreakers: modelCircuitBreaker.getStatuses(), timestamp: new Date().toISOString() }); } diff --git a/test-circuit-breaker-fallback.ts b/test-circuit-breaker-fallback.ts new file mode 100644 index 0000000..b80c53c --- /dev/null +++ b/test-circuit-breaker-fallback.ts @@ -0,0 +1,362 @@ +import http from 'http'; +import assert from 'assert'; +import app from './src/index'; +import { config } from './src/config'; +import { configStore } from './src/configStore'; +import { modelCircuitBreaker } from './src/modelCircuitBreaker'; +import { telemetryTracker } from './src/telemetryTracker'; + +const PORT = 3997; +const API_KEY = 'test_password'; + +console.log('๐Ÿงช Starting Fast-Failover & Model Circuit Breaker Test Suite...\n'); + +async function runTests() { + // Set short timeouts for testing + config.candidateTimeoutMs = 300; + config.streamFirstTokenTimeoutMs = 250; + config.modelCooldownDurationMs = 1500; + config.maxTargetTimeoutRetries = 0; + + let requestCount503 = 0; + let requestCount429 = 0; + + // Mock upstream provider server + const mockUpstream = http.createServer((req, res) => { + let body = ''; + req.on('data', chunk => (body += chunk)); + req.on('end', () => { + const parsed = JSON.parse(body || '{}'); + const model = parsed.model; + + if (model === 'mock-overloaded-model') { + requestCount503++; + res.writeHead(503, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + error: { + message: '[503 Service Unavailable] This model is currently experiencing high demand. Spikes in demand are usually temporary. Please try again later.', + type: 'server_error', + code: 'model_overloaded' + } + }) + ); + } else if (model === 'mock-quota-rate-limited-model') { + requestCount429++; + if (requestCount429 === 1) { + // Key 1 hits 429 + res.writeHead(429, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + error: { + message: 'Resource has been exhausted (check quota).', + type: 'insufficient_quota', + code: 'rate_limit_exceeded' + } + }) + ); + } else { + // Key 2 succeeds + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + id: 'chatcmpl-mock-success-quota', + object: 'chat.completion', + created: Math.floor(Date.now() / 1000), + model: 'mock-quota-rate-limited-model', + choices: [{ message: { role: 'assistant', content: 'Key 2 succeeded on 429 rotation' } }], + usage: { prompt_tokens: 10, completion_tokens: 10, total_tokens: 20 } + }) + ); + } + } else if (model === 'mock-slow-hanging-model') { + // Hangs past candidateTimeoutMs + setTimeout(() => { + if (!res.writableEnded) { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ choices: [{ message: { content: 'slow' } }] })); + } + }, 800); + } else if (model === 'mock-healthy-tier1-model') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + id: 'chatcmpl-mock-tier1', + object: 'chat.completion', + created: Math.floor(Date.now() / 1000), + model: 'mock-healthy-tier1-model', + choices: [{ message: { role: 'assistant', content: 'Tier 1 fallback served instantly.' } }], + usage: { prompt_tokens: 12, completion_tokens: 8, total_tokens: 20 } + }) + ); + } else { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + id: 'chatcmpl-default', + object: 'chat.completion', + choices: [{ message: { role: 'assistant', content: 'Default response' } }], + usage: { prompt_tokens: 5, completion_tokens: 5, total_tokens: 10 } + }) + ); + } + }); + }); + + await new Promise(resolve => mockUpstream.listen(0, resolve)); + const upstreamPort = (mockUpstream.address() as any).port; + const upstreamBaseUrl = `http://localhost:${upstreamPort}`; + + const server = http.createServer(app); + await new Promise(resolve => server.listen(PORT, resolve)); + const baseUrl = `http://localhost:${PORT}`; + + const testModelOverloadName = `model-failover-overload-${Date.now()}`; + const testModelQuotaName = `model-quota-rotation-${Date.now()}`; + const testModelTimeoutName = `model-timeout-cascade-${Date.now()}`; + + try { + // ------------------------------------------------------------------------- + // TEST 1: Zero-Tolerance 503 Overload Fast-Failover + // Tier 0 has 3 keys for 'mock-overloaded-model'. + // Tier 1 has 1 key for 'mock-healthy-tier1-model'. + // ------------------------------------------------------------------------- + console.log('1. Testing Zero-Tolerance 503 Overload Fast-Failover...'); + const provOverloaded = configStore.saveProvider({ + name: 'Google AI Studio Mock (Overloaded)', + type: 'custom', + baseUrl: upstreamBaseUrl, + keys: ['key-overloaded-1', 'key-overloaded-2', 'key-overloaded-3'] + }); + + const provHealthy = configStore.saveProvider({ + name: 'Google AI Studio Mock (Tier 1)', + type: 'custom', + baseUrl: upstreamBaseUrl, + keys: ['key-healthy-1'] + }); + + const testModelOverload = configStore.saveCustomModel({ + name: testModelOverloadName, + description: 'Testing 503 zero-tolerance skip and fast-cascade', + tiers: [ + { + tierIndex: 0, + name: 'Tier 0 Overloaded', + targets: [{ providerId: provOverloaded.id, model: 'mock-overloaded-model' }] + }, + { + tierIndex: 1, + name: 'Tier 1 Healthy', + targets: [{ providerId: provHealthy.id, model: 'mock-healthy-tier1-model' }] + } + ] + }); + + const req1Start = Date.now(); + const res1 = await fetch(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${API_KEY}` + }, + body: JSON.stringify({ + model: testModelOverload.name, + messages: [{ role: 'user', content: 'Test fast failover on 503' }] + }) + }); + + assert.strictEqual(res1.status, 200); + const data1 = (await res1.json()) as any; + assert.strictEqual(data1.choices[0].message.content, 'Tier 1 fallback served instantly.'); + + // Verify upstream only received 1 request for the overloaded model (NOT 3 keys!) + assert.strictEqual(requestCount503, 1, 'Upstream should only be hit ONCE on 503 before cascading'); + + // Verify telemetry recorded the skip and nextAction + const recentJourneys = telemetryTracker.getRecentJourneys(5); + const j1 = recentJourneys.find(j => j.requestedModel === testModelOverload.name); + assert.ok(j1, 'Journey must be recorded'); + assert.strictEqual(j1.totalHops, 2, 'Should only have 2 hops: Hop 1 (503) -> Hop 2 (Tier 1 200 OK)'); + assert.strictEqual(j1.finalStatus, 'success_fallback'); + assert.strictEqual(j1.steps[0].status, 'server_error'); + assert.ok(j1.steps[0].nextAction?.includes('Model overloaded (503) โ€” skipped 2 remaining key(s)')); + assert.strictEqual(j1.steps[1].status, 'success'); + + // Verify individual keys were NOT marked rate-limited (key quota preserved!) + const updatedProvOverloaded = configStore.getProviderById(provOverloaded.id)!; + for (const k of updatedProvOverloaded.keys) { + assert.strictEqual(k.rateLimitedUntil, null, '503 must NEVER mark individual keys rate-limited'); + } + console.log(' โœ“ Zero-tolerance 503 fast-failover skipped remaining keys and preserved key quota.'); + + // ------------------------------------------------------------------------- + // TEST 2: Circuit Breaker Bypasses Tier 0 Instantly on Subsequent Requests + // ------------------------------------------------------------------------- + console.log('\n2. Testing Circuit Breaker Cooldown Bypasses Tier 0 Instantly...'); + const req2Start = Date.now(); + const res2 = await fetch(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${API_KEY}` + }, + body: JSON.stringify({ + model: testModelOverload.name, + messages: [{ role: 'user', content: 'Second request while in cooldown' }] + }) + }); + const req2Duration = Date.now() - req2Start; + assert.strictEqual(res2.status, 200); + const data2 = (await res2.json()) as any; + assert.strictEqual(data2.choices[0].message.content, 'Tier 1 fallback served instantly.'); + + // Request 503 count should STILL be 1 (Tier 0 was bypassed with 0ms delay!) + assert.strictEqual(requestCount503, 1, 'Overloaded model must be bypassed completely while in cooldown'); + assert.ok(req2Duration < 150, `Subsequent request should complete instantly without Tier 0 hops (took ${req2Duration}ms)`); + + const j2 = telemetryTracker.getRecentJourneys(5)[0]; + assert.strictEqual(j2.totalHops, 1, 'Subsequent request should have exactly 1 hop directly on Tier 1'); + assert.strictEqual(j2.finalServedBy?.tierIndex, 1); + console.log(` โœ“ Subsequent request bypassed Tier 0 instantly (0ms latency, completed in ${req2Duration}ms).`); + + // ------------------------------------------------------------------------- + // TEST 3: HTTP 429 Quota Exhaustion Still Rotates All Keys (Quota Preserved) + // ------------------------------------------------------------------------- + console.log('\n3. Testing 429 Quota Exhaustion preserves key rotation within tier...'); + const provQuota = configStore.saveProvider({ + name: 'Quota Rotation Provider', + type: 'custom', + baseUrl: upstreamBaseUrl, + keys: ['key-quota-1', 'key-quota-2'] + }); + + const testModelQuota = configStore.saveCustomModel({ + name: testModelQuotaName, + tiers: [ + { + tierIndex: 0, + name: 'Tier 0 Quota', + targets: [{ providerId: provQuota.id, model: 'mock-quota-rate-limited-model' }] + } + ] + }); + + const res3 = await fetch(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${API_KEY}` + }, + body: JSON.stringify({ + model: testModelQuota.name, + messages: [{ role: 'user', content: 'Test 429 quota rotation' }] + }) + }); + + assert.strictEqual(res3.status, 200); + const data3 = (await res3.json()) as any; + assert.strictEqual(data3.choices[0].message.content, 'Key 2 succeeded on 429 rotation'); + + // Verify one key was marked rate limited, the other succeeded, and model circuit breaker was NOT tripped + assert.strictEqual(requestCount429, 2, 'Both keys should be rotated on 429 quota exhaustion'); + const updatedProvQuota = configStore.getProviderById(provQuota.id)!; + const rateLimitedKey = updatedProvQuota.keys.find(k => k.rateLimitedUntil && k.rateLimitedUntil > Date.now()); + assert.ok(rateLimitedKey, 'The key that hit 429 must be marked rate limited'); + const successfulKey = updatedProvQuota.keys.find(k => !k.rateLimitedUntil && (k.requestCount || 0) > 0); + assert.ok(successfulKey, 'The other key must succeed without rate limit'); + assert.strictEqual(modelCircuitBreaker.isTargetAvailable(provQuota.id, 'mock-quota-rate-limited-model'), true, 'Model circuit breaker must NOT trip on key-level 429 quota error'); + console.log(' โœ“ 429 quota rotation fully preserved: rotated from Key 1 to Key 2 without tripping model circuit breaker.'); + + // ------------------------------------------------------------------------- + // TEST 4: Candidate Timeout Fast-Cascade + // ------------------------------------------------------------------------- + console.log('\n4. Testing Candidate Timeout Fast-Cascade...'); + const provHanging = configStore.saveProvider({ + name: 'Hanging Provider', + type: 'custom', + baseUrl: upstreamBaseUrl, + keys: ['key-hang-1', 'key-hang-2'] + }); + + const testModelTimeout = configStore.saveCustomModel({ + name: testModelTimeoutName, + tiers: [ + { + tierIndex: 0, + name: 'Tier 0 Slow', + targets: [{ providerId: provHanging.id, model: 'mock-slow-hanging-model' }] + }, + { + tierIndex: 1, + name: 'Tier 1 Fast', + targets: [{ providerId: provHealthy.id, model: 'mock-healthy-tier1-model' }] + } + ] + }); + + const res4 = await fetch(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${API_KEY}` + }, + body: JSON.stringify({ + model: testModelTimeout.name, + messages: [{ role: 'user', content: 'Test timeout cascade' }] + }) + }); + + assert.strictEqual(res4.status, 200); + const data4 = (await res4.json()) as any; + assert.strictEqual(data4.choices[0].message.content, 'Tier 1 fallback served instantly.'); + + const j4 = telemetryTracker.getRecentJourneys(5)[0]; + assert.strictEqual(j4.totalHops, 2, 'Should abort slow candidate and cascade to Tier 1 without waiting on second hanging key'); + assert.strictEqual(j4.steps[0].status, 'timeout'); + assert.ok(j4.steps[0].nextAction?.includes('Target timeout โ€” skipped 1 remaining key(s)')); + console.log(' โœ“ Candidate timeout aborted and fast-cascaded to Tier 1 without wasting time on remaining keys.'); + + // ------------------------------------------------------------------------- + // TEST 5: Admin API Circuit Breaker Reset Endpoint + // ------------------------------------------------------------------------- + console.log('\n5. Testing POST /api/admin/circuit-breaker/reset...'); + // Currently provOverloaded is in cooldown + assert.strictEqual(modelCircuitBreaker.isTargetAvailable(provOverloaded.id, 'mock-overloaded-model'), false); + + const resetRes = await fetch(`${baseUrl}/api/admin/circuit-breaker/reset`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${API_KEY}` + }, + body: JSON.stringify({}) + }); + assert.strictEqual(resetRes.status, 200); + const resetData = (await resetRes.json()) as any; + assert.strictEqual(resetData.success, true); + + // After reset, provOverloaded is available again + assert.strictEqual(modelCircuitBreaker.isTargetAvailable(provOverloaded.id, 'mock-overloaded-model'), true); + console.log(' โœ“ Admin circuit breaker reset successfully restored target availability.'); + + // Cleanup + configStore.deleteCustomModel(testModelOverload.id); + configStore.deleteCustomModel(testModelQuota.id); + configStore.deleteCustomModel(testModelTimeout.id); + configStore.deleteProvider(provOverloaded.id); + configStore.deleteProvider(provHealthy.id); + configStore.deleteProvider(provQuota.id); + configStore.deleteProvider(provHanging.id); + + console.log('\n๐ŸŽ‰ ALL CIRCUIT BREAKER & FAST-FAILOVER TESTS PASSED SUCCESSFULLY!\n'); + } finally { + server.close(); + mockUpstream.close(); + } +} + +runTests().catch(err => { + console.error('Test failed with error:', err); + process.exit(1); +});