mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
fix(metrics): unify request TPS and reject unreliable timing
This commit is contained in:
+14
-55
@@ -18,18 +18,16 @@ function escapeHtml(str) {
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function formatMetric(value, unit = '', estimated = false) {
|
||||
return Number.isFinite(value) ? `${estimated ? '≈' : ''}${value.toFixed(1)}${unit}` : '—';
|
||||
function formatMetric(value, unit = '') {
|
||||
return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—';
|
||||
}
|
||||
|
||||
function speedReasonText(reason) {
|
||||
return ({
|
||||
compaction: '自动压缩不计测速',
|
||||
incomplete_or_invalid_timing: '未完成或计时缺失',
|
||||
tool_timing_unavailable: '工具输出无法独立计时',
|
||||
no_answer_text: '无正文',
|
||||
token_breakdown_unavailable: '输出 Token 构成不明',
|
||||
answer_start_unavailable: '缺少正文起点',
|
||||
invalid_output_tokens: '输出 Token 计数无效',
|
||||
short_timing: '计时过短,暂不测速',
|
||||
short_sample: '短样本,不计均速',
|
||||
legacy_cache: '旧缓存,等待重新读取',
|
||||
})[reason] || '';
|
||||
@@ -39,25 +37,6 @@ function sampleSummary(summary) {
|
||||
return `${summary?.sampleCount || 0}/${(summary?.sampleCount || 0) + (summary?.excludedCount || 0)} 步`;
|
||||
}
|
||||
|
||||
// Display a measured request rate when the answer phase cannot be separated.
|
||||
// This presentation choice never changes the backend's homogeneous means.
|
||||
function stepSpeedDisplay(step = {}, mode = 'stream') {
|
||||
const reason = speedReasonText(step.selectedSpeedReason || step.speedReason);
|
||||
const valid = step.measurementVersion === 1 && step.isComplete === true;
|
||||
if (valid && mode !== 'total' && !step.isCompactionStep && Number.isFinite(step.streamTokPerSec)) {
|
||||
return { value: step.streamTokPerSec, estimated: true, label: '正文估算',
|
||||
detail: step.responseShortSample ? '正文估算 · 短样本' : '正文估算',
|
||||
explanation: reason || '正文阶段估算' };
|
||||
}
|
||||
if (valid && Number.isFinite(step.totalTokPerSec) && step.totalDurationSec > 0) {
|
||||
return { value: step.totalTokPerSec, estimated: false, label: '整体吞吐',
|
||||
detail: step.isCompactionStep ? '整体吞吐 · 压缩' : '整体吞吐',
|
||||
explanation: `${mode !== 'total' && reason ? `${reason};` : ''}总输出 Token(含思考)÷ 请求总耗时${mode !== 'total' ? ';不计正文均速' : ''}${step.isCompactionStep ? ';压缩不计均速' : ''}` };
|
||||
}
|
||||
return { value: null, estimated: false, label: '待计时', detail: reason || '计时不可用',
|
||||
explanation: reason || '计时不可用' };
|
||||
}
|
||||
|
||||
function formatTokens(num) {
|
||||
const n = Number(num || 0);
|
||||
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
||||
@@ -175,15 +154,14 @@ function renderAllPools(pools, activeFamily) {
|
||||
let lastStepsRenderSig = '';
|
||||
let lastModelsRenderSig = '';
|
||||
|
||||
function renderTables(activeConv, modelBreakdown, speedMode = 'stream') {
|
||||
const estimated = speedMode !== 'total';
|
||||
function renderTables(activeConv, modelBreakdown) {
|
||||
const steps = activeConv.recentSteps || [];
|
||||
const tabStepsBtn = $('tab-steps-btn');
|
||||
if (tabStepsBtn) {
|
||||
tabStepsBtn.textContent = `当前会话步骤测速与计费 (${steps.length}步)`;
|
||||
}
|
||||
|
||||
const stepsSig = `${activeConv.cascadeId || ''}:${speedMode}:${JSON.stringify(steps)}`;
|
||||
const stepsSig = `${activeConv.cascadeId || ''}:${JSON.stringify(steps)}`;
|
||||
if (stepsSig !== lastStepsRenderSig) {
|
||||
lastStepsRenderSig = stepsSig;
|
||||
const stepsTbody = $('steps-tbody');
|
||||
@@ -198,8 +176,6 @@ function renderTables(activeConv, modelBreakdown, speedMode = 'stream') {
|
||||
: '';
|
||||
const compTag = st.isCompactionStep ? ' [压缩汇总步]' : '';
|
||||
const reason = speedReasonText(st.selectedSpeedReason);
|
||||
const displaySpeed = stepSpeedDisplay(st, speedMode);
|
||||
const timingSource = st.responseTimingSource === 'post_thinking_estimate' ? '总时长减记录的思考阶段(估算)' : st.responseTimingSource === 'native_text_stream' ? '无思考正文的原始流时长(估算)' : '不可用';
|
||||
const stepCostVal = Number(st.costUsd || 0);
|
||||
const stepCostDisplay = stepCostVal >= 1 ? `$${stepCostVal.toFixed(2)}` : `$${stepCostVal.toFixed(3)}`;
|
||||
const costStyle =
|
||||
@@ -208,11 +184,11 @@ function renderTables(activeConv, modelBreakdown, speedMode = 'stream') {
|
||||
: '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}正文/工具输出: ${st.responseTokens} tok | 正文阶段: ${formatMetric(st.streamDurationSec, 's')} (${timingSource}) | 请求总耗时: ${formatMetric(st.totalDurationSec, 's')} | 整体吞吐: ${formatMetric(st.totalTokPerSec, ' tok/s')} | ${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 = `
|
||||
<td>#${Number(st.stepIndex)}${compTag ? '<span class="muted">⚡</span>' : ''}</td>
|
||||
<td>${escapeHtml(st.modelShort)}</td>
|
||||
<td title="${escapeHtml(displaySpeed.explanation)}"><strong style="color: var(--speed-accent)">${formatMetric(displaySpeed.value, ' tok/s', displaySpeed.estimated)}</strong><div class="speed-detail muted">${escapeHtml(displaySpeed.detail)}</div></td>
|
||||
<td><strong style="color: var(--speed-accent)">${formatMetric(st.tokPerSec, ' tok/s')}</strong>${reason ? `<div class="speed-detail muted">${escapeHtml(reason)}</div>` : ''}</td>
|
||||
<td>${formatMetric(st.ttftSec, 's')}</td>
|
||||
<td>${formatTokens(st.contextTokens)} / +${Number(st.outputTokens)}</td>
|
||||
<td style="color: var(--cache-green)">${Number(st.cacheHitPct)}%</td>
|
||||
@@ -228,7 +204,7 @@ function renderTables(activeConv, modelBreakdown, speedMode = 'stream') {
|
||||
}
|
||||
|
||||
const models = modelBreakdown || [];
|
||||
const modelsSig = `${speedMode}:${JSON.stringify(models)}`;
|
||||
const modelsSig = JSON.stringify(models);
|
||||
if (modelsSig !== lastModelsRenderSig) {
|
||||
lastModelsRenderSig = modelsSig;
|
||||
const modelsTbody = $('models-tbody');
|
||||
@@ -239,7 +215,7 @@ function renderTables(activeConv, modelBreakdown, speedMode = 'stream') {
|
||||
tr.innerHTML = `
|
||||
<td><strong>${escapeHtml(m.shortName)}</strong> <span class="muted">(${Number(m.calls)})</span></td>
|
||||
<td>${Number(m.calls)}</td>
|
||||
<td>${formatMetric(m.avgTokPerSec, ' tok/s', estimated)}<div class="speed-detail muted">有效 ${sampleSummary(m.speedSummary)}</div></td>
|
||||
<td>${formatMetric(m.avgTokPerSec, ' tok/s')}<div class="speed-detail muted">有效 ${sampleSummary(m.speedSummary)}</div></td>
|
||||
<td>${formatTokens(m.totalTokens)}</td>
|
||||
<td>${pricePrefix}${Number(m.costUsd).toFixed(2)}</td>
|
||||
`;
|
||||
@@ -340,20 +316,13 @@ function applyTelemetryToDom(data) {
|
||||
}
|
||||
|
||||
// 2. Status strip metrics
|
||||
const estimatedSpeed = settings.speedMode !== 'total';
|
||||
const latestSpeed = stepSpeedDisplay(active.recentSteps?.[0], settings.speedMode);
|
||||
$('tok-per-sec').textContent = formatMetric(latestSpeed.value, ' tok/s', latestSpeed.estimated);
|
||||
$('latest-speed-basis').textContent = latestSpeed.label;
|
||||
$('speed-mode-toggle').title = `最新一步:${latestSpeed.explanation};点击切换均速口径`;
|
||||
$('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 = formatMetric(active.avgTokPerSec, '', estimatedSpeed);
|
||||
$('avg-speed-label').textContent = estimatedSpeed ? '正文均速' : '整体均速';
|
||||
$('avg-speed-value').textContent = formatMetric(active.avgTokPerSec);
|
||||
$('speed-sample-count').textContent = `有效 ${sampleSummary(active.speedSummary)}`;
|
||||
$('speed-sample-count').title = Object.entries(active.speedSummary?.excludedReasons || {}).map(([reason, count]) => `${speedReasonText(reason)}:${count} 步`).join(';') || '全部有效;自动压缩单独排除';
|
||||
$('speed-method-note').textContent = estimatedSpeed
|
||||
? '正文均速只计有效正文样本;其余已完成且计时有效的步骤显示整体 TPS,口径逐步标注。'
|
||||
: '含思考的输出 Token ÷ 请求总耗时;不含调用之间的空闲和外部工具执行时间。';
|
||||
const latestStepCost = Number(active.latestStepCostUsd ?? active.recentSteps?.[0]?.costUsd ?? 0);
|
||||
if ($('step-cost-value')) {
|
||||
$('step-cost-value').textContent = `$${latestStepCost.toFixed(3)}`;
|
||||
@@ -366,7 +335,6 @@ function applyTelemetryToDom(data) {
|
||||
$('active-model-short').title = active.activeModelLabel || '';
|
||||
$('today-tokens').textContent = formatTokens(quotas.today?.tokens || 0);
|
||||
$('today-cost').textContent = `$${Number(quotas.today?.costUsd || 0).toFixed(2)}`;
|
||||
$('speed-mode-badge').textContent = settings.speedMode === 'total' ? '均速:整体吞吐' : '均速:正文估算';
|
||||
|
||||
// 3. Context Window Popover Section
|
||||
const limitTokens = ctx.limitTokens || 256000;
|
||||
@@ -440,12 +408,11 @@ function applyTelemetryToDom(data) {
|
||||
settings.weeklyLimitMode === 'custom_tokens' || settings.weeklyLimitMode === 'custom_cost'
|
||||
? settings.weeklyLimitMode
|
||||
: 'official';
|
||||
$('setting-speed-mode').value = settings.speedMode || 'stream';
|
||||
$('setting-weekly-mode').value = wkMode;
|
||||
$('setting-weekly-tokens').value = settings.weeklyTokenBudget || 150000000;
|
||||
$('setting-weekly-cost').value = settings.weeklyCostBudget || 100;
|
||||
|
||||
renderTables(active, data.modelBreakdown, settings.speedMode);
|
||||
renderTables(active, data.modelBreakdown);
|
||||
}
|
||||
|
||||
let manualRefreshFeedbackTimer = null;
|
||||
@@ -589,13 +556,6 @@ function bindEvents() {
|
||||
});
|
||||
});
|
||||
|
||||
// Toggle speed mode by clicking tok/s
|
||||
$('speed-mode-toggle').addEventListener('click', () => {
|
||||
const current = latestTelemetry?.settings?.speedMode || 'stream';
|
||||
const next = current === 'stream' ? 'total' : 'stream';
|
||||
updateSettings({ speedMode: next });
|
||||
});
|
||||
|
||||
// Toggle all model pools
|
||||
$('pool-switch-toggle').addEventListener('click', () => {
|
||||
showAllPools = !showAllPools;
|
||||
@@ -633,7 +593,6 @@ function bindEvents() {
|
||||
|
||||
$('save-settings-btn').addEventListener('click', () => {
|
||||
updateSettings({
|
||||
speedMode: $('setting-speed-mode').value,
|
||||
weeklyLimitMode: $('setting-weekly-mode').value,
|
||||
weeklyTokenBudget: Number($('setting-weekly-tokens').value),
|
||||
weeklyCostBudget: Number($('setting-weekly-cost').value),
|
||||
|
||||
@@ -26,13 +26,12 @@
|
||||
<!-- Compact Speed & Token Status Strip (1:1 replica of the left status bar above input) -->
|
||||
<section class="status-strip-card" aria-label="实时测速与消耗状态栏">
|
||||
<div class="strip-row strip-row-main">
|
||||
<span class="speed-group" title="最新一步;点击切换「正文估算」与「整体吞吐」" id="speed-mode-toggle">
|
||||
<span class="speed-group" title="总输出 Token ÷ 请求总耗时(含等待与思考)" id="speed-status">
|
||||
<span id="speed-dot" class="speed-dot"></span>
|
||||
<strong id="tok-per-sec" class="speed-value">—</strong>
|
||||
<small id="latest-speed-basis" class="muted">待计时</small>
|
||||
</span>
|
||||
<span class="metric-item">首Token <strong id="ttft-value">—</strong></span>
|
||||
<span class="metric-item"><span id="avg-speed-label">正文均速</span> <strong id="avg-speed-value">—</strong> <small id="speed-sample-count" class="muted">有效 0/0 步</small></span>
|
||||
<span class="metric-item">均速 <strong id="avg-speed-value">—</strong> <small id="speed-sample-count" class="muted">有效 0/0 步</small></span>
|
||||
<span class="strip-divider">|</span>
|
||||
<span class="metric-item" title="最新一步消费 / 当前会话累计消费">本步 <strong id="step-cost-value" class="cost-value">$0.000</strong> · 累计 <strong id="session-cost-value" class="cost-value">$0.00</strong></span>
|
||||
<span class="metric-item">缓存 <strong id="cache-hit-value" class="cache-value">0%</strong></span>
|
||||
@@ -51,9 +50,8 @@
|
||||
<span class="today-summary">
|
||||
今日 <strong id="today-tokens">0</strong> · ≈<strong id="today-cost">$0.00</strong>
|
||||
</span>
|
||||
<span class="speed-mode-label muted" id="speed-mode-badge">均速:正文估算</span>
|
||||
</div>
|
||||
<div id="speed-method-note" class="speed-method-note muted">正文均速只计有效正文样本;其余已完成且计时有效的步骤显示整体 TPS,口径逐步标注。</div>
|
||||
<div id="speed-method-note" class="speed-method-note muted" title="总耗时不包含请求之间的空闲与外部工具执行时间。低于 0.5 秒的请求不测速;少于 50 个输出 Token 的步骤显示 TPS,但不计均速。">TPS = 总输出 Token ÷ 请求总耗时(含等待与思考)</div>
|
||||
</section>
|
||||
|
||||
<!-- Quota & Context Popover Card (1:1 replica of the right popover card in screenshot) -->
|
||||
@@ -245,13 +243,6 @@
|
||||
<section id="settings-card" class="details-card" hidden>
|
||||
<h3 class="settings-title">监控口径与周限额基准设置</h3>
|
||||
<div class="settings-grid">
|
||||
<label class="field-label">
|
||||
<span>tok/s 测速口径</span>
|
||||
<select id="setting-speed-mode">
|
||||
<option value="stream">正文均速 (工具步骤显示整体 TPS)</option>
|
||||
<option value="total">请求整体吞吐 (含等待与思考)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field-label">
|
||||
<span>每周进度条统计维度</span>
|
||||
<select id="setting-weekly-mode">
|
||||
|
||||
+7
-14
@@ -20,7 +20,6 @@ const DEFAULT_SETTINGS = {
|
||||
weeklyTokenBudget: 150000000, // 150M tokens default custom weekly target
|
||||
weeklyCostBudget: 100, // $100 default custom weekly cost target (matches Ultra weekly pool)
|
||||
weeklyLimitMode: 'official', // 'official' | 'custom_tokens' | 'custom_cost'
|
||||
speedMode: 'stream', // Answer-phase estimate, or request-level throughput; never mixed.
|
||||
};
|
||||
|
||||
// Official API pricing in USD per 1M tokens (Input, CacheRead, Output incl. Thinking)
|
||||
@@ -59,7 +58,7 @@ const PLACEHOLDER_MAP = {
|
||||
};
|
||||
|
||||
// In-memory cache of trajectory step usage: cascadeId -> { signature, steps }
|
||||
const CACHE_SCHEMA_VERSION = 'v6-speed-metrics';
|
||||
const CACHE_SCHEMA_VERSION = 'v7-request-throughput';
|
||||
let trajectoryCache = Object.fromEntries(Object.entries(loadJson(CACHE_FILE, {})).map(([id, entry]) => [
|
||||
id, { ...entry, steps: (entry.steps || []).map(normalizeCachedStep) },
|
||||
]));
|
||||
@@ -85,7 +84,8 @@ function saveJson(filePath, data) {
|
||||
}
|
||||
|
||||
function loadSettings() {
|
||||
return { ...DEFAULT_SETTINGS, ...loadJson(SETTINGS_FILE, {}) };
|
||||
const { speedMode: _legacySpeedMode, ...settings } = loadJson(SETTINGS_FILE, {});
|
||||
return { ...DEFAULT_SETTINGS, ...settings };
|
||||
}
|
||||
|
||||
function roundMetric(value) {
|
||||
@@ -618,15 +618,12 @@ async function buildTelemetryPayloadInternal(
|
||||
if (Number(trajRes.numTotalSteps) > rawSteps.length) throw new Error('Incomplete trajectory; retaining cached usage');
|
||||
const generatorMeta = trajRes?.trajectory?.generatorMetadata || [];
|
||||
const steps = extractModelSteps(rawSteps, generatorMeta);
|
||||
const prevLast = prev?.steps?.[prev.steps.length - 1];
|
||||
const nextLast = steps[steps.length - 1];
|
||||
const stepsChanged =
|
||||
!prev ||
|
||||
prev.signature !== sig ||
|
||||
Boolean(prev.wasRunning) !== isRunning ||
|
||||
prev.steps?.length !== steps.length ||
|
||||
prevLast?.outputTokens !== nextLast?.outputTokens ||
|
||||
prevLast?.totalDurationSec !== nextLast?.totalDurationSec;
|
||||
JSON.stringify(prev.steps) !== JSON.stringify(steps);
|
||||
|
||||
const lastStepMs = nextLast?.createdAtMs || 0;
|
||||
const resolvedLastModMs = Math.max(conv.lastModifiedMs || 0, lastStepMs);
|
||||
@@ -662,9 +659,7 @@ async function buildTelemetryPayloadInternal(
|
||||
const activeEntry = activeCascadeId ? trajectoryCache[activeCascadeId] : null;
|
||||
const activeSteps = activeEntry?.steps || [];
|
||||
|
||||
const useStreamSpeed = settings.speedMode !== 'total';
|
||||
const speedMode = useStreamSpeed ? 'stream' : 'total';
|
||||
const sessionSpeed = summarizeSpeed(activeSteps, speedMode);
|
||||
const sessionSpeed = summarizeSpeed(activeSteps);
|
||||
const sessionTtft = summarizeTtft(activeSteps);
|
||||
let sessionCostUsd = 0;
|
||||
let sessionInputTokens = 0;
|
||||
@@ -673,7 +668,7 @@ async function buildTelemetryPayloadInternal(
|
||||
const enrichedActiveSteps = activeSteps.map((st) => {
|
||||
const mInfo = resolveModelInfo(st.modelKey, dynamicModelMap, st.apiProvider);
|
||||
const costUsd = computeStepCost(st, mInfo.pricing);
|
||||
const metric = speedMetric(st, speedMode);
|
||||
const metric = speedMetric(st);
|
||||
|
||||
sessionCostUsd += costUsd;
|
||||
sessionInputTokens += st.inputTokens;
|
||||
@@ -822,7 +817,7 @@ async function buildTelemetryPayloadInternal(
|
||||
});
|
||||
}
|
||||
const agg = perModelStats.get(mInfo.label);
|
||||
accumulateSpeed(agg.speedAccumulator, st, speedMode);
|
||||
accumulateSpeed(agg.speedAccumulator, st);
|
||||
|
||||
agg.calls += 1;
|
||||
agg.inputTokens += st.inputTokens;
|
||||
@@ -916,7 +911,6 @@ async function buildTelemetryPayloadInternal(
|
||||
latestTokPerSec: latestEnriched?.tokPerSec ?? null,
|
||||
latestTtftSec: latestEnriched?.ttftSec ?? null,
|
||||
latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null,
|
||||
latestTotalTokPerSec: roundMetric(speedMetric(latestEnriched || {}, 'total').value),
|
||||
avgTokPerSec: sessionAvgTokPerSec,
|
||||
speedSummary: sessionSpeed,
|
||||
ttftSummary: sessionTtft,
|
||||
@@ -1089,7 +1083,6 @@ app.api('/api/settings', (data, req) => {
|
||||
weeklyTokenBudget: Number(data.weeklyTokenBudget || current.weeklyTokenBudget),
|
||||
weeklyCostBudget: Number(data.weeklyCostBudget || current.weeklyCostBudget),
|
||||
weeklyLimitMode: data.weeklyLimitMode || current.weeklyLimitMode,
|
||||
speedMode: data.speedMode || current.speedMode,
|
||||
};
|
||||
saveJson(SETTINGS_FILE, updated);
|
||||
return updated;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Client-observed timing estimates, not server-side decoding benchmarks.
|
||||
export const MEASUREMENT_VERSION = 1;
|
||||
export const MIN_MEAN_RESPONSE_TOKENS = 50;
|
||||
export const MIN_MEAN_RESPONSE_SECONDS = 0.5;
|
||||
// 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 = 2;
|
||||
export const MIN_SPEED_DURATION_SECONDS = 0.5;
|
||||
export const MIN_MEAN_OUTPUT_TOKENS = 50;
|
||||
|
||||
export function parseIsoMs(value) {
|
||||
if (typeof value !== 'string' || !value) return 0;
|
||||
@@ -44,70 +45,43 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
const inputTokens = Number(u.inputTokens || 0);
|
||||
const cacheReadTokens = Number(u.cacheReadTokens || 0);
|
||||
const outputTokens = Number(u.outputTokens || 0);
|
||||
const rawThinking = p.thinkingTokens ?? u.thinkingOutputTokens ?? chat?.usage?.thinkingOutputTokens;
|
||||
const thinkingTokens = Number(rawThinking ?? 0);
|
||||
const rawResponse = p.responseTokens ?? u.responseOutputTokens ?? chat?.usage?.responseOutputTokens;
|
||||
const responseTokens = Number(rawResponse ?? Math.max(0, outputTokens - thinkingTokens));
|
||||
const breakdownKnown = validCount(rawResponse) || validCount(rawThinking);
|
||||
const hasVisibleText = String(p.modifiedResponse || p.response || '').trim().length > 0;
|
||||
const hasToolCalls = Array.isArray(p.toolCalls) && p.toolCalls.length > 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 start = parseIsoMs(m.createdAt);
|
||||
const end = parseIsoMs(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 viewableDelaySec = elapsed(start, parseIsoMs(m.viewableAt));
|
||||
const nativeTtftSec = duration(chat?.timeToFirstToken);
|
||||
// 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);
|
||||
const totalTokPerSec = complete && totalDurationSec > 0 && validCount(u.outputTokens)
|
||||
? outputTokens / totalDurationSec : null;
|
||||
|
||||
let streamDurationSec = null;
|
||||
let responseTimingSource = null;
|
||||
let speedReason = null;
|
||||
if (isCompactionStep) speedReason = 'compaction';
|
||||
else if (!complete) speedReason = 'incomplete_or_invalid_timing';
|
||||
else if (hasToolCalls) speedReason = 'tool_timing_unavailable';
|
||||
else if (!hasVisibleText) speedReason = 'no_answer_text';
|
||||
else if (!breakdownKnown || !validCount(u.outputTokens) || !validCount(responseTokens) ||
|
||||
!validCount(thinkingTokens) || responseTokens <= 0 || responseTokens + thinkingTokens > outputTokens) {
|
||||
speedReason = 'token_breakdown_unavailable';
|
||||
} else if (thinkingTokens > 0) {
|
||||
if (thinkingDurationSec > 0 && thinkingDurationSec < totalDurationSec) {
|
||||
streamDurationSec = totalDurationSec - thinkingDurationSec;
|
||||
responseTimingSource = 'post_thinking_estimate';
|
||||
} else speedReason = 'answer_start_unavailable';
|
||||
} else if (responseTokens === outputTokens && nativeStreamSec > 0 && nativeStreamSec <= totalDurationSec + 0.001) {
|
||||
streamDurationSec = nativeStreamSec;
|
||||
responseTimingSource = 'native_text_stream';
|
||||
} else speedReason = 'answer_start_unavailable';
|
||||
|
||||
const streamTokPerSec = streamDurationSec > 0 ? responseTokens / streamDurationSec : null;
|
||||
// Short samples retain their estimate. The threshold changes eligibility only,
|
||||
// never the formula or the displayed metric. There is no TPS-based clipping.
|
||||
const responseShortSample = streamTokPerSec !== null &&
|
||||
(responseTokens < MIN_MEAN_RESPONSE_TOKENS || streamDurationSec < MIN_MEAN_RESPONSE_SECONDS);
|
||||
if (responseShortSample) speedReason = 'short_sample';
|
||||
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';
|
||||
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 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, hasToolCalls,
|
||||
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),
|
||||
maxContextBudgetTokens: Number(context?.maxContextTokens || 256000),
|
||||
measurementVersion: MEASUREMENT_VERSION,
|
||||
isComplete: complete, nativeTtftSec, nativeStreamSec, viewableDelaySec,
|
||||
isComplete: complete, nativeTtftSec, nativeStreamSec,
|
||||
viewableDelaySec: elapsed(start, parseIsoMs(m.viewableAt)),
|
||||
ttftSec: nativeTtftSec, ttftSource: nativeTtftSec === null ? 'unavailable' : 'native',
|
||||
thinkingDurationSec, totalDurationSec, streamDurationSec,
|
||||
streamTokens: streamTokPerSec === null ? null : responseTokens,
|
||||
totalTokPerSec, streamTokPerSec,
|
||||
speedBasis: streamTokPerSec === null ? 'unavailable' : 'response_estimate',
|
||||
responseTimingSource, responseShortSample,
|
||||
responseSampleEligible: streamTokPerSec !== null && !responseShortSample,
|
||||
thinkingDurationSec, totalDurationSec, totalTokPerSec,
|
||||
speedBasis: totalTokPerSec === null ? 'unavailable' : 'request_total',
|
||||
speedSampleEligible: totalTokPerSec !== null && !shortOutputSample && !isCompactionStep,
|
||||
speedReason,
|
||||
});
|
||||
});
|
||||
@@ -116,49 +90,40 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
|
||||
export function normalizeCachedStep(step) {
|
||||
if (step.measurementVersion === MEASUREMENT_VERSION) return step;
|
||||
// v5 did not retain the original TTFT or trustworthy phase boundaries. Keep
|
||||
// accounting, but do not reconstruct measurements from its derived values.
|
||||
// Keep billing through failed reloads, but never show old derived speeds as
|
||||
// current measurements. Raw trajectories rebuild measurements after migration.
|
||||
return {
|
||||
...step, measurementVersion: null, isComplete: false,
|
||||
nativeTtftSec: null, nativeStreamSec: null, viewableDelaySec: null,
|
||||
ttftSec: null, ttftSource: 'unavailable', thinkingDurationSec: null,
|
||||
totalDurationSec: null, streamDurationSec: null, streamTokens: null,
|
||||
totalTokPerSec: null, streamTokPerSec: null, speedBasis: 'unavailable',
|
||||
responseTimingSource: null, responseShortSample: false,
|
||||
responseSampleEligible: false, speedReason: 'legacy_cache',
|
||||
totalDurationSec: null, totalTokPerSec: null,
|
||||
streamDurationSec: null, streamTokens: null, streamTokPerSec: null,
|
||||
speedBasis: 'unavailable', speedSampleEligible: false, speedReason: 'legacy_cache',
|
||||
};
|
||||
}
|
||||
|
||||
export function speedMetric(step, mode) {
|
||||
export function speedMetric(step) {
|
||||
const missing = (reason) => ({ value: null, tokens: 0, seconds: 0, eligible: false, reason });
|
||||
if (step.measurementVersion !== MEASUREMENT_VERSION) return missing('legacy_cache');
|
||||
if (step.isCompactionStep) return missing('compaction');
|
||||
if (mode === 'total') {
|
||||
if (!Number.isFinite(step.totalTokPerSec) || !(step.totalDurationSec > 0) || !step.isComplete) {
|
||||
return missing('incomplete_or_invalid_timing');
|
||||
}
|
||||
return { value: step.totalTokPerSec, tokens: step.outputTokens, seconds: step.totalDurationSec, eligible: true, reason: null };
|
||||
if (!step.isComplete || !Number.isFinite(step.totalTokPerSec) ||
|
||||
!(step.totalDurationSec >= MIN_SPEED_DURATION_SECONDS)) {
|
||||
return missing(step.speedReason || 'incomplete_or_invalid_timing');
|
||||
}
|
||||
if (!Number.isFinite(step.streamTokPerSec) || !(step.streamDurationSec > 0)) return missing(step.speedReason || 'answer_start_unavailable');
|
||||
return {
|
||||
value: step.streamTokPerSec, tokens: step.streamTokens, seconds: step.streamDurationSec,
|
||||
eligible: step.responseSampleEligible === true, reason: step.speedReason,
|
||||
};
|
||||
return { value: step.totalTokPerSec, tokens: step.outputTokens, seconds: step.totalDurationSec,
|
||||
eligible: step.speedSampleEligible === true && !step.isCompactionStep, reason: step.speedReason };
|
||||
}
|
||||
|
||||
export function createSpeedAccumulator() {
|
||||
return { tokens: 0, seconds: 0, sampleCount: 0, excludedCount: 0, excludedReasons: {}, timingSources: {} };
|
||||
return { tokens: 0, seconds: 0, sampleCount: 0, excludedCount: 0, excludedReasons: {} };
|
||||
}
|
||||
|
||||
export function accumulateSpeed(acc, step, mode) {
|
||||
export function accumulateSpeed(acc, step) {
|
||||
if (step.isCompactionStep) return;
|
||||
const metric = speedMetric(step, mode);
|
||||
const metric = speedMetric(step);
|
||||
if (metric.eligible) {
|
||||
acc.tokens += metric.tokens;
|
||||
acc.seconds += metric.seconds;
|
||||
acc.sampleCount++;
|
||||
const source = mode === 'total' ? 'request_total' : step.responseTimingSource;
|
||||
acc.timingSources[source] = (acc.timingSources[source] || 0) + 1;
|
||||
} else {
|
||||
acc.excludedCount++;
|
||||
acc.excludedReasons[metric.reason] = (acc.excludedReasons[metric.reason] || 0) + 1;
|
||||
@@ -169,9 +134,9 @@ export function finishSpeed(acc) {
|
||||
return { ...acc, avgTokPerSec: acc.seconds > 0 ? acc.tokens / acc.seconds : null };
|
||||
}
|
||||
|
||||
export function summarizeSpeed(steps, mode) {
|
||||
export function summarizeSpeed(steps) {
|
||||
const acc = createSpeedAccumulator();
|
||||
for (const step of steps) accumulateSpeed(acc, step, mode);
|
||||
for (const step of steps) accumulateSpeed(acc, step);
|
||||
return finishSpeed(acc);
|
||||
}
|
||||
|
||||
|
||||
@@ -191,7 +191,7 @@ body {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
cursor: pointer;
|
||||
cursor: default;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
|
||||
@@ -22,20 +22,21 @@ 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,/^v6-speed-metrics:/);
|
||||
assert.match(h.state.saves[0].data.test.signature,/^v7-request-throughput:/);
|
||||
});
|
||||
test('mode switching applies to latest step, session mean and per-model mean',async()=>{
|
||||
const h=backendHarness({cache:{test:old},trajectories:{test:raw},settings:{speedMode:'total'}});
|
||||
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,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()=>{
|
||||
const h=backendHarness({cache:{test:old},trajectories:{test:{}}});
|
||||
@@ -51,3 +52,16 @@ test('a partial trajectory cannot replace a complete historical cache',async()=>
|
||||
assert.equal(h.state.saves.length,0);
|
||||
assert.match(h.state.errors[0],/Incomplete trajectory/);
|
||||
});
|
||||
|
||||
test('a TTFT-only correction is persisted even when usage, duration and signature match',async()=>{
|
||||
const h=backendHarness({cache:{test:old},trajectories:{test:raw},summaries:{test:{
|
||||
stepCount:1,lastModifiedTime:'2026-01-01T00:00:10Z',status:'CASCADE_RUN_STATUS_RUNNING',
|
||||
}}});
|
||||
await h.buildTelemetryPayloadInternal('test');
|
||||
h.state.trajectories.test=structuredClone(raw);
|
||||
h.state.trajectories.test.trajectory.generatorMetadata[0].chatModel.timeToFirstToken='9s';
|
||||
const next=await h.buildTelemetryPayloadInternal('test');
|
||||
assert.equal(next.activeConversation.latestTtftSec,9);
|
||||
assert.equal(h.state.saves.length,2);
|
||||
assert.equal(h.state.saves[1].data.test.steps[0].ttftSec,9);
|
||||
});
|
||||
|
||||
@@ -2,54 +2,42 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
import {summarizeSpeed} from '../speed-metrics.mjs';
|
||||
|
||||
const context = vm.createContext({window: {}});
|
||||
const source = readFileSync(new URL('../app.js', import.meta.url), 'utf8');
|
||||
assert.match(source, /\ninit\(\);\s*$/);
|
||||
vm.runInContext(source.replace(/\ninit\(\);\s*$/, '\n'), context);
|
||||
const show = (step, mode = 'stream') => context.stepSpeedDisplay(step, mode);
|
||||
const tool = {measurementVersion: 1, isComplete: true, hasToolCalls: true,
|
||||
outputTokens: 300, totalDurationSec: 10, totalTokPerSec: 30,
|
||||
streamTokPerSec: null, responseSampleEligible: false,
|
||||
speedReason: 'tool_timing_unavailable'};
|
||||
const answer = {measurementVersion: 1, isComplete: true, outputTokens: 600,
|
||||
totalDurationSec: 10, totalTokPerSec: 60, streamTokPerSec: 100,
|
||||
streamTokens: 500, streamDurationSec: 5, responseSampleEligible: true,
|
||||
responseTimingSource: 'post_thinking_estimate'};
|
||||
|
||||
test('completed tools have a labelled total TPS without contaminating the response mean', () => {
|
||||
const display = show(tool);
|
||||
assert.equal(display.value, 30);
|
||||
assert.equal(display.label, '整体吞吐');
|
||||
assert.equal(display.estimated, false);
|
||||
assert.match(display.explanation, /不计正文均速/);
|
||||
assert.equal(summarizeSpeed([tool, answer], 'stream').avgTokPerSec, 100);
|
||||
assert.equal(summarizeSpeed([tool, answer], 'total').avgTokPerSec, 45);
|
||||
assert.equal(tool.streamTokPerSec, null);
|
||||
function page() {
|
||||
function element(){return {children:[],_html:'',textContent:'',title:'',scrollTop:0,
|
||||
get innerHTML(){return this._html;},set innerHTML(s){this._html=s;this.children=[];},
|
||||
appendChild(child){if(child.fragment)this.children.push(...child.children);else this.children.push(child);},
|
||||
closest(){return null;}};}
|
||||
const elements=Object.fromEntries(['tab-steps-btn','steps-tbody','models-tbody'].map(id=>[id,element()]));
|
||||
const document={getElementById:id=>elements[id],createElement:element,createDocumentFragment:()=>({...element(),fragment:true})};
|
||||
const source=readFileSync(new URL('../app.js',import.meta.url),'utf8');
|
||||
assert.match(source,/\ninit\(\);\s*$/);
|
||||
const ctx=vm.createContext({window:{},document});
|
||||
vm.runInContext(source.replace(/\ninit\(\);\s*$/,'\n'),ctx);
|
||||
return {ctx,elements};
|
||||
}
|
||||
const step={stepIndex:1,modelShort:'test',outputTokens:300,responseTokens:200,thinkingTokens:100,
|
||||
totalDurationSec:10,tokPerSec:30,ttftSec:2,costUsd:.01};
|
||||
test('tools and text render one TPS column without per-row speed categories',()=>{
|
||||
const {ctx,elements}=page();
|
||||
ctx.renderTables({recentSteps:[{...step,hasToolCalls:true}]},[]);
|
||||
const row=elements['steps-tbody'].children[0];
|
||||
assert.match(row.innerHTML,/30\.0 tok\/s/);
|
||||
assert.doesNotMatch(row.innerHTML,/正文估算|整体吞吐|≈/);
|
||||
assert.match(row.title,/含等待与思考/);
|
||||
});
|
||||
test('answer and total modes keep their distinct labels and formulas', () => {
|
||||
assert.equal(show(answer).value, 100);
|
||||
assert.equal(show(answer).label, '正文估算');
|
||||
assert.equal(show(answer).estimated, true);
|
||||
assert.equal(show(answer, 'total').value, 60);
|
||||
assert.equal(show(answer, 'total').label, '整体吞吐');
|
||||
assert.equal(show({...answer, responseShortSample: true}).detail, '正文估算 · 短样本');
|
||||
test('unknown and zero are distinct, and insufficient timing explains the missing rate',()=>{
|
||||
const {ctx,elements}=page();
|
||||
ctx.renderTables({recentSteps:[{...step,tokPerSec:null,ttftSec:null,selectedSpeedReason:'short_timing'}]},[]);
|
||||
assert.match(elements['steps-tbody'].children[0].innerHTML,/计时过短/);
|
||||
assert.match(elements['steps-tbody'].children[0].innerHTML,/<td>—<\/td>/);
|
||||
ctx.renderTables({recentSteps:[{...step,tokPerSec:0,ttftSec:0}]},[]);
|
||||
assert.match(elements['steps-tbody'].children[0].innerHTML,/0\.0 tok\/s/);
|
||||
assert.match(elements['steps-tbody'].children[0].innerHTML,/<td>0\.0s<\/td>/);
|
||||
});
|
||||
test('missing answer start can display measured total TPS, including zero output', () => {
|
||||
assert.equal(show({...tool, hasToolCalls: false, speedReason: 'answer_start_unavailable'}).value, 30);
|
||||
assert.equal(show({...tool, outputTokens: 0, totalTokPerSec: 0}).value, 0);
|
||||
});
|
||||
test('incomplete and legacy rows never acquire a fabricated total TPS', () => {
|
||||
assert.equal(show({...tool, isComplete: false}).value, null);
|
||||
assert.equal(show({...tool, measurementVersion: null}).value, null);
|
||||
assert.equal(show({...tool, totalTokPerSec: null}).value, null);
|
||||
assert.equal(show({...tool, totalDurationSec: 0}).value, null);
|
||||
assert.equal(show().value, null);
|
||||
});
|
||||
test('compaction can show its measured rate while remaining excluded from means', () => {
|
||||
const step = {...tool, isCompactionStep: true, speedReason: 'compaction'};
|
||||
assert.equal(show(step).value, 30);
|
||||
assert.match(show(step).detail, /压缩/);
|
||||
assert.equal(summarizeSpeed([step], 'total').sampleCount, 0);
|
||||
test('a TTFT-only correction refreshes the table even when TPS and step count do not change',()=>{
|
||||
const {ctx,elements}=page();
|
||||
ctx.renderTables({recentSteps:[step]},[]);
|
||||
ctx.renderTables({recentSteps:[{...step,ttftSec:12.974}]},[]);
|
||||
assert.match(elements['steps-tbody'].children[0].innerHTML,/<td>13\.0s<\/td>/);
|
||||
});
|
||||
|
||||
@@ -1,104 +1,108 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft } from '../speed-metrics.mjs';
|
||||
import {extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../speed-metrics.mjs';
|
||||
|
||||
function sample({ total = 12, ttft = '2s', stream = '10s', output = 1100, thinking = 100, response = 1000, thinkingDuration = '4s', tools = false, text = true, status = 'CORTEX_STEP_STATUS_DONE' } = {}) {
|
||||
const createdAt = '2026-01-01T00:00:00Z';
|
||||
const s = { status, type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', metadata: {
|
||||
createdAt, viewableAt: '2026-01-01T00:00:02Z',
|
||||
finishedGeneratingAt: new Date(Date.parse(createdAt) + total * 1000).toISOString(),
|
||||
modelUsage: { inputTokens: '500', cacheReadTokens: '2000', outputTokens: String(output), thinkingOutputTokens: String(thinking), responseOutputTokens: String(response) },
|
||||
}, plannerResponse: { response: text ? 'answer' : '', thinkingDuration, toolCalls: tools ? [{}] : [] } };
|
||||
const gm = { stepIndices: [0], chatModel: { timeToFirstToken: ttft, streamingDuration: stream } };
|
||||
return { s, gm };
|
||||
function sample({total=12,ttft='2s',stream='10s',output=1100,thinking=100,response=1000,
|
||||
thinkingDuration='4s',tools=false,text=true,status='CORTEX_STEP_STATUS_DONE'}={}) {
|
||||
const s={status,type:'CORTEX_STEP_TYPE_PLANNER_RESPONSE',metadata:{
|
||||
createdAt:'2026-01-01T00:00:00Z',viewableAt:'2026-01-01T00:00:02Z',
|
||||
finishedGeneratingAt:new Date(Date.parse('2026-01-01T00:00:00Z')+total*1000).toISOString(),
|
||||
modelUsage:{inputTokens:'500',cacheReadTokens:'2000',outputTokens:String(output),thinkingOutputTokens:String(thinking),responseOutputTokens:String(response)},
|
||||
},plannerResponse:{response:text?'answer':'',thinkingDuration,toolCalls:tools?[{}]:[]}};
|
||||
const gm={stepIndices:[0],chatModel:{timeToFirstToken:ttft,streamingDuration:stream}};
|
||||
return {s,gm};
|
||||
}
|
||||
function parse(options) { const {s,gm}=sample(options); return extractModelSteps([s],[gm])[0]; }
|
||||
function parse(options) {const {s,gm}=sample(options);return extractModelSteps([s],[gm])[0];}
|
||||
|
||||
test('raw TTFT is not replaced by a thinking-token ratio, even for buffered tools', () => {
|
||||
const s=parse({total:20,ttft:'19.9s',stream:'0.1s',thinkingDuration:'19.95s',tools:true,text:false});
|
||||
assert.equal(s.ttftSec,19.9);
|
||||
assert.equal(s.streamTokPerSec,null);
|
||||
assert.equal(s.totalTokPerSec,55);
|
||||
});
|
||||
test('missing TTFT stays unknown; separately preserve the viewable-event delay', () => {
|
||||
const raw=sample(); delete raw.gm.chatModel.timeToFirstToken;
|
||||
const measured=extractModelSteps([raw.s],[raw.gm])[0];
|
||||
assert.equal(measured.ttftSec,null);
|
||||
assert.equal(measured.viewableDelaySec,2);
|
||||
});
|
||||
test('a reported zero TTFT is valid and missing data is not zero', () => {
|
||||
const s=parse({ttft:'0s'});
|
||||
assert.equal(s.ttftSec,0);
|
||||
assert.deepEqual(summarizeTtft([s]),{sampleCount:1,avgSec:0});
|
||||
});
|
||||
test('pure-text thinking phases are explicitly estimates', () => {
|
||||
const s=parse();
|
||||
assert.equal(s.streamTokPerSec,125);
|
||||
assert.equal(s.totalTokPerSec,1100/12);
|
||||
assert.equal(s.speedBasis,'response_estimate');
|
||||
assert.equal(s.responseTimingSource,'post_thinking_estimate');
|
||||
});
|
||||
test('a native stream spanning reasoning does not become a pure-answer timer', () => {
|
||||
const raw=sample(); delete raw.s.plannerResponse.thinkingDuration;
|
||||
const unknown=extractModelSteps([raw.s],[raw.gm])[0];
|
||||
assert.equal(unknown.streamTokPerSec,null);
|
||||
assert.equal(unknown.speedReason,'answer_start_unavailable');
|
||||
});
|
||||
test('mixed text/tool and tool-only output never enter the answer mean', () => {
|
||||
for (const text of [true,false]) {
|
||||
const s=parse({tools:true,text});
|
||||
assert.equal(s.streamTokPerSec,null);
|
||||
assert.equal(summarizeSpeed([s],'stream').sampleCount,0);
|
||||
assert.equal(summarizeSpeed([s],'total').sampleCount,1);
|
||||
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,1100/12);
|
||||
assert.equal(step.speedBasis,'request_total');
|
||||
assert.equal(step.speedSampleEligible,true);
|
||||
}
|
||||
});
|
||||
test('short greeting keeps its phase estimate without falling back to whole-call speed', () => {
|
||||
const s=parse({output:13,thinking:0,response:13,total:5.015,ttft:'4.897s',stream:'0.118s',thinkingDuration:undefined});
|
||||
assert.equal(s.streamTokPerSec,13/.118);
|
||||
assert.equal(s.responseShortSample,true);
|
||||
assert.equal(summarizeSpeed([s],'stream').avgTokPerSec,null);
|
||||
assert.equal(speedMetric(s,'total').value,13/5.015);
|
||||
test('buffered JSON cannot create a burst peak by shortening native or thinking phase timers',()=>{
|
||||
for(const stream of ['0.001s','0.01s','1s','10s',undefined]){
|
||||
for(const thinkingDuration of ['0.01s','9.999s',undefined]){
|
||||
const step=parse({total:10,ttft:'9.999s',stream,thinkingDuration,output:300,tools:true,text:false});
|
||||
assert.equal(step.totalTokPerSec,30);
|
||||
assert.equal(step.ttftSec,9.999);
|
||||
}
|
||||
}
|
||||
});
|
||||
test('mean uses summed tokens/time of eligible samples, not an arithmetic mean or fallback', () => {
|
||||
const a=parse(); // 1000 / 8
|
||||
const b=parse({output:600,response:500}); // 500 / 8
|
||||
const tool=parse({tools:true});
|
||||
const result=summarizeSpeed([a,b,tool],'stream');
|
||||
assert.equal(result.avgTokPerSec,1500/16);
|
||||
assert.equal(result.sampleCount,2);
|
||||
assert.equal(result.excludedCount,1);
|
||||
test('TTFT is the exact native value, never a token-ratio guess or viewable-event substitute',()=>{
|
||||
assert.equal(parse({total:20,ttft:'19.9s',thinkingDuration:'19.95s',tools:true,text:false}).ttftSec,19.9);
|
||||
const {s,gm}=sample();delete gm.chatModel.timeToFirstToken;
|
||||
const step=extractModelSteps([s],[gm])[0];
|
||||
assert.equal(step.ttftSec,null);assert.equal(step.viewableDelaySec,2);
|
||||
assert.deepEqual(summarizeTtft([step]),{sampleCount:0,avgSec:null});
|
||||
});
|
||||
test('unfinished and invalid-order requests do not invent completion from viewableAt', () => {
|
||||
const raw=sample(); delete raw.s.metadata.finishedGeneratingAt;
|
||||
assert.equal(extractModelSteps([raw.s],[raw.gm])[0].totalTokPerSec,null);
|
||||
test('zero TTFT is preserved and malformed or negative durations remain unknown',()=>{
|
||||
const zero=parse({ttft:'0s'});
|
||||
assert.equal(zero.ttftSec,0);
|
||||
assert.equal(summarizeTtft([zero]).avgSec,0);
|
||||
for(const ttft of ['-1s','12garbage','NaNs','Infinitys',''])assert.equal(parse({ttft}).ttftSec,null);
|
||||
});
|
||||
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,1100/12);
|
||||
assert.equal(summarizeSpeed([short]).avgTokPerSec,null);
|
||||
assert.equal(parse({output:50}).speedSampleEligible,true);
|
||||
});
|
||||
test('sub-half-second whole requests are withheld, never divided by a tiny interval',()=>{
|
||||
const tiny=parse({total:.05,output:1000});
|
||||
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);
|
||||
});
|
||||
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});
|
||||
const mean=summarizeSpeed([a,b]);
|
||||
assert.equal(mean.tokens,2000);assert.equal(mean.seconds,30);
|
||||
assert.equal(mean.avgTokPerSec,2000/30);assert.equal(mean.sampleCount,2);
|
||||
});
|
||||
test('unfinished, missing-completion and reversed-time requests cannot fabricate speed',()=>{
|
||||
const {s,gm}=sample();delete s.metadata.finishedGeneratingAt;
|
||||
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,null);
|
||||
assert.equal(parse({total:-1}).totalTokPerSec,null);
|
||||
assert.equal(parse({total:0}).totalTokPerSec,null);
|
||||
assert.equal(parse({status:'CORTEX_STEP_STATUS_GENERATING'}).totalTokPerSec,null);
|
||||
});
|
||||
test('zero response token count and invalid breakdowns are not overwritten', () => {
|
||||
assert.equal(parse({response:0}).responseTokens,0);
|
||||
assert.equal(parse({response:0}).streamTokPerSec,null);
|
||||
assert.equal(parse({response:2000}).streamTokPerSec,null);
|
||||
test('zero output is a real zero; malformed or missing output counts cannot produce rates',()=>{
|
||||
const zero=parse({output:0,response:0,thinking:0});
|
||||
assert.equal(zero.totalTokPerSec,0);assert.equal(zero.responseTokens,0);
|
||||
for(const output of [-1,1.5,NaN,Infinity])assert.equal(parse({output}).totalTokPerSec,null);
|
||||
const {s,gm}=sample();delete s.metadata.modelUsage.outputTokens;
|
||||
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,null);
|
||||
});
|
||||
test('there is no rate-based clipping or method switch around 260 TPS', () => {
|
||||
const below=parse({output:2172,response:2072});
|
||||
const above=parse({output:2188,response:2088});
|
||||
assert.equal(below.streamTokPerSec,259);
|
||||
assert.equal(above.streamTokPerSec,261);
|
||||
assert.equal(above.speedBasis,below.speedBasis);
|
||||
test('missing phase/token breakdown cannot change a valid full-request rate',()=>{
|
||||
const {s,gm}=sample();delete s.plannerResponse.thinkingDuration;
|
||||
delete s.metadata.modelUsage.thinkingOutputTokens;delete s.metadata.modelUsage.responseOutputTokens;
|
||||
delete gm.chatModel.streamingDuration;
|
||||
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,1100/12);
|
||||
});
|
||||
test('old cache keeps accounting but drops all derived timing, including manipulated TTFT', () => {
|
||||
const old={inputTokens:500,cacheReadTokens:2000,outputTokens:1100,ttftSec:0.4,streamTokPerSec:99,totalTokPerSec:55};
|
||||
const migrated=normalizeCachedStep(old);
|
||||
assert.equal(migrated.outputTokens,1100);
|
||||
assert.equal(migrated.inputTokens,500);
|
||||
assert.equal(migrated.cacheReadTokens,2000);
|
||||
assert.equal(migrated.ttftSec,null);
|
||||
assert.equal(speedMetric(migrated,'total').value,null);
|
||||
assert.equal(speedMetric(migrated,'stream').reason,'legacy_cache');
|
||||
test('no rate-dependent cap or formula switch at the former 260 TPS boundary',()=>{
|
||||
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(a.speedBasis,b.speedBasis);
|
||||
});
|
||||
test('compaction retains its billed tokens but is excluded from both speed aggregates', () => {
|
||||
const {s,gm}=sample(); s.type='CORTEX_STEP_TYPE_CHECKPOINT';
|
||||
const parsed=extractModelSteps([s],[gm])[0];
|
||||
assert.equal(parsed.outputTokens,1100);
|
||||
for(const mode of ['stream','total']) assert.equal(summarizeSpeed([parsed],mode).sampleCount,0);
|
||||
test('legacy cache retains billing but cannot masquerade as current measurements',()=>{
|
||||
for(const measurementVersion of [undefined,1]){
|
||||
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);
|
||||
assert.equal(migrated.ttftSec,null);assert.equal(speedMetric(migrated).value,null);
|
||||
assert.equal(speedMetric(migrated).reason,'legacy_cache');
|
||||
}
|
||||
});
|
||||
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';
|
||||
const step=extractModelSteps([s],[gm])[0];
|
||||
assert.equal(step.outputTokens,1100);assert.equal(speedMetric(step).value,1100/12);
|
||||
assert.equal(summarizeSpeed([step]).sampleCount,0);
|
||||
assert.equal(summarizeTtft([step]).sampleCount,0);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user