feat(panel): add step anomaly diagnostics, >=100 tok/s integer speed formatting, and capsule alignment fix

This commit is contained in:
fish
2026-11-19 22:28:39 +09:00
parent dfba5ead7b
commit 4a4e483209
20 changed files with 3546 additions and 143 deletions
+360
View File
@@ -597,6 +597,260 @@ export function extractContextBreakdown(chat) {
};
}
const ANOMALY_SEVERITY_PRIORITY = Object.freeze({
rate_limit: 9,
auth_or_model: 8,
timeout: 7,
capacity: 6,
disconnect: 5,
upstream: 4,
model_output: 3,
safety: 2,
error: 1,
canceled: 0,
});
/**
* 将模型调用重试、超时或错误文本归类为标准化异常类型。
*
* @param {string} [rawError='']
* @param {{ reasonCode?: number, errorCode?: number, isCanceled?: boolean }} [opts]
* @returns {'timeout'|'rate_limit'|'capacity'|'disconnect'|'upstream'|'model_output'|'safety'|'auth_or_model'|'canceled'|'error'}
*/
export function classifyStepAnomalyError(
rawError = '',
{ reasonCode = 0, errorCode = 0, isCanceled = false } = {}
) {
const s = String(rawError || '').trim();
if (isCanceled || /context canceled by user|stream reading error:\s*context canceled/i.test(s)) {
return 'canceled';
}
if (reasonCode === 2 || /model output error|model produced invalid output|invalid tool call/i.test(s)) {
return 'model_output';
}
if (
errorCode === 429 ||
/\b429\b|RESOURCE_EXHAUSTED|quota reached|rate.?limit/i.test(s)
) {
return 'rate_limit';
}
if (
/stream idle timeout|TLS handshake timeout|i\/o timeout|context deadline exceeded|\btimeout\b/i.test(
s
)
) {
return 'timeout';
}
if (
errorCode === 503 ||
/\b503\b|UNAVAILABLE|No capacity available|overloaded|high demand/i.test(s)
) {
return 'capacity';
}
if (
/wsarecv|wsasend|forcibly closed|connection reset|broken pipe|ECONNRESET|unexpected EOF|:\s*EOF\b|The stream was interrupted|no such host|dial tcp|tls:|bad record MAC/i.test(
s
)
) {
return 'disconnect';
}
if (/safety filter|content safety|sensitive words/i.test(s)) {
return 'safety';
}
if (
errorCode === 500 ||
errorCode === 502 ||
errorCode === 504 ||
/\b(?:500|502|504)\b|\bINTERNAL\b|BAD_GATEWAY/i.test(s)
) {
return 'upstream';
}
if (
errorCode === 400 ||
errorCode === 401 ||
errorCode === 403 ||
errorCode === 404 ||
/\b(?:400|401|403|404)\b|PERMISSION_DENIED|UNAUTHENTICATED|FAILED_PRECONDITION|NOT_FOUND|unknown model|unsupported mime/i.test(
s
)
) {
return 'auth_or_model';
}
return 'error';
}
function cleanAnomalyErrorExcerpt(rawText) {
let s = String(rawText || '')
.replace(/\s+/g, ' ')
.trim();
if (!s) return '';
s = s.replace(/^API error \(attempt \d+\):\s*/i, '');
s = s.replace(/^agent executor error:\s*generating and executing:\s*/i, '');
s = s.replace(/^request failed:\s*/i, '');
return s.length > 180 ? `${s.slice(0, 179)}…` : s;
}
function extractErrorStepPayload(step) {
if (!step || typeof step !== 'object') return null;
const em = step.errorMessage;
const errObj = em?.error && typeof em.error === 'object' ? em.error : em;
const shortErr = String(
errObj?.shortError ||
errObj?.message ||
step.error ||
''
).trim();
const userMsg = String(errObj?.userErrorMessage || '').trim();
const fallbackContent =
!shortErr && !userMsg && typeof step.content === 'string'
? step.content.replace(/^Error:\s*/i, '').trim()
: '';
const message = shortErr || userMsg || fallbackContent;
if (!message) return null;
const errorCode = Number(errObj?.errorCode || 0) || 0;
const terminal = Boolean(em?.shouldShowUser);
return { message, userMsg, errorCode, terminal };
}
function buildStepAnomalyRecord(step, meta, chat, pendingErrorSteps = []) {
const retryInfosRaw = [
...(Array.isArray(chat?.retryInfos) ? chat.retryInfos : []),
...(Array.isArray(meta?.retryInfos) ? meta.retryInfos : []),
];
const retryErrorEntries = [];
for (let i = 0; i < retryInfosRaw.length; i += 1) {
const ri = retryInfosRaw[i];
if (!ri || typeof ri !== 'object') continue;
const errText = String(ri.error || ri.errorMessage || '').trim();
const reasonCode = Number(ri.reasonCode || 0) || 0;
const delaySec = duration(ri.retryDelay);
if (!errText && !(reasonCode > 0 && reasonCode !== 3)) continue;
const kind = classifyStepAnomalyError(errText, { reasonCode });
// 纯用户取消且无其他重试时不重复打告警微标(速度列已有「已取消」)
if (kind === 'canceled') continue;
retryErrorEntries.push({
attempt: retryErrorEntries.length + 1,
kind,
delaySec: delaySec != null && delaySec > 0 ? +delaySec.toFixed(1) : 0,
message: cleanAnomalyErrorExcerpt(errText),
terminal: reasonCode === 3,
source: 'retry',
});
}
const events = [...retryErrorEntries];
const declaredRetryCount = Math.max(0, Math.floor(Number(chat?.retryCount || 0)));
// 合并同一轮前置 ERROR_MESSAGE 步骤(对已被 retryInfos 记录的同源重试做去重,保留断流续跑/安全过滤/离线日志补充)
const usedRetryKinds = new Map();
for (const ev of retryErrorEntries) {
usedRetryKinds.set(ev.kind, (usedRetryKinds.get(ev.kind) || 0) + 1);
}
const matchedKindBudget = new Map(usedRetryKinds);
for (const errStep of pendingErrorSteps || []) {
const info = extractErrorStepPayload(errStep);
if (!info) continue;
const kind = classifyStepAnomalyError(info.message, { errorCode: info.errorCode });
if (kind === 'canceled') continue;
const isInterruptOrSafety =
kind === 'safety' ||
/The stream was interrupted/i.test(info.message) ||
info.terminal;
if (!isInterruptOrSafety) {
const rem = matchedKindBudget.get(kind) || 0;
if (rem > 0) {
matchedKindBudget.set(kind, rem - 1);
continue;
}
}
events.push({
attempt: events.length + 1,
kind,
delaySec: 0,
message: cleanAnomalyErrorExcerpt(info.message),
terminal: Boolean(info.terminal),
source: 'error_step',
});
}
const isStatusError = step?.status === 'CORTEX_STEP_STATUS_ERROR';
const isStatusInterrupted = step?.status === 'CORTEX_STEP_STATUS_INTERRUPTED';
if (events.length === 0 && (isStatusError || isStatusInterrupted)) {
events.push({
attempt: 1,
kind: isStatusInterrupted ? 'disconnect' : 'error',
delaySec: 0,
message: '',
terminal: isStatusError,
source: 'status',
});
}
const count = Math.max(events.length, declaredRetryCount);
if (count <= 0) return null;
if (events.length === 0 && declaredRetryCount > 0) {
events.push({
attempt: 1,
kind: 'error',
delaySec: 0,
message: '',
terminal: false,
source: 'retry_count',
});
}
const kinds = {};
let totalDelaySec = 0;
let hasDanger = isStatusError;
for (const ev of events) {
kinds[ev.kind] = (kinds[ev.kind] || 0) + 1;
if (ev.delaySec > 0) totalDelaySec += ev.delaySec;
if (ev.terminal || ev.kind === 'rate_limit' || ev.kind === 'auth_or_model') {
hasDanger = true;
}
}
// 归并主分类:按出现次数降序,同次数按严重度优先级决胜
let primaryKind = events[0].kind;
let bestCount = -1;
let bestPrio = -1;
for (const [k, c] of Object.entries(kinds)) {
const prio = ANOMALY_SEVERITY_PRIORITY[k] ?? 1;
if (c > bestCount || (c === bestCount && prio > bestPrio)) {
primaryKind = k;
bestCount = c;
bestPrio = prio;
}
}
const roundedDelay = totalDelaySec > 0 ? +totalDelaySec.toFixed(1) : 0;
const severity = hasDanger ? 'danger' : 'warn';
const compactEvents = events.slice(0, 6).map((ev, idx) => ({
attempt: idx + 1,
kind: ev.kind,
...(ev.delaySec > 0 ? { delaySec: ev.delaySec } : {}),
...(ev.message ? { message: ev.message } : {}),
...(ev.terminal ? { terminal: true } : {}),
}));
const kindSig = Object.entries(kinds)
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([k, v]) => `${k}=${v}`)
.join(',');
const sig = `${primaryKind}:${count}:${severity}:${roundedDelay}:${kindSig}`;
return {
anomaly: {
count,
primaryKind,
severity,
totalDelaySec: roundedDelay,
kinds,
events: compactEvents,
},
anomalySig: sig,
};
}
/**
* 从原始轨迹步骤数组与生成器元数据中提取标准化模型步骤指标。
*
@@ -790,10 +1044,95 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
let pendingTurnCleanPrompts = [];
let pendingTurnDoorbellOnly = false;
let pendingErrorSteps = [];
const isErrorMessageStep = (step) => {
if (!step || typeof step !== 'object') return false;
const t = String(step.type || '').trim().toUpperCase();
return (
t === 'CORTEX_STEP_TYPE_ERROR_MESSAGE' ||
t === 'ERROR_MESSAGE' ||
Boolean(step.errorMessage && typeof step.errorMessage === 'object')
);
};
const mergeTrailingErrorsIntoStep = (targetStep, errSteps) => {
if (!targetStep || !Array.isArray(errSteps) || errSteps.length === 0) return;
const prevEvents = Array.isArray(targetStep.anomaly?.events) ? targetStep.anomaly.events : [];
const trailingRec = buildStepAnomalyRecord(null, null, null, errSteps);
if (!trailingRec) return;
const isStatusOnlyPlaceholder =
prevEvents.length === 1 &&
Number(targetStep.anomaly?.count || 0) === 1 &&
!prevEvents[0].message &&
!(Number(prevEvents[0].delaySec) > 0) &&
(prevEvents[0].kind === 'error' || prevEvents[0].kind === 'disconnect');
if (prevEvents.length === 0 || isStatusOnlyPlaceholder) {
const nextAnomaly =
isStatusOnlyPlaceholder &&
targetStep.anomaly?.severity === 'danger' &&
trailingRec.anomaly.severity !== 'danger'
? { ...trailingRec.anomaly, severity: 'danger' }
: trailingRec.anomaly;
targetStep.anomaly = nextAnomaly;
targetStep.anomalySig =
nextAnomaly === trailingRec.anomaly
? trailingRec.anomalySig
: trailingRec.anomalySig.replace(':warn:', ':danger:');
return;
}
const mergedKinds = { ...(targetStep.anomaly.kinds || {}) };
for (const [k, c] of Object.entries(trailingRec.anomaly.kinds || {})) {
mergedKinds[k] = (mergedKinds[k] || 0) + c;
}
const mergedCount = Number(targetStep.anomaly.count || 0) + Number(trailingRec.anomaly.count || 0);
const mergedDelay = +(
Number(targetStep.anomaly.totalDelaySec || 0) + Number(trailingRec.anomaly.totalDelaySec || 0)
).toFixed(1);
const mergedSeverity =
targetStep.anomaly.severity === 'danger' || trailingRec.anomaly.severity === 'danger'
? 'danger'
: 'warn';
let primaryKind = targetStep.anomaly.primaryKind || trailingRec.anomaly.primaryKind;
let bestCount = -1;
let bestPrio = -1;
for (const [k, c] of Object.entries(mergedKinds)) {
const prio = ANOMALY_SEVERITY_PRIORITY[k] ?? 1;
if (c > bestCount || (c === bestCount && prio > bestPrio)) {
primaryKind = k;
bestCount = c;
bestPrio = prio;
}
}
const combinedEvents = [...prevEvents, ...(trailingRec.anomaly.events || [])]
.slice(0, 6)
.map((ev, i) => ({ ...ev, attempt: i + 1 }));
const kindSig = Object.entries(mergedKinds)
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([k, v]) => `${k}=${v}`)
.join(',');
targetStep.anomaly = {
count: mergedCount,
primaryKind,
severity: mergedSeverity,
totalDelaySec: mergedDelay,
kinds: mergedKinds,
events: combinedEvents,
};
targetStep.anomalySig = `${primaryKind}:${mergedCount}:${mergedSeverity}:${mergedDelay}:${kindSig}`;
};
rawSteps.forEach((s, index) => {
const isHumanBoundary = isUserTurnBoundary(s);
const isWakeupBoundary = !isHumanBoundary && isSystemWakeupBoundary(s);
if (isHumanBoundary || isWakeupBoundary) {
if (pendingErrorSteps.length > 0 && result.length > 0) {
const lastPrev = result[result.length - 1];
if (lastPrev.turnIndex === activeTurnIndex) {
mergeTrailingErrorsIntoStep(lastPrev, pendingErrorSteps);
}
}
pendingErrorSteps = [];
const { cleanText, legacyPrompt, hasMedia, isDoorbellOnly = false } = isHumanBoundary
? extractUserTurnInfo(s)
: extractSystemWakeupInfo(s);
@@ -825,11 +1164,18 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
}
}
if (isErrorMessageStep(s)) {
pendingErrorSteps.push(s);
return;
}
const m = s?.metadata;
const u = m?.modelUsage || m?.retryInfos?.[0]?.usage;
if (!u) {
return;
}
const stepPendingErrors = pendingErrorSteps;
pendingErrorSteps = [];
let stepIsTurnStart = false;
let stepTurnPrompt = '';
@@ -917,6 +1263,10 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
let timingReason = null;
if (s.status === 'CORTEX_STEP_STATUS_CANCELED') {
timingReason = 'canceled';
} else if (s.status === 'CORTEX_STEP_STATUS_ERROR') {
timingReason = 'error';
} else if (s.status === 'CORTEX_STEP_STATUS_INTERRUPTED') {
timingReason = 'interrupted';
} else if (!complete || !(totalDurationSec > 0)) {
timingReason = 'incomplete_or_invalid_timing';
} else if (!validCount(u.outputTokens)) {
@@ -981,6 +1331,8 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
? 'Orchestrator Worker (Hydrogen)'
: rawDisplayName;
const anomalyRec = buildStepAnomalyRecord(s, m, chat, stepPendingErrors);
result.push({
stepIndex,
isCompactionStep,
@@ -1020,6 +1372,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
speedSampleEligible:
totalTokPerSec !== null && !shortOutputSample && !isCompactionStep,
speedReason,
...(anomalyRec ? { anomaly: anomalyRec.anomaly, anomalySig: anomalyRec.anomalySig } : {}),
turnIndex: activeTurnIndex,
isTurnStart: stepIsTurnStart,
...(stepIsTurnStart && stepTurnPrompt ? { turnPrompt: stepTurnPrompt } : {}),
@@ -1028,6 +1381,13 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
});
});
if (pendingErrorSteps.length > 0 && result.length > 0) {
const lastStep = result[result.length - 1];
if (lastStep.turnIndex === activeTurnIndex) {
mergeTrailingErrorsIntoStep(lastStep, pendingErrorSteps);
}
}
// 末尾步骤上下文回填:若最后一个非压缩步骤缺少 contextBreakdown,且最近一次有效的 generatorMetadata 未跨过压缩边界,则补齐
if (
result.length > 0 &&