fix(metrics): separate answer estimates from request throughput

This commit is contained in:
yuhuan2498281558
2026-10-15 03:39:58 +08:00
parent 44386f38d8
commit 33c7b88a49
10 changed files with 483 additions and 217 deletions
+44 -12
View File
@@ -18,6 +18,27 @@ function escapeHtml(str) {
.replace(/"/g, '"');
}
function formatMetric(value, unit = '', estimated = false) {
return Number.isFinite(value) ? `${estimated ? '≈' : ''}${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: '缺少正文起点',
short_sample: '短样本,不计均速',
legacy_cache: '旧缓存,等待重新读取',
})[reason] || '';
}
function sampleSummary(summary) {
return `${summary?.sampleCount || 0}/${(summary?.sampleCount || 0) + (summary?.excludedCount || 0)} 步`;
}
function formatTokens(num) {
const n = Number(num || 0);
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
@@ -135,14 +156,15 @@ function renderAllPools(pools, activeFamily) {
let lastStepsRenderSig = '';
let lastModelsRenderSig = '';
function renderTables(activeConv, modelBreakdown) {
function renderTables(activeConv, modelBreakdown, speedMode = 'stream') {
const estimated = speedMode !== 'total';
const steps = activeConv.recentSteps || [];
const tabStepsBtn = $('tab-steps-btn');
if (tabStepsBtn) {
tabStepsBtn.textContent = `当前会话步骤测速与计费 (${steps.length}步)`;
}
const stepsSig = `${activeConv.cascadeId || ''}:${steps.length}:${steps[0]?.stepIndex ?? -1}:${steps[0]?.tokPerSec ?? 0}:${steps[0]?.costUsd ?? 0}`;
const stepsSig = `${activeConv.cascadeId || ''}:${speedMode}:${JSON.stringify(steps)}`;
if (stepsSig !== lastStepsRenderSig) {
lastStepsRenderSig = stepsSig;
const stepsTbody = $('steps-tbody');
@@ -156,6 +178,8 @@ function renderTables(activeConv, modelBreakdown) {
? `思考: ${st.thinkingTokens} tok${st.thinkingDurationSec ? ` (${st.thinkingDurationSec}s)` : ''} | `
: '';
const compTag = st.isCompactionStep ? ' [压缩汇总步]' : '';
const reason = speedReasonText(st.selectedSpeedReason);
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 =
@@ -164,12 +188,12 @@ 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}正文/工具输出: ${st.responseTokens} tok | 流耗时: ${st.streamDurationSec}s | 总耗时: ${st.totalDurationSec}s`;
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.innerHTML = `
<td>#${Number(st.stepIndex)}${compTag ? '<span class="muted">⚡</span>' : ''}</td>
<td>${escapeHtml(st.modelShort)}</td>
<td><strong style="color: var(--speed-accent)">${Number(st.tokPerSec).toFixed(1)}</strong> tok/s</td>
<td>${Number(st.ttftSec).toFixed(1)}s</td>
<td><strong style="color: var(--speed-accent)">${formatMetric(st.tokPerSec, ' tok/s', estimated)}</strong><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>
<td style="${costStyle}">${stepCostDisplay}</td>
@@ -184,7 +208,7 @@ function renderTables(activeConv, modelBreakdown) {
}
const models = modelBreakdown || [];
const modelsSig = models.map((m) => `${m.modelId}:${m.calls}:${m.totalTokens}:${m.avgTokPerSec}`).join('|');
const modelsSig = `${speedMode}:${JSON.stringify(models)}`;
if (modelsSig !== lastModelsRenderSig) {
lastModelsRenderSig = modelsSig;
const modelsTbody = $('models-tbody');
@@ -195,7 +219,7 @@ function renderTables(activeConv, modelBreakdown) {
tr.innerHTML = `
<td><strong>${escapeHtml(m.shortName)}</strong> <span class="muted">(${Number(m.calls)})</span></td>
<td>${Number(m.calls)}</td>
<td>${Number(m.avgTokPerSec).toFixed(1)} tok/s</td>
<td>${formatMetric(m.avgTokPerSec, ' tok/s', estimated)}<div class="speed-detail muted">有效 ${sampleSummary(m.speedSummary)}</div></td>
<td>${formatTokens(m.totalTokens)}</td>
<td>${pricePrefix}${Number(m.costUsd).toFixed(2)}</td>
`;
@@ -296,9 +320,17 @@ function applyTelemetryToDom(data) {
}
// 2. Status strip metrics
$('tok-per-sec').textContent = `${Number(active.latestTokPerSec || 0).toFixed(1)} tok/s`;
$('ttft-value').textContent = `${Number(active.latestTtftSec || 0).toFixed(1)}s`;
$('avg-speed-value').textContent = `${Number(active.avgTokPerSec || 0).toFixed(1)}`;
const estimatedSpeed = settings.speedMode !== 'total';
$('tok-per-sec').textContent = formatMetric(active.latestTokPerSec, ' tok/s', estimatedSpeed);
$('speed-mode-toggle').title = `最新一步:${speedReasonText(active.latestSpeedReason) || (estimatedSpeed ? '正文阶段估算' : '请求整体吞吐')};点击切换口径`;
$('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);
$('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
? '正文阶段估算;工具混合输出和起点不明的步骤不计均速,短样本单列。'
: '含思考的输出 Token ÷ 请求总耗时;不含调用之间的空闲和外部工具执行时间。';
const latestStepCost = Number(active.latestStepCostUsd ?? active.recentSteps?.[0]?.costUsd ?? 0);
if ($('step-cost-value')) {
$('step-cost-value').textContent = `$${latestStepCost.toFixed(3)}`;
@@ -311,7 +343,7 @@ 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' ? '整体测速(含思考)' : '输出流测速';
$('speed-mode-badge').textContent = settings.speedMode === 'total' ? '整体吞吐' : '正文估算';
// 3. Context Window Popover Section
const limitTokens = ctx.limitTokens || 256000;
@@ -390,7 +422,7 @@ function applyTelemetryToDom(data) {
$('setting-weekly-tokens').value = settings.weeklyTokenBudget || 150000000;
$('setting-weekly-cost').value = settings.weeklyCostBudget || 100;
renderTables(active, data.modelBreakdown);
renderTables(active, data.modelBreakdown, settings.speedMode);
}
let manualRefreshFeedbackTimer = null;
+9 -8
View File
@@ -26,12 +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="最新一步;点击切换「正文估算」与「整体吞吐」" id="speed-mode-toggle">
<span id="speed-dot" class="speed-dot"></span>
<strong id="tok-per-sec" class="speed-value">0.0 tok/s</strong>
<strong id="tok-per-sec" class="speed-value">—</strong>
</span>
<span class="metric-item">首字 <strong id="ttft-value">0.0s</strong></span>
<span class="metric-item">均速 <strong id="avg-speed-value">0.0</strong></span>
<span class="metric-item">首Token <strong id="ttft-value">—</strong></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>
@@ -50,8 +50,9 @@
<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>
<span class="speed-mode-label muted" id="speed-mode-badge">正文估算</span>
</div>
<div id="speed-method-note" class="speed-method-note muted">正文阶段估算;计时不明的步骤不计均速。</div>
</section>
<!-- Quota & Context Popover Card (1:1 replica of the right popover card in screenshot) -->
@@ -210,7 +211,7 @@
<th>步</th>
<th>模型</th>
<th>速度</th>
<th>首字</th>
<th>首Token</th>
<th>上下文/输出</th>
<th>缓存</th>
<th>消费</th>
@@ -246,8 +247,8 @@
<label class="field-label">
<span>tok/s 测速口径</span>
<select id="setting-speed-mode">
<option value="stream">纯输出流速度 (扣除首字思考时间)</option>
<option value="total">整体生成速度 (含首字思考总耗时)</option>
<option value="stream">正文阶段估算 (仅有效纯文本样本)</option>
<option value="total">请求整体吞吐 (含等待与思考)</option>
</select>
</label>
<label class="field-label">
+31 -192
View File
@@ -4,6 +4,7 @@ import { homedir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Response, SidecarApp } from 'sidecar_sdk';
import { extractModelSteps, parseIsoMs, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft, createSpeedAccumulator, accumulateSpeed, finishSpeed } from './speed-metrics.mjs';
const HERE = dirname(fileURLToPath(import.meta.url));
const DATA_DIR = process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR || join(HERE, '.data');
@@ -19,7 +20,7 @@ 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', // 'stream' (streamTokens / streamTime) | 'total' (outputTokens / totalTime)
speedMode: 'stream', // Answer-phase estimate, or request-level throughput; never mixed.
};
// Official API pricing in USD per 1M tokens (Input, CacheRead, Output incl. Thinking)
@@ -58,8 +59,10 @@ const PLACEHOLDER_MAP = {
};
// In-memory cache of trajectory step usage: cascadeId -> { signature, steps }
const CACHE_SCHEMA_VERSION = 'v5';
let trajectoryCache = loadJson(CACHE_FILE, {});
const CACHE_SCHEMA_VERSION = 'v6-speed-metrics';
let trajectoryCache = Object.fromEntries(Object.entries(loadJson(CACHE_FILE, {})).map(([id, entry]) => [
id, { ...entry, steps: (entry.steps || []).map(normalizeCachedStep) },
]));
const inFlightRequests = new Map();
let quotaSummaryCache = { ts: 0, data: null, error: null };
@@ -85,21 +88,8 @@ function loadSettings() {
return { ...DEFAULT_SETTINGS, ...loadJson(SETTINGS_FILE, {}) };
}
function parseIsoMs(isoStr) {
if (!isoStr || typeof isoStr !== 'string') return 0;
const baseMs = Date.parse(isoStr);
if (!baseMs || Number.isNaN(baseMs)) return 0;
const match = isoStr.match(/\.(\d+)Z$/);
if (!match) return baseMs;
const fracSec = Number(`0.${match[1]}`);
const wholeSecMs = Math.floor(baseMs / 1000) * 1000;
return wholeSecMs + fracSec * 1000;
}
function parseDurationSec(durStr) {
if (!durStr || typeof durStr !== 'string') return 0;
const n = Number.parseFloat(durStr);
return Number.isFinite(n) && n > 0 ? n : 0;
function roundMetric(value) {
return Number.isFinite(value) ? +value.toFixed(1) : null;
}
async function callLsRpc(method, body = {}, timeoutMs = 5000) {
@@ -240,145 +230,6 @@ function computeStepCost(step, pricing) {
return inCost + cacheCost + outCost;
}
function extractModelSteps(rawSteps = [], generatorMetadata = []) {
const genMetaByStep = new Map();
for (const gm of generatorMetadata || []) {
const indices = gm?.stepIndices || [];
for (const idx of indices) {
genMetaByStep.set(Number(idx), gm);
}
}
const parsed = [];
rawSteps.forEach((s, idx) => {
const m = s?.metadata;
const isCompactionStep = s?.type === 'CORTEX_STEP_TYPE_CHECKPOINT';
const u = m?.modelUsage || (m?.retryInfos?.[0]?.usage ?? null);
if (!u) return;
const stepIndex = s?.metadata?.sourceTrajectoryStepInfo?.stepIndex ?? idx;
const gm = m?.generatorMetadata?.[0] || genMetaByStep.get(Number(stepIndex)) || genMetaByStep.get(idx) || null;
const chatModel = gm?.chatModel || null;
const ctxWinMeta = chatModel?.chatStartMetadata?.contextWindowMetadata || null;
const p = s?.plannerResponse || {};
const inputTokens = Number(u.inputTokens || 0);
const cacheReadTokens = Number(u.cacheReadTokens || 0);
const outputTokens = Number(u.outputTokens || 0);
const thinkingTokens = Number(p.thinkingTokens || u.thinkingOutputTokens || chatModel?.usage?.thinkingOutputTokens || 0);
const responseTokens = Number(
p.responseTokens || u.responseOutputTokens || chatModel?.usage?.responseOutputTokens || Math.max(0, outputTokens - thinkingTokens)
);
const createdAtMs = parseIsoMs(m.createdAt);
const viewableAtMs = parseIsoMs(m.viewableAt || m.createdAt) || createdAtMs;
const finishedAtMs =
parseIsoMs(m.finishedGeneratingAt || m.completedAt || m.viewableAt || m.createdAt) ||
viewableAtMs;
const rawViewableSec =
createdAtMs > 0 && viewableAtMs >= createdAtMs
? Math.max(0.05, (viewableAtMs - createdAtMs) / 1000)
: 0;
const afterViewableSec =
viewableAtMs > 0 && finishedAtMs > viewableAtMs
? (finishedAtMs - viewableAtMs) / 1000
: 0;
const totalDurationSec =
createdAtMs > 0 && finishedAtMs > createdAtMs
? (finishedAtMs - createdAtMs) / 1000
: 0;
const nativeTtftSec = parseDurationSec(chatModel?.timeToFirstToken);
const nativeStreamSec = parseDurationSec(chatModel?.streamingDuration);
const thinkingDurationSec = parseDurationSec(p.thinkingDuration);
const respText = String(p.modifiedResponse || p.response || '').trim();
const hasVisibleText = respText.length > 0;
const hasToolCalls = Array.isArray(p.toolCalls) && p.toolCalls.length > 0;
let ttftSec = nativeTtftSec > 0 ? nativeTtftSec : rawViewableSec;
let streamTokens = outputTokens;
let streamDurationSec = 0;
let speedBasis = 'model_stream';
const postThinkingSec =
thinkingDurationSec > 0 && totalDurationSec > thinkingDurationSec
? totalDurationSec - thinkingDurationSec
: afterViewableSec;
if (hasVisibleText && responseTokens > 0 && postThinkingSec >= 0.35) {
streamTokens = responseTokens;
streamDurationSec = postThinkingSec;
speedBasis = 'response_stream';
} else if (
nativeStreamSec >= 1.0 &&
outputTokens > 0 &&
(!hasToolCalls || nativeStreamSec >= totalDurationSec * 0.35)
) {
// Unbuffered streaming (e.g. write_to_file streaming file content)
streamTokens = responseTokens > 0 ? responseTokens : outputTokens;
streamDurationSec = nativeStreamSec;
speedBasis = 'native_stream';
} else {
// Buffered tool call (e.g. run_command where server buffers JSON until completion):
// use totalDurationSec for decoding rate, and thinkingDurationSec (if < total) for TTFT
streamTokens = outputTokens;
streamDurationSec = totalDurationSec;
speedBasis = 'total_fallback';
if (!hasVisibleText && hasToolCalls && thinkingDurationSec > 0 && thinkingDurationSec >= totalDurationSec * 0.9) {
// Server merged thinking + buffered tool generation into thinkingDuration;
// estimate true TTFT from thinking token ratio
const thinkRatio = outputTokens > 0 ? Math.min(0.85, thinkingTokens / outputTokens) : 0.2;
ttftSec = Math.max(0.4, totalDurationSec * thinkRatio);
}
}
const totalTokPerSec =
totalDurationSec >= 0.12 && outputTokens > 0 ? outputTokens / totalDurationSec : 0;
let streamTokPerSec =
streamDurationSec >= 0.12 && streamTokens > 0
? streamTokens / streamDurationSec
: totalTokPerSec;
// Guard against mixed text + buffered large tool call spikes
if (hasToolCalls && streamTokPerSec > 260 && totalTokPerSec > 0 && totalTokPerSec < 180) {
streamTokens = outputTokens;
streamDurationSec = totalDurationSec;
streamTokPerSec = totalTokPerSec;
speedBasis = 'total_fallback';
}
const estimatedContextTokens = Number(ctxWinMeta?.estimatedTokensUsed || 0);
const maxContextBudgetTokens = Number(ctxWinMeta?.maxContextTokens || 256000);
parsed.push({
stepIndex,
isCompactionStep,
modelKey: u.model || chatModel?.model || m.generatorModel || 'MODEL_PLACEHOLDER_M418',
apiProvider: u.apiProvider || chatModel?.usage?.apiProvider || '',
createdAt: m.createdAt || null,
createdAtMs: Math.floor(createdAtMs),
hasVisibleText,
inputTokens,
cacheReadTokens,
outputTokens,
thinkingTokens,
responseTokens,
streamTokens,
speedBasis,
estimatedContextTokens,
maxContextBudgetTokens,
thinkingDurationSec: +thinkingDurationSec.toFixed(3),
ttftSec: +ttftSec.toFixed(3),
streamDurationSec: +streamDurationSec.toFixed(3),
totalDurationSec: +totalDurationSec.toFixed(3),
streamTokPerSec,
totalTokPerSec,
});
});
return parsed;
}
function getStartOfLocalDayMs(now = new Date()) {
const d = new Date(now);
d.setHours(0, 0, 0, 0);
@@ -762,7 +613,9 @@ async function buildTelemetryPayloadInternal(
const prev = trajectoryCache[conv.cascadeId];
try {
const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId });
const rawSteps = trajRes?.trajectory?.steps || [];
if (!Array.isArray(trajRes?.trajectory?.steps)) throw new Error('Trajectory steps unavailable');
const rawSteps = trajRes.trajectory.steps;
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];
@@ -810,8 +663,9 @@ async function buildTelemetryPayloadInternal(
const activeSteps = activeEntry?.steps || [];
const useStreamSpeed = settings.speedMode !== 'total';
let sessionSpeedNumeratorTokens = 0;
let sessionSpeedDenominatorSec = 0;
const speedMode = useStreamSpeed ? 'stream' : 'total';
const sessionSpeed = summarizeSpeed(activeSteps, speedMode);
const sessionTtft = summarizeTtft(activeSteps);
let sessionCostUsd = 0;
let sessionInputTokens = 0;
let sessionCacheReadTokens = 0;
@@ -819,24 +673,13 @@ async function buildTelemetryPayloadInternal(
const enrichedActiveSteps = activeSteps.map((st) => {
const mInfo = resolveModelInfo(st.modelKey, dynamicModelMap, st.apiProvider);
const costUsd = computeStepCost(st, mInfo.pricing);
const stepStreamTokens = st.streamTokens ?? st.outputTokens;
const stepStreamSec = st.streamDurationSec > 0 ? st.streamDurationSec : st.totalDurationSec;
if (!st.isCompactionStep) {
if (useStreamSpeed) {
sessionSpeedNumeratorTokens += stepStreamTokens;
sessionSpeedDenominatorSec += stepStreamSec;
} else {
sessionSpeedNumeratorTokens += st.outputTokens;
sessionSpeedDenominatorSec += st.totalDurationSec;
}
}
const metric = speedMetric(st, speedMode);
sessionCostUsd += costUsd;
sessionInputTokens += st.inputTokens;
sessionCacheReadTokens += st.cacheReadTokens;
const tokPerSec = useStreamSpeed ? st.streamTokPerSec : st.totalTokPerSec;
const tokPerSec = metric.value;
const totalPrompt = st.inputTokens + st.cacheReadTokens;
const cacheHitPct = totalPrompt > 0 ? (st.cacheReadTokens / totalPrompt) * 100 : 0;
@@ -849,8 +692,9 @@ async function buildTelemetryPayloadInternal(
modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label,
modelShort: st.isCompactionStep ? `${mInfo.shortName}·压缩` : mInfo.shortName,
family: mInfo.family,
tokPerSec: +tokPerSec.toFixed(1),
ttftSec: +st.ttftSec.toFixed(1),
tokPerSec: roundMetric(tokPerSec),
selectedSpeedReason: metric.reason,
ttftSec: st.nativeTtftSec,
cacheHitPct: +cacheHitPct.toFixed(1),
costUsd: +costUsd.toFixed(4),
inCostUsd: +inCostUsd.toFixed(4),
@@ -863,10 +707,7 @@ async function buildTelemetryPayloadInternal(
const latestEnriched =
enrichedActiveSteps.length > 0 ? enrichedActiveSteps[enrichedActiveSteps.length - 1] : null;
const sessionAvgTokPerSec =
sessionSpeedDenominatorSec > 0.1
? +(sessionSpeedNumeratorTokens / sessionSpeedDenominatorSec).toFixed(1)
: latestEnriched?.tokPerSec || 0;
const sessionAvgTokPerSec = roundMetric(sessionSpeed.avgTokPerSec);
// Context breakdown from the latest step
const ctxCached = latestEnriched?.cacheReadTokens || 0;
@@ -975,24 +816,20 @@ async function buildTelemetryPayloadInternal(
inputTokens: 0,
cacheReadTokens: 0,
outputTokens: 0,
speedTokens: 0,
totalTokens: 0,
costUsd: 0,
totalDurationSec: 0,
speedAccumulator: createSpeedAccumulator(),
});
}
const agg = perModelStats.get(mInfo.label);
const stepStreamTokens = st.streamTokens ?? st.outputTokens;
const stepStreamSec = st.streamDurationSec > 0 ? st.streamDurationSec : st.totalDurationSec;
accumulateSpeed(agg.speedAccumulator, st, speedMode);
agg.calls += 1;
agg.inputTokens += st.inputTokens;
agg.cacheReadTokens += st.cacheReadTokens;
agg.outputTokens += st.outputTokens;
agg.speedTokens += useStreamSpeed ? stepStreamTokens : st.outputTokens;
agg.totalTokens += stepTotalTokens;
agg.costUsd += stepCost;
agg.totalDurationSec += useStreamSpeed ? stepStreamSec : st.totalDurationSec;
}
}
}
@@ -1076,9 +913,13 @@ async function buildTelemetryPayloadInternal(
isRunning: activeConvSummary?.status === 'CASCADE_RUN_STATUS_RUNNING',
status: activeConvSummary?.status || 'IDLE',
stepCount: enrichedActiveSteps.length,
latestTokPerSec: latestEnriched?.tokPerSec ?? 0,
latestTtftSec: latestEnriched?.ttftSec ?? 0,
latestTokPerSec: latestEnriched?.tokPerSec ?? null,
latestTtftSec: latestEnriched?.ttftSec ?? null,
latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null,
latestTotalTokPerSec: roundMetric(speedMetric(latestEnriched || {}, 'total').value),
avgTokPerSec: sessionAvgTokPerSec,
speedSummary: sessionSpeed,
ttftSummary: sessionTtft,
latestStepCostUsd: latestEnriched?.costUsd ?? 0,
sessionCostUsd: +sessionCostUsd.toFixed(2),
latestCacheHitPct,
@@ -1153,13 +994,11 @@ async function buildTelemetryPayloadInternal(
},
modelBreakdown: Array.from(perModelStats.values())
.sort((a, b) => b.calls - a.calls || String(a.label).localeCompare(String(b.label)))
.map((m) => ({
.map(({ speedAccumulator, ...m }) => ({
...m,
costUsd: +m.costUsd.toFixed(3),
avgTokPerSec:
m.totalDurationSec > 0.1
? +((m.speedTokens ?? m.outputTokens) / m.totalDurationSec).toFixed(1)
: 0,
avgTokPerSec: roundMetric(finishSpeed(speedAccumulator).avgTokPerSec),
speedSummary: finishSpeed(speedAccumulator),
})),
};
}
+4 -1
View File
@@ -3,5 +3,8 @@
"version": "1.0.0",
"private": true,
"type": "module",
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor."
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",
"scripts": {
"test": "node --test test/*.test.mjs"
}
}
+182
View File
@@ -0,0 +1,182 @@
// 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;
export function parseIsoMs(value) {
if (typeof value !== 'string' || !value) return 0;
const ms = Date.parse(value);
if (!Number.isFinite(ms)) return 0;
const fraction = value.match(/\.(\d+)Z$/);
return fraction ? Math.floor(ms / 1000) * 1000 + Number(`0.${fraction[1]}`) * 1000 : ms;
}
function duration(value) {
if (typeof value !== 'string' || !/^\d+(?:\.\d+)?s$/.test(value)) return null;
const n = Number(value.slice(0, -1));
return Number.isFinite(n) && n >= 0 ? n : null;
}
function validCount(value) {
return value !== undefined && value !== null && value !== '' &&
Number.isSafeInteger(Number(value)) && Number(value) >= 0;
}
function elapsed(start, end) {
return start > 0 && end >= start ? (end - start) / 1000 : null;
}
export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
const genByStep = new Map();
for (const gm of generatorMetadata || []) {
for (const index of gm?.stepIndices || []) genByStep.set(Number(index), gm);
}
const result = [];
rawSteps.forEach((s, index) => {
const m = s?.metadata;
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 chat = gm?.chatModel;
const p = s.plannerResponse || {};
const isCompactionStep = s.type === 'CORTEX_STEP_TYPE_CHECKPOINT';
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 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);
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';
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,
inputTokens, cacheReadTokens, outputTokens, thinkingTokens, responseTokens,
estimatedContextTokens: Number(context?.estimatedTokensUsed || 0),
maxContextBudgetTokens: Number(context?.maxContextTokens || 256000),
measurementVersion: MEASUREMENT_VERSION,
isComplete: complete, nativeTtftSec, nativeStreamSec, viewableDelaySec,
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,
speedReason,
});
});
return result;
}
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.
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',
};
}
export function speedMetric(step, mode) {
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 (!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,
};
}
export function createSpeedAccumulator() {
return { tokens: 0, seconds: 0, sampleCount: 0, excludedCount: 0, excludedReasons: {}, timingSources: {} };
}
export function accumulateSpeed(acc, step, mode) {
if (step.isCompactionStep) return;
const metric = speedMetric(step, mode);
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;
}
}
export function finishSpeed(acc) {
return { ...acc, avgTokPerSec: acc.seconds > 0 ? acc.tokens / acc.seconds : null };
}
export function summarizeSpeed(steps, mode) {
const acc = createSpeedAccumulator();
for (const step of steps) accumulateSpeed(acc, step, mode);
return finishSpeed(acc);
}
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);
return { sampleCount: values.length, avgSec: values.length ? values.reduce((a,b) => a+b,0) / values.length : null };
}
+4
View File
@@ -811,3 +811,7 @@ body {
.muted {
color: var(--muted-foreground, #656d76);
}
.speed-method-note { font-size: 11px; margin-top: 6px; }
.speed-detail { font-size: 10px; white-space: normal; max-width: 150px; }
#steps-tbody td:nth-child(3) { min-width: 120px; }
+34
View File
@@ -0,0 +1,34 @@
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import * as metrics from '../speed-metrics.mjs';
export function backendHarness({cache={},settings={},trajectories={},summaries={},sourceText=null}={}) {
const source=(sourceText ?? fs.readFileSync(new URL('../main.mjs',import.meta.url),'utf8'))
.replace(/^import .*;\r?\n/gm,'').replaceAll('import.meta.url',JSON.stringify('file:///test/main.mjs'));
const state={calls:[],errors:[],saves:[],trajectories};
const ctx={
...metrics, URL, AbortSignal,
process:{env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
console:{error:m=>state.errors.push(m)},
existsSync:p=>p.endsWith('settings.json') || p.endsWith('trajectory_usage_cache.json'),
mkdirSync:()=>{},readdirSync:()=>[],statSync:()=>({mtimeMs:0}),
readFileSync:p=>JSON.stringify(p.endsWith('settings.json')?settings:cache),
writeFileSync:(p,s)=>state.saves.push({path:p,data:JSON.parse(s)}),
homedir:()=>'/test-home',dirname:path.dirname,join:path.join,fileURLToPath:()=>'/test/main.mjs',
Response:class {constructor(body,options){this.body=body;this.options=options;}},
SidecarApp:class {page(){} api(){} run(){}},
fetch:async(url,options)=>{
const method=url.split('/').pop(); const body=JSON.parse(options.body);state.calls.push({method,body});
if(method==='GetCascadeTrajectory') {
const data=state.trajectories[body.cascadeId];
if(data instanceof Error) throw data;
return {ok:true,json:async()=>data||{}};
}
const data={GetUserStatus:{userStatus:{}},GetAllCascadeTrajectories:{trajectorySummaries:summaries},RetrieveUserQuotaSummary:{response:{groups:[]}}}[method];
return {ok:true,json:async()=>data};
},
};
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost};',ctx);
return {...ctx.api,state};
}
+53
View File
@@ -0,0 +1,53 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {backendHarness} from './backend-harness.mjs';
const raw={trajectory:{steps:[{status:'CORTEX_STEP_STATUS_DONE',metadata:{
createdAt:'2026-01-01T00:00:00Z',finishedGeneratingAt:'2026-01-01T00:00:10Z',
modelUsage:{inputTokens:'100',cacheReadTokens:'200',outputTokens:'600',thinkingOutputTokens:'100',responseOutputTokens:'500'},
},plannerResponse:{response:'answer',thinkingDuration:'5s'}}],generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'3s',streamingDuration:'7s'}}]}};
const old={signature:'v5:old',title:'test',steps:[{stepIndex:0,modelKey:'MODEL_PLACEHOLDER_M418',inputTokens:100,cacheReadTokens:200,outputTokens:600,thinkingTokens:100,responseTokens:500,createdAtMs:1767225600000,ttftSec:0.4,streamTokPerSec:200,streamTokens:500,streamDurationSec:2.5,totalDurationSec:10,totalTokPerSec:60}]};
test('failed migration retains all accounting, makes legacy speed and TTFT unavailable',async()=>{
const h=backendHarness({cache:{test:old},trajectories:{test:new Error('offline')}});
const p=await h.buildTelemetryPayloadInternal('test');
assert.equal(p.activeConversation.latestTokPerSec,null);
assert.equal(p.activeConversation.latestTtftSec,null);
assert.equal(p.activeConversation.avgTokPerSec,null);
assert.equal(p.activeConversation.recentSteps[0].outputTokens,600);
assert.equal(p.consumption.session.totalTokens,900);
assert.equal(p.modelBreakdown[0].avgTokPerSec,null);
assert.equal(h.state.saves.length,0);
});
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.latestTtftSec,3);
assert.equal(p.activeConversation.avgTokPerSec,100);
assert.equal(p.modelBreakdown[0].avgTokPerSec,100);
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:/);
});
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'}});
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);
});
test('a malformed successful RPC cannot erase previously recorded usage',async()=>{
const h=backendHarness({cache:{test:old},trajectories:{test:{}}});
const p=await h.buildTelemetryPayloadInternal('test');
assert.equal(p.consumption.session.totalTokens,900);
assert.equal(p.activeConversation.latestTtftSec,null);
assert.equal(h.state.saves.length,0);
});
test('a partial trajectory cannot replace a complete historical cache',async()=>{
const h=backendHarness({cache:{test:old},trajectories:{test:{trajectory:{steps:[]},numTotalSteps:3}}});
const p=await h.buildTelemetryPayloadInternal('test');
assert.equal(p.consumption.session.totalTokens,900);
assert.equal(h.state.saves.length,0);
assert.match(h.state.errors[0],/Incomplete trajectory/);
});
+104
View File
@@ -0,0 +1,104 @@
import test from 'node:test';
import assert from 'node:assert/strict';
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 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('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('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('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);
assert.equal(parse({total:-1}).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('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('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('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);
});