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
This commit is contained in:
tyuXX 2026-11-04 20:44:57 +00:00
parent ae0e04c65a
commit 4434d308d6
9 changed files with 931 additions and 72 deletions

View file

@ -24,8 +24,17 @@ RATE_LIMIT_DURATION_MS=60000
# ENABLE_NON_STREAMING_KEEPALIVE=true # ENABLE_NON_STREAMING_KEEPALIVE=true
# NON_STREAMING_KEEPALIVE_DELAY_MS=20000 # NON_STREAMING_KEEPALIVE_DELAY_MS=20000
# Candidate timeout per provider attempt before rotating (in ms) # Candidate timeout per provider attempt before rotating (in ms, default 20s)
# CANDIDATE_TIMEOUT_MS=60000 # 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) # Cloudflare Tunnel configuration (for Docker deployment)
# Get your tunnel token from: https://dash.cloudflare.com/ # Get your tunnel token from: https://dash.cloudflare.com/

View file

@ -8,7 +8,7 @@
"start": "node dist/index.js", "start": "node dist/index.js",
"dev": "ts-node src/index.ts", "dev": "ts-node src/index.ts",
"watch": "tsc --watch", "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"], "keywords": ["openai", "gemini", "api", "rotation"],
"author": "", "author": "",

View file

@ -4,6 +4,7 @@ import { revolverEngine } from './revolverEngine';
import { ProviderType } from './revolverTypes'; import { ProviderType } from './revolverTypes';
import { liveWatcher } from './liveWatcher'; import { liveWatcher } from './liveWatcher';
import { telemetryTracker } from './telemetryTracker'; import { telemetryTracker } from './telemetryTracker';
import { modelCircuitBreaker } from './modelCircuitBreaker';
const router = Router(); 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 // 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; const limit = req.query.limit ? parseInt(req.query.limit as string, 10) : 50;
res.json({ res.json({
journeys: telemetryTracker.getRecentJourneys(limit), 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.'
}); });
}); });

View file

@ -2017,7 +2017,7 @@ export function renderAdminHtml(): string {
const data = await res.json(); const data = await res.json();
cachedKeys = data.keys || []; cachedKeys = data.keys || [];
cachedJourneys = data.journeys || []; cachedJourneys = data.journeys || [];
renderTelemetryKeys(cachedKeys); renderTelemetryKeys(cachedKeys, data.circuitBreakers);
renderTelemetryJourneys(cachedJourneys); renderTelemetryJourneys(cachedJourneys);
} catch (err) { } catch (err) {
showToast('Telemetry load failed: ' + err.message, 'error'); showToast('Telemetry load failed: ' + err.message, 'error');
@ -2043,11 +2043,11 @@ export function renderAdminHtml(): string {
if (msg.type === 'snapshot') { if (msg.type === 'snapshot') {
cachedKeys = msg.keys || []; cachedKeys = msg.keys || [];
cachedJourneys = msg.journeys || []; cachedJourneys = msg.journeys || [];
renderTelemetryKeys(cachedKeys); renderTelemetryKeys(cachedKeys, msg.circuitBreakers);
renderTelemetryJourneys(cachedJourneys); renderTelemetryJourneys(cachedJourneys);
} else if (msg.type === 'key_status_update') { } else if (msg.type === 'key_status_update') {
cachedKeys = msg.keys || []; cachedKeys = msg.keys || [];
renderTelemetryKeys(cachedKeys); renderTelemetryKeys(cachedKeys, msg.circuitBreakers);
} else if (msg.type === 'fallback_journey') { } else if (msg.type === 'fallback_journey') {
cachedJourneys.unshift(msg.data); cachedJourneys.unshift(msg.data);
if (cachedJourneys.length > 50) cachedJourneys.length = 50; 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'); const container = document.getElementById('telemetry-list');
if (!container) return; if (!container) return;
container.innerHTML = ''; 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
? '<span class="badge badge-warning"><i class="fas fa-fire"></i> Cooldown (' + cb.cooldownRemainingSeconds + 's remaining)</span>'
: (cb.status === 'half_open'
? '<span class="badge badge-info"><i class="fas fa-stethoscope"></i> Probing (Half-Open)</span>'
: '<span class="badge badge-success"><i class="fas fa-check"></i> Healthy</span>');
cbRows += '<div style="background: rgba(0,0,0,0.2); border: 1px solid var(--border-dark); border-radius: 8px; padding: 0.6rem 0.75rem; margin-top: 0.5rem; font-size: 0.8rem; display: flex; justify-content: space-between; align-items: center;">' +
'<div>' +
'<strong><code>' + escapeHtml(cb.model) + '</code></strong> <span style="color: var(--muted-dark); font-size: 0.75rem;">(' + escapeHtml(cb.providerId) + ')</span>' +
(cb.lastError ? '<div style="font-size: 0.72rem; color: var(--accent-danger); margin-top: 0.2rem; max-width: 400px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">' + escapeHtml(cb.lastError) + '</div>' : '') +
'</div>' +
'<div>' + badge + '</div>' +
'</div>';
});
cbCard.innerHTML = '<div class="card-title" style="display: flex; justify-content: space-between; align-items: center;">' +
'<span><i class="fas fa-shield-alt" style="color: var(--accent-warning); margin-right: 0.5rem;"></i> Model Circuit Breakers (Overload Protection)</span>' +
'<button id="reset-cb-btn" class="nav-btn" style="font-size: 0.72rem; padding: 0.2rem 0.5rem;"><i class="fas fa-undo"></i> Reset All</button>' +
'</div>' +
'<div style="margin-top: 0.5rem;">' + cbRows + '</div>';
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) { if (!keys || keys.length === 0) {
container.innerHTML = '<p style="color: var(--muted-dark);">No provider keys configured.</p>'; container.innerHTML = '<p style="color: var(--muted-dark);">No provider keys configured.</p>';
return; return;

View file

@ -15,7 +15,11 @@ export const config = {
keepAliveIntervalMs: parseInt(process.env.KEEPALIVE_INTERVAL_MS || '15000', 10), keepAliveIntervalMs: parseInt(process.env.KEEPALIVE_INTERVAL_MS || '15000', 10),
enableNonStreamingKeepAlive: process.env.ENABLE_NON_STREAMING_KEEPALIVE !== 'false', enableNonStreamingKeepAlive: process.env.ENABLE_NON_STREAMING_KEEPALIVE !== 'false',
nonStreamingKeepAliveDelayMs: parseInt(process.env.NON_STREAMING_KEEPALIVE_DELAY_MS || '20000', 10), 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) { if (!config.apiPassword) {

238
src/modelCircuitBreaker.ts Normal file
View file

@ -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<string, TargetHealthInternal> = 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();

View file

@ -13,6 +13,7 @@ import {
import { OpenAIChatRequest, OpenAIChatResponse } from './openaiTypes'; import { OpenAIChatRequest, OpenAIChatResponse } from './openaiTypes';
import { telemetryTracker, FallbackStep, RequestFallbackJourney } from './telemetryTracker'; import { telemetryTracker, FallbackStep, RequestFallbackJourney } from './telemetryTracker';
import { liveWatcher } from './liveWatcher'; import { liveWatcher } from './liveWatcher';
import { modelCircuitBreaker } from './modelCircuitBreaker';
interface CandidateExecution { interface CandidateExecution {
tier: FallbackTier; tier: FallbackTier;
@ -79,10 +80,15 @@ export class RevolverEngine {
return Date.now() < keyConfig.rateLimitedUntil; return Date.now() < keyConfig.rateLimitedUntil;
} }
private getCandidatesForTier(tier: FallbackTier, modelId: string): CandidateExecution[] { public getCandidatesForTier(tier: FallbackTier, modelId: string, allowCooldownProbes = false): CandidateExecution[] {
const candidates: CandidateExecution[] = []; const candidates: CandidateExecution[] = [];
for (const target of tier.targets) { 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); const provider = this.store.getProviderById(target.providerId);
if (!provider || provider.keys.length === 0) continue; 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: { public async executeChatCompletion(params: {
requestBody: OpenAIChatRequest; requestBody: OpenAIChatRequest;
requestId: string; requestId: string;
@ -303,9 +325,20 @@ export class RevolverEngine {
let totalHops = 0; let totalHops = 0;
let lastError: any = null; 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... // Traverse tiers: Tier 0 -> Tier 1 -> Tier 2...
for (const tier of sortedTiers) { for (let tIdx = 0; tIdx < sortedTiers.length; tIdx++) {
const candidates = this.getCandidatesForTier(tier, customModel.id); const tier = sortedTiers[tIdx];
let candidates = this.getCandidatesForTier(tier, customModel.id, allowProbes);
if (candidates.length === 0) { 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.`); console.warn(`[REVOLVER] No candidates found in Tier ${tier.tierIndex} ('${tier.name || 'Tier ' + tier.tierIndex}') for model '${customModel.name}'. Skipping tier.`);
continue; 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)...`); console.log(`[REVOLVER] Attempting Tier ${tier.tierIndex} ('${tier.name || 'Tier ' + tier.tierIndex}') with ${candidates.length} candidate(s)...`);
// Try candidates in this tier // 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) { if (isCancelled || res.destroyed) {
cleanupTimers(); cleanupTimers();
return; return;
@ -322,8 +356,7 @@ export class RevolverEngine {
const candidateStart = Date.now(); const candidateStart = Date.now();
totalHops++; totalHops++;
const isLastCandidateInTier = candidate === candidates[candidates.length - 1]; const isLastTier = tIdx === sortedTiers.length - 1;
const isLastTier = tier === sortedTiers[sortedTiers.length - 1];
try { 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}]`); 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(); 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 stepDuration = Date.now() - candidateStart;
const successStep: FallbackStep = { const successStep: FallbackStep = {
stepIndex: totalHops, stepIndex: totalHops,
@ -411,7 +447,8 @@ export class RevolverEngine {
cleanupTimers(); cleanupTimers();
if (isCancelled || res.destroyed) return; 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, { this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, {
incrementCount: true, incrementCount: true,
rateLimitedUntil: null rateLimitedUntil: null
@ -496,18 +533,62 @@ export class RevolverEngine {
const stepDuration = Date.now() - candidateStart; const stepDuration = Date.now() - candidateStart;
const isRateLimit = this.isRateLimitOrQuotaError(err); const isRateLimit = this.isRateLimitOrQuotaError(err);
const isServerErr = this.isServerError(err); const isServerErr = this.isServerError(err);
const cooldown = isRateLimit ? config.rateLimitDurationMs : (isServerErr ? 15000 : undefined); const isTimeout = this.isTimeoutError(err);
const statusType = isRateLimit ? 'rate_limited' : (isServerErr ? 'server_error' : 'failed'); 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 = ''; let nextAction = '';
if (!isLastCandidateInTier) { if (shouldFastFailTarget) {
nextAction = `Rotating to next key in Tier ${tier.tierIndex}`; const skipNote = skippedRemainingCount > 0
} else if (!isLastTier) { ? `skipped ${skippedRemainingCount} remaining key(s) for ${candidate.target.model}`
nextAction = `Tier ${tier.tierIndex} exhausted. Cascading to Fallback Tier ${sortedTiers[sortedTiers.indexOf(tier) + 1]?.tierIndex ?? 'next'}`; : `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 { } 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 = { const failedStep: FallbackStep = {
stepIndex: totalHops, stepIndex: totalHops,
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
@ -521,10 +602,10 @@ export class RevolverEngine {
maskedKey: this.store.maskKey(candidate.keyConfig.key), maskedKey: this.store.maskKey(candidate.keyConfig.key),
durationMs: stepDuration, durationMs: stepDuration,
status: statusType, status: statusType,
statusCode: err.status || (isRateLimit ? 429 : 500), statusCode: err.status || (isRateLimit ? 429 : (isTimeout ? 504 : 500)),
errorMessage: err.message, errorMessage: err.message,
rateLimitedUntil: cooldown ? Date.now() + cooldown : null, rateLimitedUntil: isRateLimit ? Date.now() + config.rateLimitDurationMs : null,
cooldownSeconds: cooldown ? Math.ceil(cooldown / 1000) : undefined, cooldownSeconds: cooldownSecs,
nextAction nextAction
}; };
fallbackSteps.push(failedStep); fallbackSteps.push(failedStep);
@ -568,11 +649,12 @@ export class RevolverEngine {
throw err; throw err;
} }
// Mark key rate limited or increment error // Update Key Stats: ONLY mark rateLimitedUntil if isRateLimit is true (429)!
if (isRateLimit || isServerErr) { // Model-level overloads/timeouts do NOT penalize individual key quota.
console.warn(`[REVOLVER] Marking key ${this.store.maskKey(candidate.keyConfig.key)} rate-limited for ${cooldown! / 1000}s`); 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, { this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, {
rateLimitedUntil: Date.now() + cooldown!, rateLimitedUntil: Date.now() + config.rateLimitDurationMs,
incrementError: true incrementError: true
}); });
} else { } else {
@ -853,6 +935,35 @@ export class RevolverEngine {
// Start streaming from Gemini // Start streaming from Gemini
const result = await chat.sendMessageStream(lastMessage.parts[0].text); 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<any>;
let ttftTimer: NodeJS.Timeout | null = null;
const ttftPromise = new Promise<never>((_, 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 headers haven't been committed, commit them now
if (!res.headersSent) { if (!res.headersSent) {
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8'); res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
@ -864,13 +975,35 @@ export class RevolverEngine {
} }
} }
let fullContent = ''; if (!firstResult.done && firstResult.value) {
let promptTokens = 0; const text = firstResult.value.text();
let completionTokens = 0; 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; if (res.destroyed) break;
const text = chunk.text(); const { done, value } = await streamIterator.next();
if (done) break;
const text = value.text();
fullContent += text; fullContent += text;
liveWatcher.appendStreamChunk(requestId, text); liveWatcher.appendStreamChunk(requestId, text);
onStreamStart(); onStreamStart();
@ -1000,57 +1133,89 @@ export class RevolverEngine {
const decoder = new TextDecoder(); const decoder = new TextDecoder();
let buffer = ''; let buffer = '';
let totalOutputChars = 0; let totalOutputChars = 0;
let streamHasStarted = false;
try { const processText = (textChunk: string) => {
while (true) { buffer += textChunk;
if (res.destroyed) break; const lines = buffer.split('\n');
const { done, value } = await reader.read(); buffer = lines.pop() || '';
if (done) break;
const text = decoder.decode(value, { stream: true }); for (const line of lines) {
buffer += text; const trimmed = line.trim();
if (!trimmed) {
res.write('\n');
continue;
}
const lines = buffer.split('\n'); if (trimmed.startsWith('data: ')) {
buffer = lines.pop() || ''; const dataStr = trimmed.slice(6);
if (dataStr === '[DONE]') {
for (const line of lines) { res.write('data: [DONE]\n\n');
const trimmed = line.trim();
if (!trimmed) {
res.write('\n');
continue; continue;
} }
if (trimmed.startsWith('data: ')) { try {
const dataStr = trimmed.slice(6); const parsed = JSON.parse(dataStr);
if (dataStr === '[DONE]') { parsed.model = requestedModelName;
res.write('data: [DONE]\n\n'); if (parsed.choices?.[0]?.delta?.content) {
continue; onStreamStart();
streamHasStarted = true;
const delta = parsed.choices[0].delta.content;
totalOutputChars += delta.length;
liveWatcher.appendStreamChunk(requestId, delta);
} }
res.write(`data: ${JSON.stringify(parsed)}\n\n`);
try { } catch {
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(`${line}\n`); 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<never>((_, 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 { } finally {
if (!res.destroyed) { if (ttftTimer) {
res.end(); 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 estimatedInput = Math.ceil(JSON.stringify(requestBody.messages).length / 4);
const estimatedOutput = Math.ceil(totalOutputChars / 4); const estimatedOutput = Math.ceil(totalOutputChars / 4);
@ -1119,6 +1284,7 @@ export class RevolverEngine {
const content = resp.choices?.[0]?.message?.content || ''; const content = resp.choices?.[0]?.message?.content || '';
const duration = Date.now() - candidateStart; const duration = Date.now() - candidateStart;
modelCircuitBreaker.recordSuccess(candidate.provider.id, candidate.target.model);
this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, {
incrementCount: true, incrementCount: true,
rateLimitedUntil: null rateLimitedUntil: null
@ -1145,11 +1311,22 @@ export class RevolverEngine {
} catch (err: any) { } catch (err: any) {
lastError = err; lastError = err;
const isRateLimit = this.isRateLimitOrQuotaError(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) { if (isRateLimit) {
this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, {
rateLimitedUntil: Date.now() + config.rateLimitDurationMs, rateLimitedUntil: Date.now() + config.rateLimitDurationMs,
incrementError: true incrementError: true
}); });
} else {
this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, {
incrementError: true
});
} }
} }
} }

View file

@ -1,6 +1,7 @@
import { Response } from 'express'; import { Response } from 'express';
import { ProviderType } from './revolverTypes'; import { ProviderType } from './revolverTypes';
import { configStore } from './configStore'; import { configStore } from './configStore';
import { modelCircuitBreaker, ModelTargetHealthStatus } from './modelCircuitBreaker';
export interface FallbackStep { export interface FallbackStep {
stepIndex: number; stepIndex: number;
@ -136,6 +137,7 @@ export class TelemetryTracker {
type: 'snapshot', type: 'snapshot',
journeys: this.getRecentJourneys(20), journeys: this.getRecentJourneys(20),
keys: this.getKeyTelemetry(), keys: this.getKeyTelemetry(),
circuitBreakers: modelCircuitBreaker.getStatuses(),
timestamp: new Date().toISOString() timestamp: new Date().toISOString()
}; };
res.write(`data: ${JSON.stringify(initialData)}\n\n`); res.write(`data: ${JSON.stringify(initialData)}\n\n`);
@ -151,6 +153,7 @@ export class TelemetryTracker {
this.broadcast({ this.broadcast({
type: 'key_status_update', type: 'key_status_update',
keys: this.getKeyTelemetry(), keys: this.getKeyTelemetry(),
circuitBreakers: modelCircuitBreaker.getStatuses(),
timestamp: new Date().toISOString() timestamp: new Date().toISOString()
}); });
} }

View file

@ -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<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);
});