mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(metrics): add guarded response-phase estimates and scoped averages
This commit is contained in:
@@ -7,8 +7,8 @@ Antigravity 实时测速与官方额度监控侧边栏插件(UI Extension Side
|
||||
## ✨ 核心功能
|
||||
|
||||
- **⚡ 实时 `tok/s` 测速与会话均速**
|
||||
- 分开显示**正文阶段估算 (`stream`)** 与**请求整体吞吐 (`total`)**。正文估算只接受纯文本且阶段计时可用的步骤,显示 `≈`;整体吞吐使用含思考的输出 Token 除以请求总耗时。两者不互相回退,也不混算均速。
|
||||
- 工具调用和正文/工具混合输出无法独立计时,正文速度显示 `—`,仍可切换到整体吞吐查看。短于 0.5 秒或少于 50 个正文 Token 的样本保留估算,但不计正文均速;这些门槛只用于样本筛选,不会切换公式或限制 TPS。
|
||||
- 保留一个 TPS 列。含正文且计时、原生用量符合要求的步骤,以正文与工具参数的合计 Token 估算非思考阶段速度,标记 `≈`;纯工具、短阶段或数据不足的步骤保留含等待的请求速率。
|
||||
- 均速优先汇总可估算步骤的 Token 与阶段时长,并显示覆盖步数;没有可估算步骤时使用全请求均速。两种时间口径不混合,具体公式与回退原因可悬停查看。
|
||||
- **⏱️ 首字耗时 (TTFT) & 缓存命中率**
|
||||
- 显示原始 `timeToFirstToken`(可能先返回思考内容,非必然为答案首字);缺失显示 `—`,不再按思考 Token 比例推算。悬停可见会话平均 TTFT。同时显示 Prompt 缓存读取命中率(`cacheReadTokens` 占比)。
|
||||
- **📊 上下文窗口四色分段监控(默认对齐 `256k` 自动压缩阈值)**
|
||||
@@ -160,10 +160,11 @@ git -C ~/.gemini/config/plugins/usage-monitor pull
|
||||
|
||||
本地试用分支:`codex/tps-metrics-trial`。
|
||||
|
||||
- **TPS**:统一采用输出 Token(含思考和工具参数)/ 已完成请求的总时长,不包含相邻工具步骤的执行耗时或用户停顿。完整请求不足 0.5 秒或计时无效时不显示速率。
|
||||
- **均速**:有效样本 Token 合计 / 有效样本时长合计。少于 50 个输出 Token 的请求保留单步速率但不计均速;自动压缩仍计费,不计均速。
|
||||
- **首 Token**:保留原生数值;缺失显示未知,不使用 Token 比例推算,也不把它直接当作可扣除的等待时间。
|
||||
- **缓存**:`v7-request-throughput`,测速调整不改变历史 Token 与费用账目。
|
||||
- **TPS**:含正文时,尝试用原生 `responseOutputTokens / (totalDurationSec - (thinkingDuration ?? timeToFirstToken))` 估算正文与工具合计的非思考阶段速度。要求原生思考/非思考 Token 计数与总数一致,阶段计时一致、至少 0.5 秒、非思考输出至少 50 Token;必须有生成完成时间,不能用工具执行完成时间代替。
|
||||
- **回退**:纯工具、短阶段、计时或用量缺失时保留总输出 / 完整请求耗时。完整请求不足 0.5 秒或未完成时不显示速率。没有 TPS 上限,不根据算出的速度改分母;这些保护只能剔除已知不可靠样本,不能保证所有缓冲都可识别。
|
||||
- **均速**:优先使用可估算步骤的非思考 Token 合计 / 阶段时长合计,不掺入回退步骤;没有可估算步骤时才使用全请求均速,低于 50 个总输出 Token 的短请求不计此均速。覆盖步数和口径会显示。自动压缩仍计费,不计均速。
|
||||
- **首 Token**:继续原样展示原生 TTFT,缺失显示未知,不使用 Token 比例推算。估算步骤的悬停信息附带正文开始延迟估计,不将其称为服务端精确首 token 时间。
|
||||
- **缓存**:`v8-guarded-phase` / measurementVersion 3。旧缓存重新读取原始轨迹;失败时保留 Token 和费用,不沿用旧派生速率。
|
||||
- **验证**:在 `sidecars/panel` 执行 `npm test`。测试使用本地合成数据,不触发模型生成。
|
||||
- **退回原版**:保存本地改动后执行 `git switch main`,关闭再开启插件;主分支没有诊断采集器。
|
||||
|
||||
|
||||
+31
-7
@@ -22,6 +22,23 @@ function formatMetric(value, unit = '') {
|
||||
return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—';
|
||||
}
|
||||
|
||||
function formatSpeed(value, basis, unit = '') {
|
||||
return `${Number.isFinite(value) && basis === 'response_phase_estimate' ? '≈' : ''}${formatMetric(value, unit)}`;
|
||||
}
|
||||
|
||||
function speedDescription(step) {
|
||||
if (step.speedBasis === 'response_phase_estimate') {
|
||||
return `阶段估算:正文及工具 ${step.responseTokens} Token ÷ ${formatMetric(step.phaseDurationSec, 's')};已扣除等待及思考,非服务端精确解码速度;正文开始延迟约 ${formatMetric(step.answerStartDelaySec, 's')}`;
|
||||
}
|
||||
return `TPS = 总输出 ${step.outputTokens} Token ÷ 请求总耗时 ${formatMetric(step.totalDurationSec, 's')}(含等待与思考);${speedReasonText(step.phaseReason)}`;
|
||||
}
|
||||
|
||||
function meanDescription(summary) {
|
||||
return summary?.basis === 'response_phase_estimate'
|
||||
? `均速仅汇总可估算步骤的非思考 Token 与阶段时长,覆盖 ${sampleSummary(summary)};其他步骤仍显示含等待的速率,不混入此均速`
|
||||
: `暂无可用阶段估算,均速使用总输出 Token ÷ 请求总耗时(含等待与思考),覆盖 ${sampleSummary(summary)}`;
|
||||
}
|
||||
|
||||
function speedReasonText(reason) {
|
||||
return ({
|
||||
compaction: '自动压缩不计测速',
|
||||
@@ -30,6 +47,11 @@ function speedReasonText(reason) {
|
||||
short_timing: '计时过短,暂不测速',
|
||||
short_sample: '短样本,不计均速',
|
||||
legacy_cache: '旧缓存,等待重新读取',
|
||||
no_visible_text: '缺少正文起点,保留完整请求计时',
|
||||
invalid_phase_tokens: '非思考 Token 计数缺失或不一致',
|
||||
invalid_phase_timing: '阶段计时缺失或不一致',
|
||||
short_phase: '阶段不足 0.5 秒,可能整包返回,保留完整请求计时',
|
||||
short_phase_sample: '非思考输出不足 50 Token,保留完整请求计时',
|
||||
})[reason] || '';
|
||||
}
|
||||
|
||||
@@ -184,11 +206,11 @@ 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 | TPS = 总输出 ${st.outputTokens} Token ÷ 请求总耗时 ${formatMetric(st.totalDurationSec, '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}${speedDescription(st)} | ${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)">${formatMetric(st.tokPerSec, ' tok/s')}</strong>${reason ? `<div class="speed-detail muted">${escapeHtml(reason)}</div>` : ''}</td>
|
||||
<td><strong style="color: var(--speed-accent)">${formatSpeed(st.tokPerSec, st.speedBasis, ' 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>
|
||||
@@ -211,11 +233,12 @@ function renderTables(activeConv, modelBreakdown) {
|
||||
modelsTbody.innerHTML = '';
|
||||
for (const m of models) {
|
||||
const tr = document.createElement('tr');
|
||||
tr.title = meanDescription(m.speedSummary);
|
||||
const pricePrefix = m.isEstimatedPrice ? '≈$' : '$';
|
||||
tr.innerHTML = `
|
||||
<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')}<div class="speed-detail muted">有效 ${sampleSummary(m.speedSummary)}</div></td>
|
||||
<td>${formatSpeed(m.avgTokPerSec, m.speedSummary?.basis, ' 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>
|
||||
`;
|
||||
@@ -316,13 +339,14 @@ function applyTelemetryToDom(data) {
|
||||
}
|
||||
|
||||
// 2. Status strip metrics
|
||||
$('tok-per-sec').textContent = formatMetric(active.latestTokPerSec, ' tok/s');
|
||||
$('speed-status').title = `最新一步:总输出 Token ÷ 请求总耗时(含等待与思考);${speedReasonText(active.latestSpeedReason) || '计时有效'}`;
|
||||
$('tok-per-sec').textContent = formatSpeed(active.latestTokPerSec, active.latestSpeedBasis, ' tok/s');
|
||||
$('speed-status').title = `最新一步:${speedDescription(active.recentSteps?.[0] || {})};${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);
|
||||
$('avg-speed-value').textContent = formatSpeed(active.avgTokPerSec, active.speedSummary?.basis);
|
||||
$('avg-speed-value').title = meanDescription(active.speedSummary);
|
||||
$('speed-sample-count').textContent = `有效 ${sampleSummary(active.speedSummary)}`;
|
||||
$('speed-sample-count').title = Object.entries(active.speedSummary?.excludedReasons || {}).map(([reason, count]) => `${speedReasonText(reason)}:${count} 步`).join(';') || '全部有效;自动压缩单独排除';
|
||||
$('speed-sample-count').title = meanDescription(active.speedSummary) + ';' + Object.entries(active.speedSummary?.excludedReasons || {}).map(([reason, count]) => `${speedReasonText(reason)}:${count} 步`).join(';');
|
||||
const latestStepCost = Number(active.latestStepCostUsd ?? active.recentSteps?.[0]?.costUsd ?? 0);
|
||||
if ($('step-cost-value')) {
|
||||
$('step-cost-value').textContent = `$${latestStepCost.toFixed(3)}`;
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
<!-- 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="总输出 Token ÷ 请求总耗时(含等待与思考)" id="speed-status">
|
||||
<span class="speed-group" title="优先使用阶段估算;计时不足时保留含等待的速率" id="speed-status">
|
||||
<span id="speed-dot" class="speed-dot"></span>
|
||||
<strong id="tok-per-sec" class="speed-value">—</strong>
|
||||
</span>
|
||||
@@ -51,7 +51,7 @@
|
||||
今日 <strong id="today-tokens">0</strong> · ≈<strong id="today-cost">$0.00</strong>
|
||||
</span>
|
||||
</div>
|
||||
<div id="speed-method-note" class="speed-method-note muted" title="总耗时不包含请求之间的空闲与外部工具执行时间。低于 0.5 秒的请求不测速;少于 50 个输出 Token 的步骤显示 TPS,但不计均速。">TPS = 总输出 Token ÷ 请求总耗时(含等待与思考)</div>
|
||||
<div id="speed-method-note" class="speed-method-note muted" title="阶段估算要求有正文、原生 Token 计数一致、阶段至少 0.5 秒且非思考输出至少 50 Token。均速优先只汇总这些步骤;没有可估算步骤时使用含等待的全请求均速。悬停可查看口径与排除原因。">≈ 为扣除等待及思考后的估算;其余 TPS 含等待。均速按同一口径汇总。</div>
|
||||
</section>
|
||||
|
||||
<!-- Quota & Context Popover Card (1:1 replica of the right popover card in screenshot) -->
|
||||
|
||||
@@ -59,7 +59,7 @@ const PLACEHOLDER_MAP = {
|
||||
};
|
||||
|
||||
// In-memory cache of trajectory step usage: cascadeId -> { signature, steps }
|
||||
const CACHE_SCHEMA_VERSION = 'v7-request-throughput';
|
||||
const CACHE_SCHEMA_VERSION = 'v8-guarded-phase';
|
||||
let trajectoryCache = Object.fromEntries(Object.entries(loadJson(CACHE_FILE, {})).map(([id, entry]) => [
|
||||
id, { ...entry, steps: (entry.steps || []).map(normalizeCachedStep) },
|
||||
]));
|
||||
@@ -913,6 +913,8 @@ async function buildTelemetryPayloadInternal(
|
||||
latestTokPerSec: latestEnriched?.tokPerSec ?? null,
|
||||
latestTtftSec: latestEnriched?.ttftSec ?? null,
|
||||
latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null,
|
||||
latestSpeedBasis: latestEnriched?.speedBasis ?? 'unavailable',
|
||||
latestPhaseReason: latestEnriched?.phaseReason ?? null,
|
||||
avgTokPerSec: sessionAvgTokPerSec,
|
||||
speedSummary: sessionSpeed,
|
||||
ttftSummary: sessionTtft,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// 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;
|
||||
// A guarded estimate of the non-thinking response phase (text + tool JSON).
|
||||
// Buffered/short samples retain request throughput. Means never mix scopes.
|
||||
export const MEASUREMENT_VERSION = 3;
|
||||
export const MIN_SPEED_DURATION_SECONDS = 0.5;
|
||||
export const MIN_MEAN_OUTPUT_TOKENS = 50;
|
||||
|
||||
@@ -47,14 +47,16 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
const outputTokens = Number(u.outputTokens || 0);
|
||||
const thinkingTokens = Number(p.thinkingTokens ?? u.thinkingOutputTokens ?? chat?.usage?.thinkingOutputTokens ?? 0);
|
||||
const responseTokens = Number(p.responseTokens ?? u.responseOutputTokens ?? chat?.usage?.responseOutputTokens ?? Math.max(0, outputTokens - thinkingTokens));
|
||||
const nativeResponseTokens = u.responseOutputTokens ?? chat?.usage?.responseOutputTokens;
|
||||
const nativeThinkingTokens = u.thinkingOutputTokens ?? chat?.usage?.thinkingOutputTokens;
|
||||
const hasVisibleText = String(p.modifiedResponse || p.response || '').trim().length > 0;
|
||||
const start = parseIsoMs(m.createdAt);
|
||||
const end = parseIsoMs(m.finishedGeneratingAt || m.completedAt);
|
||||
const 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 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.
|
||||
// These are client-observed boundaries, not server token timestamps.
|
||||
const nativeStreamSec = duration(chat?.streamingDuration);
|
||||
const thinkingDurationSec = duration(p.thinkingDuration);
|
||||
let timingReason = null;
|
||||
@@ -64,13 +66,31 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
const totalTokPerSec = timingReason === null ? outputTokens / totalDurationSec : null;
|
||||
const shortOutputSample = totalTokPerSec !== null && outputTokens < MIN_MEAN_OUTPUT_TOKENS;
|
||||
const speedReason = timingReason || (isCompactionStep ? 'compaction' : shortOutputSample ? 'short_sample' : null);
|
||||
const phaseOffsetSec = thinkingDurationSec ?? nativeTtftSec;
|
||||
const phaseDurationSec = totalDurationSec !== null && phaseOffsetSec !== null
|
||||
? totalDurationSec - phaseOffsetSec : null;
|
||||
let phaseReason = timingReason;
|
||||
if (!phaseReason && isCompactionStep) phaseReason = 'compaction';
|
||||
if (!phaseReason && !hasVisibleText) phaseReason = 'no_visible_text';
|
||||
if (!phaseReason && (!validCount(nativeResponseTokens) || !validCount(nativeThinkingTokens) ||
|
||||
Number(nativeResponseTokens) !== responseTokens ||
|
||||
Number(nativeResponseTokens) + Number(nativeThinkingTokens) !== outputTokens)) phaseReason = 'invalid_phase_tokens';
|
||||
if (!phaseReason && (!m.finishedGeneratingAt || phaseOffsetSec === null ||
|
||||
(p.thinkingDuration != null && thinkingDurationSec === null) ||
|
||||
!(phaseDurationSec > 0) ||
|
||||
(nativeTtftSec !== null && phaseOffsetSec + 0.01 < nativeTtftSec) ||
|
||||
(nativeStreamSec !== null && nativeTtftSec !== null &&
|
||||
Math.abs(totalDurationSec - nativeTtftSec - nativeStreamSec) > 0.01))) phaseReason = 'invalid_phase_timing';
|
||||
if (!phaseReason && phaseDurationSec < MIN_SPEED_DURATION_SECONDS) phaseReason = 'short_phase';
|
||||
if (!phaseReason && responseTokens < MIN_MEAN_OUTPUT_TOKENS) phaseReason = 'short_phase_sample';
|
||||
const phaseTokPerSec = phaseReason === null ? responseTokens / phaseDurationSec : null;
|
||||
const context = chat?.chatStartMetadata?.contextWindowMetadata;
|
||||
result.push({
|
||||
stepIndex, isCompactionStep,
|
||||
modelKey: u.model || chat?.model || m.generatorModel || 'MODEL_PLACEHOLDER_M418',
|
||||
apiProvider: u.apiProvider || chat?.usage?.apiProvider || '',
|
||||
createdAt: m.createdAt || null, createdAtMs: Math.floor(start),
|
||||
hasVisibleText: String(p.modifiedResponse || p.response || '').trim().length > 0,
|
||||
hasVisibleText,
|
||||
hasToolCalls: Array.isArray(p.toolCalls) && p.toolCalls.length > 0,
|
||||
inputTokens, cacheReadTokens, outputTokens, thinkingTokens, responseTokens,
|
||||
estimatedContextTokens: Number(context?.estimatedTokensUsed || 0),
|
||||
@@ -80,7 +100,10 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
viewableDelaySec: elapsed(start, parseIsoMs(m.viewableAt)),
|
||||
ttftSec: nativeTtftSec, ttftSource: nativeTtftSec === null ? 'unavailable' : 'native',
|
||||
thinkingDurationSec, totalDurationSec, totalTokPerSec,
|
||||
speedBasis: totalTokPerSec === null ? 'unavailable' : 'request_total',
|
||||
phaseDurationSec: phaseTokPerSec === null ? null : phaseDurationSec,
|
||||
phaseTokPerSec, phaseReason,
|
||||
answerStartDelaySec: phaseTokPerSec === null ? null : phaseOffsetSec,
|
||||
speedBasis: phaseTokPerSec !== null ? 'response_phase_estimate' : totalTokPerSec === null ? 'unavailable' : 'request_total',
|
||||
speedSampleEligible: totalTokPerSec !== null && !shortOutputSample && !isCompactionStep,
|
||||
speedReason,
|
||||
});
|
||||
@@ -97,6 +120,7 @@ export function normalizeCachedStep(step) {
|
||||
nativeTtftSec: null, nativeStreamSec: null, viewableDelaySec: null,
|
||||
ttftSec: null, ttftSource: 'unavailable', thinkingDurationSec: null,
|
||||
totalDurationSec: null, totalTokPerSec: null,
|
||||
phaseDurationSec: null, phaseTokPerSec: null, phaseReason: 'legacy_cache', answerStartDelaySec: null,
|
||||
streamDurationSec: null, streamTokens: null, streamTokPerSec: null,
|
||||
speedBasis: 'unavailable', speedSampleEligible: false, speedReason: 'legacy_cache',
|
||||
};
|
||||
@@ -109,29 +133,45 @@ export function speedMetric(step) {
|
||||
!(step.totalDurationSec >= MIN_SPEED_DURATION_SECONDS)) {
|
||||
return missing(step.speedReason || 'incomplete_or_invalid_timing');
|
||||
}
|
||||
if (step.speedBasis === 'response_phase_estimate' && Number.isFinite(step.phaseTokPerSec) &&
|
||||
step.phaseDurationSec >= MIN_SPEED_DURATION_SECONDS && step.responseTokens >= MIN_MEAN_OUTPUT_TOKENS) {
|
||||
return { value: step.phaseTokPerSec, tokens: step.responseTokens, seconds: step.phaseDurationSec,
|
||||
eligible: !step.isCompactionStep, reason: null };
|
||||
}
|
||||
return { value: step.totalTokPerSec, tokens: step.outputTokens, seconds: step.totalDurationSec,
|
||||
eligible: step.speedSampleEligible === true && !step.isCompactionStep, reason: step.speedReason };
|
||||
}
|
||||
|
||||
export function createSpeedAccumulator() {
|
||||
return { tokens: 0, seconds: 0, sampleCount: 0, excludedCount: 0, excludedReasons: {} };
|
||||
const bucket = () => ({ tokens: 0, seconds: 0, sampleCount: 0, excludedCount: 0, excludedReasons: {} });
|
||||
return { phase: bucket(), overall: bucket() };
|
||||
}
|
||||
|
||||
export function accumulateSpeed(acc, step) {
|
||||
if (step.isCompactionStep) return;
|
||||
const metric = speedMetric(step);
|
||||
if (metric.eligible) {
|
||||
acc.tokens += metric.tokens;
|
||||
acc.seconds += metric.seconds;
|
||||
acc.sampleCount++;
|
||||
} else {
|
||||
acc.excludedCount++;
|
||||
acc.excludedReasons[metric.reason] = (acc.excludedReasons[metric.reason] || 0) + 1;
|
||||
function add(bucket, eligible, tokens, seconds, reason) {
|
||||
if (eligible) {
|
||||
bucket.tokens += tokens;
|
||||
bucket.seconds += seconds;
|
||||
bucket.sampleCount++;
|
||||
} else {
|
||||
bucket.excludedCount++;
|
||||
bucket.excludedReasons[reason] = (bucket.excludedReasons[reason] || 0) + 1;
|
||||
}
|
||||
}
|
||||
add(acc.phase, metric.eligible && step.speedBasis === 'response_phase_estimate',
|
||||
metric.tokens, metric.seconds, step.phaseReason || metric.reason || 'unavailable');
|
||||
add(acc.overall, metric.value !== null && step.outputTokens >= MIN_MEAN_OUTPUT_TOKENS,
|
||||
step.outputTokens, step.totalDurationSec, metric.reason || 'short_sample');
|
||||
}
|
||||
|
||||
export function finishSpeed(acc) {
|
||||
return { ...acc, avgTokPerSec: acc.seconds > 0 ? acc.tokens / acc.seconds : null };
|
||||
const usePhase = acc.phase.sampleCount > 0;
|
||||
const chosen = usePhase ? acc.phase : acc.overall;
|
||||
return { ...chosen, basis: usePhase ? 'response_phase_estimate' : 'request_total',
|
||||
avgTokPerSec: chosen.seconds > 0 ? chosen.tokens / chosen.seconds : null,
|
||||
overall: { ...acc.overall, avgTokPerSec: acc.overall.seconds > 0 ? acc.overall.tokens / acc.overall.seconds : null } };
|
||||
}
|
||||
|
||||
export function summarizeSpeed(steps) {
|
||||
|
||||
@@ -3,12 +3,12 @@ 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}={}) {
|
||||
export function backendHarness({cache={},settings={},trajectories={},summaries={},sourceText=null,metricsImplementation=metrics}={}) {
|
||||
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,
|
||||
...metricsImplementation, 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'),
|
||||
|
||||
@@ -22,20 +22,20 @@ test('failed migration retains all accounting, makes legacy speed and TTFT unava
|
||||
test('successful migration rebuilds measurements and uses the same mean in both tables',async()=>{
|
||||
const h=backendHarness({cache:{test:old},trajectories:{test:raw}});
|
||||
const p=await h.buildTelemetryPayloadInternal('test');
|
||||
assert.equal(p.activeConversation.latestTokPerSec,60);
|
||||
assert.equal(p.activeConversation.latestTokPerSec,100);
|
||||
assert.equal(p.activeConversation.latestTtftSec,3);
|
||||
assert.equal(p.activeConversation.avgTokPerSec,60);
|
||||
assert.equal(p.modelBreakdown[0].avgTokPerSec,60);
|
||||
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,/^v7-request-throughput:/);
|
||||
assert.match(h.state.saves[0].data.test.signature,/^v8-guarded-phase:/);
|
||||
});
|
||||
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.activeConversation.latestTokPerSec,100);
|
||||
assert.equal(p.activeConversation.avgTokPerSec,100);
|
||||
assert.equal(p.modelBreakdown[0].avgTokPerSec,100);
|
||||
assert.equal(p.settings.speedMode,undefined);
|
||||
});
|
||||
test('a malformed successful RPC cannot erase previously recorded usage',async()=>{
|
||||
|
||||
@@ -41,3 +41,13 @@ test('a TTFT-only correction refreshes the table even when TPS and step count do
|
||||
ctx.renderTables({recentSteps:[{...step,ttftSec:12.974}]},[]);
|
||||
assert.match(elements['steps-tbody'].children[0].innerHTML,/<td>13\.0s<\/td>/);
|
||||
});
|
||||
|
||||
test('one TPS column marks estimates and explains full-time fallbacks in the tooltip',()=>{
|
||||
const {ctx,elements}=page();
|
||||
ctx.renderTables({recentSteps:[{...step,speedBasis:'response_phase_estimate',phaseDurationSec:2,answerStartDelaySec:8,tokPerSec:100}]},[]);
|
||||
assert.match(elements['steps-tbody'].children[0].innerHTML,/≈100\.0 tok\/s/);
|
||||
assert.match(elements['steps-tbody'].children[0].title,/非服务端精确解码速度/);
|
||||
ctx.renderTables({recentSteps:[{...step,speedBasis:'request_total',phaseReason:'short_phase'}]},[]);
|
||||
assert.doesNotMatch(elements['steps-tbody'].children[0].innerHTML,/≈/);
|
||||
assert.match(elements['steps-tbody'].children[0].title,/阶段不足 0.5 秒/);
|
||||
});
|
||||
|
||||
@@ -14,11 +14,11 @@ function sample({total=12,ttft='2s',stream='10s',output=1100,thinking=100,respon
|
||||
}
|
||||
function parse(options) {const {s,gm}=sample(options);return extractModelSteps([s],[gm])[0];}
|
||||
|
||||
test('text, tools and mixed output all use total output / full request duration',()=>{
|
||||
test('text and mixed output estimate the combined response phase; pure tools retain total time',()=>{
|
||||
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(speedMetric(step).value,text ? 1000/8 : 1100/12);
|
||||
assert.equal(step.speedBasis,text ? 'response_phase_estimate' : 'request_total');
|
||||
assert.equal(step.speedSampleEligible,true);
|
||||
}
|
||||
});
|
||||
@@ -48,7 +48,7 @@ test('short output keeps the same formula but does not bias the mean',()=>{
|
||||
const short=parse({output:13,response:13,thinking:0,total:5.015,stream:'0.118s'});
|
||||
assert.equal(short.totalTokPerSec,13/5.015);
|
||||
assert.equal(short.speedReason,'short_sample');
|
||||
assert.equal(summarizeSpeed([short,parse()]).avgTokPerSec,1100/12);
|
||||
assert.equal(summarizeSpeed([short,parse()]).avgTokPerSec,1000/8);
|
||||
assert.equal(summarizeSpeed([short]).avgTokPerSec,null);
|
||||
assert.equal(parse({output:50}).speedSampleEligible,true);
|
||||
});
|
||||
@@ -86,12 +86,15 @@ test('missing phase/token breakdown cannot change a valid full-request rate',()=
|
||||
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,1100/12);
|
||||
});
|
||||
test('no rate-dependent cap or formula switch at the former 260 TPS boundary',()=>{
|
||||
const a=parse({total:10,output:2590,tools:true}),b=parse({total:10,output:2610,tools:true});
|
||||
const opts={total:10,thinking:0,thinkingDuration:'0s',ttft:'0s',stream:'10s',tools:true};
|
||||
const a=parse({...opts,output:2590,response:2590}),b=parse({...opts,output:2610,response:2610});
|
||||
assert.equal(a.totalTokPerSec,259);assert.equal(b.totalTokPerSec,261);
|
||||
assert.equal(speedMetric(a).value,259);assert.equal(speedMetric(b).value,261);
|
||||
assert.equal(a.speedBasis,'response_phase_estimate');
|
||||
assert.equal(a.speedBasis,b.speedBasis);
|
||||
});
|
||||
test('legacy cache retains billing but cannot masquerade as current measurements',()=>{
|
||||
for(const measurementVersion of [undefined,1]){
|
||||
for(const measurementVersion of [undefined,1,2]){
|
||||
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);
|
||||
@@ -99,6 +102,51 @@ test('legacy cache retains billing but cannot masquerade as current measurements
|
||||
assert.equal(speedMetric(migrated).reason,'legacy_cache');
|
||||
}
|
||||
});
|
||||
|
||||
test('afternoon visible-text counterexample #284 uses full time instead of a 6751 TPS tail',()=>{
|
||||
const {s,gm}=sample({output:64,thinking:33,response:31,ttft:'7.0108593s',stream:'0.0045919s'});
|
||||
s.metadata.finishedGeneratingAt='2026-01-01T00:00:07.015451200Z';
|
||||
delete s.plannerResponse.thinkingDuration;
|
||||
const step=extractModelSteps([s],[gm])[0];
|
||||
assert.equal(step.hasVisibleText,true);assert.equal(step.phaseReason,'short_phase');
|
||||
assert.equal(step.speedBasis,'request_total');assert(speedMetric(step).value<10);
|
||||
});
|
||||
test('phase and overall means never mix denominators, regardless of step order',()=>{
|
||||
const phase=parse(),tools=parse({tools:true,text:false,total:100,output:10000});
|
||||
for(const rows of [[phase,tools],[tools,phase]]){
|
||||
const mean=summarizeSpeed(rows);
|
||||
assert.equal(mean.avgTokPerSec,125);assert.equal(mean.basis,'response_phase_estimate');
|
||||
assert.equal(mean.sampleCount,1);assert.equal(mean.excludedCount,1);
|
||||
assert.equal(mean.overall.avgTokPerSec,11100/112);
|
||||
assert.equal(speedMetric(tools).value,100);
|
||||
}
|
||||
const fallback=summarizeSpeed([tools]);
|
||||
assert.equal(fallback.avgTokPerSec,100);assert.equal(fallback.basis,'request_total');
|
||||
});
|
||||
test('short response phases, inconsistent counts and invalid phase clocks retain the request rate',()=>{
|
||||
for(const opts of [
|
||||
{thinkingDuration:'11.99s'}, {thinkingDuration:'12s'}, {thinkingDuration:'13s'},
|
||||
{thinkingDuration:'-1s'}, {thinkingDuration:'1s'}, {stream:'0.01s'},
|
||||
{response:999}, {output:1100,thinking:1080,response:20},
|
||||
]){
|
||||
const step=parse(opts);
|
||||
assert.equal(step.speedBasis,'request_total');assert.equal(speedMetric(step).value,1100/12);
|
||||
}
|
||||
});
|
||||
test('missing thinking duration can use native TTFT, but missing native breakdown cannot be guessed',()=>{
|
||||
const {s,gm}=sample();delete s.plannerResponse.thinkingDuration;
|
||||
const step=extractModelSteps([s],[gm])[0];
|
||||
assert.equal(step.phaseTokPerSec,100);assert.equal(step.answerStartDelaySec,2);
|
||||
delete s.metadata.modelUsage.responseOutputTokens;
|
||||
const missing=extractModelSteps([s],[gm])[0];
|
||||
assert.equal(missing.phaseReason,'invalid_phase_tokens');assert.equal(missing.phaseTokPerSec,null);
|
||||
assert.equal(speedMetric(missing).value,1100/12);
|
||||
});
|
||||
test('completedAt remains a total-time fallback but cannot substitute for generation end in phase estimates',()=>{
|
||||
const {s,gm}=sample();s.metadata.completedAt=s.metadata.finishedGeneratingAt;delete s.metadata.finishedGeneratingAt;
|
||||
const step=extractModelSteps([s],[gm])[0];
|
||||
assert.equal(step.totalTokPerSec,1100/12);assert.equal(step.phaseReason,'invalid_phase_timing');
|
||||
});
|
||||
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];
|
||||
|
||||
Reference in New Issue
Block a user