feat(admin): add live key+model fallback telemetry and RAM-buffered live request log watcher
- Add TelemetryTracker to record request fallback journeys, tracking step-by-step cascades across tiers, candidate error codes, cooldowns, and next actions - Add LiveWatcher for RAM-only interactive request inspection with 250-item FIFO safety cap and automatic memory flush on toggle off - Add REST and SSE streaming endpoints for real-time telemetry and live request logs - Upgrade Admin Telemetry tab with visual fallback breadcrumbs and live key health matrix - Add dedicated Live Logs tab with deep multi-tab inspector (Input, Output, Metadata, Debug), search, filters, and JSON export - Add unit and integration tests (test-live-watcher.ts, test-telemetry-fallback.ts)
This commit is contained in:
parent
0e83233715
commit
299c5f4c9e
11 changed files with 2603 additions and 71 deletions
|
|
@ -11,6 +11,8 @@ import {
|
|||
ExecutionDiagnosticTrace
|
||||
} from './revolverTypes';
|
||||
import { OpenAIChatRequest, OpenAIChatResponse } from './openaiTypes';
|
||||
import { telemetryTracker, FallbackStep, RequestFallbackJourney } from './telemetryTracker';
|
||||
import { liveWatcher } from './liveWatcher';
|
||||
|
||||
interface CandidateExecution {
|
||||
tier: FallbackTier;
|
||||
|
|
@ -239,6 +241,7 @@ export class RevolverEngine {
|
|||
if (!res.writableEnded) {
|
||||
isCancelled = true;
|
||||
if (onCancelled) onCancelled();
|
||||
liveWatcher.cancelRequest(requestId);
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -257,12 +260,14 @@ export class RevolverEngine {
|
|||
// Immediately transmit an initial SSE comment ping so Cloudflare Edge receives response bytes instantly
|
||||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.write(': keep-alive\n\n');
|
||||
liveWatcher.recordKeepAlive(requestId, 'sse_comment');
|
||||
}
|
||||
|
||||
// Keep connection active with periodic SSE comments while waiting for model thinking / generation
|
||||
keepAliveTimer = setInterval(() => {
|
||||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.write(': keep-alive\n\n');
|
||||
liveWatcher.recordKeepAlive(requestId, 'sse_comment');
|
||||
}
|
||||
}, config.keepAliveIntervalMs);
|
||||
} else if (config.enableNonStreamingKeepAlive) {
|
||||
|
|
@ -282,6 +287,7 @@ export class RevolverEngine {
|
|||
}
|
||||
}
|
||||
res.write(' ');
|
||||
liveWatcher.recordKeepAlive(requestId, 'whitespace');
|
||||
}, config.nonStreamingKeepAliveDelayMs);
|
||||
}
|
||||
|
||||
|
|
@ -292,6 +298,9 @@ export class RevolverEngine {
|
|||
throw new Error(`Custom model '${customModel.name}' has no fallback tiers defined.`);
|
||||
}
|
||||
|
||||
const journeyStart = Date.now();
|
||||
const fallbackSteps: FallbackStep[] = [];
|
||||
let totalHops = 0;
|
||||
let lastError: any = null;
|
||||
|
||||
// Traverse tiers: Tier 0 -> Tier 1 -> Tier 2...
|
||||
|
|
@ -311,11 +320,16 @@ export class RevolverEngine {
|
|||
return;
|
||||
}
|
||||
|
||||
const candidateStart = Date.now();
|
||||
totalHops++;
|
||||
const isLastCandidateInTier = candidate === candidates[candidates.length - 1];
|
||||
const isLastTier = tier === sortedTiers[sortedTiers.length - 1];
|
||||
|
||||
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}]`);
|
||||
|
||||
if (isStreaming) {
|
||||
await this.executeStreaming({
|
||||
const streamResult = await this.executeStreaming({
|
||||
candidate,
|
||||
requestBody,
|
||||
requestedModelName,
|
||||
|
|
@ -327,7 +341,64 @@ export class RevolverEngine {
|
|||
onSuccess
|
||||
});
|
||||
cleanupTimers();
|
||||
// If stream finished successfully, return
|
||||
|
||||
const stepDuration = Date.now() - candidateStart;
|
||||
const successStep: FallbackStep = {
|
||||
stepIndex: totalHops,
|
||||
timestamp: new Date().toISOString(),
|
||||
tierIndex: tier.tierIndex,
|
||||
tierName: tier.name || `Tier ${tier.tierIndex}`,
|
||||
providerId: candidate.provider.id,
|
||||
providerName: candidate.provider.name,
|
||||
providerType: candidate.provider.type,
|
||||
model: candidate.target.model,
|
||||
keyIndex: candidate.keyIndex,
|
||||
maskedKey: this.store.maskKey(candidate.keyConfig.key),
|
||||
durationMs: stepDuration,
|
||||
status: 'success',
|
||||
statusCode: 200,
|
||||
nextAction: 'Served successfully'
|
||||
};
|
||||
fallbackSteps.push(successStep);
|
||||
liveWatcher.recordCandidateStep(requestId, successStep);
|
||||
|
||||
const promptTokens = streamResult?.promptTokens || Math.ceil(JSON.stringify(requestBody.messages).length / 4);
|
||||
const completionTokens = streamResult?.completionTokens || 0;
|
||||
const journey: RequestFallbackJourney = {
|
||||
requestId,
|
||||
timestamp: new Date().toISOString(),
|
||||
requestedModel: requestBody.model || requestedModelName,
|
||||
resolvedModelName: customModel.name,
|
||||
resolvedModelId: customModel.id,
|
||||
finalStatus: fallbackSteps.length > 1 ? 'success_fallback' : 'success_direct',
|
||||
totalDurationMs: Date.now() - journeyStart,
|
||||
totalHops,
|
||||
fallbackOccurred: fallbackSteps.length > 1,
|
||||
finalServedBy: {
|
||||
tierIndex: tier.tierIndex,
|
||||
tierName: tier.name || `Tier ${tier.tierIndex}`,
|
||||
providerName: candidate.provider.name,
|
||||
providerType: candidate.provider.type,
|
||||
model: candidate.target.model,
|
||||
maskedKey: this.store.maskKey(candidate.keyConfig.key)
|
||||
},
|
||||
tokens: {
|
||||
promptTokens,
|
||||
completionTokens,
|
||||
totalTokens: promptTokens + completionTokens
|
||||
},
|
||||
steps: fallbackSteps
|
||||
};
|
||||
telemetryTracker.recordJourney(journey);
|
||||
telemetryTracker.broadcastKeyStatus();
|
||||
liveWatcher.completeRequest({
|
||||
requestId,
|
||||
statusCode: 200,
|
||||
journey,
|
||||
tokens: { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens },
|
||||
finishReason: streamResult?.finishReason || 'stop'
|
||||
});
|
||||
|
||||
return;
|
||||
} else {
|
||||
const responseData = await this.executeNonStreaming({
|
||||
|
|
@ -346,12 +417,69 @@ export class RevolverEngine {
|
|||
rateLimitedUntil: null
|
||||
});
|
||||
|
||||
const promptTokens = responseData.usage?.prompt_tokens || 0;
|
||||
const completionTokens = responseData.usage?.completion_tokens || 0;
|
||||
|
||||
if (onSuccess) {
|
||||
const promptTokens = responseData.usage?.prompt_tokens || 0;
|
||||
const completionTokens = responseData.usage?.completion_tokens || 0;
|
||||
onSuccess({ input: promptTokens, output: completionTokens });
|
||||
}
|
||||
|
||||
const stepDuration = Date.now() - candidateStart;
|
||||
const successStep: FallbackStep = {
|
||||
stepIndex: totalHops,
|
||||
timestamp: new Date().toISOString(),
|
||||
tierIndex: tier.tierIndex,
|
||||
tierName: tier.name || `Tier ${tier.tierIndex}`,
|
||||
providerId: candidate.provider.id,
|
||||
providerName: candidate.provider.name,
|
||||
providerType: candidate.provider.type,
|
||||
model: candidate.target.model,
|
||||
keyIndex: candidate.keyIndex,
|
||||
maskedKey: this.store.maskKey(candidate.keyConfig.key),
|
||||
durationMs: stepDuration,
|
||||
status: 'success',
|
||||
statusCode: 200,
|
||||
nextAction: 'Served successfully'
|
||||
};
|
||||
fallbackSteps.push(successStep);
|
||||
liveWatcher.recordCandidateStep(requestId, successStep);
|
||||
|
||||
const journey: RequestFallbackJourney = {
|
||||
requestId,
|
||||
timestamp: new Date().toISOString(),
|
||||
requestedModel: requestBody.model || requestedModelName,
|
||||
resolvedModelName: customModel.name,
|
||||
resolvedModelId: customModel.id,
|
||||
finalStatus: fallbackSteps.length > 1 ? 'success_fallback' : 'success_direct',
|
||||
totalDurationMs: Date.now() - journeyStart,
|
||||
totalHops,
|
||||
fallbackOccurred: fallbackSteps.length > 1,
|
||||
finalServedBy: {
|
||||
tierIndex: tier.tierIndex,
|
||||
tierName: tier.name || `Tier ${tier.tierIndex}`,
|
||||
providerName: candidate.provider.name,
|
||||
providerType: candidate.provider.type,
|
||||
model: candidate.target.model,
|
||||
maskedKey: this.store.maskKey(candidate.keyConfig.key)
|
||||
},
|
||||
tokens: {
|
||||
promptTokens,
|
||||
completionTokens,
|
||||
totalTokens: promptTokens + completionTokens
|
||||
},
|
||||
steps: fallbackSteps
|
||||
};
|
||||
telemetryTracker.recordJourney(journey);
|
||||
telemetryTracker.broadcastKeyStatus();
|
||||
liveWatcher.completeRequest({
|
||||
requestId,
|
||||
statusCode: 200,
|
||||
journey,
|
||||
responseData,
|
||||
tokens: { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens },
|
||||
finishReason: responseData.choices?.[0]?.finish_reason || 'stop'
|
||||
});
|
||||
|
||||
if (res.headersSent) {
|
||||
// Chunked keep-alive headers were already emitted
|
||||
res.write(JSON.stringify(responseData));
|
||||
|
|
@ -365,10 +493,67 @@ export class RevolverEngine {
|
|||
lastError = err;
|
||||
console.error(`[REVOLVER] Candidate failed (Provider: '${candidate.provider.name}', Model: '${candidate.target.model}'):`, err.message);
|
||||
|
||||
const stepDuration = Date.now() - candidateStart;
|
||||
const isRateLimit = this.isRateLimitOrQuotaError(err);
|
||||
const isServerErr = this.isServerError(err);
|
||||
const cooldown = isRateLimit ? config.rateLimitDurationMs : (isServerErr ? 15000 : undefined);
|
||||
const statusType = isRateLimit ? 'rate_limited' : (isServerErr ? 'server_error' : 'failed');
|
||||
|
||||
let nextAction = '';
|
||||
if (!isLastCandidateInTier) {
|
||||
nextAction = `Rotating to next key in Tier ${tier.tierIndex}`;
|
||||
} else if (!isLastTier) {
|
||||
nextAction = `Tier ${tier.tierIndex} exhausted. Cascading to Fallback Tier ${sortedTiers[sortedTiers.indexOf(tier) + 1]?.tierIndex ?? 'next'}`;
|
||||
} else {
|
||||
nextAction = 'All tiers and candidates exhausted';
|
||||
}
|
||||
|
||||
const failedStep: FallbackStep = {
|
||||
stepIndex: totalHops,
|
||||
timestamp: new Date().toISOString(),
|
||||
tierIndex: tier.tierIndex,
|
||||
tierName: tier.name || `Tier ${tier.tierIndex}`,
|
||||
providerId: candidate.provider.id,
|
||||
providerName: candidate.provider.name,
|
||||
providerType: candidate.provider.type,
|
||||
model: candidate.target.model,
|
||||
keyIndex: candidate.keyIndex,
|
||||
maskedKey: this.store.maskKey(candidate.keyConfig.key),
|
||||
durationMs: stepDuration,
|
||||
status: statusType,
|
||||
statusCode: err.status || (isRateLimit ? 429 : 500),
|
||||
errorMessage: err.message,
|
||||
rateLimitedUntil: cooldown ? Date.now() + cooldown : null,
|
||||
cooldownSeconds: cooldown ? Math.ceil(cooldown / 1000) : undefined,
|
||||
nextAction
|
||||
};
|
||||
fallbackSteps.push(failedStep);
|
||||
liveWatcher.recordCandidateStep(requestId, failedStep);
|
||||
|
||||
// If stream has already started sending content bytes to the client, we cannot fail over cleanly
|
||||
if (streamStarted) {
|
||||
cleanupTimers();
|
||||
if (onFailure) onFailure('stream_interrupted');
|
||||
const journey: RequestFallbackJourney = {
|
||||
requestId,
|
||||
timestamp: new Date().toISOString(),
|
||||
requestedModel: requestBody.model || requestedModelName,
|
||||
resolvedModelName: customModel.name,
|
||||
resolvedModelId: customModel.id,
|
||||
finalStatus: 'all_tiers_exhausted',
|
||||
totalDurationMs: Date.now() - journeyStart,
|
||||
totalHops,
|
||||
fallbackOccurred: true,
|
||||
steps: fallbackSteps
|
||||
};
|
||||
telemetryTracker.recordJourney(journey);
|
||||
telemetryTracker.broadcastKeyStatus();
|
||||
liveWatcher.failRequest({
|
||||
requestId,
|
||||
statusCode: 500,
|
||||
error: err,
|
||||
journey
|
||||
});
|
||||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.write(`data: ${JSON.stringify({
|
||||
error: {
|
||||
|
|
@ -384,14 +569,10 @@ export class RevolverEngine {
|
|||
}
|
||||
|
||||
// Mark key rate limited or increment error
|
||||
const isRateLimit = this.isRateLimitOrQuotaError(err);
|
||||
const isServerErr = this.isServerError(err);
|
||||
|
||||
if (isRateLimit || isServerErr) {
|
||||
const cooldown = isRateLimit ? config.rateLimitDurationMs : 15000;
|
||||
console.warn(`[REVOLVER] Marking key ${this.store.maskKey(candidate.keyConfig.key)} rate-limited for ${cooldown / 1000}s`);
|
||||
console.warn(`[REVOLVER] Marking key ${this.store.maskKey(candidate.keyConfig.key)} rate-limited for ${cooldown! / 1000}s`);
|
||||
this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, {
|
||||
rateLimitedUntil: Date.now() + cooldown,
|
||||
rateLimitedUntil: Date.now() + cooldown!,
|
||||
incrementError: true
|
||||
});
|
||||
} else {
|
||||
|
|
@ -399,6 +580,7 @@ export class RevolverEngine {
|
|||
incrementError: true
|
||||
});
|
||||
}
|
||||
telemetryTracker.broadcastKeyStatus();
|
||||
|
||||
// Continue loop to try next candidate in this tier
|
||||
}
|
||||
|
|
@ -412,6 +594,27 @@ export class RevolverEngine {
|
|||
if (onFailure) onFailure('all_tiers_exhausted');
|
||||
const finalErrorMessage = lastError ? lastError.message : 'All model tiers and provider keys are exhausted or rate-limited.';
|
||||
|
||||
const journey: RequestFallbackJourney = {
|
||||
requestId,
|
||||
timestamp: new Date().toISOString(),
|
||||
requestedModel: requestBody.model || requestedModelName,
|
||||
resolvedModelName: customModel.name,
|
||||
resolvedModelId: customModel.id,
|
||||
finalStatus: 'all_tiers_exhausted',
|
||||
totalDurationMs: Date.now() - journeyStart,
|
||||
totalHops,
|
||||
fallbackOccurred: true,
|
||||
steps: fallbackSteps
|
||||
};
|
||||
telemetryTracker.recordJourney(journey);
|
||||
telemetryTracker.broadcastKeyStatus();
|
||||
liveWatcher.failRequest({
|
||||
requestId,
|
||||
statusCode: 503,
|
||||
error: lastError || new Error(finalErrorMessage),
|
||||
journey
|
||||
});
|
||||
|
||||
if (isStreaming) {
|
||||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.write(`data: ${JSON.stringify({
|
||||
|
|
@ -588,7 +791,7 @@ export class RevolverEngine {
|
|||
res: Response;
|
||||
onStreamStart: () => void;
|
||||
onSuccess?: (tokens: { input: number; output: number }) => void;
|
||||
}): Promise<void> {
|
||||
}): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> {
|
||||
const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params;
|
||||
|
||||
if (candidate.provider.type === 'gemini') {
|
||||
|
|
@ -622,7 +825,7 @@ export class RevolverEngine {
|
|||
res: Response;
|
||||
onStreamStart: () => void;
|
||||
onSuccess?: (tokens: { input: number; output: number }) => void;
|
||||
}): Promise<void> {
|
||||
}): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> {
|
||||
const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params;
|
||||
const genAI = this.getGeminiClient(candidate.keyConfig.key);
|
||||
|
||||
|
|
@ -669,6 +872,7 @@ export class RevolverEngine {
|
|||
if (res.destroyed) break;
|
||||
const text = chunk.text();
|
||||
fullContent += text;
|
||||
liveWatcher.appendStreamChunk(requestId, text);
|
||||
onStreamStart();
|
||||
|
||||
const chunkResponse = {
|
||||
|
|
@ -727,6 +931,12 @@ export class RevolverEngine {
|
|||
if (onSuccess) {
|
||||
onSuccess({ input: promptTokens, output: completionTokens });
|
||||
}
|
||||
|
||||
return {
|
||||
promptTokens,
|
||||
completionTokens,
|
||||
finishReason: 'stop'
|
||||
};
|
||||
}
|
||||
|
||||
private async executeOpenAICompatibleStreaming(params: {
|
||||
|
|
@ -737,7 +947,7 @@ export class RevolverEngine {
|
|||
res: Response;
|
||||
onStreamStart: () => void;
|
||||
onSuccess?: (tokens: { input: number; output: number }) => void;
|
||||
}): Promise<void> {
|
||||
}): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> {
|
||||
const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params;
|
||||
|
||||
const baseUrl = (candidate.provider.baseUrl || this.store.getDefaultBaseUrl(candidate.provider.type)).replace(/\/+$/, '');
|
||||
|
|
@ -822,7 +1032,9 @@ export class RevolverEngine {
|
|||
parsed.model = requestedModelName;
|
||||
if (parsed.choices?.[0]?.delta?.content) {
|
||||
onStreamStart();
|
||||
totalOutputChars += parsed.choices[0].delta.content.length;
|
||||
const delta = parsed.choices[0].delta.content;
|
||||
totalOutputChars += delta.length;
|
||||
liveWatcher.appendStreamChunk(requestId, delta);
|
||||
}
|
||||
res.write(`data: ${JSON.stringify(parsed)}\n\n`);
|
||||
} catch {
|
||||
|
|
@ -850,6 +1062,12 @@ export class RevolverEngine {
|
|||
if (onSuccess) {
|
||||
onSuccess({ input: estimatedInput, output: estimatedOutput });
|
||||
}
|
||||
|
||||
return {
|
||||
promptTokens: estimatedInput,
|
||||
completionTokens: estimatedOutput,
|
||||
finishReason: 'stop'
|
||||
};
|
||||
}
|
||||
|
||||
// Diagnostic Test Prompt Runner for the Admin Playground
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue