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