Open History to see the last commit
1/**
2 * Merges per-environment usage summaries into the single view the page renders.
3 *
4 * Pure, so the de-duplication and derivation rules can be tested without a
5 * connected environment.
6 *
7 * @module usageMerge
8 */
9import {
10 USAGE_MERGE_COMPATIBLE_SINCE,
11 type EnvironmentId,
12 type UsageBucket,
13 type UsageProviderKind,
14 type UsageSource,
15 type UsageSourceFingerprint,
16 type UsageSummary,
17 type UsageTokenTotals,
18} from "@t3tools/contracts";
19
20export interface EnvironmentUsage {
21 readonly environmentId: EnvironmentId;
22 readonly label: string;
23 readonly summary: UsageSummary;
24}
25
26export interface ProviderTotals {
27 readonly provider: UsageProviderKind;
28 readonly costUsd: number;
29 readonly totalTokens: number;
30 readonly records: number;
31 readonly sessions: number;
32 readonly costShare: number;
33 readonly tokenShare: number;
34}
35
36export interface ModelTotals {
37 readonly model: string;
38 readonly provider: UsageProviderKind;
39 readonly costUsd: number;
40 readonly totalTokens: number;
41 readonly tokens: UsageTokenTotals;
42 readonly records: number;
43 /**
44 * Records whose tokens are counted here but which contributed nothing to
45 * `costUsd`. When it equals `records` the cost is unknown, not zero.
46 */
47 readonly unpricedRecords: number;
48 /**
49 * Tokens with no known rates, which a custom price would cover. A cell that
50 * mixes these with reported costs counts its tokens by record share.
51 */
52 readonly unpricedTokens: number;
53 readonly costShare: number;
54}
55
56/**
57 * A model whose every record lacked rates has an unknown cost, not a zero one.
58 * Clients must not present its `costUsd` as a real dollar figure.
59 */
60export function isModelCostUnknown(model: ModelTotals): boolean {
61 return model.records > 0 && model.unpricedRecords >= model.records;
62}
63
64export interface DailyTotals {
65 readonly day: string;
66 readonly costUsd: number;
67 readonly totalTokens: number;
68 readonly byProvider: ReadonlyMap<UsageProviderKind, { costUsd: number; totalTokens: number }>;
69}
70
71export interface HourlyTotals {
72 readonly day: string;
73 readonly hourStart: string;
74 readonly costUsd: number;
75 readonly totalTokens: number;
76 readonly byProvider: ReadonlyMap<UsageProviderKind, { costUsd: number; totalTokens: number }>;
77}
78
79export interface CostQuality {
80 readonly providerReportedShare: number;
81 readonly modelPricedShare: number;
82 readonly unpricedShare: number;
83 readonly cacheSavingsUsd: number;
84}
85
86/**
87 * `costUsd` by token category. `unsplit` is cost no rates could split,
88 * including all cost from servers that predate the split.
89 */
90export interface CategoryCost {
91 readonly input: number;
92 readonly cacheRead: number;
93 readonly cacheWrite: number;
94 readonly output: number;
95 readonly unsplit: number;
96}
97
98/** `costUsd` by request speed. Servers that predate speeds count as standard. */
99export interface SpeedCost {
100 readonly standard: number;
101 readonly fast: number;
102 readonly ultrafast: number;
103 /** What fast and ultrafast requests cost above the standard rate. */
104 readonly premium: number;
105}
106
107export interface UsageContractMismatch {
108 readonly environmentId: EnvironmentId;
109 readonly direction: "serverBehind" | "clientBehind";
110 readonly contractVersion: number;
111}
112
113export interface MergedUsage {
114 readonly costUsd: number;
115 readonly uncachedInputTokens: number;
116 readonly cachedInputTokens: number;
117 readonly cacheCreationTokens: number;
118 readonly outputTokens: number;
119 readonly reasoningTokens: number;
120 readonly totalTokens: number;
121 readonly records: number;
122 readonly sessions: number;
123 readonly providers: readonly ProviderTotals[];
124 readonly models: readonly ModelTotals[];
125 readonly daily: readonly DailyTotals[];
126 readonly hourly: readonly HourlyTotals[];
127 readonly costQuality: CostQuality;
128 readonly categoryCost: CategoryCost;
129 readonly speedCost: SpeedCost;
130 /** Environments whose data was dropped as a duplicate of another's. */
131 readonly duplicateSources: readonly string[];
132 readonly contributingEnvironments: readonly EnvironmentId[];
133 readonly contractMismatches: readonly UsageContractMismatch[];
134}
135
136/**
137 * Two sources are the same physical transcript directory only when host,
138 * provider, path and filesystem identity all agree.
139 *
140 * `volumeId` is what stops two machines that happen to share a hostname and a
141 * home path, which is every Mac in a fleet, from collapsing into one source and
142 * having one of them silently dropped.
143 */
144function fingerprintKey(fingerprint: UsageSourceFingerprint): string {
145 return [
146 fingerprint.hostId,
147 fingerprint.provider,
148 fingerprint.resolvedHomePath,
149 fingerprint.volumeId,
150 ].join(" ");
151}
152
153function bucketsForSource(summary: UsageSummary, source: UsageSource): readonly UsageBucket[] {
154 const providerSources = summary.sources.filter(
155 (entry) => entry.fingerprint.provider === source.fingerprint.provider,
156 );
157 return summary.buckets.filter(
158 (bucket) =>
159 bucket.provider === source.fingerprint.provider &&
160 (bucket.sourcePath === source.fingerprint.resolvedHomePath ||
161 (bucket.sourcePath === undefined && providerSources.length === 1)),
162 );
163}
164
165function bucketKey(bucket: UsageBucket): string {
166 return JSON.stringify([bucket.day, bucket.hourStart ?? null, bucket.provider, bucket.model]);
167}
168
169/**
170 * Decides which environment owns each physical transcript directory.
171 *
172 * Several environments on one machine (worktree servers, for instance) resolve
173 * the same provider home and would otherwise double count every token. The
174 * Complete scans claim a fingerprint ahead of partial scans, then the most
175 * recently read scan wins within each status. A newer partial scan can still
176 * contribute cells absent from an older complete scan. Environment ids break
177 * ties so the result is stable when summaries have the same read time.
178 */
179function claimSources(environments: readonly EnvironmentUsage[]): {
180 readonly ownerByFingerprint: ReadonlyMap<string, EnvironmentId>;
181 readonly supplementalBucketsByEnvironment: ReadonlyMap<EnvironmentId, ReadonlySet<UsageBucket>>;
182 readonly sessionsByFingerprint: ReadonlyMap<string, number>;
183 readonly duplicates: readonly string[];
184} {
185 const ownerByFingerprint = new Map<string, EnvironmentId>();
186 const ownerScanByFingerprint = new Map<
187 string,
188 { environment: EnvironmentUsage; source: UsageSource }
189 >();
190 const seenBucketKeysByFingerprint = new Map<string, Set<string>>();
191 const supplementalBucketsByEnvironment = new Map<EnvironmentId, Set<UsageBucket>>();
192 const sessionsByFingerprint = new Map<string, number>();
193 const duplicates: string[] = [];
194
195 const ordered = [...environments].sort(
196 (a, b) =>
197 (Date.parse(b.summary.readAt) || 0) - (Date.parse(a.summary.readAt) || 0) ||
198 a.environmentId.localeCompare(b.environmentId),
199 );
200
201 // A complete scan takes precedence over a newer partial scan of the same
202 // directory. Partial history still contributes when no complete copy exists.
203 for (const status of ["ok", "partial", "failed"] as const) {
204 for (const environment of ordered) {
205 for (const source of environment.summary.sources) {
206 if (source.status !== status) continue;
207 const key = fingerprintKey(source.fingerprint);
208 if (ownerByFingerprint.has(key)) {
209 duplicates.push(`${environment.label}: ${source.fingerprint.resolvedHomePath}`);
210 continue;
211 }
212 ownerByFingerprint.set(key, environment.environmentId);
213 ownerScanByFingerprint.set(key, { environment, source });
214 sessionsByFingerprint.set(key, source.distinctSessions);
215 }
216 }
217 }
218
219 // A newer partial scan may contain usage recorded after an older complete
220 // scan. Keep cells absent from the complete scan. Aggregated cells do not
221 // reveal enough to reconcile overlapping records without double counting.
222 for (const environment of ordered) {
223 for (const source of environment.summary.sources) {
224 if (source.status !== "partial") continue;
225 const key = fingerprintKey(source.fingerprint);
226 const owner = ownerScanByFingerprint.get(key);
227 if (
228 owner?.source.status !== "ok" ||
229 Date.parse(environment.summary.readAt) <= Date.parse(owner.environment.summary.readAt)
230 ) {
231 continue;
232 }
233 let seen = seenBucketKeysByFingerprint.get(key);
234 if (seen === undefined) {
235 seen = new Set(bucketsForSource(owner.environment.summary, owner.source).map(bucketKey));
236 seenBucketKeysByFingerprint.set(key, seen);
237 }
238 const supplemental =
239 supplementalBucketsByEnvironment.get(environment.environmentId) ?? new Set<UsageBucket>();
240 let added = false;
241 for (const bucket of bucketsForSource(environment.summary, source)) {
242 const cell = bucketKey(bucket);
243 if (seen.has(cell)) continue;
244 seen.add(cell);
245 supplemental.add(bucket);
246 added = true;
247 }
248 if (!added) continue;
249 supplementalBucketsByEnvironment.set(environment.environmentId, supplemental);
250 sessionsByFingerprint.set(
251 key,
252 Math.max(sessionsByFingerprint.get(key) ?? 0, source.distinctSessions),
253 );
254 }
255 }
256
257 return {
258 ownerByFingerprint,
259 supplementalBucketsByEnvironment,
260 sessionsByFingerprint,
261 duplicates,
262 };
263}
264
265/** Sources this environment owns after fingerprint claims, plus their buckets. */
266function ownedContribution(
267 environment: EnvironmentUsage,
268 ownerByFingerprint: ReadonlyMap<string, EnvironmentId>,
269 supplementalBuckets: ReadonlySet<UsageBucket>,
270 sessionsByFingerprint: ReadonlyMap<string, number>,
271): {
272 readonly buckets: readonly UsageBucket[];
273 readonly sessionsByProvider: ReadonlyMap<UsageProviderKind, number>;
274} {
275 const ownedProviders = new Set<UsageProviderKind>();
276 const ownedSources = new Set<string>();
277 const sessionsByProvider = new Map<UsageProviderKind, number>();
278 for (const source of environment.summary.sources) {
279 if (source.status === "missing") continue;
280 const key = fingerprintKey(source.fingerprint);
281 if (ownerByFingerprint.get(key) === environment.environmentId) {
282 const provider = source.fingerprint.provider;
283 ownedProviders.add(provider);
284 ownedSources.add(`${provider}\u0000${source.fingerprint.resolvedHomePath}`);
285 // Distinct within a directory. Summing per-bucket session counts instead
286 // would count a session once per day and model it spans.
287 sessionsByProvider.set(
288 provider,
289 (sessionsByProvider.get(provider) ?? 0) +
290 (sessionsByFingerprint.get(key) ?? source.distinctSessions),
291 );
292 }
293 }
294 return {
295 buckets: environment.summary.buckets.filter(
296 (bucket) =>
297 supplementalBuckets.has(bucket) ||
298 (bucket.sourcePath === undefined
299 ? ownedProviders.has(bucket.provider)
300 : ownedSources.has(`${bucket.provider}\u0000${bucket.sourcePath}`)),
301 ),
302 sessionsByProvider,
303 };
304}
305
306function bucketTokens(bucket: UsageBucket): number {
307 // reasoningTokens is a subset of outputTokens and must not be added again.
308 return (
309 bucket.totals.uncachedInputTokens +
310 bucket.totals.cachedInputTokens +
311 bucket.totals.cacheCreationTokens +
312 bucket.totals.outputTokens
313 );
314}
315
316export function isCompatibleUsageContractVersion(version: number, expected: number): boolean {
317 return version >= USAGE_MERGE_COMPATIBLE_SINCE && version <= expected;
318}
319
320const EMPTY_MERGED: MergedUsage = {
321 costUsd: 0,
322 uncachedInputTokens: 0,
323 cachedInputTokens: 0,
324 cacheCreationTokens: 0,
325 outputTokens: 0,
326 reasoningTokens: 0,
327 totalTokens: 0,
328 records: 0,
329 sessions: 0,
330 providers: [],
331 models: [],
332 daily: [],
333 hourly: [],
334 costQuality: {
335 providerReportedShare: 0,
336 modelPricedShare: 0,
337 unpricedShare: 0,
338 cacheSavingsUsd: 0,
339 },
340 categoryCost: { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, unsplit: 0 },
341 speedCost: { standard: 0, fast: 0, ultrafast: 0, premium: 0 },
342 duplicateSources: [],
343 contributingEnvironments: [],
344 contractMismatches: [],
345};
346
347/**
348 * Merges every connected environment's summary.
349 *
350 * `expectedContractVersion` guards against incompatible server code: rather
351 * than blocking the page, its data is excluded and the mismatch direction is
352 * reported so the UI can identify which side needs updating. Versions in
353 * [{@link USAGE_MERGE_COMPATIBLE_SINCE}, expected] still merge, so an additive
354 * provider expansion does not drop Claude/Codex totals from older servers.
355 */
356export function mergeUsage(
357 environments: readonly EnvironmentUsage[],
358 expectedContractVersion: number,
359): MergedUsage {
360 if (environments.length === 0) return EMPTY_MERGED;
361
362 const current: EnvironmentUsage[] = [];
363 const contractMismatches: UsageContractMismatch[] = [];
364 for (const environment of environments) {
365 if (
366 isCompatibleUsageContractVersion(environment.summary.contractVersion, expectedContractVersion)
367 ) {
368 current.push(environment);
369 } else {
370 contractMismatches.push({
371 environmentId: environment.environmentId,
372 direction:
373 environment.summary.contractVersion < expectedContractVersion
374 ? "serverBehind"
375 : "clientBehind",
376 contractVersion: environment.summary.contractVersion,
377 });
378 }
379 }
380
381 const {
382 ownerByFingerprint,
383 supplementalBucketsByEnvironment,
384 sessionsByFingerprint,
385 duplicates,
386 } = claimSources(current);
387
388 let costUsd = 0;
389 let uncachedInputTokens = 0;
390 let cachedInputTokens = 0;
391 let cacheCreationTokens = 0;
392 let outputTokens = 0;
393 let reasoningTokens = 0;
394 let records = 0;
395 let sessions = 0;
396 let cacheSavingsUsd = 0;
397 let providerReportedRecords = 0;
398 let unpricedRecords = 0;
399 const categoryCost = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 };
400 const speedCost = { fast: 0, ultrafast: 0, premium: 0 };
401
402 const providerAccumulator = new Map<
403 UsageProviderKind,
404 { costUsd: number; totalTokens: number; records: number; sessions: number }
405 >();
406 const modelAccumulator = new Map<
407 string,
408 {
409 provider: UsageProviderKind;
410 costUsd: number;
411 totalTokens: number;
412 tokens: UsageTokenTotals;
413 records: number;
414 unpricedRecords: number;
415 unpricedTokens: number;
416 }
417 >();
418 const dailyAccumulator = new Map<
419 string,
420 {
421 costUsd: number;
422 totalTokens: number;
423 byProvider: Map<UsageProviderKind, { costUsd: number; totalTokens: number }>;
424 }
425 >();
426 const hourlyAccumulator = new Map<
427 string,
428 {
429 day: string;
430 hourStart: string;
431 costUsd: number;
432 totalTokens: number;
433 byProvider: Map<UsageProviderKind, { costUsd: number; totalTokens: number }>;
434 }
435 >();
436 const contributingEnvironments: EnvironmentId[] = [];
437
438 for (const environment of current) {
439 const { buckets, sessionsByProvider } = ownedContribution(
440 environment,
441 ownerByFingerprint,
442 supplementalBucketsByEnvironment.get(environment.environmentId) ?? new Set(),
443 sessionsByFingerprint,
444 );
445 if (buckets.length > 0) contributingEnvironments.push(environment.environmentId);
446
447 for (const [providerKind, providerSessions] of sessionsByProvider) {
448 sessions += providerSessions;
449 if (providerSessions === 0) continue;
450 const provider = providerAccumulator.get(providerKind) ?? {
451 costUsd: 0,
452 totalTokens: 0,
453 records: 0,
454 sessions: 0,
455 };
456 provider.sessions += providerSessions;
457 providerAccumulator.set(providerKind, provider);
458 }
459
460 for (const bucket of buckets) {
461 const tokens = bucketTokens(bucket);
462
463 costUsd += bucket.costUsd;
464 cacheSavingsUsd += bucket.cacheSavingsUsd;
465 uncachedInputTokens += bucket.totals.uncachedInputTokens;
466 cachedInputTokens += bucket.totals.cachedInputTokens;
467 cacheCreationTokens += bucket.totals.cacheCreationTokens;
468 outputTokens += bucket.totals.outputTokens;
469 reasoningTokens += bucket.totals.reasoningTokens;
470 records += bucket.records;
471 unpricedRecords += bucket.unpricedRecords;
472 if (bucket.costSource === "providerReported") providerReportedRecords += bucket.records;
473 if (bucket.categoryCostUsd !== undefined) {
474 categoryCost.input += bucket.categoryCostUsd.input;
475 categoryCost.cacheRead += bucket.categoryCostUsd.cacheRead;
476 categoryCost.cacheWrite += bucket.categoryCostUsd.cacheWrite;
477 categoryCost.output += bucket.categoryCostUsd.output;
478 }
479 speedCost.fast += bucket.fastCostUsd ?? 0;
480 speedCost.ultrafast += bucket.ultrafastCostUsd ?? 0;
481 speedCost.premium += bucket.speedPremiumUsd ?? 0;
482
483 const provider = providerAccumulator.get(bucket.provider) ?? {
484 costUsd: 0,
485 totalTokens: 0,
486 records: 0,
487 sessions: 0,
488 };
489 provider.costUsd += bucket.costUsd;
490 provider.totalTokens += tokens;
491 provider.records += bucket.records;
492 providerAccumulator.set(bucket.provider, provider);
493
494 const modelKey = `${bucket.provider} ${bucket.model}`;
495 const model = modelAccumulator.get(modelKey) ?? {
496 provider: bucket.provider,
497 costUsd: 0,
498 totalTokens: 0,
499 tokens: {
500 uncachedInputTokens: 0,
501 cachedInputTokens: 0,
502 cacheCreationTokens: 0,
503 outputTokens: 0,
504 reasoningTokens: 0,
505 },
506 records: 0,
507 unpricedRecords: 0,
508 unpricedTokens: 0,
509 };
510 model.costUsd += bucket.costUsd;
511 model.totalTokens += tokens;
512 model.tokens = {
513 uncachedInputTokens: model.tokens.uncachedInputTokens + bucket.totals.uncachedInputTokens,
514 cachedInputTokens: model.tokens.cachedInputTokens + bucket.totals.cachedInputTokens,
515 cacheCreationTokens: model.tokens.cacheCreationTokens + bucket.totals.cacheCreationTokens,
516 outputTokens: model.tokens.outputTokens + bucket.totals.outputTokens,
517 reasoningTokens: model.tokens.reasoningTokens + bucket.totals.reasoningTokens,
518 };
519 model.records += bucket.records;
520 model.unpricedRecords += bucket.unpricedRecords;
521 if (bucket.records > 0) {
522 model.unpricedTokens += (tokens * bucket.unpricedRecords) / bucket.records;
523 }
524 modelAccumulator.set(modelKey, model);
525
526 const day = dailyAccumulator.get(bucket.day) ?? {
527 costUsd: 0,
528 totalTokens: 0,
529 byProvider: new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(),
530 };
531 day.costUsd += bucket.costUsd;
532 day.totalTokens += tokens;
533 const dayProvider = day.byProvider.get(bucket.provider) ?? { costUsd: 0, totalTokens: 0 };
534 dayProvider.costUsd += bucket.costUsd;
535 dayProvider.totalTokens += tokens;
536 day.byProvider.set(bucket.provider, dayProvider);
537 dailyAccumulator.set(bucket.day, day);
538
539 if (bucket.hourStart !== undefined) {
540 const hour = hourlyAccumulator.get(bucket.hourStart) ?? {
541 day: bucket.day,
542 hourStart: bucket.hourStart,
543 costUsd: 0,
544 totalTokens: 0,
545 byProvider: new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(),
546 };
547 hour.costUsd += bucket.costUsd;
548 hour.totalTokens += tokens;
549 const hourProvider = hour.byProvider.get(bucket.provider) ?? {
550 costUsd: 0,
551 totalTokens: 0,
552 };
553 hourProvider.costUsd += bucket.costUsd;
554 hourProvider.totalTokens += tokens;
555 hour.byProvider.set(bucket.provider, hourProvider);
556 hourlyAccumulator.set(bucket.hourStart, hour);
557 }
558 }
559 }
560
561 const totalTokens = uncachedInputTokens + cachedInputTokens + cacheCreationTokens + outputTokens;
562
563 const providers: ProviderTotals[] = [...providerAccumulator.entries()]
564 .map(([provider, totals]) => ({
565 provider,
566 costUsd: totals.costUsd,
567 totalTokens: totals.totalTokens,
568 records: totals.records,
569 sessions: totals.sessions,
570 costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd,
571 tokenShare: totalTokens === 0 ? 0 : totals.totalTokens / totalTokens,
572 }))
573 .sort((a, b) => b.costUsd - a.costUsd);
574
575 const models: ModelTotals[] = [...modelAccumulator.entries()]
576 .map(([key, totals]) => ({
577 model: key.slice(key.indexOf(" ") + 1),
578 provider: totals.provider,
579 costUsd: totals.costUsd,
580 totalTokens: totals.totalTokens,
581 tokens: totals.tokens,
582 records: totals.records,
583 unpricedRecords: totals.unpricedRecords,
584 unpricedTokens: totals.unpricedTokens,
585 costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd,
586 }))
587 .sort((a, b) => b.costUsd - a.costUsd || b.totalTokens - a.totalTokens);
588
589 const daily: DailyTotals[] = [...dailyAccumulator.entries()]
590 .map(([day, totals]) => ({
591 day,
592 costUsd: totals.costUsd,
593 totalTokens: totals.totalTokens,
594 byProvider: totals.byProvider,
595 }))
596 .sort((a, b) => a.day.localeCompare(b.day));
597
598 const hourly: HourlyTotals[] = [...hourlyAccumulator.values()].sort((a, b) =>
599 a.hourStart.localeCompare(b.hourStart),
600 );
601
602 return {
603 costUsd,
604 uncachedInputTokens,
605 cachedInputTokens,
606 cacheCreationTokens,
607 outputTokens,
608 reasoningTokens,
609 totalTokens,
610 records,
611 sessions,
612 providers,
613 models,
614 daily,
615 hourly,
616 costQuality: {
617 providerReportedShare: records === 0 ? 0 : providerReportedRecords / records,
618 unpricedShare: records === 0 ? 0 : unpricedRecords / records,
619 modelPricedShare:
620 records === 0 ? 0 : (records - providerReportedRecords - unpricedRecords) / records,
621 cacheSavingsUsd,
622 },
623 // Clamped so float error never shows as a negative remainder.
624 categoryCost: {
625 ...categoryCost,
626 unsplit: Math.max(
627 0,
628 costUsd -
629 categoryCost.input -
630 categoryCost.cacheRead -
631 categoryCost.cacheWrite -
632 categoryCost.output,
633 ),
634 },
635 speedCost: {
636 ...speedCost,
637 standard: Math.max(0, costUsd - speedCost.fast - speedCost.ultrafast),
638 },
639 duplicateSources: duplicates,
640 contributingEnvironments,
641 contractMismatches,
642 };
643}