diff --git a/README.md b/README.md index fe23136..93fd28c 100644 --- a/README.md +++ b/README.md @@ -7,8 +7,8 @@ Antigravity 实时测速与官方额度监控侧边栏插件(UI Extension Side ## ✨ 核心功能 - **⚡ 实时 `tok/s` 测速与会话均速** - - 保留一个 TPS 列。含正文且计时、原生用量符合要求的步骤,以正文与工具参数的合计 Token 估算非思考阶段速度,标记 `≈`;纯工具、短阶段或数据不足的步骤保留含等待的请求速率。 - - 均速优先汇总可估算步骤的 Token 与阶段时长,并显示覆盖步数;没有可估算步骤时使用全请求均速。两种时间口径不混合,具体公式与回退原因可悬停查看。 + - 保留一个 TPS 列。正文、工具和混合输出统一采用总输出 Token(含思考)/ 完整请求耗时,包含等待与思考,不减首 Token 时间,不显示阶段估算或 `≈`。 + - 会话及模型均速均为有效样本的总输出 Token 合计 / 请求时长合计,显示有效步数;不平均单步 TPS,不混合不同时间口径。 - **⏱️ 首字耗时 (TTFT) & 缓存命中率** - 显示原始 `timeToFirstToken`(可能先返回思考内容,非必然为答案首字);缺失显示 `—`,不再按思考 Token 比例推算。悬停可见会话平均 TTFT。同时显示 Prompt 缓存读取命中率(`cacheReadTokens` 占比)。 - **📊 上下文窗口四色分段监控(默认对齐 `256k` 自动压缩阈值)** @@ -19,7 +19,7 @@ Antigravity 实时测速与官方额度监控侧边栏插件(UI Extension Side - 自动扫描本地全量历史会话并聚合统计 **💬 本对话消耗** 与 **👤 本机累计消耗**(总 Token、精确官方 API 美元费用、输入/缓存/输出明细、Gemini 与 Claude/GPT 模型池分账),同时完整捕获 `CORTEX_STEP_TYPE_CHECKPOINT` 后台自动压缩步骤写入 `metadata.retryInfos[0].usage` 的隐藏 Token 消耗。 - 支持 **`全部` / `近5h` / `今日` / `本周` / `30天` / `自定义起止时间`** 一键切换筛选,底部「按模型汇总」表也会同步按所选时间段过滤。 - **📋 全量步骤测速与计费明细表 & 按模型汇总表** - - 提供当前会话**全量历史步骤**(无 15 步截断限制,支持吸顶表头平滑滚动)的单步测速与**单步精确美元消费 (`$0.XXX`)** 明细(鼠标悬停可查看每步的输入/缓存/输出费用拆解、折合 5h/周限扣减百分比、思考 Token/耗时与正文输出流耗时),以及所选时间段内按模型分类的调用次数、均速、总 Token 与 API 费用统计。 + - 提供当前会话**全量历史步骤**(无 15 步截断限制,支持吸顶表头平滑滚动)的单步测速与**按 API 价表估算的单步美元费用 (`$0.XXX`)** 明细(悬停可查看输入/缓存/输出费用拆解及请求耗时),以及所选时间段内按模型分类的调用次数、均速、总 Token 与 API 费用统计。 --- @@ -160,11 +160,11 @@ git -C ~/.gemini/config/plugins/usage-monitor pull 本地试用分支:`codex/tps-metrics-trial`。 -- **TPS**:含正文时,尝试用原生 `responseOutputTokens / (totalDurationSec - (thinkingDuration ?? timeToFirstToken))` 估算正文与工具合计的非思考阶段速度。要求原生思考/非思考 Token 计数与总数一致,阶段计时一致、至少 0.5 秒、非思考输出至少 50 Token;必须有生成完成时间,不能用工具执行完成时间代替。 -- **回退**:纯工具、短阶段、计时或用量缺失时保留总输出 / 完整请求耗时。完整请求不足 0.5 秒或未完成时不显示速率。没有 TPS 上限,不根据算出的速度改分母;这些保护只能剔除已知不可靠样本,不能保证所有缓冲都可识别。 -- **均速**:优先使用可估算步骤的非思考 Token 合计 / 阶段时长合计,不掺入回退步骤;没有可估算步骤时才使用全请求均速,低于 50 个总输出 Token 的短请求不计此均速。覆盖步数和口径会显示。自动压缩仍计费,不计均速。 -- **首 Token**:继续原样展示原生 TTFT,缺失显示未知,不使用 Token 比例推算。估算步骤的悬停信息附带正文开始延迟估计,不将其称为服务端精确首 token 时间。 -- **缓存**:`v8-guarded-phase` / measurementVersion 3。旧缓存重新读取原始轨迹;失败时保留 Token 和费用,不沿用旧派生速率。 +- **TPS**:统一使用总输出 Token(含思考、正文及工具参数)/ 已完成请求的总时长。使用 `createdAt` 到 `finishedGeneratingAt`,缺失生成结束字段时以 `completedAt` 作为步骤完成边界;不另加相邻工具步骤的执行耗时或请求间空闲。不扣首 Token 或 thinkingDuration,不再估算阶段 TPS。 +- **计时保护**:完整请求至少 0.5 秒,起止时间有效且步骤已完成;原生 TTFT 不应超过完整请求时长(允许 10 ms 打点误差)。输出计数必须是有效非负整数。纳秒时间戳先相减再转换,避免临界值舍入;无效样本显示原因,不修改分母或设置 TPS 上限。 +- **均速**:有效步骤总输出 Token 合计 / 请求时长合计,所有输出类型同口径。少于 50 个输出 Token 的请求保留单步速率,但不计均速;覆盖步数会显示。自动压缩仍计费,不计速度或 TTFT 均值。 +- **首 Token**:保留原生 TTFT,包括真实零值;缺失显示未知,不按 Token 比例推算。元数据按源步骤索引匹配,忽略非模型元数据,避免分页时错配。平均 TTFT 只包含已完成且计时一致的普通模型步骤。 +- **缓存**:`v9-unified-throughput` / measurementVersion 4。旧缓存重新读取原始轨迹;失败时保留 Token 和费用,不沿用旧派生速率。表中缓存百分比是本次请求的缓存命中率,原始记录为零时保留 0%,不沿用上一请求的高命中率。 - **验证**:在 `sidecars/panel` 执行 `npm test`。测试使用本地合成数据,不触发模型生成。 - **退回原版**:保存本地改动后执行 `git switch main`,关闭再开启插件;主分支没有诊断采集器。 diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 20afca4..0b0eaaa 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -22,36 +22,15 @@ function formatMetric(value, unit = '') { return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—'; } -function formatSpeed(value, basis, unit = '') { - return `${Number.isFinite(value) && basis === 'response_phase_estimate' ? '≈' : ''}${formatMetric(value, unit)}`; -} - -function speedDescription(step) { - if (step.speedBasis === 'response_phase_estimate') { - return `阶段估算:正文及工具 ${step.responseTokens} Token ÷ ${formatMetric(step.phaseDurationSec, 's')};已扣除等待及思考,非服务端精确解码速度;正文开始延迟约 ${formatMetric(step.answerStartDelaySec, 's')}`; - } - return `TPS = 总输出 ${step.outputTokens} Token ÷ 请求总耗时 ${formatMetric(step.totalDurationSec, 's')}(含等待与思考);${speedReasonText(step.phaseReason)}`; -} - -function meanDescription(summary) { - return summary?.basis === 'response_phase_estimate' - ? `均速仅汇总可估算步骤的非思考 Token 与阶段时长,覆盖 ${sampleSummary(summary)};其他步骤仍显示含等待的速率,不混入此均速` - : `暂无可用阶段估算,均速使用总输出 Token ÷ 请求总耗时(含等待与思考),覆盖 ${sampleSummary(summary)}`; -} - function speedReasonText(reason) { return ({ compaction: '自动压缩不计测速', incomplete_or_invalid_timing: '未完成或计时缺失', invalid_output_tokens: '输出 Token 计数无效', + inconsistent_timing: '原生首响应与总计时不一致', short_timing: '计时过短,暂不测速', short_sample: '短样本,不计均速', legacy_cache: '旧缓存,等待重新读取', - no_visible_text: '缺少正文起点,保留完整请求计时', - invalid_phase_tokens: '非思考 Token 计数缺失或不一致', - invalid_phase_timing: '阶段计时缺失或不一致', - short_phase: '阶段不足 0.5 秒,可能整包返回,保留完整请求计时', - short_phase_sample: '非思考输出不足 50 Token,保留完整请求计时', })[reason] || ''; } @@ -206,14 +185,14 @@ function renderTables(activeConv, modelBreakdown) { : 'color: var(--foreground); font-weight: 600;'; const pct5h = (stepCostVal / 0.25).toFixed(2); const pctWk = stepCostVal.toFixed(3); - tr.title = `单步消费: $${stepCostVal.toFixed(4)} (入 $${Number(st.inCostUsd || 0).toFixed(4)} + 缓 $${Number(st.cacheCostUsd || 0).toFixed(4)} + 出 $${Number(st.outCostUsd || 0).toFixed(4)} | 约合 5h ${pct5h}% / 周限 ${pctWk}%) | ${thinkInfo}${speedDescription(st)} | ${reason}`; + tr.title = `单步消费: $${stepCostVal.toFixed(4)} (入 $${Number(st.inCostUsd || 0).toFixed(4)} + 缓 $${Number(st.cacheCostUsd || 0).toFixed(4)} + 出 $${Number(st.outCostUsd || 0).toFixed(4)} | 约合 5h ${pct5h}% / 周限 ${pctWk}%) | ${thinkInfo}正文/工具输出: ${st.responseTokens} tok | TPS = 总输出 ${st.outputTokens} Token ÷ 请求总耗时 ${formatMetric(st.totalDurationSec, 's')}(含等待与思考) | ${reason}`; tr.innerHTML = ` #${Number(st.stepIndex)}${compTag ? '⚡' : ''} ${escapeHtml(st.modelShort)} - ${formatSpeed(st.tokPerSec, st.speedBasis, ' tok/s')}${reason ? `
${escapeHtml(reason)}
` : ''} + ${formatMetric(st.tokPerSec, ' tok/s')}${reason ? `
${escapeHtml(reason)}
` : ''} ${formatMetric(st.ttftSec, 's')} ${formatTokens(st.contextTokens)} / +${Number(st.outputTokens)} - ${Number(st.cacheHitPct)}% + ${Number(st.cacheHitPct)}% ${stepCostDisplay} `; frag.appendChild(tr); @@ -233,12 +212,11 @@ function renderTables(activeConv, modelBreakdown) { modelsTbody.innerHTML = ''; for (const m of models) { const tr = document.createElement('tr'); - tr.title = meanDescription(m.speedSummary); const pricePrefix = m.isEstimatedPrice ? '≈$' : '$'; tr.innerHTML = ` ${escapeHtml(m.shortName)} (${Number(m.calls)}) ${Number(m.calls)} - ${formatSpeed(m.avgTokPerSec, m.speedSummary?.basis, ' tok/s')}
有效 ${sampleSummary(m.speedSummary)}
+ ${formatMetric(m.avgTokPerSec, ' tok/s')}
有效 ${sampleSummary(m.speedSummary)}
${formatTokens(m.totalTokens)} ${pricePrefix}${Number(m.costUsd).toFixed(2)} `; @@ -339,14 +317,13 @@ function applyTelemetryToDom(data) { } // 2. Status strip metrics - $('tok-per-sec').textContent = formatSpeed(active.latestTokPerSec, active.latestSpeedBasis, ' tok/s'); - $('speed-status').title = `最新一步:${speedDescription(active.recentSteps?.[0] || {})};${speedReasonText(active.latestSpeedReason)}`; + $('tok-per-sec').textContent = formatMetric(active.latestTokPerSec, ' tok/s'); + $('speed-status').title = `最新一步:总输出 Token ÷ 请求总耗时(含等待与思考);${speedReasonText(active.latestSpeedReason) || '计时有效'}`; $('ttft-value').textContent = formatMetric(active.latestTtftSec, 's'); - $('ttft-value').title = `原始首 Token 延迟,可能先返回思考内容;会话平均 ${formatMetric(active.ttftSummary?.avgSec, 's')}(${active.ttftSummary?.sampleCount || 0} 步)`; - $('avg-speed-value').textContent = formatSpeed(active.avgTokPerSec, active.speedSummary?.basis); - $('avg-speed-value').title = meanDescription(active.speedSummary); + $('ttft-value').title = `原始首 Token 延迟,可能先返回思考内容;会话平均 ${formatMetric(active.ttftSummary?.avgSec, 's')}(${active.ttftSummary?.sampleCount || 0} 个已完成且计时一致的步骤)`; + $('avg-speed-value').textContent = formatMetric(active.avgTokPerSec); $('speed-sample-count').textContent = `有效 ${sampleSummary(active.speedSummary)}`; - $('speed-sample-count').title = meanDescription(active.speedSummary) + ';' + Object.entries(active.speedSummary?.excludedReasons || {}).map(([reason, count]) => `${speedReasonText(reason)}:${count} 步`).join(';'); + $('speed-sample-count').title = Object.entries(active.speedSummary?.excludedReasons || {}).map(([reason, count]) => `${speedReasonText(reason)}:${count} 步`).join(';') || '全部有效;自动压缩单独排除'; const latestStepCost = Number(active.latestStepCostUsd ?? active.recentSteps?.[0]?.costUsd ?? 0); if ($('step-cost-value')) { $('step-cost-value').textContent = `$${latestStepCost.toFixed(3)}`; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 595db4a..1935622 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -26,7 +26,7 @@
- + — @@ -51,7 +51,7 @@ 今日 0 · ≈$0.00
-
≈ 为扣除等待及思考后的估算;其余 TPS 含等待。均速按同一口径汇总。
+
TPS = 总输出 Token ÷ 请求总耗时(含等待与思考)
diff --git a/sidecars/panel/main.mjs b/sidecars/panel/main.mjs index 10d1670..a5d4ef4 100644 --- a/sidecars/panel/main.mjs +++ b/sidecars/panel/main.mjs @@ -59,7 +59,7 @@ const PLACEHOLDER_MAP = { }; // In-memory cache of trajectory step usage: cascadeId -> { signature, steps } -const CACHE_SCHEMA_VERSION = 'v8-guarded-phase'; +const CACHE_SCHEMA_VERSION = 'v9-unified-throughput'; let trajectoryCache = Object.fromEntries(Object.entries(loadJson(CACHE_FILE, {})).map(([id, entry]) => [ id, { ...entry, steps: (entry.steps || []).map(normalizeCachedStep) }, ])); @@ -913,8 +913,6 @@ async function buildTelemetryPayloadInternal( latestTokPerSec: latestEnriched?.tokPerSec ?? null, latestTtftSec: latestEnriched?.ttftSec ?? null, latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null, - latestSpeedBasis: latestEnriched?.speedBasis ?? 'unavailable', - latestPhaseReason: latestEnriched?.phaseReason ?? null, avgTokPerSec: sessionAvgTokPerSec, speedSummary: sessionSpeed, ttftSummary: sessionTtft, diff --git a/sidecars/panel/speed-metrics.mjs b/sidecars/panel/speed-metrics.mjs index 94cf4aa..665728a 100644 --- a/sidecars/panel/speed-metrics.mjs +++ b/sidecars/panel/speed-metrics.mjs @@ -1,6 +1,6 @@ -// A guarded estimate of the non-thinking response phase (text + tool JSON). -// Buffered/short samples retain request throughput. Means never mix scopes. -export const MEASUREMENT_VERSION = 3; +// Client-observed request throughput, including waiting and thinking. +// One formula for text and tools; no rate-based clipping or denominator changes. +export const MEASUREMENT_VERSION = 4; export const MIN_SPEED_DURATION_SECONDS = 0.5; export const MIN_MEAN_OUTPUT_TOKENS = 50; @@ -19,10 +19,26 @@ function duration(value) { } function validCount(value) { - return value !== undefined && value !== null && value !== '' && + return (typeof value === 'number' || (typeof value === 'string' && /^\d+$/.test(value))) && Number.isSafeInteger(Number(value)) && Number(value) >= 0; } +// Subtract timestamps before converting to Number so epoch-sized floats do not +// round a 499,999,999 ns request up across the 0.5 second validity threshold. +function timestampNs(value) { + if (typeof value !== 'string') return null; + const match = value.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/); + if (!match) return null; + const ms = Date.parse(match[1] + match[3]); + return Number.isFinite(ms) ? BigInt(ms) * 1_000_000n + BigInt((match[2] || '').padEnd(9, '0')) : null; +} + +function requestDuration(startValue, endValue) { + const start = timestampNs(startValue), end = timestampNs(endValue); + return start !== null && end !== null && start > 0n && end >= start + ? Number(end - start) / 1e9 : null; +} + function elapsed(start, end) { return start > 0 && end >= start ? (end - start) / 1000 : null; } @@ -30,6 +46,7 @@ function elapsed(start, end) { export function extractModelSteps(rawSteps = [], generatorMetadata = []) { const genByStep = new Map(); for (const gm of generatorMetadata || []) { + if (!gm?.chatModel) continue; for (const index of gm?.stepIndices || []) genByStep.set(Number(index), gm); } const result = []; @@ -38,7 +55,8 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { const u = m?.modelUsage || m?.retryInfos?.[0]?.usage; if (!u) return; const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index; - const gm = m.generatorMetadata?.[0] || genByStep.get(Number(stepIndex)) || genByStep.get(index); + const inlineChat = Array.isArray(m.generatorMetadata) ? m.generatorMetadata.find(g => g?.chatModel) : null; + const gm = inlineChat || genByStep.get(Number(stepIndex)); const chat = gm?.chatModel; const p = s.plannerResponse || {}; const isCompactionStep = s.type === 'CORTEX_STEP_TYPE_CHECKPOINT'; @@ -47,50 +65,31 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { const outputTokens = Number(u.outputTokens || 0); const thinkingTokens = Number(p.thinkingTokens ?? u.thinkingOutputTokens ?? chat?.usage?.thinkingOutputTokens ?? 0); const responseTokens = Number(p.responseTokens ?? u.responseOutputTokens ?? chat?.usage?.responseOutputTokens ?? Math.max(0, outputTokens - thinkingTokens)); - const nativeResponseTokens = u.responseOutputTokens ?? chat?.usage?.responseOutputTokens; - const nativeThinkingTokens = u.thinkingOutputTokens ?? chat?.usage?.thinkingOutputTokens; - const hasVisibleText = String(p.modifiedResponse || p.response || '').trim().length > 0; const start = parseIsoMs(m.createdAt); - const end = parseIsoMs(m.finishedGeneratingAt || m.completedAt); + const measuredDuration = requestDuration(m.createdAt, m.finishedGeneratingAt || m.completedAt); const explicitlyIncomplete = Boolean(s.status && s.status !== 'CORTEX_STEP_STATUS_DONE'); - const complete = !explicitlyIncomplete && start > 0 && end >= start; - const totalDurationSec = complete ? elapsed(start, end) : null; + const complete = !explicitlyIncomplete && measuredDuration !== null; + const totalDurationSec = complete ? measuredDuration : null; const nativeTtftSec = duration(chat?.timeToFirstToken); - // These are client-observed boundaries, not server token timestamps. + // These phase timers remain diagnostic only: buffered tools can make them + // tiny, so neither is used as a divisor or subtracted from request time. const nativeStreamSec = duration(chat?.streamingDuration); const thinkingDurationSec = duration(p.thinkingDuration); let timingReason = null; if (!complete || !(totalDurationSec > 0)) timingReason = 'incomplete_or_invalid_timing'; else if (!validCount(u.outputTokens)) timingReason = 'invalid_output_tokens'; else if (totalDurationSec < MIN_SPEED_DURATION_SECONDS) timingReason = 'short_timing'; + else if (nativeTtftSec !== null && nativeTtftSec > totalDurationSec + 0.01) timingReason = 'inconsistent_timing'; const totalTokPerSec = timingReason === null ? outputTokens / totalDurationSec : null; const shortOutputSample = totalTokPerSec !== null && outputTokens < MIN_MEAN_OUTPUT_TOKENS; const speedReason = timingReason || (isCompactionStep ? 'compaction' : shortOutputSample ? 'short_sample' : null); - const phaseOffsetSec = thinkingDurationSec ?? nativeTtftSec; - const phaseDurationSec = totalDurationSec !== null && phaseOffsetSec !== null - ? totalDurationSec - phaseOffsetSec : null; - let phaseReason = timingReason; - if (!phaseReason && isCompactionStep) phaseReason = 'compaction'; - if (!phaseReason && !hasVisibleText) phaseReason = 'no_visible_text'; - if (!phaseReason && (!validCount(nativeResponseTokens) || !validCount(nativeThinkingTokens) || - Number(nativeResponseTokens) !== responseTokens || - Number(nativeResponseTokens) + Number(nativeThinkingTokens) !== outputTokens)) phaseReason = 'invalid_phase_tokens'; - if (!phaseReason && (!m.finishedGeneratingAt || phaseOffsetSec === null || - (p.thinkingDuration != null && thinkingDurationSec === null) || - !(phaseDurationSec > 0) || - (nativeTtftSec !== null && phaseOffsetSec + 0.01 < nativeTtftSec) || - (nativeStreamSec !== null && nativeTtftSec !== null && - Math.abs(totalDurationSec - nativeTtftSec - nativeStreamSec) > 0.01))) phaseReason = 'invalid_phase_timing'; - if (!phaseReason && phaseDurationSec < MIN_SPEED_DURATION_SECONDS) phaseReason = 'short_phase'; - if (!phaseReason && responseTokens < MIN_MEAN_OUTPUT_TOKENS) phaseReason = 'short_phase_sample'; - const phaseTokPerSec = phaseReason === null ? responseTokens / phaseDurationSec : null; const context = chat?.chatStartMetadata?.contextWindowMetadata; result.push({ stepIndex, isCompactionStep, modelKey: u.model || chat?.model || m.generatorModel || 'MODEL_PLACEHOLDER_M418', apiProvider: u.apiProvider || chat?.usage?.apiProvider || '', createdAt: m.createdAt || null, createdAtMs: Math.floor(start), - hasVisibleText, + hasVisibleText: String(p.modifiedResponse || p.response || '').trim().length > 0, hasToolCalls: Array.isArray(p.toolCalls) && p.toolCalls.length > 0, inputTokens, cacheReadTokens, outputTokens, thinkingTokens, responseTokens, estimatedContextTokens: Number(context?.estimatedTokensUsed || 0), @@ -100,10 +99,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { viewableDelaySec: elapsed(start, parseIsoMs(m.viewableAt)), ttftSec: nativeTtftSec, ttftSource: nativeTtftSec === null ? 'unavailable' : 'native', thinkingDurationSec, totalDurationSec, totalTokPerSec, - phaseDurationSec: phaseTokPerSec === null ? null : phaseDurationSec, - phaseTokPerSec, phaseReason, - answerStartDelaySec: phaseTokPerSec === null ? null : phaseOffsetSec, - speedBasis: phaseTokPerSec !== null ? 'response_phase_estimate' : totalTokPerSec === null ? 'unavailable' : 'request_total', + speedBasis: totalTokPerSec === null ? 'unavailable' : 'request_total', speedSampleEligible: totalTokPerSec !== null && !shortOutputSample && !isCompactionStep, speedReason, }); @@ -133,45 +129,29 @@ export function speedMetric(step) { !(step.totalDurationSec >= MIN_SPEED_DURATION_SECONDS)) { return missing(step.speedReason || 'incomplete_or_invalid_timing'); } - if (step.speedBasis === 'response_phase_estimate' && Number.isFinite(step.phaseTokPerSec) && - step.phaseDurationSec >= MIN_SPEED_DURATION_SECONDS && step.responseTokens >= MIN_MEAN_OUTPUT_TOKENS) { - return { value: step.phaseTokPerSec, tokens: step.responseTokens, seconds: step.phaseDurationSec, - eligible: !step.isCompactionStep, reason: null }; - } return { value: step.totalTokPerSec, tokens: step.outputTokens, seconds: step.totalDurationSec, eligible: step.speedSampleEligible === true && !step.isCompactionStep, reason: step.speedReason }; } export function createSpeedAccumulator() { - const bucket = () => ({ tokens: 0, seconds: 0, sampleCount: 0, excludedCount: 0, excludedReasons: {} }); - return { phase: bucket(), overall: bucket() }; + return { tokens: 0, seconds: 0, sampleCount: 0, excludedCount: 0, excludedReasons: {} }; } export function accumulateSpeed(acc, step) { if (step.isCompactionStep) return; const metric = speedMetric(step); - function add(bucket, eligible, tokens, seconds, reason) { - if (eligible) { - bucket.tokens += tokens; - bucket.seconds += seconds; - bucket.sampleCount++; - } else { - bucket.excludedCount++; - bucket.excludedReasons[reason] = (bucket.excludedReasons[reason] || 0) + 1; - } + if (metric.eligible) { + acc.tokens += metric.tokens; + acc.seconds += metric.seconds; + acc.sampleCount++; + } else { + acc.excludedCount++; + acc.excludedReasons[metric.reason] = (acc.excludedReasons[metric.reason] || 0) + 1; } - add(acc.phase, metric.eligible && step.speedBasis === 'response_phase_estimate', - metric.tokens, metric.seconds, step.phaseReason || metric.reason || 'unavailable'); - add(acc.overall, metric.value !== null && step.outputTokens >= MIN_MEAN_OUTPUT_TOKENS, - step.outputTokens, step.totalDurationSec, metric.reason || 'short_sample'); } export function finishSpeed(acc) { - const usePhase = acc.phase.sampleCount > 0; - const chosen = usePhase ? acc.phase : acc.overall; - return { ...chosen, basis: usePhase ? 'response_phase_estimate' : 'request_total', - avgTokPerSec: chosen.seconds > 0 ? chosen.tokens / chosen.seconds : null, - overall: { ...acc.overall, avgTokPerSec: acc.overall.seconds > 0 ? acc.overall.tokens / acc.overall.seconds : null } }; + return { ...acc, avgTokPerSec: acc.seconds > 0 ? acc.tokens / acc.seconds : null }; } export function summarizeSpeed(steps) { @@ -182,6 +162,8 @@ export function summarizeSpeed(steps) { export function summarizeTtft(steps) { const values = steps.filter(s => !s.isCompactionStep && s.measurementVersion === MEASUREMENT_VERSION && - Number.isFinite(s.nativeTtftSec) && s.nativeTtftSec >= 0).map(s => s.nativeTtftSec); + s.isComplete && Number.isFinite(s.totalDurationSec) && + Number.isFinite(s.nativeTtftSec) && s.nativeTtftSec >= 0 && + s.nativeTtftSec <= s.totalDurationSec + 0.01).map(s => s.nativeTtftSec); return { sampleCount: values.length, avgSec: values.length ? values.reduce((a,b) => a+b,0) / values.length : null }; } diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs index 3d060f7..31c05c1 100644 --- a/sidecars/panel/test/backend.test.mjs +++ b/sidecars/panel/test/backend.test.mjs @@ -22,20 +22,20 @@ test('failed migration retains all accounting, makes legacy speed and TTFT unava test('successful migration rebuilds measurements and uses the same mean in both tables',async()=>{ const h=backendHarness({cache:{test:old},trajectories:{test:raw}}); const p=await h.buildTelemetryPayloadInternal('test'); - assert.equal(p.activeConversation.latestTokPerSec,100); + assert.equal(p.activeConversation.latestTokPerSec,60); assert.equal(p.activeConversation.latestTtftSec,3); - assert.equal(p.activeConversation.avgTokPerSec,100); - assert.equal(p.modelBreakdown[0].avgTokPerSec,100); + assert.equal(p.activeConversation.avgTokPerSec,60); + assert.equal(p.modelBreakdown[0].avgTokPerSec,60); assert.equal(p.modelBreakdown[0].speedSummary.sampleCount,1); assert.equal(p.consumption.session.totalTokens,900); - assert.match(h.state.saves[0].data.test.signature,/^v8-guarded-phase:/); + assert.match(h.state.saves[0].data.test.signature,/^v9-unified-throughput:/); }); test('a legacy stream setting cannot re-enable mixed speed formulas',async()=>{ const h=backendHarness({cache:{test:old},trajectories:{test:raw},settings:{speedMode:'stream'}}); const p=await h.buildTelemetryPayloadInternal('test'); - assert.equal(p.activeConversation.latestTokPerSec,100); - assert.equal(p.activeConversation.avgTokPerSec,100); - assert.equal(p.modelBreakdown[0].avgTokPerSec,100); + assert.equal(p.activeConversation.latestTokPerSec,60); + assert.equal(p.activeConversation.avgTokPerSec,60); + assert.equal(p.modelBreakdown[0].avgTokPerSec,60); assert.equal(p.settings.speedMode,undefined); }); test('a malformed successful RPC cannot erase previously recorded usage',async()=>{ diff --git a/sidecars/panel/test/speed-display.test.mjs b/sidecars/panel/test/speed-display.test.mjs index cc9b16c..740cbc5 100644 --- a/sidecars/panel/test/speed-display.test.mjs +++ b/sidecars/panel/test/speed-display.test.mjs @@ -42,12 +42,11 @@ test('a TTFT-only correction refreshes the table even when TPS and step count do assert.match(elements['steps-tbody'].children[0].innerHTML,/13\.0s<\/td>/); }); -test('one TPS column marks estimates and explains full-time fallbacks in the tooltip',()=>{ +test('contradictory timing is explained and zero cache remains a per-request usage fact',()=>{ const {ctx,elements}=page(); - ctx.renderTables({recentSteps:[{...step,speedBasis:'response_phase_estimate',phaseDurationSec:2,answerStartDelaySec:8,tokPerSec:100}]},[]); - assert.match(elements['steps-tbody'].children[0].innerHTML,/≈100\.0 tok\/s/); - assert.match(elements['steps-tbody'].children[0].title,/非服务端精确解码速度/); - ctx.renderTables({recentSteps:[{...step,speedBasis:'request_total',phaseReason:'short_phase'}]},[]); - assert.doesNotMatch(elements['steps-tbody'].children[0].innerHTML,/≈/); - assert.match(elements['steps-tbody'].children[0].title,/阶段不足 0.5 秒/); + ctx.renderTables({recentSteps:[{...step,tokPerSec:null,cacheHitPct:0,selectedSpeedReason:'inconsistent_timing'}]},[]); + const row=elements['steps-tbody'].children[0]; + assert.match(row.innerHTML,/原生首响应与总计时不一致/); + assert.match(row.innerHTML,/不是缓存容量/);assert.match(row.innerHTML,/>0%<\/td>/); + assert.doesNotMatch(row.innerHTML,/≈/); }); diff --git a/sidecars/panel/test/speed-metrics.test.mjs b/sidecars/panel/test/speed-metrics.test.mjs index 1bf643a..18810cd 100644 --- a/sidecars/panel/test/speed-metrics.test.mjs +++ b/sidecars/panel/test/speed-metrics.test.mjs @@ -14,11 +14,11 @@ function sample({total=12,ttft='2s',stream='10s',output=1100,thinking=100,respon } function parse(options) {const {s,gm}=sample(options);return extractModelSteps([s],[gm])[0];} -test('text and mixed output estimate the combined response phase; pure tools retain total time',()=>{ +test('text, tools and mixed output all use total output / full request duration',()=>{ for(const tools of [false,true])for(const text of [false,true]){ const step=parse({tools,text}); - assert.equal(speedMetric(step).value,text ? 1000/8 : 1100/12); - assert.equal(step.speedBasis,text ? 'response_phase_estimate' : 'request_total'); + assert.equal(speedMetric(step).value,1100/12); + assert.equal(step.speedBasis,'request_total'); assert.equal(step.speedSampleEligible,true); } }); @@ -48,7 +48,7 @@ test('short output keeps the same formula but does not bias the mean',()=>{ const short=parse({output:13,response:13,thinking:0,total:5.015,stream:'0.118s'}); assert.equal(short.totalTokPerSec,13/5.015); assert.equal(short.speedReason,'short_sample'); - assert.equal(summarizeSpeed([short,parse()]).avgTokPerSec,1000/8); + assert.equal(summarizeSpeed([short,parse()]).avgTokPerSec,1100/12); assert.equal(summarizeSpeed([short]).avgTokPerSec,null); assert.equal(parse({output:50}).speedSampleEligible,true); }); @@ -57,7 +57,7 @@ test('sub-half-second whole requests are withheld, never divided by a tiny inter assert.equal(tiny.totalTokPerSec,null);assert.equal(tiny.speedReason,'short_timing'); assert.equal(speedMetric(tiny).value,null); assert.equal(summarizeSpeed([tiny]).sampleCount,0); - assert.equal(parse({total:.5,output:100}).totalTokPerSec,200); + assert.equal(parse({total:.5,output:100,ttft:'0.1s'}).totalTokPerSec,200); }); test('weighted mean matches token/time totals and does not average step rates',()=>{ const a=parse({output:1000,total:10}),b=parse({output:1000,total:20,tools:true}); @@ -86,15 +86,12 @@ test('missing phase/token breakdown cannot change a valid full-request rate',()= assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,1100/12); }); test('no rate-dependent cap or formula switch at the former 260 TPS boundary',()=>{ - const opts={total:10,thinking:0,thinkingDuration:'0s',ttft:'0s',stream:'10s',tools:true}; - const a=parse({...opts,output:2590,response:2590}),b=parse({...opts,output:2610,response:2610}); + const a=parse({total:10,output:2590,tools:true}),b=parse({total:10,output:2610,tools:true}); assert.equal(a.totalTokPerSec,259);assert.equal(b.totalTokPerSec,261); - assert.equal(speedMetric(a).value,259);assert.equal(speedMetric(b).value,261); - assert.equal(a.speedBasis,'response_phase_estimate'); assert.equal(a.speedBasis,b.speedBasis); }); test('legacy cache retains billing but cannot masquerade as current measurements',()=>{ - for(const measurementVersion of [undefined,1,2]){ + for(const measurementVersion of [undefined,1,2,3]){ const old={measurementVersion,inputTokens:500,cacheReadTokens:2000,outputTokens:1100,ttftSec:0.4,totalTokPerSec:55}; const migrated=normalizeCachedStep(old); assert.equal(migrated.outputTokens,1100);assert.equal(migrated.inputTokens,500); @@ -103,49 +100,53 @@ test('legacy cache retains billing but cannot masquerade as current measurements } }); -test('afternoon visible-text counterexample #284 uses full time instead of a 6751 TPS tail',()=>{ +test('half-second cutoff uses the original nanoseconds, not rounded epoch milliseconds',()=>{ + const {s,gm}=sample({output:100,ttft:'0.1s'}); + s.metadata.createdAt='2026-01-01T00:00:00.000000001Z'; + s.metadata.finishedGeneratingAt='2026-01-01T00:00:00.500000000Z'; + const below=extractModelSteps([s],[gm])[0]; + assert.equal(below.totalDurationSec,.499999999);assert.equal(below.totalTokPerSec,null); + s.metadata.finishedGeneratingAt='2026-01-01T00:00:00.500000001Z'; + assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,200); + s.metadata.createdAt='2026-01-01T08:00:00.000000001+08:00'; + assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,200); +}); +test('non-chat generator metadata cannot overwrite matching model timing',()=>{ + const {s,gm}=sample();s.metadata.sourceTrajectoryStepInfo={stepIndex:42};gm.stepIndices=[42]; + const other={stepIndices:[42],tool:{}}; + assert.equal(extractModelSteps([s],[gm,other])[0].nativeTtftSec,2); + s.metadata.generatorMetadata=[other,{chatModel:{timeToFirstToken:'3s'}}]; + assert.equal(extractModelSteps([s],[gm])[0].nativeTtftSec,3); +}); +test('a paginated source step never borrows timing from an unrelated array position',()=>{ + const {s,gm}=sample();s.metadata.sourceTrajectoryStepInfo={stepIndex:42}; + const step=extractModelSteps([s],[gm])[0]; + assert.equal(step.nativeTtftSec,null);assert.equal(step.totalTokPerSec,1100/12); +}); +test('contradictory native TTFT is preserved but cannot validate TPS or bias the TTFT mean',()=>{ + const bad=parse({total:5,ttft:'9s'}); + assert.equal(bad.nativeTtftSec,9);assert.equal(bad.totalTokPerSec,null); + assert.equal(bad.speedReason,'inconsistent_timing'); + assert.deepEqual(summarizeTtft([bad,parse()]),{sampleCount:1,avgSec:2}); +}); +test('unfinished steps do not enter the TTFT mean even when partial metadata includes TTFT',()=>{ + const partial=parse({status:'CORTEX_STEP_STATUS_GENERATING',ttft:'8s'}); + assert.deepEqual(summarizeTtft([partial,parse()]),{sampleCount:1,avgSec:2}); +}); +test('coercible non-token values cannot silently become zero or one output token',()=>{ + for(const value of [true,false,' ',[],{}]){ + const {s,gm}=sample();s.metadata.modelUsage.outputTokens=value; + assert.equal(extractModelSteps([s],[gm])[0].speedReason,'invalid_output_tokens'); + } +}); +test('visible buffered text and tools use full time without a rate-dependent switch',()=>{ const {s,gm}=sample({output:64,thinking:33,response:31,ttft:'7.0108593s',stream:'0.0045919s'}); s.metadata.finishedGeneratingAt='2026-01-01T00:00:07.015451200Z'; delete s.plannerResponse.thinkingDuration; const step=extractModelSteps([s],[gm])[0]; - assert.equal(step.hasVisibleText,true);assert.equal(step.phaseReason,'short_phase'); - assert.equal(step.speedBasis,'request_total');assert(speedMetric(step).value<10); -}); -test('phase and overall means never mix denominators, regardless of step order',()=>{ - const phase=parse(),tools=parse({tools:true,text:false,total:100,output:10000}); - for(const rows of [[phase,tools],[tools,phase]]){ - const mean=summarizeSpeed(rows); - assert.equal(mean.avgTokPerSec,125);assert.equal(mean.basis,'response_phase_estimate'); - assert.equal(mean.sampleCount,1);assert.equal(mean.excludedCount,1); - assert.equal(mean.overall.avgTokPerSec,11100/112); - assert.equal(speedMetric(tools).value,100); - } - const fallback=summarizeSpeed([tools]); - assert.equal(fallback.avgTokPerSec,100);assert.equal(fallback.basis,'request_total'); -}); -test('short response phases, inconsistent counts and invalid phase clocks retain the request rate',()=>{ - for(const opts of [ - {thinkingDuration:'11.99s'}, {thinkingDuration:'12s'}, {thinkingDuration:'13s'}, - {thinkingDuration:'-1s'}, {thinkingDuration:'1s'}, {stream:'0.01s'}, - {response:999}, {output:1100,thinking:1080,response:20}, - ]){ - const step=parse(opts); - assert.equal(step.speedBasis,'request_total');assert.equal(speedMetric(step).value,1100/12); - } -}); -test('missing thinking duration can use native TTFT, but missing native breakdown cannot be guessed',()=>{ - const {s,gm}=sample();delete s.plannerResponse.thinkingDuration; - const step=extractModelSteps([s],[gm])[0]; - assert.equal(step.phaseTokPerSec,100);assert.equal(step.answerStartDelaySec,2); - delete s.metadata.modelUsage.responseOutputTokens; - const missing=extractModelSteps([s],[gm])[0]; - assert.equal(missing.phaseReason,'invalid_phase_tokens');assert.equal(missing.phaseTokPerSec,null); - assert.equal(speedMetric(missing).value,1100/12); -}); -test('completedAt remains a total-time fallback but cannot substitute for generation end in phase estimates',()=>{ - const {s,gm}=sample();s.metadata.completedAt=s.metadata.finishedGeneratingAt;delete s.metadata.finishedGeneratingAt; - const step=extractModelSteps([s],[gm])[0]; - assert.equal(step.totalTokPerSec,1100/12);assert.equal(step.phaseReason,'invalid_phase_timing'); + assert.equal(step.totalDurationSec,7.0154512); + assert.equal(speedMetric(step).value,64/7.0154512); + assert.equal(step.speedBasis,'request_total'); }); test('compaction displays a valid rate and retains billing but is excluded from speed/TTFT means',()=>{ const {s,gm}=sample();s.type='CORTEX_STEP_TYPE_CHECKPOINT';