GeminiRevolver/test-content-length-resilience.ts

365 lines
15 KiB
TypeScript

import http from 'http';
import assert from 'assert';
import app from './src/index';
import { revolverEngine } from './src/revolverEngine';
import { configStore } from './src/configStore';
import { telemetryTracker } from './src/telemetryTracker';
const PORT = 3999;
const API_KEY = 'test_password';
console.log('🧪 Starting Content-Length Resilience & Upstream Failover Test Suite...\n');
async function runTests() {
const server = http.createServer(app);
await new Promise<void>((resolve) => server.listen(PORT, resolve));
const createdModelIds: string[] = [];
const createdProviderIds: string[] = [];
try {
// =========================================================================
// Test 1: Unit Test isServerError() logic via revolverEngine private access
// =========================================================================
console.log('1. Testing isServerError detection across all Content-Length and socket error variants...');
const isServerErrorFn = (revolverEngine as any).isServerError.bind(revolverEngine);
// 1.1 HTTP 5xx codes
assert.strictEqual(isServerErrorFn({ status: 500 }), true, '500 should be server error');
assert.strictEqual(isServerErrorFn({ status: 502 }), true, '502 should be server error');
assert.strictEqual(isServerErrorFn({ status: 503 }), true, '503 should be server error');
assert.strictEqual(isServerErrorFn({ statusCode: 504 }), true, '504 should be server error');
// 1.2 Undici Content-Length Mismatch Errors
const undiciContentLengthErr = new TypeError('fetch failed');
(undiciContentLengthErr as any).cause = {
name: 'ResponseContentLengthMismatchError',
code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH',
message: 'Response body length does not match content-length header'
};
assert.strictEqual(isServerErrorFn(undiciContentLengthErr), true, 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH must be server error');
// 1.3 Exact string from prompt: Content-Length header of network response exceeds response Body.
const exactPromptErr = new TypeError('fetch failed');
(exactPromptErr as any).cause = new Error('Content-Length header of network response exceeds response Body.');
assert.strictEqual(isServerErrorFn(exactPromptErr), true, 'Exact Content-Length mismatch string must be server error');
// 1.4 Socket closed prematurely (UND_ERR_SOCKET / other side closed)
const undiciSocketErr = new TypeError('fetch failed');
(undiciSocketErr as any).cause = {
name: 'SocketError',
code: 'UND_ERR_SOCKET',
message: 'other side closed'
};
assert.strictEqual(isServerErrorFn(undiciSocketErr), true, 'UND_ERR_SOCKET other side closed must be server error');
// 1.5 Node standard network errors
assert.strictEqual(isServerErrorFn({ code: 'ECONNRESET' }), true, 'ECONNRESET must be server error');
assert.strictEqual(isServerErrorFn({ code: 'ETIMEDOUT' }), true, 'ETIMEDOUT must be server error');
assert.strictEqual(isServerErrorFn({ code: 'ECONNREFUSED' }), true, 'ECONNREFUSED must be server error');
// 1.6 Client errors that should NOT be server error
assert.strictEqual(isServerErrorFn({ status: 400 }), false, '400 must NOT be server error');
assert.strictEqual(isServerErrorFn({ status: 401 }), false, '401 must NOT be server error');
assert.strictEqual(isServerErrorFn({ status: 404 }), false, '404 must NOT be server error');
assert.strictEqual(isServerErrorFn({ status: 429 }), false, '429 must NOT be server error (handled as rate limit)');
console.log(' ✓ isServerError accurately identifies undici/network/Content-Length mismatch errors.\n');
// =========================================================================
// Test 2: Non-Streaming: Recovery of valid JSON when upstream claims inflated Content-Length
// =========================================================================
console.log('2. Testing Non-Streaming recovery when upstream returns valid JSON but terminates with Content-Length mismatch...');
const validJsonPayload = {
id: 'chatcmpl-recovered-123',
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model: 'resilient-model',
choices: [
{
index: 0,
message: { role: 'assistant', content: 'Successfully parsed even with Content-Length header mismatch!' },
finish_reason: 'stop'
}
],
usage: { prompt_tokens: 10, completion_tokens: 12, total_tokens: 22 }
};
const validJsonStr = JSON.stringify(validJsonPayload);
// Mock server returns Content-Length: 5000, writes only ~250 bytes, then abruptly closes
const mockMismatchedServer = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': '5000' // Inflated Content-Length
});
res.write(validJsonStr);
// Abruptly destroy socket to trigger Content-Length mismatch on standard client
setTimeout(() => {
res.destroy();
}, 50);
});
await new Promise<void>((resolve) => mockMismatchedServer.listen(0, resolve));
const mismatchPort = (mockMismatchedServer.address() as any).port;
// Create provider with the mock server URL
const p1 = configStore.saveProvider({
name: 'Mismatched Content-Length Provider',
type: 'custom',
baseUrl: `http://localhost:${mismatchPort}`,
keys: ['mock-key-1']
});
createdProviderIds.push(p1.id);
const m1 = configStore.saveCustomModel({
name: 'model-mismatch-recovery',
tiers: [
{
tierIndex: 0,
name: 'Tier 0',
targets: [{ providerId: p1.id, model: 'mismatch-model' }]
}
]
});
createdModelIds.push(m1.id);
// Make non-streaming request to Revolver
const req1 = await fetch(`http://localhost:${PORT}/v1/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify({
model: 'model-mismatch-recovery',
messages: [{ role: 'user', content: 'Test prompt' }],
stream: false
})
});
assert.strictEqual(req1.status, 200, `Expected 200 OK, got ${req1.status}`);
const data1 = (await req1.json()) as any;
assert.strictEqual(data1.choices[0].message.content, 'Successfully parsed even with Content-Length header mismatch!');
console.log(' ✓ Revolver recovered full valid JSON payload despite upstream Content-Length mismatch.\n');
mockMismatchedServer.close();
// =========================================================================
// Test 3: Non-Streaming: Failover to Candidate 2 when upstream terminates with truly corrupted/truncated JSON
// =========================================================================
console.log('3. Testing Non-Streaming failover to Candidate 2 when Candidate 1 drops with truncated broken JSON...');
// Server 1 returns truncated broken JSON and closes socket
const mockCorruptedServer = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': '500'
});
res.write('{"choices": [{"message": {"content": "Truncated cut-off');
setTimeout(() => {
res.destroy();
}, 30);
});
await new Promise<void>((resolve) => mockCorruptedServer.listen(0, resolve));
const corruptPort = (mockCorruptedServer.address() as any).port;
// Server 2 returns valid 200 response
const mockHealthyServer = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
id: 'chatcmpl-healthy-candidate',
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model: 'healthy-model',
choices: [
{
index: 0,
message: { role: 'assistant', content: 'Candidate 2 saved the day!' },
finish_reason: 'stop'
}
],
usage: { prompt_tokens: 5, completion_tokens: 8, total_tokens: 13 }
}));
});
await new Promise<void>((resolve) => mockHealthyServer.listen(0, resolve));
const healthyPort = (mockHealthyServer.address() as any).port;
const pCorrupt = configStore.saveProvider({
name: 'Corrupted Provider',
type: 'custom',
baseUrl: `http://localhost:${corruptPort}`,
keys: ['corrupt-key']
});
createdProviderIds.push(pCorrupt.id);
const pHealthy = configStore.saveProvider({
name: 'Healthy Provider',
type: 'custom',
baseUrl: `http://localhost:${healthyPort}`,
keys: ['healthy-key']
});
createdProviderIds.push(pHealthy.id);
const mFailover = configStore.saveCustomModel({
name: 'model-failover-test',
tiers: [
{
tierIndex: 0,
name: 'Tier 0',
targets: [
{ providerId: pCorrupt.id, model: 'corrupt-model' },
{ providerId: pHealthy.id, model: 'healthy-model' }
]
}
]
});
createdModelIds.push(mFailover.id);
const req2 = await fetch(`http://localhost:${PORT}/v1/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify({
model: 'model-failover-test',
messages: [{ role: 'user', content: 'Failover please' }],
stream: false
})
});
assert.strictEqual(req2.status, 200, `Expected 200 OK after failover, got ${req2.status}`);
const data2 = (await req2.json()) as any;
assert.strictEqual(data2.choices[0].message.content, 'Candidate 2 saved the day!');
// Verify Telemetry Tracker recorded candidate 1 failure and candidate 2 success
const latestJourneys = telemetryTracker.getRecentJourneys(1);
assert.strictEqual(latestJourneys.length, 1);
const j = latestJourneys[0];
assert.strictEqual(j.finalStatus, 'success_fallback');
assert.strictEqual(j.steps.length, 2);
assert.strictEqual(j.steps[0].status, 'server_error');
assert.strictEqual(j.steps[1].status, 'success');
console.log(' ✓ Revolver detected socket truncation, marked candidate 1 with server_error, and served via candidate 2.\n');
mockCorruptedServer.close();
mockHealthyServer.close();
// =========================================================================
// Test 4: Streaming: Failover to Candidate 2 when Candidate 1 drops stream before first token
// =========================================================================
console.log('4. Testing Streaming failover to Candidate 2 when Candidate 1 terminates stream prematurely...');
// Stream Server 1: Sends SSE 200 OK headers, but immediately destroys socket before data
const mockStreamCorrupt = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
setTimeout(() => {
res.destroy();
}, 30);
});
await new Promise<void>((resolve) => mockStreamCorrupt.listen(0, resolve));
const streamCorruptPort = (mockStreamCorrupt.address() as any).port;
// Stream Server 2: Sends proper SSE chunks and [DONE]
const mockStreamHealthy = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write(`data: ${JSON.stringify({
id: 'chatcmpl-stream-healthy',
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: 'healthy-stream-model',
choices: [{ index: 0, delta: { content: 'Streaming seamless failover succeeded!' }, finish_reason: null }]
})}\n\n`);
res.write('data: [DONE]\n\n');
res.end();
});
await new Promise<void>((resolve) => mockStreamHealthy.listen(0, resolve));
const streamHealthyPort = (mockStreamHealthy.address() as any).port;
const pStreamCorrupt = configStore.saveProvider({
name: 'Stream Corrupt Provider',
type: 'custom',
baseUrl: `http://localhost:${streamCorruptPort}`,
keys: ['stream-key-1']
});
createdProviderIds.push(pStreamCorrupt.id);
const pStreamHealthy = configStore.saveProvider({
name: 'Stream Healthy Provider',
type: 'custom',
baseUrl: `http://localhost:${streamHealthyPort}`,
keys: ['stream-key-2']
});
createdProviderIds.push(pStreamHealthy.id);
const mStreamFailover = configStore.saveCustomModel({
name: 'model-stream-failover-test',
tiers: [
{
tierIndex: 0,
name: 'Tier 0',
targets: [
{ providerId: pStreamCorrupt.id, model: 'corrupt-stream' },
{ providerId: pStreamHealthy.id, model: 'healthy-stream' }
]
}
]
});
createdModelIds.push(mStreamFailover.id);
const req3 = await fetch(`http://localhost:${PORT}/v1/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify({
model: 'model-stream-failover-test',
messages: [{ role: 'user', content: 'Stream failover please' }],
stream: true
})
});
assert.strictEqual(req3.status, 200, `Expected 200 OK for stream, got ${req3.status}`);
const streamBody = await req3.text();
assert.ok(streamBody.includes('Streaming seamless failover succeeded!'), 'Stream body must contain content from Candidate 2');
assert.ok(streamBody.includes('[DONE]'), 'Stream body must end with [DONE]');
console.log(' ✓ Revolver caught stream drop on candidate 1 and cleanly streamed candidate 2 to client.\n');
mockStreamCorrupt.close();
mockStreamHealthy.close();
// =========================================================================
// Test 5: Verify Cache-Control: no-cache, no-transform header is sent downstream
// =========================================================================
console.log('5. Testing downstream Cache-Control: no-cache, no-transform headers...');
const cacheHeader = req1.headers.get('cache-control');
assert.ok(cacheHeader && cacheHeader.includes('no-transform'), 'Downstream response must include no-transform to prevent proxy compression mismatches');
console.log(' ✓ Cache-Control: no-cache, no-transform verified on downstream responses.\n');
console.log('🎉 ALL CONTENT-LENGTH RESILIENCE & FAILOVER TESTS PASSED SUCCESSFULLY!\n');
} finally {
for (const mId of createdModelIds) {
try { configStore.deleteCustomModel(mId); } catch {}
}
for (const pId of createdProviderIds) {
try { configStore.deleteProvider(pId); } catch {}
}
server.close();
}
}
runTests().catch((err) => {
console.error('❌ Test suite failed:', err);
process.exit(1);
});