fix timeouts
This commit is contained in:
parent
9105599c64
commit
b8628cc0f1
4 changed files with 403 additions and 241 deletions
|
|
@ -30,6 +30,9 @@ RATE_LIMIT_DURATION_MS=60000
|
|||
# Streaming Time-To-First-Token (TTFT) timeout before failover (in ms, default 15s)
|
||||
# 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_COOLDOWN_MS=60000
|
||||
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ export const config = {
|
|||
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),
|
||||
streamIdleTimeoutMs: parseInt(process.env.STREAM_IDLE_TIMEOUT_MS || '120000', 10),
|
||||
modelCooldownDurationMs: parseInt(process.env.MODEL_COOLDOWN_MS || '60000', 10),
|
||||
maxTargetTimeoutRetries: parseInt(process.env.MAX_TARGET_TIMEOUT_RETRIES || '0', 10),
|
||||
maxTargetOverloadRetries: parseInt(process.env.MAX_TARGET_OVERLOAD_RETRIES || '1', 10),
|
||||
|
|
|
|||
|
|
@ -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: {
|
||||
requestBody: OpenAIChatRequest;
|
||||
requestId: string;
|
||||
|
|
@ -674,6 +707,7 @@ export class RevolverEngine {
|
|||
const hasReachedOverloadLimit = isModelOverload && overloadAttempts >= maxOverloadAttempts;
|
||||
|
||||
let tripResult = { tripped: false, cooldownSeconds: 0, reason: '' };
|
||||
if (!streamStarted) {
|
||||
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);
|
||||
|
|
@ -690,6 +724,7 @@ export class RevolverEngine {
|
|||
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.
|
||||
// Enforce this cap in ALL modes (normal and allPairsOnCooldown emergency mode).
|
||||
|
|
@ -1193,7 +1228,7 @@ export class RevolverEngine {
|
|||
model: candidate.target.model,
|
||||
systemInstruction: systemInstruction || undefined,
|
||||
safetySettings: shouldDisableModeration ? GEMINI_SAFETY_SETTINGS_BLOCK_NONE : undefined
|
||||
}, { timeout: config.candidateTimeoutMs });
|
||||
});
|
||||
|
||||
const lastMessage = geminiMessages[geminiMessages.length - 1];
|
||||
if (!lastMessage || lastMessage.role !== 'user') {
|
||||
|
|
@ -1209,9 +1244,15 @@ export class RevolverEngine {
|
|||
}
|
||||
});
|
||||
|
||||
// Start streaming from Gemini
|
||||
const result = await chat.sendMessageStream(lastMessage.parts[0].text);
|
||||
const abortController = new AbortController();
|
||||
const onClientClose = () => {
|
||||
if (!res.writableEnded) {
|
||||
abortController.abort();
|
||||
}
|
||||
};
|
||||
res.on('close', onClientClose);
|
||||
|
||||
let result: Awaited<ReturnType<typeof chat.sendMessageStream>>;
|
||||
let fullContent = '';
|
||||
let promptTokens = 0;
|
||||
let completionTokens = 0;
|
||||
|
|
@ -1220,30 +1261,24 @@ export class RevolverEngine {
|
|||
: { mode: 'none' as const, filters: [] };
|
||||
const collectedChunkTraces: FilterExecutionStepTrace[] = [];
|
||||
|
||||
try {
|
||||
// Start streaming from Gemini with connection/headers timeout
|
||||
result = await this.raceWithTimeout(
|
||||
() => chat.sendMessageStream(lastMessage.parts[0].text, { signal: abortController.signal }),
|
||||
config.candidateTimeoutMs,
|
||||
'The operation was aborted due to timeout',
|
||||
(err) => abortController.abort(err)
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
const firstResult = await this.raceWithTimeout(
|
||||
() => streamIterator.next(),
|
||||
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) {
|
||||
|
|
@ -1310,7 +1345,12 @@ export class RevolverEngine {
|
|||
|
||||
while (true) {
|
||||
if (res.destroyed) break;
|
||||
const { done, value } = await streamIterator.next();
|
||||
const { done, value } = await this.raceWithTimeout(
|
||||
() => streamIterator.next(),
|
||||
config.streamIdleTimeoutMs,
|
||||
`Streaming idle timeout: no chunks received within ${config.streamIdleTimeoutMs}ms`,
|
||||
(err) => abortController.abort(err)
|
||||
);
|
||||
if (done) break;
|
||||
|
||||
let text = '';
|
||||
|
|
@ -1324,6 +1364,9 @@ export class RevolverEngine {
|
|||
}
|
||||
handleGeminiChunk(text);
|
||||
}
|
||||
} finally {
|
||||
res.off('close', onClientClose);
|
||||
}
|
||||
|
||||
if (streamStrategy.mode === 'buffer_full' && customModel) {
|
||||
const outputFilterResult = this.filterEngine.applyOutputFilters({
|
||||
|
|
@ -1438,7 +1481,32 @@ export class RevolverEngine {
|
|||
stream: true
|
||||
};
|
||||
|
||||
const response = await fetch(url, {
|
||||
const abortController = new AbortController();
|
||||
const onClientClose = () => {
|
||||
if (!res.writableEnded) {
|
||||
abortController.abort();
|
||||
}
|
||||
};
|
||||
res.on('close', onClientClose);
|
||||
|
||||
let buffer = '';
|
||||
let totalOutputChars = 0;
|
||||
let fullContent = '';
|
||||
let finishReason = 'stop';
|
||||
let streamHasStarted = false;
|
||||
const streamStrategy = customModel
|
||||
? this.filterEngine.getStreamingStrategy(customModel)
|
||||
: { mode: 'none' as const, filters: [] };
|
||||
const collectedChunkTraces: FilterExecutionStepTrace[] = [];
|
||||
|
||||
try {
|
||||
let connectionTimer: NodeJS.Timeout | null = setTimeout(() => {
|
||||
abortController.abort(this.createTimeoutError('The operation was aborted due to timeout'));
|
||||
}, config.candidateTimeoutMs);
|
||||
|
||||
let response: globalThis.Response;
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
|
|
@ -1446,7 +1514,7 @@ export class RevolverEngine {
|
|||
'Accept-Encoding': 'identity'
|
||||
},
|
||||
body: JSON.stringify(forwardedBody),
|
||||
signal: AbortSignal.timeout(config.candidateTimeoutMs)
|
||||
signal: abortController.signal
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
|
|
@ -1465,6 +1533,12 @@ export class RevolverEngine {
|
|||
(err as any).status = response.status;
|
||||
throw err;
|
||||
}
|
||||
} finally {
|
||||
if (connectionTimer) {
|
||||
clearTimeout(connectionTimer);
|
||||
connectionTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error('Response body is null from provider stream.');
|
||||
|
|
@ -1483,15 +1557,6 @@ export class RevolverEngine {
|
|||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
let totalOutputChars = 0;
|
||||
let fullContent = '';
|
||||
let finishReason = 'stop';
|
||||
let streamHasStarted = false;
|
||||
const streamStrategy = customModel
|
||||
? this.filterEngine.getStreamingStrategy(customModel)
|
||||
: { mode: 'none' as const, filters: [] };
|
||||
const collectedChunkTraces: FilterExecutionStepTrace[] = [];
|
||||
|
||||
const processText = (textChunk: string) => {
|
||||
buffer += textChunk;
|
||||
|
|
@ -1522,6 +1587,17 @@ export class RevolverEngine {
|
|||
if (parsed.choices?.[0]?.finish_reason) {
|
||||
finishReason = parsed.choices[0].finish_reason;
|
||||
}
|
||||
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') {
|
||||
|
|
@ -1563,29 +1639,18 @@ export class RevolverEngine {
|
|||
}
|
||||
};
|
||||
|
||||
// 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);
|
||||
});
|
||||
const abortStreamRead = (err: Error) => {
|
||||
reader.cancel(err).catch(() => {});
|
||||
abortController.abort(err);
|
||||
};
|
||||
|
||||
let firstReadResult: { done?: boolean; value?: Uint8Array };
|
||||
try {
|
||||
firstReadResult = await Promise.race([
|
||||
reader.read(),
|
||||
ttftPromise
|
||||
]);
|
||||
} finally {
|
||||
if (ttftTimer) {
|
||||
clearTimeout(ttftTimer);
|
||||
ttftTimer = null;
|
||||
}
|
||||
}
|
||||
// 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 });
|
||||
|
|
@ -1594,7 +1659,12 @@ export class RevolverEngine {
|
|||
|
||||
while (true) {
|
||||
if (res.destroyed) break;
|
||||
const { done, value } = await reader.read();
|
||||
const { done, value } = await this.raceWithTimeout(
|
||||
() => reader.read(),
|
||||
config.streamIdleTimeoutMs,
|
||||
`Streaming idle timeout: no chunks received within ${config.streamIdleTimeoutMs}ms`,
|
||||
abortStreamRead
|
||||
);
|
||||
if (done) break;
|
||||
|
||||
const text = decoder.decode(value, { stream: true });
|
||||
|
|
@ -1605,6 +1675,9 @@ export class RevolverEngine {
|
|||
if (buffer.trim()) {
|
||||
processText('\n');
|
||||
}
|
||||
} finally {
|
||||
res.off('close', onClientClose);
|
||||
}
|
||||
|
||||
if (streamStrategy.mode === 'buffer_full' && customModel) {
|
||||
const outputFilterResult = this.filterEngine.applyOutputFilters({
|
||||
|
|
|
|||
|
|
@ -14,13 +14,33 @@ async function runKeepAliveTests() {
|
|||
// 1. Create a mock upstream OpenAI-compatible server
|
||||
let mockStreamDelay = 250;
|
||||
let mockNonStreamDelay = 250;
|
||||
let mockLongStreamMode = false;
|
||||
|
||||
const mockUpstream = http.createServer((req, res) => {
|
||||
let body = '';
|
||||
req.on('data', chunk => (body += chunk));
|
||||
req.on('end', () => {
|
||||
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(() => {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
|
|
@ -186,6 +206,71 @@ async function runKeepAliveTests() {
|
|||
assert.strictEqual(fastData.choices[0].message.content, 'Mock non-streaming answer');
|
||||
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 {
|
||||
// Cleanup
|
||||
configStore.deleteCustomModel(testModel.id);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue