fix: preserve unknown model identity and pending costs

This commit is contained in:
yuhuan2498281558
2026-10-16 18:30:59 +08:00
parent 1e469441bd
commit 9af5fc7446
17 changed files with 804 additions and 112 deletions
+35
View File
@@ -0,0 +1,35 @@
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={},userStatus={},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={
...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'),
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(){}},
StreamDiagnostics:class {status(){return {enabled:false};} start(){}},
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,resolveModelInfo};',ctx);
return {...ctx.api,state};
}
+73
View File
@@ -0,0 +1,73 @@
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,1);
assert.equal(h.state.saves[0].data.test.steps[0].outputTokens,600);
assert.equal(h.state.saves[0].data.test.steps[0].modelKey,'unknown');
});
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.latestTtftSec,3);
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,/^v10-model-identity:/);
});
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:{}}});
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,1);
assert.equal(h.state.saves[0].data.test.steps[0].outputTokens,600);
assert.equal(h.state.saves[0].data.test.steps[0].modelKey,'unknown');
});
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,1);
assert.equal(h.state.saves[0].data.test.steps[0].outputTokens,600);
assert.equal(h.state.saves[0].data.test.steps[0].modelKey,'unknown');
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);
});
+155
View File
@@ -0,0 +1,155 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../speed-metrics.mjs';
import { formatUsd } from '../src/core/formatters.js';
import { backendHarness } from './backend-harness.mjs';
const FLASH = 'MODEL_PLACEHOLDER_M318', ARGON = 'MODEL_PLACEHOLDER_M418';
const createdAtMs = Date.now() - 20_000;
function step(index, model, checkpoint = false) {
return { type: checkpoint ? 'CORTEX_STEP_TYPE_CHECKPOINT' : 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
status: 'CORTEX_STEP_STATUS_DONE', metadata: {
sourceTrajectoryStepInfo: { stepIndex: index },
createdAt: new Date(createdAtMs).toISOString(), completedAt: new Date(createdAtMs + 10_000).toISOString(),
modelUsage: { ...(model === undefined ? {} : { model }), apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
inputTokens: '1000', cacheReadTokens: '9000', outputTokens: '1000' },
} };
}
async function payload(steps, options = {}) {
return backendHarness({ summaries: { test: { stepCount: steps.length } },
trajectories: { test: { trajectory: { steps } } }, ...options }).buildTelemetryPayloadInternal('test');
}
test('missing checkpoint identity stays unknown between Flash steps; its token totals survive', async () => {
const rows = [step(209, FLASH), step(211, undefined, true), step(212, FLASH)];
const p = await payload(rows);
const cp = p.activeConversation.recentSteps.find(s => s.stepIndex === 211);
assert.equal(cp.modelKey, 'unknown'); assert.equal(cp.modelShort, '模型未知·压缩');
assert.equal(cp.costUsd, null); assert.equal(cp.inCostUsd, null);
assert.equal(cp.contextTokens, 11000); assert.equal(cp.tokPerSec, 100);
assert.equal(p.activeConversation.speedSummary.sampleCount, 2);
assert.equal(p.consumption.account.totalTokens, 33000);
assert.equal(p.consumption.account.unpricedCalls, 1);
assert.equal(p.modelBreakdown.find(m => m.label === '模型未知').unpricedCalls, 1);
assert.equal(p.modelBreakdown.find(m => m.shortName === 'flash-3.8-high').calls, 2);
assert(!p.modelBreakdown.some(m => /argon/i.test(m.label)));
assert.equal(p.consumption.trendSeries.reduce((n,s) => n+(s.unpricedCalls || 0),0), 1);
assert.equal(p.consumption.sourcesBreakdown[0].unpricedCalls, 1);
assert.equal(p.consumption.monthlySeries.reduce((n,s) => n+(s.unpricedCalls || 0),0), 1);
});
test('checkpoint can explicitly use a different model; no neighbour-based overwrite', async () => {
const p = await payload([step(209, FLASH), step(211, ARGON, true), step(212, FLASH)]);
const cp = p.activeConversation.recentSteps.find(s => s.stepIndex === 211);
assert.equal(cp.modelShort, 'argon-4·压缩'); assert.equal(cp.modelSource, 'usage.model');
assert.equal(cp.costUsd, 0.0129); assert.equal(p.consumption.account.unpricedCalls, 0);
});
test('ordinary calls with missing model are unknown too', () => {
const [s] = extractModelSteps([step(1)]);
assert.equal(s.modelKey, 'unknown'); assert.equal(s.modelSource, 'unavailable');
assert.equal(s.totalTokPerSec, 100);
});
test('retry usage preserves its own model and counters', () => {
const row = step(211, FLASH, true);
row.metadata.retryInfos = [{ usage: row.metadata.modelUsage }]; delete row.metadata.modelUsage;
const [s] = extractModelSteps([row]);
assert.equal(s.modelKey, FLASH); assert.equal(s.inputTokens, 1000);
});
test('matching generator usage supplies model and wins over requested generator model', () => {
const [s] = extractModelSteps([step(211)], [{stepIndices: [211], chatModel: {
usage: { model: FLASH }, model: ARGON,
}}]);
assert.equal(s.modelKey, FLASH); assert.equal(s.modelSource, 'chat.usage.model');
});
test('unrelated generator metadata never supplies the missing model', () => {
const [s] = extractModelSteps([step(211)], [{stepIndices: [0], chatModel: {model: FLASH}}]);
assert.equal(s.modelKey, 'unknown');
});
test('unspecified enum values fall through to actual step model evidence', () => {
for (const missing of ['', ' ', 'unknown', 'MODEL_UNSPECIFIED', 'MODEL_UNKNOWN', '0', 0, null]) {
const row = step(211, missing); row.metadata.generatorModel = FLASH;
const [s] = extractModelSteps([row]); assert.equal(s.modelKey, FLASH);
}
});
test('response model and display name are preserved when enum model is absent', async () => {
const row = step(211);
const raw = {trajectory: { steps: [row], generatorMetadata: [{stepIndices:[211],chatModel:{
responseModel:'gemini-3.8-flash-high',modelDisplayName:'Gemini 3.8 Flash (High)',
}}]}};
const p = await payload([], {trajectories: {test:raw}});
assert.equal(p.activeConversation.activeModelShort,'flash-3.8-high');
});
test('server model catalog overrides static placeholder mapping', () => {
const {resolveModelInfo} = backendHarness();
const result = resolveModelInfo(ARGON, new Map([[ARGON, {modelId:'gemini-3.8-flash-high', label:'Gemini 3.8 Flash (High)'}]]));
assert.equal(result.shortName,'flash-3.8-high'); assert.equal(result.pricing.input,0.75);
});
test('uncatalogued model keeps identity and does not borrow another model price', async () => {
const p = await payload([step(211, 'MODEL_PLACEHOLDER_M999')]);
assert.equal(p.activeConversation.activeModelShort,'MODEL_PLACEHOLDER_M999');
assert.equal(p.activeConversation.latestStepCostUsd,null);
assert.equal(p.consumption.account.unpricedCalls,1);
});
test('old ambiguous Argon cache is persisted as unresolved while retaining modern measurements', async () => {
const original = extractModelSteps([step(211, ARGON, true)])[0];
delete original.modelIdentityVersion; delete original.modelSource;
const old = {signature:'v9-unified-throughput:old',steps:[original]};
const h = backendHarness({cache:{test:old},trajectories:{test:new Error('offline')}});
const p = await h.buildTelemetryPayloadInternal('test');
const s = p.activeConversation.recentSteps[0];
assert.equal(s.modelKey,'unknown'); assert.equal(s.legacyModelKey,ARGON);
assert.equal(s.modelSource,'legacy_unverified'); assert.equal(s.totalTokPerSec,100);
assert.equal(p.consumption.account.totalTokens,11000);
assert.equal(p.consumption.account.unpricedCalls,1);
assert.equal(h.state.saves.length,1);
await h.buildTelemetryPayloadInternal('test');
assert.equal(h.state.saves.length,1,'do not rewrite identical migrated cache every poll');
h.state.trajectories.test = {trajectory:{steps:[step(211,FLASH,true)]}};
const restored = await h.buildTelemetryPayloadInternal('test');
assert.equal(restored.activeConversation.activeModelShort,'flash-3.8-high·压缩');
assert.equal(restored.consumption.account.unpricedCalls,0);
});
test('explicit historical models and verified real Argon identities survive cache load', () => {
const known = extractModelSteps([step(211, ARGON)])[0];
assert.equal(normalizeCachedStep(known).modelKey,ARGON);
const flash = {...known,modelKey:FLASH}; delete flash.modelIdentityVersion;
assert.equal(normalizeCachedStep(flash).modelKey,FLASH);
assert.equal(normalizeCachedStep(flash).modelIdentityVersion, MODEL_IDENTITY_VERSION);
});
test('empty session does not invent an Argon model or a model quota pool', async () => {
const p = await backendHarness().buildTelemetryPayloadInternal('test');
assert.equal(p.activeConversation.activeModelShort,'模型未知');
assert.equal(p.quotas.activePool.isAvailable,false); assert.equal(p.quotas.activePool.family,'Unknown');
});
test('unknown cost renders as pending, known subtotals disclose missing calls', () => {
assert.equal(formatUsd(null),'待定'); assert.equal(formatUsd(0),'$0.00');
assert.equal(formatUsd(0.1,{unpricedCalls:1}),'$0.10 + 待定');
});
test('custom cost budget cannot claim a complete remaining percentage when prices are missing', async () => {
const p = await payload([step(211)], {settings:{weeklyLimitMode:'custom_cost'}});
assert.equal(p.quotas.weekly.usedPct,null); assert.equal(p.quotas.weekly.remainingPct,null);
});
test('frontend considers a model-only correction a real telemetry update', () => {
const source = fs.readFileSync(new URL('../src/store/telemetryStore.js',import.meta.url),'utf8');
const fn = source.slice(source.indexOf('function isEquivalentTelemetry'),source.indexOf('export async function fetchTelemetry'));
const ctx = {}; vm.runInNewContext(fn+'\nglobalThis.compare=isEquivalentTelemetry;',ctx);
const a={activeConversation:{recentSteps:[{modelKey:'unknown',modelShort:'模型未知',costUsd:null}]}};
const b=structuredClone(a); b.activeConversation.recentSteps[0].modelShort='new-model';
assert.equal(ctx.compare(a,b),false); assert.equal(ctx.compare(a,structuredClone(a)),true);
});
+157
View File
@@ -0,0 +1,157 @@
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 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];}
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('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('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('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,ttft:'0.1s'}).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 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('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('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('legacy cache retains billing but cannot masquerade as current measurements',()=>{
for(const measurementVersion of [undefined,1,2,3]){
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('half-second cutoff uses the original nanoseconds, not rounded epoch milliseconds',()=>{
const {s,gm}=sample({output:100,ttft:'0.1s'});
s.metadata.createdAt='2026-01-01T00:00:00.000000001Z';
s.metadata.finishedGeneratingAt='2026-01-01T00:00:00.500000000Z';
const below=extractModelSteps([s],[gm])[0];
assert.equal(below.totalDurationSec,.499999999);assert.equal(below.totalTokPerSec,null);
s.metadata.finishedGeneratingAt='2026-01-01T00:00:00.500000001Z';
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,200);
s.metadata.createdAt='2026-01-01T08:00:00.000000001+08:00';
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,200);
});
test('non-chat generator metadata cannot overwrite matching model timing',()=>{
const {s,gm}=sample();s.metadata.sourceTrajectoryStepInfo={stepIndex:42};gm.stepIndices=[42];
const other={stepIndices:[42],tool:{}};
assert.equal(extractModelSteps([s],[gm,other])[0].nativeTtftSec,2);
s.metadata.generatorMetadata=[other,{chatModel:{timeToFirstToken:'3s'}}];
assert.equal(extractModelSteps([s],[gm])[0].nativeTtftSec,3);
});
test('a paginated source step never borrows timing from an unrelated array position',()=>{
const {s,gm}=sample();s.metadata.sourceTrajectoryStepInfo={stepIndex:42};
const step=extractModelSteps([s],[gm])[0];
assert.equal(step.nativeTtftSec,null);assert.equal(step.totalTokPerSec,1100/12);
});
test('contradictory native TTFT is preserved but cannot validate TPS or bias the TTFT mean',()=>{
const bad=parse({total:5,ttft:'9s'});
assert.equal(bad.nativeTtftSec,9);assert.equal(bad.totalTokPerSec,null);
assert.equal(bad.speedReason,'inconsistent_timing');
assert.deepEqual(summarizeTtft([bad,parse()]),{sampleCount:1,avgSec:2});
});
test('unfinished steps do not enter the TTFT mean even when partial metadata includes TTFT',()=>{
const partial=parse({status:'CORTEX_STEP_STATUS_GENERATING',ttft:'8s'});
assert.deepEqual(summarizeTtft([partial,parse()]),{sampleCount:1,avgSec:2});
});
test('coercible non-token values cannot silently become zero or one output token',()=>{
for(const value of [true,false,' ',[],{}]){
const {s,gm}=sample();s.metadata.modelUsage.outputTokens=value;
assert.equal(extractModelSteps([s],[gm])[0].speedReason,'invalid_output_tokens');
}
});
test('visible buffered text and tools use full time without a rate-dependent switch',()=>{
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.totalDurationSec,7.0154512);
assert.equal(speedMetric(step).value,64/7.0154512);
assert.equal(step.speedBasis,'request_total');
});
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);
});
@@ -0,0 +1,194 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { ConnectJsonDecoder, StreamObservation, StreamDiagnostics, encodeConnectJson } from '../stream-diagnostics.mjs';
const ID = '12345678-1234-1234-1234-123456789abc';
const CREATED = '2026-10-15T01:00:00.000Z';
const FINISHED = '2026-10-15T01:00:08.000Z';
const event = (ms, batch = ms) => ({ elapsedMs: ms, receiveBatch: batch, receivedAt: CREATED });
const model = (p = {}, done = false, extra = {}) => ({
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', status: done ? 'CORTEX_STEP_STATUS_DONE' : 'CORTEX_STEP_STATUS_STREAMING',
metadata: { createdAt: CREATED, ...(done ? { finishedGeneratingAt: FINISHED, modelUsage: { outputTokens: '400' } } : {}) },
plannerResponse: p, ...extra,
});
const update = (indices, steps, totalLength, more = {}) => ({ update: { conversationId: ID,
mainTrajectoryUpdate: { stepsUpdate: { indices, steps, totalLength }, ...more } } });
function observer() {
const records = [];
const observation = new StreamObservation({ conversationId: ID, connectedWallMs: Date.parse(CREATED) - 1000, emit: r => records.push(r) });
return { records, observation };
}
test('Connect decoder reconstructs fragmented headers/UTF-8 and keeps coalesced messages separate', () => {
const a = { update: { text: '中文🙂' } };
const b = { update: { text: 'second' } };
const bytes = Buffer.concat([encodeConnectJson(a), encodeConnectJson(b)]);
const decoder = new ConnectJsonDecoder();
const messages = [];
for (let i = 0; i < bytes.length; i += 3) messages.push(...decoder.push(bytes.subarray(i, i + 3)));
decoder.finish();
assert.deepEqual(messages.map(m => m.value), [a, b]);
const end = encodeConnectJson({}); end[0] = 2;
assert.equal(decoder.push(end)[0].end, true);
assert.throws(() => decoder.push(encodeConnectJson(a)), /data_after_end/);
});
test('Connect decoder rejects oversized, compressed, malformed and truncated frames', () => {
const huge = Buffer.from([0, 0, 0, 1, 0]);
assert.throws(() => new ConnectJsonDecoder(100).push(huge), /frame_too_large/);
const compressed = encodeConnectJson({}); compressed[0] = 1;
assert.throws(() => new ConnectJsonDecoder().push(compressed), /unsupported_frame_flags/);
assert.throws(() => new ConnectJsonDecoder().push(Buffer.from([0, 0, 0, 0, 1, 120])), /invalid_frame_json/);
const decoder = new ConnectJsonDecoder(); decoder.push(Buffer.from([0, 0]));
assert.throws(() => decoder.finish(), /truncated_frame/);
});
test('history, delayed rehydration and status-only notifications never become live output', () => {
const { observation: o, records } = observer();
o.accept({ update: { conversationId: ID, status: 'IDLE' } }, event(0));
assert.equal(o.initialized, false);
o.accept(update([9], [model({ response: 'old response' }, true)], 10), event(1));
o.accept(update([4], [model({ response: 'late history' }, true)], 10), event(2));
assert.equal(o.contentEvents, 0);
assert.equal(o.recent.length, 0);
assert.deepEqual(records.map(r => r.kind), ['baseline']);
});
test('tool arguments, thinking and text are counted independently; receive batches are not tokens', () => {
const { observation: o, records } = observer();
o.accept(update([], [], 10), event(0));
o.accept(update([10], [model()], 11), event(10));
o.accept(update([10], [model({ thinking: 'hidden-secret', response: '中', toolCalls: [{ argumentsJson: '{', name: 'secret-tool' }] })], 11), event(20, 2));
o.accept(update([10], [model({ thinking: 'hidden-secret!', response: '中文', toolCalls: [{ argumentsJson: '{"secret":"' }] })], 11), event(20, 2));
const full = model({ thinking: 'hidden-secret!', response: '中文', toolCalls: [{ argumentsJson: '{"secret":"argument-secret"}' }] }, true);
o.accept(update([10], [full], 11), event(120, 3));
o.accept(update([10], [full], 11), event(300, 4));
o.accept(update([], [], 11, { generatorMetadatasUpdate: { generatorMetadatas: [{ stepIndices: [10], chatModel: {
usage: { outputTokens: '400', thinkingOutputTokens: '50', responseHeader: { authorization: 'credential-secret' } },
timeToFirstToken: '7.999s', streamingDuration: '0.001s', systemPrompt: 'prompt-secret',
} }] } }), event(400, 5));
const r = o.recent[0];
assert.equal(r.contentEvents, 3);
assert.equal(r.contentReceiveBatches, 2);
assert.equal(r.toolArgumentEvents, 3);
assert.equal(r.observedSpanMs, 100);
assert.equal(r.channels.text.bytes, 6);
assert.equal(r.channels.text.utf16Units, 2);
assert.equal(r.usage.outputTokens, 400);
assert.equal(r.nativeStreamSec, 0.001);
assert.equal(r.partialCapture, false);
const serialized = JSON.stringify([records, r]);
for (const secret of ['hidden-secret', 'argument-secret', 'secret-tool', 'credential-secret', 'prompt-secret', '中文']) assert.ok(!serialized.includes(secret));
assert.ok(!/tokPerSec|tps|firstTokenMs/i.test(serialized));
});
test('same-batch delivery is not reported as a timed stream, even with several updates', () => {
const { observation: o } = observer();
o.accept(update([], [], 0), event(0));
o.accept(update([0], [model({ response: 'a' })], 1), event(5, 1));
o.accept(update([0], [model({ response: 'ab' }, true)], 1), event(5, 1));
assert.equal(o.recent[0].observation, 'single_receive_batch');
assert.equal(o.recent[0].observedSpanMs, 0);
});
test('rewrites, shrinking output and tool-only updates are retained as revisions', () => {
const { observation: o, records } = observer();
o.accept(update([], [], 0), event(0));
o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'abcd' }] })], 1), event(10));
o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'wxyz' }] })], 1), event(20));
o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'wx' }] }, true)], 1), event(30));
assert.equal(o.recent[0].revisions, 2);
assert.equal(o.recent[0].toolArgumentEvents, 3);
assert.equal(records.at(-1).changes.toolArguments.deltaBytes, -2);
assert.equal(records.at(-1).changes.toolArguments.appendOnly, false);
});
test('joining during generation marks partial capture and excludes initial content from updates', () => {
const { observation: o } = observer();
o.accept(update([2], [model({ response: 'already there' })], 3), event(10));
o.accept(update([2], [model({ response: 'already there plus more' }, true)], 3), event(20));
assert.equal(o.recent[0].partialCapture, true);
assert.equal(o.recent[0].contentEvents, 1);
assert.equal(o.recent[0].observation, 'partial_capture');
});
test('missing or earlier creation time never claims a complete observation', () => {
const { observation: o } = observer();
o.accept(update([], [], 0), event(0));
o.accept(update([0], [model({ response: 'arrived' }, true, { metadata: { finishedGeneratingAt: FINISHED } })], 1), event(20));
assert.equal(o.recent[0].partialCapture, true);
assert.throws(() => o.accept(update([], [model()], 2), event(25)), /invalid_step_indices/);
});
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function until(check) {
for (let i = 0; i < 100; i++) { if (check()) return; await sleep(10); }
assert.fail('timed out');
}
function temp(t) {
const dir = mkdtempSync(join(tmpdir(), 'usage-monitor-diag-test-'));
t.after(() => {
const absolute = resolve(dir);
assert.equal(dirname(absolute), resolve(tmpdir()));
assert.ok(absolute.startsWith(join(resolve(tmpdir()), 'usage-monitor-diag-test-')));
rmSync(absolute, { recursive: true, force: true });
});
return dir;
}
test('collector only subscribes to read APIs, persists counters and stops without touching billing', async t => {
const dir = temp(t);
const calls = [];
let streamController;
const fetchImpl = async (url, options) => {
calls.push({ url, options });
if (url.endsWith('GetAllCascadeTrajectories')) return new Response(JSON.stringify({ trajectorySummaries: { [ID]: { stepCount: 0, lastModifiedTime: CREATED } } }));
assert.ok(url.endsWith('StreamAgentStateUpdates'));
const request = new ConnectJsonDecoder().push(options.body)[0].value;
assert.equal(request.trajectoryVerbosity, 'CLIENT_TRAJECTORY_VERBOSITY_FULL');
const stream = new ReadableStream({ start(c) {
streamController = c;
c.enqueue(encodeConnectJson(update([], [], 0)));
options.signal.addEventListener('abort', () => c.error(new Error('aborted')), { once: true });
} });
return new Response(stream, { headers: { 'Content-Type': 'application/connect+json' } });
};
const d = new StreamDiagnostics({ dataDir: dir, lsAddress: '127.0.0.1:1', csrfToken: 'secret-csrf', fetchImpl, pollMs: 60000 });
t.after(() => d.stop());
assert.equal(d.status().enabled, false);
d.configure({ enabled: true });
await until(() => d.status().phase === 'collecting');
streamController.enqueue(encodeConnectJson(update([0], [model({ toolCalls: [{ argumentsJson: 'private-arguments' }] }, true)], 1)));
await until(() => d.status().contentEvents === 1);
assert.equal(d.status().affectsTps, false);
d.configure({ enabled: false });
await sleep(10);
assert.equal(d.status().phase, 'disabled');
assert.equal(d.current, null);
const log = readFileSync(join(dir, 'stream-diagnostics', 'events.jsonl'), 'utf8');
assert.ok(!log.includes('secret-csrf'));
assert.ok(!log.includes('private-arguments'));
assert.ok(log.includes('step_update'));
assert.deepEqual(readdirSync(dir).sort(), ['stream-diagnostics', 'stream-diagnostics-config.json']);
assert.equal(calls.length, 2);
});
test('failed subscriptions back off and never expose the server error body', async t => {
const dir = temp(t);
let calls = 0;
const d = new StreamDiagnostics({ dataDir: dir, lsAddress: '127.0.0.1:1', csrfToken: 'csrf', pollMs: 10, retryMs: 5000,
fetchImpl: async url => {
calls++;
if (url.endsWith('GetAllCascadeTrajectories')) return new Response(JSON.stringify({ trajectorySummaries: { [ID]: {} } }));
return new Response('private server error with credentials', { status: 403 });
} });
t.after(() => d.stop());
d.configure({ enabled: true });
await until(() => d.status().error === 'stream_http_403');
await sleep(40);
assert.equal(calls, 2);
assert.ok(!JSON.stringify(d.status()).includes('private'));
});