- 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
362 lines
15 KiB
TypeScript
362 lines
15 KiB
TypeScript
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<void>(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<void>(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);
|
|
});
|