feat: add Gemini content moderation disable option and sequential emergency probe recovery when all targets are in cooldown

This commit is contained in:
tyuXX 2026-11-05 17:59:37 +00:00
parent e860faba14
commit 343208216e
10 changed files with 452 additions and 25 deletions

View file

@ -36,6 +36,9 @@ RATE_LIMIT_DURATION_MS=60000
# Max consecutive timeouts per model target before tripping circuit breaker (default 0 when fallback tier exists)
# MAX_TARGET_TIMEOUT_RETRIES=0
# Disable Gemini Content Moderation (injects HarmBlockThreshold.BLOCK_NONE to prevent safety blocks & proxy errors)
# DISABLE_GEMINI_MODERATION=true
# Cloudflare Tunnel configuration (for Docker deployment)
# Get your tunnel token from: https://dash.cloudflare.com/
CLOUDFLARE_TUNNEL_TOKEN=your_cloudflare_tunnel_token_here

View file

@ -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 && API_PASSWORD=test_password ts-node test-content-length-resilience.ts && API_PASSWORD=test_password ts-node test-circuit-breaker-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 && API_PASSWORD=test_password ts-node test-circuit-breaker-fallback.ts && API_PASSWORD=test_password ts-node test-moderation-and-cooldown-recovery.ts"
},
"keywords": ["openai", "gemini", "api", "rotation"],
"author": "",

View file

@ -34,7 +34,7 @@ router.get('/config', (req: Request, res: Response) => {
// POST /api/admin/providers (Create or Update provider)
router.post('/providers', (req: Request, res: Response) => {
const { id, name, type, baseUrl, keys } = req.body;
const { id, name, type, baseUrl, keys, disableModeration } = req.body;
if (!name || typeof name !== 'string') {
res.status(400).json({ error: 'Provider name is required.' });
@ -58,7 +58,8 @@ router.post('/providers', (req: Request, res: Response) => {
name,
type,
baseUrl,
keys
keys,
disableModeration: typeof disableModeration === 'boolean' ? disableModeration : undefined
});
res.json(saved);
} catch (err: any) {

View file

@ -1231,6 +1231,16 @@ export function renderAdminHtml(): string {
<textarea id="provider-keys" class="form-textarea" placeholder="Paste keys here, one per line:&#10;key1&#10;key2&#10;key3" required></textarea>
</div>
<div class="form-group" id="provider-moderation-group" style="display: flex; align-items: flex-start; gap: 0.6rem; margin-top: 0.75rem; background: rgba(0,0,0,0.15); padding: 0.75rem; border-radius: 8px; border: 1px solid var(--border-dark);">
<input type="checkbox" id="provider-disable-moderation" checked style="margin-top: 3px; accent-color: var(--accent-blue); width: 16px; height: 16px; cursor: pointer;">
<label for="provider-disable-moderation" style="font-size: 0.85rem; cursor: pointer; user-select: none;">
<strong>Disable Gemini Content Moderation (BLOCK_NONE)</strong>
<span class="form-hint" style="display: block; font-size: 0.75rem; color: var(--text-muted); margin-top: 2px;">
Injects official API safety thresholds (HarmBlockThreshold.BLOCK_NONE) to prevent upstream safety blocks & "Unknown response" errors
</span>
</label>
</div>
<div id="provider-test-area" style="display: none; border-top: 1px solid var(--border-dark); padding-top: 1rem;">
<div class="form-label">
<span>Verify Keys Live</span>
@ -1614,6 +1624,7 @@ export function renderAdminHtml(): string {
providerTypeSelect.value = 'gemini';
providerUrlInput.value = defaultUrls.gemini;
document.getElementById('provider-keys').value = '';
document.getElementById('provider-disable-moderation').checked = true;
document.getElementById('provider-test-area').style.display = 'none';
openModal('provider-modal');
});
@ -1628,6 +1639,7 @@ export function renderAdminHtml(): string {
providerTypeSelect.value = p.type;
providerUrlInput.value = p.baseUrl || defaultUrls[p.type];
document.getElementById('provider-keys').value = (p.keys || []).map(k => k.key).join('\\n');
document.getElementById('provider-disable-moderation').checked = p.disableModeration !== false;
const testArea = document.getElementById('provider-test-area');
const testList = document.getElementById('provider-test-keys-list');
@ -1694,6 +1706,7 @@ export function renderAdminHtml(): string {
const type = providerTypeSelect.value;
const baseUrl = providerUrlInput.value.trim();
const rawKeys = document.getElementById('provider-keys').value.split('\\n').map(k => k.trim()).filter(Boolean);
const disableModeration = document.getElementById('provider-disable-moderation').checked;
if (rawKeys.length === 0) {
showToast('Please provide at least one API key.', 'error');
@ -1703,7 +1716,7 @@ export function renderAdminHtml(): string {
try {
const res = await apiRequest('/api/admin/providers', {
method: 'POST',
body: { id: id || undefined, name, type, baseUrl, keys: rawKeys }
body: { id: id || undefined, name, type, baseUrl, keys: rawKeys, disableModeration }
});
if (!res.ok) {
const err = await res.json();

View file

@ -19,7 +19,9 @@ export const config = {
// 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)
maxTargetTimeoutRetries: parseInt(process.env.MAX_TARGET_TIMEOUT_RETRIES || '0', 10),
// Gemini Content Moderation
disableGeminiModeration: process.env.DISABLE_GEMINI_MODERATION !== 'false'
};
if (!config.apiPassword) {

View file

@ -149,6 +149,7 @@ export class ConfigStore {
type: ProviderType;
baseUrl?: string;
keys: (string | ProviderKeyConfig)[];
disableModeration?: boolean;
}): ProviderConfig {
const now = new Date().toISOString();
const existingIndex = providerInput.id ? this.data.providers.findIndex(p => p.id === providerInput.id) : -1;
@ -196,6 +197,9 @@ export class ConfigStore {
type: providerInput.type,
baseUrl: providerInput.baseUrl?.trim() || defaultBaseUrl,
keys: processedKeys,
disableModeration: providerInput.disableModeration !== undefined
? providerInput.disableModeration
: this.data.providers[existingIndex].disableModeration,
updatedAt: now
};
this.data.providers[existingIndex] = updated;
@ -208,6 +212,7 @@ export class ConfigStore {
type: providerInput.type,
baseUrl: providerInput.baseUrl?.trim() || defaultBaseUrl,
keys: processedKeys,
disableModeration: providerInput.disableModeration,
createdAt: now,
updatedAt: now
};

View file

@ -175,6 +175,47 @@ export class ModelCircuitBreaker {
};
}
/**
* Check if target is explicitly in active cooldown.
*/
public isTargetInCooldown(providerId: string, model: string): boolean {
const target = this.getOrCreate(providerId, model);
const now = Date.now();
if (target.status === 'cooldown') {
if (target.cooldownUntil && now >= target.cooldownUntil) {
return false;
}
return true;
}
return false;
}
/**
* Revoke cooldown for a target to allow emergency probe execution.
*/
public revokeCooldown(providerId: string, model: string): void {
const target = this.getOrCreate(providerId, model);
target.status = 'half_open';
target.cooldownUntil = null;
target.probeInFlight = true;
target.probeStartedAt = Date.now();
}
/**
* Explicitly trip a target back into cooldown.
*/
public tripCooldown(providerId: string, model: string, reason = 'Probe execution failed'): void {
const target = this.getOrCreate(providerId, model);
const now = Date.now();
const cooldownMs = config.modelCooldownDurationMs;
target.status = 'cooldown';
target.cooldownUntil = now + cooldownMs;
target.probeInFlight = false;
target.lastFailedAt = now;
target.lastError = reason;
console.warn(`[CIRCUIT_BREAKER] Put target ${providerId} / ${model} back on cooldown for ${Math.ceil(cooldownMs / 1000)}s: ${reason}`);
}
/**
* Record a model target success.
* Closes circuit breaker and restores healthy status.

View file

@ -1,5 +1,5 @@
import { Response } from 'express';
import { GoogleGenerativeAI } from '@google/generative-ai';
import { GoogleGenerativeAI, HarmCategory, HarmBlockThreshold } from '@google/generative-ai';
import { config } from './config';
import { configStore, ConfigStore } from './configStore';
import {
@ -15,6 +15,25 @@ import { telemetryTracker, FallbackStep, RequestFallbackJourney } from './teleme
import { liveWatcher } from './liveWatcher';
import { modelCircuitBreaker } from './modelCircuitBreaker';
export const GEMINI_SAFETY_SETTINGS_BLOCK_NONE = [
{
category: HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
{
category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
{
category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
{
category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
];
interface CandidateExecution {
tier: FallbackTier;
target: ModelTarget;
@ -80,6 +99,28 @@ export class RevolverEngine {
return Date.now() < keyConfig.rateLimitedUntil;
}
public areAllKeyModelPairsOnCooldown(customModel: CustomModelConfig): boolean {
let totalPairs = 0;
for (const tier of customModel.tiers) {
for (const target of tier.targets) {
const provider = this.store.getProviderById(target.providerId);
if (!provider || provider.keys.length === 0) continue;
const isTargetAvail = modelCircuitBreaker.isTargetAvailable(target.providerId, target.model);
for (const keyConfig of provider.keys) {
totalPairs++;
const isKeyAvail = !this.isKeyRateLimited(keyConfig);
if (isTargetAvail && isKeyAvail) {
return false;
}
}
}
}
return totalPairs > 0;
}
public getCandidatesForTier(tier: FallbackTier, modelId: string, allowCooldownProbes = false, advancePointer = true): CandidateExecution[] {
const candidates: CandidateExecution[] = [];
@ -368,7 +409,13 @@ export class RevolverEngine {
break;
}
}
const allowProbes = !hasAvailableCandidateAcrossTiers;
const allPairsOnCooldown = this.areAllKeyModelPairsOnCooldown(customModel);
if (allPairsOnCooldown) {
console.warn(`[REVOLVER] All tiers and key-model pairs for model '${customModel.name}' are on cooldown. Entering emergency sequential recovery mode.`);
}
const allowProbes = !hasAvailableCandidateAcrossTiers || allPairsOnCooldown;
// Traverse tiers: Tier 0 -> Tier 1 -> Tier 2...
for (let tIdx = 0; tIdx < sortedTiers.length; tIdx++) {
@ -393,6 +440,17 @@ export class RevolverEngine {
totalHops++;
const isLastTier = tIdx === sortedTiers.length - 1;
if (allPairsOnCooldown) {
// Revoke cooldown for this key-model pair to attempt emergency recovery
modelCircuitBreaker.revokeCooldown(candidate.provider.id, candidate.target.model);
if (this.isKeyRateLimited(candidate.keyConfig)) {
this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, {
rateLimitedUntil: null
});
}
console.log(`[REVOLVER] [EMERGENCY PROBE] Revoked cooldown for Candidate [Provider: '${candidate.provider.name}', Model: '${candidate.target.model}', Key: ${this.store.maskKey(candidate.keyConfig.key)}]. Attempting request...`);
}
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}]`);
@ -574,12 +632,20 @@ export class RevolverEngine {
const isModelOverload = modelCircuitBreaker.isModelOverloadOrUnavailable(err);
let tripResult = { tripped: false, cooldownSeconds: 0, reason: '' };
if (isModelOverload || isTimeout) {
if (allPairsOnCooldown) {
// When all pairs were on cooldown, emergency probe failed: put target and key back on cooldown immediately
modelCircuitBreaker.tripCooldown(candidate.provider.id, candidate.target.model, detailedErrorMessage);
this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, {
rateLimitedUntil: Date.now() + config.rateLimitDurationMs,
incrementError: true
});
} else 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;
// (Only when NOT in allPairsOnCooldown mode, where every key-model pair in line is given its sequential turn)
const shouldFastFailTarget = !allPairsOnCooldown && (isModelOverload || (isTimeout && config.maxTargetTimeoutRetries === 0) || tripResult.tripped);
let skippedRemainingCount = 0;
if (shouldFastFailTarget) {
@ -599,7 +665,16 @@ export class RevolverEngine {
const nextTier = !isLastTier ? sortedTiers[tIdx + 1] : null;
let nextAction = '';
if (shouldFastFailTarget) {
if (allPairsOnCooldown) {
if (!isLastCandidateInTier) {
const nextCandidate = candidates[cIdx + 1];
nextAction = `Emergency probe failed. Put back on cooldown. Revoking cooldown for next key-model pair in line (${nextCandidate.target.model} Key ${nextCandidate.keyIndex + 1})`;
} else if (nextTier) {
nextAction = `Emergency probes failed for Tier ${tier.tierIndex}. Failing over to Tier ${nextTier.tierIndex} in line`;
} else {
nextAction = 'All tiers and emergency candidate probes failed';
}
} else if (shouldFastFailTarget) {
const skipNote = skippedRemainingCount > 0
? `skipped ${skippedRemainingCount} remaining key(s) for ${candidate.target.model}`
: `for ${candidate.target.model}`;
@ -688,6 +763,7 @@ export class RevolverEngine {
// Update Key Stats: ONLY mark rateLimitedUntil if isRateLimit is true (429)!
// Model-level overloads/timeouts do NOT penalize individual key quota.
if (!allPairsOnCooldown) {
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, {
@ -699,6 +775,7 @@ export class RevolverEngine {
incrementError: true
});
}
}
telemetryTracker.broadcastKeyStatus();
// Continue loop to try next candidate in this tier
@ -807,9 +884,16 @@ export class RevolverEngine {
const { systemInstruction, geminiMessages } = this.convertToGeminiContent(requestBody.messages);
const shouldDisableModeration = candidate.provider.disableModeration ?? (
(requestBody as any).disable_moderation !== undefined
? !!(requestBody as any).disable_moderation
: config.disableGeminiModeration
);
const modelInstance = genAI.getGenerativeModel({
model: candidate.target.model,
systemInstruction: systemInstruction || undefined
systemInstruction: systemInstruction || undefined,
safetySettings: shouldDisableModeration ? GEMINI_SAFETY_SETTINGS_BLOCK_NONE : undefined
}, { timeout: config.candidateTimeoutMs });
const lastMessage = geminiMessages[geminiMessages.length - 1];
@ -828,7 +912,14 @@ export class RevolverEngine {
const result = await chat.sendMessage(lastMessage.parts[0].text);
const response = await result.response;
const content = response?.candidates?.[0]?.content?.parts?.[0]?.text || '';
const candidate0 = response?.candidates?.[0];
const finishReason = candidate0?.finishReason;
const isSafetyBlocked = finishReason === 'SAFETY' || response?.promptFeedback?.blockReason === 'SAFETY';
const content = candidate0?.content?.parts?.[0]?.text || '';
if (isSafetyBlocked && !content) {
throw new Error(`Gemini candidate blocked by upstream safety policy (${finishReason || response?.promptFeedback?.blockReason}).`);
}
const promptTokens = response?.usageMetadata?.promptTokenCount || 0;
const completionTokens = response?.usageMetadata?.candidatesTokenCount || Math.ceil(content.length / 4);
@ -998,9 +1089,16 @@ export class RevolverEngine {
const { systemInstruction, geminiMessages } = this.convertToGeminiContent(requestBody.messages);
const shouldDisableModeration = candidate.provider.disableModeration ?? (
(requestBody as any).disable_moderation !== undefined
? !!(requestBody as any).disable_moderation
: config.disableGeminiModeration
);
const modelInstance = genAI.getGenerativeModel({
model: candidate.target.model,
systemInstruction: systemInstruction || undefined
systemInstruction: systemInstruction || undefined,
safetySettings: shouldDisableModeration ? GEMINI_SAFETY_SETTINGS_BLOCK_NONE : undefined
}, { timeout: config.candidateTimeoutMs });
const lastMessage = geminiMessages[geminiMessages.length - 1];
@ -1061,7 +1159,15 @@ export class RevolverEngine {
}
if (!firstResult.done && firstResult.value) {
const text = firstResult.value.text();
let text = '';
try {
text = firstResult.value.text();
} catch (err: any) {
if (err?.message?.includes('SAFETY') || err?.message?.includes('blocked')) {
throw new Error(`Gemini stream blocked by upstream safety policy: ${err.message}`);
}
throw err;
}
fullContent += text;
liveWatcher.appendStreamChunk(requestId, text);
onStreamStart();
@ -1088,7 +1194,15 @@ export class RevolverEngine {
const { done, value } = await streamIterator.next();
if (done) break;
const text = value.text();
let text = '';
try {
text = value.text();
} catch (err: any) {
if (err?.message?.includes('SAFETY') || err?.message?.includes('blocked')) {
throw new Error(`Gemini stream blocked by upstream safety policy: ${err.message}`);
}
throw err;
}
fullContent += text;
liveWatcher.appendStreamChunk(requestId, text);
onStreamStart();

View file

@ -14,6 +14,7 @@ export interface ProviderConfig {
type: ProviderType;
baseUrl?: string;
keys: ProviderKeyConfig[];
disableModeration?: boolean;
createdAt: string;
updatedAt: string;
}

View file

@ -0,0 +1,247 @@
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 { revolverEngine, GEMINI_SAFETY_SETTINGS_BLOCK_NONE } from './src/revolverEngine';
import { HarmBlockThreshold } from '@google/generative-ai';
const PORT = 3998;
const API_KEY = 'test_password';
console.log('🧪 Starting Moderation Settings & Emergency Cooldown Recovery Test Suite...\n');
async function runTests() {
config.candidateTimeoutMs = 500;
config.streamFirstTokenTimeoutMs = 400;
config.modelCooldownDurationMs = 2000;
config.rateLimitDurationMs = 2000;
// =========================================================================
// TEST 1: Gemini Content Moderation Injection & Configuration
// =========================================================================
console.log('1. Testing Gemini Content Moderation Injection & Config...');
assert.strictEqual(config.disableGeminiModeration, true, 'Default disableGeminiModeration must be true');
// Verify all 4 API-supported categories exist with BLOCK_NONE
assert.strictEqual(GEMINI_SAFETY_SETTINGS_BLOCK_NONE.length, 4);
const categories = GEMINI_SAFETY_SETTINGS_BLOCK_NONE.map(s => s.category);
assert.ok(categories.includes('HARM_CATEGORY_HARASSMENT' as any));
assert.ok(categories.includes('HARM_CATEGORY_HATE_SPEECH' as any));
assert.ok(categories.includes('HARM_CATEGORY_SEXUALLY_EXPLICIT' as any));
assert.ok(categories.includes('HARM_CATEGORY_DANGEROUS_CONTENT' as any));
GEMINI_SAFETY_SETTINGS_BLOCK_NONE.forEach(s => {
assert.strictEqual(s.threshold, HarmBlockThreshold.BLOCK_NONE);
});
// Verify ProviderConfig persistence with disableModeration
const testProvMod = configStore.saveProvider({
name: 'Gemini Moderation Test Provider',
type: 'gemini',
baseUrl: 'https://generativelanguage.googleapis.com',
keys: ['AIzaSyDummyTestKeyForModeration'],
disableModeration: true
});
assert.strictEqual(testProvMod.disableModeration, true);
configStore.deleteProvider(testProvMod.id);
console.log(' ✓ Gemini content moderation settings, BLOCK_NONE injection, and provider flags verified.');
// =========================================================================
// Upstream Mock Server Setup
// =========================================================================
const candidateAttempts: string[] = [];
const mockServer = http.createServer((req, res) => {
let body = '';
req.on('data', chunk => (body += chunk));
req.on('end', () => {
const parsed = JSON.parse(body || '{}');
const authHeader = req.headers['authorization'] || '';
const key = authHeader.replace('Bearer ', '');
const model = parsed.model;
const attemptTag = `${model}:${key}`;
candidateAttempts.push(attemptTag);
if (attemptTag === 'mock-t0-model:key-t0-1') {
// Candidate 1 fails with 503
res.writeHead(503, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: { message: '[503 Service Unavailable] Model overloaded' } }));
} else if (attemptTag === 'mock-t0-model:key-t0-2') {
// Candidate 2 fails with 503
res.writeHead(503, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: { message: '[503 Service Unavailable] Model overloaded' } }));
} else if (attemptTag === 'mock-t1-model:key-t1-1') {
// Candidate 3 in Tier 1 succeeds!
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
id: 'chatcmpl-emergency-success',
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model: 'mock-t1-model',
choices: [{ message: { role: 'assistant', content: 'Emergency probe saved the request!' } }],
usage: { prompt_tokens: 10, completion_tokens: 15, total_tokens: 25 }
}));
} else if (model === 'all-fail-model') {
// All fail
res.writeHead(503, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: { message: 'Outage continues' } }));
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
choices: [{ message: { role: 'assistant', content: 'Default OK' } }]
}));
}
});
});
await new Promise<void>(resolve => mockServer.listen(0, resolve));
const upstreamPort = (mockServer.address() as any).port;
const upstreamBaseUrl = `http://localhost:${upstreamPort}`;
// Start GeminiRevolver server
const server = app.listen(PORT);
await new Promise<void>(resolve => server.once('listening', resolve));
const baseUrl = `http://localhost:${PORT}`;
try {
// =========================================================================
// TEST 2: All Tiers & Key-Model Pairs on Cooldown -> Sequential Probe Recovery
// =========================================================================
console.log('\n2. Testing sequential probe recovery when ALL tiers and key-model pairs are on cooldown...');
const pT0 = configStore.saveProvider({
name: 'Emergency Provider Tier 0',
type: 'custom',
baseUrl: upstreamBaseUrl,
keys: ['key-t0-1', 'key-t0-2']
});
const pT1 = configStore.saveProvider({
name: 'Emergency Provider Tier 1',
type: 'custom',
baseUrl: upstreamBaseUrl,
keys: ['key-t1-1']
});
const customModelName = `emergency-recovery-model-${Date.now()}`;
const testModel = configStore.saveCustomModel({
name: customModelName,
tiers: [
{
tierIndex: 0,
name: 'Tier 0',
targets: [{ providerId: pT0.id, model: 'mock-t0-model' }]
},
{
tierIndex: 1,
name: 'Tier 1',
targets: [{ providerId: pT1.id, model: 'mock-t1-model' }]
}
]
});
// Explicitly place ALL targets on circuit breaker cooldown
modelCircuitBreaker.tripCooldown(pT0.id, 'mock-t0-model', 'Simulated 503 outage');
modelCircuitBreaker.tripCooldown(pT1.id, 'mock-t1-model', 'Simulated 503 outage');
// Also mark keys rate-limited
configStore.updateKeyStats(pT0.id, 'key-t0-1', { rateLimitedUntil: Date.now() + 60000 });
configStore.updateKeyStats(pT0.id, 'key-t0-2', { rateLimitedUntil: Date.now() + 60000 });
configStore.updateKeyStats(pT1.id, 'key-t1-1', { rateLimitedUntil: Date.now() + 60000 });
// Verify all key-model pairs are detected as on cooldown
const areAllOnCooldown = revolverEngine.areAllKeyModelPairsOnCooldown(testModel);
assert.strictEqual(areAllOnCooldown, true, 'areAllKeyModelPairsOnCooldown must return true when everything is in cooldown');
candidateAttempts.length = 0;
// Send request while ALL key-model pairs are in cooldown
const response = await fetch(`${baseUrl}/v1/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify({
model: customModelName,
messages: [{ role: 'user', content: 'Emergency probe test' }],
stream: false
})
});
assert.strictEqual(response.status, 200, `Expected 200 OK after emergency sequential recovery, got ${response.status}`);
const data = (await response.json()) as any;
assert.strictEqual(data.choices[0].message.content, 'Emergency probe saved the request!');
// Verify candidates were attempted sequentially: Candidate 1 -> Candidate 2 -> Candidate 3
assert.strictEqual(candidateAttempts.length, 3);
assert.strictEqual(candidateAttempts[0], 'mock-t0-model:key-t0-1', 'Candidate 1 must be attempted first with revoked cooldown');
assert.strictEqual(candidateAttempts[1], 'mock-t0-model:key-t0-2', 'Candidate 2 must be attempted next with revoked cooldown');
assert.strictEqual(candidateAttempts[2], 'mock-t1-model:key-t1-1', 'Candidate 3 must be attempted next and succeed');
// Verify Candidate 1 and Candidate 2 were put back on cooldown upon failure
assert.strictEqual(modelCircuitBreaker.isTargetInCooldown(pT0.id, 'mock-t0-model'), true, 'Tier 0 target must be back in cooldown after failing');
// Verify Candidate 3 is now healthy
assert.strictEqual(modelCircuitBreaker.isTargetAvailable(pT1.id, 'mock-t1-model'), true, 'Tier 1 target must be healthy after successful probe');
console.log(' ✓ Emergency sequential recovery cleanly revoked Candidate 1, failed & put back on cooldown, failed Candidate 2 & put back on cooldown, and succeeded on Candidate 3.');
// =========================================================================
// TEST 3: All Tiers & Key-Model Pairs on Cooldown -> All Fail -> Graceful 503
// =========================================================================
console.log('\n3. Testing emergency recovery when ALL candidates error out...');
const allFailModelName = `all-fail-model-${Date.now()}`;
const allFailModel = configStore.saveCustomModel({
name: allFailModelName,
tiers: [
{
tierIndex: 0,
name: 'Tier 0',
targets: [{ providerId: pT0.id, model: 'all-fail-model' }]
}
]
});
modelCircuitBreaker.tripCooldown(pT0.id, 'all-fail-model', 'Outage');
configStore.updateKeyStats(pT0.id, 'key-t0-1', { rateLimitedUntil: Date.now() + 60000 });
configStore.updateKeyStats(pT0.id, 'key-t0-2', { rateLimitedUntil: Date.now() + 60000 });
const allFailRes = await fetch(`${baseUrl}/v1/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify({
model: allFailModelName,
messages: [{ role: 'user', content: 'All fail test' }],
stream: false
})
});
assert.strictEqual(allFailRes.status, 503, 'Expected 503 all_tiers_exhausted when all probes fail');
const allFailData = (await allFailRes.json()) as any;
assert.strictEqual(allFailData.error.code, 'all_tiers_exhausted');
assert.strictEqual(modelCircuitBreaker.isTargetInCooldown(pT0.id, 'all-fail-model'), true);
console.log(' ✓ When all emergency candidate probes fail, request gracefully terminated with 503 all_tiers_exhausted and all were put back on cooldown.');
// Cleanup
configStore.deleteCustomModel(testModel.id);
configStore.deleteCustomModel(allFailModel.id);
configStore.deleteProvider(pT0.id);
configStore.deleteProvider(pT1.id);
modelCircuitBreaker.reset();
console.log('\n🎉 ALL MODERATION & EMERGENCY COOLDOWN RECOVERY TESTS PASSED SUCCESSFULLY!\n');
} finally {
server.close();
mockServer.close();
}
}
runTests().catch(err => {
console.error('Test failed with error:', err);
process.exit(1);
});