fix(metrics): unify request TPS and reject unreliable timing

This commit is contained in:
yuhuan2498281558
2026-10-15 04:26:32 +08:00
parent 264b577c66
commit 04467b97ad
8 changed files with 211 additions and 297 deletions
+20 -6
View File
@@ -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);
});
+35 -47
View File
@@ -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>/);
});
+92 -88
View File
@@ -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);
});