fix timeouts

This commit is contained in:
tyuXX 2026-11-19 18:23:28 +00:00
parent 9105599c64
commit b8628cc0f1
4 changed files with 403 additions and 241 deletions

View file

@ -30,6 +30,9 @@ RATE_LIMIT_DURATION_MS=60000
# Streaming Time-To-First-Token (TTFT) timeout before failover (in ms, default 15s) # Streaming Time-To-First-Token (TTFT) timeout before failover (in ms, default 15s)
# STREAM_FIRST_TOKEN_TIMEOUT_MS=15000 # STREAM_FIRST_TOKEN_TIMEOUT_MS=15000
# Streaming per-chunk idle timeout during active generation before aborting a stalled stream (in ms, default 120s)
# STREAM_IDLE_TIMEOUT_MS=120000
# Model circuit breaker cooldown duration on 503 / high demand (in ms, default 60s) # Model circuit breaker cooldown duration on 503 / high demand (in ms, default 60s)
# MODEL_COOLDOWN_MS=60000 # MODEL_COOLDOWN_MS=60000

View file

@ -18,6 +18,7 @@ export const config = {
candidateTimeoutMs: parseInt(process.env.CANDIDATE_TIMEOUT_MS || '20000', 10), candidateTimeoutMs: parseInt(process.env.CANDIDATE_TIMEOUT_MS || '20000', 10),
// Model Overload & Fast-Failover Circuit Breaker settings // Model Overload & Fast-Failover Circuit Breaker settings
streamFirstTokenTimeoutMs: parseInt(process.env.STREAM_FIRST_TOKEN_TIMEOUT_MS || '15000', 10), streamFirstTokenTimeoutMs: parseInt(process.env.STREAM_FIRST_TOKEN_TIMEOUT_MS || '15000', 10),
streamIdleTimeoutMs: parseInt(process.env.STREAM_IDLE_TIMEOUT_MS || '120000', 10),
modelCooldownDurationMs: parseInt(process.env.MODEL_COOLDOWN_MS || '60000', 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),
maxTargetOverloadRetries: parseInt(process.env.MAX_TARGET_OVERLOAD_RETRIES || '1', 10), maxTargetOverloadRetries: parseInt(process.env.MAX_TARGET_OVERLOAD_RETRIES || '1', 10),

View file

@ -310,6 +310,39 @@ export class RevolverEngine {
); );
} }
/** Creates a TimeoutError compatible with isTimeoutError() and Node fetch abort reasons. */
private createTimeoutError(message: string): Error {
const timeoutErr = new Error(message);
timeoutErr.name = 'TimeoutError';
return timeoutErr;
}
/** Races an async operation against a timeout timer, cleaning up the timer on settlement. */
private async raceWithTimeout<T>(
operation: () => Promise<T>,
timeoutMs: number,
timeoutMessage: string,
onTimeout?: (err: Error) => void
): Promise<T> {
let timer: NodeJS.Timeout | null = null;
const timeoutPromise = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
const err = this.createTimeoutError(timeoutMessage);
if (onTimeout) onTimeout(err);
reject(err);
}, timeoutMs);
});
try {
return await Promise.race([operation(), timeoutPromise]);
} finally {
if (timer) {
clearTimeout(timer);
timer = null;
}
}
}
public async executeChatCompletion(params: { public async executeChatCompletion(params: {
requestBody: OpenAIChatRequest; requestBody: OpenAIChatRequest;
requestId: string; requestId: string;
@ -674,21 +707,23 @@ export class RevolverEngine {
const hasReachedOverloadLimit = isModelOverload && overloadAttempts >= maxOverloadAttempts; const hasReachedOverloadLimit = isModelOverload && overloadAttempts >= maxOverloadAttempts;
let tripResult = { tripped: false, cooldownSeconds: 0, reason: '' }; let tripResult = { tripped: false, cooldownSeconds: 0, reason: '' };
if (allPairsOnCooldown) { if (!streamStarted) {
// When all pairs were on cooldown, emergency probe failed: put target and key back on cooldown immediately if (allPairsOnCooldown) {
modelCircuitBreaker.tripCooldown(candidate.provider.id, candidate.target.model, detailedErrorMessage); // When all pairs were on cooldown, emergency probe failed: put target and key back on cooldown immediately
this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { modelCircuitBreaker.tripCooldown(candidate.provider.id, candidate.target.model, detailedErrorMessage);
rateLimitedUntil: Date.now() + config.rateLimitDurationMs, this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, {
incrementError: true rateLimitedUntil: Date.now() + config.rateLimitDurationMs,
}); incrementError: true
} else if (isModelOverload || isTimeout) { });
tripResult = modelCircuitBreaker.recordFailure( } else if (isModelOverload || isTimeout) {
candidate.provider.id, tripResult = modelCircuitBreaker.recordFailure(
candidate.target.model, candidate.provider.id,
err, candidate.target.model,
isTimeout, err,
candidate.provider.keys.length isTimeout,
); candidate.provider.keys.length
);
}
} }
// On 503 high-demand/overload, only try 1 more key (up to maxOverloadAttempts = 2 keys total) before skipping remaining keys for this target. // On 503 high-demand/overload, only try 1 more key (up to maxOverloadAttempts = 2 keys total) before skipping remaining keys for this target.
@ -1193,7 +1228,7 @@ export class RevolverEngine {
model: candidate.target.model, model: candidate.target.model,
systemInstruction: systemInstruction || undefined, systemInstruction: systemInstruction || undefined,
safetySettings: shouldDisableModeration ? GEMINI_SAFETY_SETTINGS_BLOCK_NONE : undefined safetySettings: shouldDisableModeration ? GEMINI_SAFETY_SETTINGS_BLOCK_NONE : undefined
}, { timeout: config.candidateTimeoutMs }); });
const lastMessage = geminiMessages[geminiMessages.length - 1]; const lastMessage = geminiMessages[geminiMessages.length - 1];
if (!lastMessage || lastMessage.role !== 'user') { if (!lastMessage || lastMessage.role !== 'user') {
@ -1209,9 +1244,15 @@ export class RevolverEngine {
} }
}); });
// Start streaming from Gemini const abortController = new AbortController();
const result = await chat.sendMessageStream(lastMessage.parts[0].text); const onClientClose = () => {
if (!res.writableEnded) {
abortController.abort();
}
};
res.on('close', onClientClose);
let result: Awaited<ReturnType<typeof chat.sendMessageStream>>;
let fullContent = ''; let fullContent = '';
let promptTokens = 0; let promptTokens = 0;
let completionTokens = 0; let completionTokens = 0;
@ -1220,109 +1261,111 @@ export class RevolverEngine {
: { mode: 'none' as const, filters: [] }; : { mode: 'none' as const, filters: [] };
const collectedChunkTraces: FilterExecutionStepTrace[] = []; const collectedChunkTraces: FilterExecutionStepTrace[] = [];
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 { try {
firstResult = await Promise.race([ // Start streaming from Gemini with connection/headers timeout
streamIterator.next(), result = await this.raceWithTimeout(
ttftPromise () => chat.sendMessageStream(lastMessage.parts[0].text, { signal: abortController.signal }),
]); config.candidateTimeoutMs,
} finally { 'The operation was aborted due to timeout',
if (ttftTimer) { (err) => abortController.abort(err)
clearTimeout(ttftTimer); );
ttftTimer = null;
}
}
// If headers haven't been committed, commit them now const streamIterator = result.stream[Symbol.asyncIterator]();
if (!res.headersSent) {
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
if (typeof res.flushHeaders === 'function') {
res.flushHeaders();
}
}
const handleGeminiChunk = (rawChunkText: string) => { // TTFT Timeout: Wait for first chunk within streamFirstTokenTimeoutMs
if (streamStrategy.mode === 'buffer_full') { const firstResult = await this.raceWithTimeout(
fullContent += rawChunkText; () => streamIterator.next(),
return; config.streamFirstTokenTimeoutMs,
`Streaming TTFT timeout: no tokens received within ${config.streamFirstTokenTimeoutMs}ms`,
(err) => abortController.abort(err)
);
// If headers haven't been committed, commit them now
if (!res.headersSent) {
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
if (typeof res.flushHeaders === 'function') {
res.flushHeaders();
}
} }
let emittedText = rawChunkText; const handleGeminiChunk = (rawChunkText: string) => {
if (streamStrategy.mode === 'chunk_by_chunk' && customModel) { if (streamStrategy.mode === 'buffer_full') {
const chunkRes = this.filterEngine.applyOutputFilters({ fullContent += rawChunkText;
text: rawChunkText, return;
customModel, }
messages: requestBody.messages,
onlyChunkByChunk: true
});
emittedText = chunkRes.text;
collectedChunkTraces.push(...chunkRes.traces);
}
fullContent += emittedText; let emittedText = rawChunkText;
liveWatcher.appendStreamChunk(requestId, emittedText); if (streamStrategy.mode === 'chunk_by_chunk' && customModel) {
onStreamStart(); const chunkRes = this.filterEngine.applyOutputFilters({
text: rawChunkText,
customModel,
messages: requestBody.messages,
onlyChunkByChunk: true
});
emittedText = chunkRes.text;
collectedChunkTraces.push(...chunkRes.traces);
}
const chunkResponse = { fullContent += emittedText;
id: `chatcmpl-${requestId}`, liveWatcher.appendStreamChunk(requestId, emittedText);
object: 'chat.completion.chunk', onStreamStart();
created: Math.floor(Date.now() / 1000),
model: requestedModelName, const chunkResponse = {
choices: [ id: `chatcmpl-${requestId}`,
{ object: 'chat.completion.chunk',
index: 0, created: Math.floor(Date.now() / 1000),
delta: { content: emittedText }, model: requestedModelName,
finish_reason: null choices: [
} {
] index: 0,
delta: { content: emittedText },
finish_reason: null
}
]
};
res.write(`data: ${JSON.stringify(chunkResponse)}\n\n`);
}; };
res.write(`data: ${JSON.stringify(chunkResponse)}\n\n`); if (!firstResult.done && firstResult.value) {
}; let text = '';
try {
if (!firstResult.done && firstResult.value) { text = firstResult.value.text();
let text = ''; } catch (err: any) {
try { if (err?.message?.includes('SAFETY') || err?.message?.includes('blocked')) {
text = firstResult.value.text(); throw new Error(`Gemini stream blocked by upstream safety policy: ${err.message}`);
} catch (err: any) { }
if (err?.message?.includes('SAFETY') || err?.message?.includes('blocked')) { throw err;
throw new Error(`Gemini stream blocked by upstream safety policy: ${err.message}`);
} }
throw err; handleGeminiChunk(text);
} }
handleGeminiChunk(text);
}
while (true) { while (true) {
if (res.destroyed) break; if (res.destroyed) break;
const { done, value } = await streamIterator.next(); const { done, value } = await this.raceWithTimeout(
if (done) break; () => streamIterator.next(),
config.streamIdleTimeoutMs,
`Streaming idle timeout: no chunks received within ${config.streamIdleTimeoutMs}ms`,
(err) => abortController.abort(err)
);
if (done) break;
let text = ''; let text = '';
try { try {
text = value.text(); text = value.text();
} catch (err: any) { } catch (err: any) {
if (err?.message?.includes('SAFETY') || err?.message?.includes('blocked')) { if (err?.message?.includes('SAFETY') || err?.message?.includes('blocked')) {
throw new Error(`Gemini stream blocked by upstream safety policy: ${err.message}`); throw new Error(`Gemini stream blocked by upstream safety policy: ${err.message}`);
}
throw err;
} }
throw err; handleGeminiChunk(text);
} }
handleGeminiChunk(text); } finally {
res.off('close', onClientClose);
} }
if (streamStrategy.mode === 'buffer_full' && customModel) { if (streamStrategy.mode === 'buffer_full' && customModel) {
@ -1438,51 +1481,14 @@ export class RevolverEngine {
stream: true stream: true
}; };
const response = await fetch(url, { const abortController = new AbortController();
method: 'POST', const onClientClose = () => {
headers: { if (!res.writableEnded) {
'Content-Type': 'application/json', abortController.abort();
'Authorization': `Bearer ${candidate.keyConfig.key}`,
'Accept-Encoding': 'identity'
},
body: JSON.stringify(forwardedBody),
signal: AbortSignal.timeout(config.candidateTimeoutMs)
});
if (!response.ok) {
let errBody = '';
try {
errBody = await response.text();
} catch (readErr: any) {
errBody = readErr.message || 'Failed to read error response';
} }
let errorDetails = errBody; };
try { res.on('close', onClientClose);
const parsed = JSON.parse(errBody);
errorDetails = parsed.error?.message || errBody;
} catch {}
const err = new Error(`Provider API error (${response.status}): ${errorDetails}`);
(err as any).status = response.status;
throw err;
}
if (!response.body) {
throw new Error('Response body is null from provider stream.');
}
// If headers haven't been committed, commit them now
if (!res.headersSent) {
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
if (typeof res.flushHeaders === 'function') {
res.flushHeaders();
}
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = ''; let buffer = '';
let totalOutputChars = 0; let totalOutputChars = 0;
let fullContent = ''; let fullContent = '';
@ -1493,117 +1499,184 @@ export class RevolverEngine {
: { mode: 'none' as const, filters: [] }; : { mode: 'none' as const, filters: [] };
const collectedChunkTraces: FilterExecutionStepTrace[] = []; const collectedChunkTraces: FilterExecutionStepTrace[] = [];
const processText = (textChunk: string) => { try {
buffer += textChunk; let connectionTimer: NodeJS.Timeout | null = setTimeout(() => {
const lines = buffer.split('\n'); abortController.abort(this.createTimeoutError('The operation was aborted due to timeout'));
buffer = lines.pop() || ''; }, config.candidateTimeoutMs);
for (const line of lines) { let response: globalThis.Response;
const trimmed = line.trim(); try {
if (!trimmed) { response = await fetch(url, {
if (streamStrategy.mode !== 'buffer_full') { method: 'POST',
res.write('\n'); headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${candidate.keyConfig.key}`,
'Accept-Encoding': 'identity'
},
body: JSON.stringify(forwardedBody),
signal: abortController.signal
});
if (!response.ok) {
let errBody = '';
try {
errBody = await response.text();
} catch (readErr: any) {
errBody = readErr.message || 'Failed to read error response';
} }
continue; let errorDetails = errBody;
try {
const parsed = JSON.parse(errBody);
errorDetails = parsed.error?.message || errBody;
} catch {}
const err = new Error(`Provider API error (${response.status}): ${errorDetails}`);
(err as any).status = response.status;
throw err;
} }
} finally {
if (connectionTimer) {
clearTimeout(connectionTimer);
connectionTimer = null;
}
}
if (trimmed.startsWith('data: ')) { if (!response.body) {
const dataStr = trimmed.slice(6); throw new Error('Response body is null from provider stream.');
if (dataStr === '[DONE]') { }
// If headers haven't been committed, commit them now
if (!res.headersSent) {
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
if (typeof res.flushHeaders === 'function') {
res.flushHeaders();
}
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
const processText = (textChunk: string) => {
buffer += textChunk;
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) {
if (streamStrategy.mode !== 'buffer_full') { if (streamStrategy.mode !== 'buffer_full') {
res.write('data: [DONE]\n\n'); res.write('\n');
} }
continue; continue;
} }
try { if (trimmed.startsWith('data: ')) {
const parsed = JSON.parse(dataStr); const dataStr = trimmed.slice(6);
parsed.model = requestedModelName; if (dataStr === '[DONE]') {
if (parsed.choices?.[0]?.finish_reason) { if (streamStrategy.mode !== 'buffer_full') {
finishReason = parsed.choices[0].finish_reason; res.write('data: [DONE]\n\n');
}
if (parsed.choices?.[0]?.delta?.content) {
const rawDelta = parsed.choices[0].delta.content;
if (streamStrategy.mode === 'buffer_full') {
fullContent += rawDelta;
totalOutputChars += rawDelta.length;
continue;
} }
continue;
}
let emittedDelta = rawDelta; try {
if (streamStrategy.mode === 'chunk_by_chunk' && customModel) { const parsed = JSON.parse(dataStr);
const chunkRes = this.filterEngine.applyOutputFilters({ parsed.model = requestedModelName;
text: rawDelta, if (parsed.choices?.[0]?.finish_reason) {
customModel, finishReason = parsed.choices[0].finish_reason;
messages: requestBody.messages,
onlyChunkByChunk: true
});
emittedDelta = chunkRes.text;
parsed.choices[0].delta.content = emittedDelta;
collectedChunkTraces.push(...chunkRes.traces);
} }
const rawReasoning = parsed.choices?.[0]?.delta?.reasoning_content ?? parsed.choices?.[0]?.delta?.reasoning;
if (typeof rawReasoning === 'string' && rawReasoning.length > 0) {
totalOutputChars += rawReasoning.length;
if (streamStrategy.mode !== 'buffer_full') {
onStreamStart();
streamHasStarted = true;
if (!parsed.choices?.[0]?.delta?.content) {
liveWatcher.appendStreamChunk(requestId, rawReasoning);
}
}
}
if (parsed.choices?.[0]?.delta?.content) {
const rawDelta = parsed.choices[0].delta.content;
if (streamStrategy.mode === 'buffer_full') {
fullContent += rawDelta;
totalOutputChars += rawDelta.length;
continue;
}
onStreamStart(); let emittedDelta = rawDelta;
streamHasStarted = true; if (streamStrategy.mode === 'chunk_by_chunk' && customModel) {
totalOutputChars += emittedDelta.length; const chunkRes = this.filterEngine.applyOutputFilters({
fullContent += emittedDelta; text: rawDelta,
liveWatcher.appendStreamChunk(requestId, emittedDelta); customModel,
} messages: requestBody.messages,
if (streamStrategy.mode !== 'buffer_full') { onlyChunkByChunk: true
res.write(`data: ${JSON.stringify(parsed)}\n\n`); });
} emittedDelta = chunkRes.text;
} catch { parsed.choices[0].delta.content = emittedDelta;
if (streamStrategy.mode !== 'buffer_full') { collectedChunkTraces.push(...chunkRes.traces);
res.write(`${line}\n`); }
onStreamStart();
streamHasStarted = true;
totalOutputChars += emittedDelta.length;
fullContent += emittedDelta;
liveWatcher.appendStreamChunk(requestId, emittedDelta);
}
if (streamStrategy.mode !== 'buffer_full') {
res.write(`data: ${JSON.stringify(parsed)}\n\n`);
}
} catch {
if (streamStrategy.mode !== 'buffer_full') {
res.write(`${line}\n`);
}
} }
} else if (streamStrategy.mode !== 'buffer_full') {
res.write(`${line}\n`);
} }
} else if (streamStrategy.mode !== 'buffer_full') {
res.write(`${line}\n`);
} }
};
const abortStreamRead = (err: Error) => {
reader.cancel(err).catch(() => {});
abortController.abort(err);
};
// TTFT Timeout: Wait for first chunk within streamFirstTokenTimeoutMs
const firstReadResult = await this.raceWithTimeout(
() => reader.read(),
config.streamFirstTokenTimeoutMs,
`Streaming TTFT timeout: no tokens received within ${config.streamFirstTokenTimeoutMs}ms`,
abortStreamRead
);
if (!firstReadResult.done && firstReadResult.value) {
const text = decoder.decode(firstReadResult.value, { stream: true });
processText(text);
} }
};
// TTFT Timeout: Wait for first chunk within streamFirstTokenTimeoutMs while (true) {
let ttftTimer: NodeJS.Timeout | null = null; if (res.destroyed) break;
const ttftPromise = new Promise<never>((_, reject) => { const { done, value } = await this.raceWithTimeout(
ttftTimer = setTimeout(() => { () => reader.read(),
try { reader.cancel(); } catch {} config.streamIdleTimeoutMs,
const timeoutErr = new Error(`Streaming TTFT timeout: no tokens received within ${config.streamFirstTokenTimeoutMs}ms`); `Streaming idle timeout: no chunks received within ${config.streamIdleTimeoutMs}ms`,
(timeoutErr as any).name = 'TimeoutError'; abortStreamRead
reject(timeoutErr); );
}, config.streamFirstTokenTimeoutMs); if (done) break;
});
let firstReadResult: { done?: boolean; value?: Uint8Array }; const text = decoder.decode(value, { stream: true });
try { processText(text);
firstReadResult = await Promise.race([ }
reader.read(),
ttftPromise // Flush any remaining partial line in buffer
]); if (buffer.trim()) {
processText('\n');
}
} finally { } finally {
if (ttftTimer) { res.off('close', onClientClose);
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);
}
// Flush any remaining partial line in buffer
if (buffer.trim()) {
processText('\n');
} }
if (streamStrategy.mode === 'buffer_full' && customModel) { if (streamStrategy.mode === 'buffer_full' && customModel) {

View file

@ -14,13 +14,33 @@ async function runKeepAliveTests() {
// 1. Create a mock upstream OpenAI-compatible server // 1. Create a mock upstream OpenAI-compatible server
let mockStreamDelay = 250; let mockStreamDelay = 250;
let mockNonStreamDelay = 250; let mockNonStreamDelay = 250;
let mockLongStreamMode = false;
const mockUpstream = http.createServer((req, res) => { const mockUpstream = http.createServer((req, res) => {
let body = ''; let body = '';
req.on('data', chunk => (body += chunk)); req.on('data', chunk => (body += chunk));
req.on('end', () => { req.on('end', () => {
const parsed = JSON.parse(body || '{}'); const parsed = JSON.parse(body || '{}');
if (parsed.stream) { if (parsed.stream && mockLongStreamMode) {
setTimeout(() => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache'
});
res.write('data: {"choices":[{"delta":{"reasoning_content":"Thinking..."}}]}\n\n');
let count = 0;
const interval = setInterval(() => {
count++;
res.write(`data: {"choices":[{"delta":{"content":"Part ${count}"}}]}\n\n`);
if (count >= 5) {
clearInterval(interval);
res.write('data: [DONE]\n\n');
res.end();
}
}, 80);
}, 50);
} else if (parsed.stream) {
setTimeout(() => { setTimeout(() => {
res.writeHead(200, { res.writeHead(200, {
'Content-Type': 'text/event-stream', 'Content-Type': 'text/event-stream',
@ -186,6 +206,71 @@ async function runKeepAliveTests() {
assert.strictEqual(fastData.choices[0].message.content, 'Mock non-streaming answer'); assert.strictEqual(fastData.choices[0].message.content, 'Mock non-streaming answer');
console.log(' ✓ Fast requests preserve standard non-chunked JSON responses.'); console.log(' ✓ Fast requests preserve standard non-chunked JSON responses.');
// TEST 4: Long streaming generation exceeding candidateTimeoutMs succeeds
console.log('\n4. Testing Long Streaming Generation exceeding candidateTimeoutMs...');
const origCandidateTimeoutMs = config.candidateTimeoutMs;
const origStreamFirstTokenTimeoutMs = config.streamFirstTokenTimeoutMs;
config.candidateTimeoutMs = 200;
config.streamFirstTokenTimeoutMs = 150;
mockLongStreamMode = true;
try {
const longStart = Date.now();
const longResp = await fetch(`${baseUrl}/v1/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${validKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'test-keepalive-model',
stream: true,
messages: [{ role: 'user', content: 'Long high-token stream' }]
})
});
assert.strictEqual(longResp.status, 200);
const longReader = longResp.body!.getReader();
const longDecoder = new TextDecoder();
let receivedReasoning = '';
let receivedLongContent = '';
let sawDone = false;
while (true) {
const { done, value } = await longReader.read();
if (done) break;
const text = longDecoder.decode(value, { stream: true });
for (const line of text.split('\n')) {
const trimmed = line.trim();
if (!trimmed.startsWith('data: ')) continue;
const payload = trimmed.slice(6);
if (payload === '[DONE]') {
sawDone = true;
continue;
}
const parsed = JSON.parse(payload);
assert.ok(!parsed.error, `Stream should not emit error: ${JSON.stringify(parsed.error)}`);
if (parsed.choices?.[0]?.delta?.reasoning_content) {
receivedReasoning += parsed.choices[0].delta.reasoning_content;
}
if (parsed.choices?.[0]?.delta?.content) {
receivedLongContent += parsed.choices[0].delta.content;
}
}
}
const longDuration = Date.now() - longStart;
assert.ok(longDuration > config.candidateTimeoutMs, `Expected stream duration (${longDuration}ms) > candidateTimeoutMs (${config.candidateTimeoutMs}ms)`);
assert.strictEqual(receivedReasoning, 'Thinking...');
assert.strictEqual(receivedLongContent, 'Part 1Part 2Part 3Part 4Part 5');
assert.strictEqual(sawDone, true, 'Long stream should complete cleanly with [DONE]');
console.log(` ✓ Long streaming generation (${longDuration}ms > ${config.candidateTimeoutMs}ms) completed with reasoning and all content chunks.`);
} finally {
mockLongStreamMode = false;
config.candidateTimeoutMs = origCandidateTimeoutMs;
config.streamFirstTokenTimeoutMs = origStreamFirstTokenTimeoutMs;
}
} finally { } finally {
// Cleanup // Cleanup
configStore.deleteCustomModel(testModel.id); configStore.deleteCustomModel(testModel.id);