feat(metrics): add guarded response-phase estimates and scoped averages

This commit is contained in:
yuhuan2498281558
2026-10-15 05:25:19 +08:00
parent d811a995ad
commit 20df69b73b
9 changed files with 172 additions and 47 deletions
+2 -2
View File
@@ -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'),
+7 -7
View File
@@ -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 秒/);
});
+54 -6
View File
@@ -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];