Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usageMerge.ts

452 lines14.4 KB

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 UsageSourceFingerprint,
15 type UsageSummary,
16} from "@t3tools/contracts";
17​
18export interface EnvironmentUsage {
19 readonly environmentId: EnvironmentId;
20 readonly label: string;
21 readonly summary: UsageSummary;
23​
24export interface ProviderTotals {
25 readonly provider: UsageProviderKind;
26 readonly costUsd: number;
27 readonly totalTokens: number;
28 readonly records: number;
29 readonly sessions: number;
30 readonly costShare: number;
31 readonly tokenShare: number;
33​
34export interface ModelTotals {
35 readonly model: string;
36 readonly provider: UsageProviderKind;
37 readonly costUsd: number;
38 readonly totalTokens: number;
39 readonly records: number;
40 /**
41 * Records whose tokens are counted here but which contributed nothing to
42 * `costUsd`. When it equals `records` the cost is unknown, not zero.
43 */
44 readonly unpricedRecords: number;
45 readonly costShare: number;
47​
48/**
49 * A model whose every record lacked rates has an unknown cost, not a zero one.
50 * Clients must not present its `costUsd` as a real dollar figure.
51 */
52export function isModelCostUnknown(model: ModelTotals): boolean {
53 return model.records > 0 && model.unpricedRecords >= model.records;
55​
56export interface DailyTotals {
57 readonly day: string;
58 readonly costUsd: number;
59 readonly totalTokens: number;
60 readonly byProvider: ReadonlyMap<UsageProviderKind, { costUsd: number; totalTokens: number }>;
62​
63export interface HourlyTotals {
64 readonly day: string;
65 readonly hourStart: string;
66 readonly costUsd: number;
67 readonly totalTokens: number;
68 readonly byProvider: ReadonlyMap<UsageProviderKind, { costUsd: number; totalTokens: number }>;
70​
71export interface CostQuality {
72 readonly providerReportedShare: number;
73 readonly modelPricedShare: number;
74 readonly unpricedShare: number;
75 readonly cacheSavingsUsd: number;
77​
78export interface MergedUsage {
79 readonly costUsd: number;
80 readonly uncachedInputTokens: number;
81 readonly cachedInputTokens: number;
82 readonly cacheCreationTokens: number;
83 readonly outputTokens: number;
84 readonly reasoningTokens: number;
85 readonly totalTokens: number;
86 readonly records: number;
87 readonly sessions: number;
88 readonly providers: readonly ProviderTotals[];
89 readonly models: readonly ModelTotals[];
90 readonly daily: readonly DailyTotals[];
91 readonly hourly: readonly HourlyTotals[];
92 readonly costQuality: CostQuality;
93 /** Environments whose data was dropped as a duplicate of another's. */
94 readonly duplicateSources: readonly string[];
95 readonly contributingEnvironments: readonly EnvironmentId[];
96 readonly staleEnvironments: readonly EnvironmentId[];
98​
99/**
100 * Two sources are the same physical transcript directory only when host,
101 * provider, path and filesystem identity all agree.
102 *
103 * `volumeId` is what stops two machines that happen to share a hostname and a
104 * home path, which is every Mac in a fleet, from collapsing into one source and
105 * having one of them silently dropped.
106 */
107function fingerprintKey(fingerprint: UsageSourceFingerprint): string {
108 return [
109 fingerprint.hostId,
110 fingerprint.provider,
111 fingerprint.resolvedHomePath,
112 fingerprint.volumeId,
113 ].join(" ");
115​
116/**
117 * Decides which environment owns each physical transcript directory.
118 *
119 * Several environments on one machine (worktree servers, for instance) resolve
120 * the same provider home and would otherwise double count every token. The
121 * most recently read summary claims a fingerprint; the rest have that provider's
122 * buckets dropped. Environment ids break ties so the winner is stable when
123 * summaries have the same read time.
124 */
125function claimSources(environments: readonly EnvironmentUsage[]): {
126 readonly ownerByFingerprint: ReadonlyMap<string, EnvironmentId>;
127 readonly duplicates: readonly string[];
128} {
129 const ownerByFingerprint = new Map<string, EnvironmentId>();
130 const duplicates: string[] = [];
131​
132 const ordered = [...environments].sort(
133 (a, b) =>
134 (Date.parse(b.summary.readAt) || 0) - (Date.parse(a.summary.readAt) || 0) ||
135 a.environmentId.localeCompare(b.environmentId),
136 );
137​
138 for (const environment of ordered) {
139 for (const source of environment.summary.sources) {
140 if (source.status === "missing") continue;
141 const key = fingerprintKey(source.fingerprint);
142 if (ownerByFingerprint.has(key)) {
143 duplicates.push(`${environment.label}: ${source.fingerprint.resolvedHomePath}`);
144 continue;
145 }
146 ownerByFingerprint.set(key, environment.environmentId);
147 }
148 }
149​
150 return { ownerByFingerprint, duplicates };
152​
153/** Sources this environment owns after fingerprint claims, plus their buckets. */
154function ownedContribution(
155 environment: EnvironmentUsage,
156 ownerByFingerprint: ReadonlyMap<string, EnvironmentId>,
157): {
158 readonly buckets: readonly UsageBucket[];
159 readonly sessionsByProvider: ReadonlyMap<UsageProviderKind, number>;
160} {
161 const ownedProviders = new Set<UsageProviderKind>();
162 const sessionsByProvider = new Map<UsageProviderKind, number>();
163 for (const source of environment.summary.sources) {
164 if (source.status === "missing") continue;
165 const key = fingerprintKey(source.fingerprint);
166 if (ownerByFingerprint.get(key) === environment.environmentId) {
167 const provider = source.fingerprint.provider;
168 ownedProviders.add(provider);
169 // Distinct within a directory. Summing per-bucket session counts instead
170 // would count a session once per day and model it spans.
171 sessionsByProvider.set(
172 provider,
173 (sessionsByProvider.get(provider) ?? 0) + source.distinctSessions,
174 );
175 }
176 }
177 return {
178 buckets: environment.summary.buckets.filter((bucket) => ownedProviders.has(bucket.provider)),
179 sessionsByProvider,
180 };
182​
183function bucketTokens(bucket: UsageBucket): number {
184 // reasoningTokens is a subset of outputTokens and must not be added again.
185 return (
186 bucket.totals.uncachedInputTokens +
187 bucket.totals.cachedInputTokens +
188 bucket.totals.cacheCreationTokens +
189 bucket.totals.outputTokens
190 );
192​
193export function isCompatibleUsageContractVersion(version: number, expected: number): boolean {
194 return version >= USAGE_MERGE_COMPATIBLE_SINCE && version <= expected;
196​
197const EMPTY_MERGED: MergedUsage = {
198 costUsd: 0,
199 uncachedInputTokens: 0,
200 cachedInputTokens: 0,
201 cacheCreationTokens: 0,
202 outputTokens: 0,
203 reasoningTokens: 0,
204 totalTokens: 0,
205 records: 0,
206 sessions: 0,
207 providers: [],
208 models: [],
209 daily: [],
210 hourly: [],
211 costQuality: {
212 providerReportedShare: 0,
213 modelPricedShare: 0,
214 unpricedShare: 0,
215 cacheSavingsUsd: 0,
216 },
217 duplicateSources: [],
218 contributingEnvironments: [],
219 staleEnvironments: [],
220};
221​
222/**
223 * Merges every connected environment's summary.
224 *
225 * `expectedContractVersion` guards against an environment running older server
226 * code: rather than blocking the page, incompatible data is excluded and its
227 * id is reported so the UI can say coverage is partial. Versions in
228 * [{@link USAGE_MERGE_COMPATIBLE_SINCE}, expected] still merge, so an additive
229 * provider expansion does not drop Claude/Codex totals from older servers.
230 */
231export function mergeUsage(
232 environments: readonly EnvironmentUsage[],
233 expectedContractVersion: number,
234): MergedUsage {
235 if (environments.length === 0) return EMPTY_MERGED;
236​
237 const current: EnvironmentUsage[] = [];
238 const staleEnvironments: EnvironmentId[] = [];
239 for (const environment of environments) {
240 if (
241 isCompatibleUsageContractVersion(environment.summary.contractVersion, expectedContractVersion)
242 ) {
243 current.push(environment);
244 } else {
245 staleEnvironments.push(environment.environmentId);
246 }
247 }
248​
249 const { ownerByFingerprint, duplicates } = claimSources(current);
250​
251 let costUsd = 0;
252 let uncachedInputTokens = 0;
253 let cachedInputTokens = 0;
254 let cacheCreationTokens = 0;
255 let outputTokens = 0;
256 let reasoningTokens = 0;
257 let records = 0;
258 let sessions = 0;
259 let cacheSavingsUsd = 0;
260 let providerReportedRecords = 0;
261 let unpricedRecords = 0;
262​
263 const providerAccumulator = new Map<
264 UsageProviderKind,
265 { costUsd: number; totalTokens: number; records: number; sessions: number }
266 >();
267 const modelAccumulator = new Map<
268 string,
269 {
270 provider: UsageProviderKind;
271 costUsd: number;
272 totalTokens: number;
273 records: number;
274 unpricedRecords: number;
275 }
276 >();
277 const dailyAccumulator = new Map<
278 string,
279 {
280 costUsd: number;
281 totalTokens: number;
282 byProvider: Map<UsageProviderKind, { costUsd: number; totalTokens: number }>;
283 }
284 >();
285 const hourlyAccumulator = new Map<
286 string,
287 {
288 day: string;
289 hourStart: string;
290 costUsd: number;
291 totalTokens: number;
292 byProvider: Map<UsageProviderKind, { costUsd: number; totalTokens: number }>;
293 }
294 >();
295 const contributingEnvironments: EnvironmentId[] = [];
296​
297 for (const environment of current) {
298 const { buckets, sessionsByProvider } = ownedContribution(environment, ownerByFingerprint);
299 if (buckets.length > 0) contributingEnvironments.push(environment.environmentId);
300​
301 for (const [providerKind, providerSessions] of sessionsByProvider) {
302 sessions += providerSessions;
303 if (providerSessions === 0) continue;
304 const provider = providerAccumulator.get(providerKind) ?? {
305 costUsd: 0,
306 totalTokens: 0,
307 records: 0,
308 sessions: 0,
309 };
310 provider.sessions += providerSessions;
311 providerAccumulator.set(providerKind, provider);
312 }
313​
314 for (const bucket of buckets) {
315 const tokens = bucketTokens(bucket);
316​
317 costUsd += bucket.costUsd;
318 cacheSavingsUsd += bucket.cacheSavingsUsd;
319 uncachedInputTokens += bucket.totals.uncachedInputTokens;
320 cachedInputTokens += bucket.totals.cachedInputTokens;
321 cacheCreationTokens += bucket.totals.cacheCreationTokens;
322 outputTokens += bucket.totals.outputTokens;
323 reasoningTokens += bucket.totals.reasoningTokens;
324 records += bucket.records;
325 unpricedRecords += bucket.unpricedRecords;
326 if (bucket.costSource === "providerReported") providerReportedRecords += bucket.records;
327​
328 const provider = providerAccumulator.get(bucket.provider) ?? {
329 costUsd: 0,
330 totalTokens: 0,
331 records: 0,
332 sessions: 0,
333 };
334 provider.costUsd += bucket.costUsd;
335 provider.totalTokens += tokens;
336 provider.records += bucket.records;
337 providerAccumulator.set(bucket.provider, provider);
338​
339 const modelKey = `${bucket.provider} ${bucket.model}`;
340 const model = modelAccumulator.get(modelKey) ?? {
341 provider: bucket.provider,
342 costUsd: 0,
343 totalTokens: 0,
344 records: 0,
345 unpricedRecords: 0,
346 };
347 model.costUsd += bucket.costUsd;
348 model.totalTokens += tokens;
349 model.records += bucket.records;
350 model.unpricedRecords += bucket.unpricedRecords;
351 modelAccumulator.set(modelKey, model);
352​
353 const day = dailyAccumulator.get(bucket.day) ?? {
354 costUsd: 0,
355 totalTokens: 0,
356 byProvider: new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(),
357 };
358 day.costUsd += bucket.costUsd;
359 day.totalTokens += tokens;
360 const dayProvider = day.byProvider.get(bucket.provider) ?? { costUsd: 0, totalTokens: 0 };
361 dayProvider.costUsd += bucket.costUsd;
362 dayProvider.totalTokens += tokens;
363 day.byProvider.set(bucket.provider, dayProvider);
364 dailyAccumulator.set(bucket.day, day);
365​
366 if (bucket.hourStart !== undefined) {
367 const hour = hourlyAccumulator.get(bucket.hourStart) ?? {
368 day: bucket.day,
369 hourStart: bucket.hourStart,
370 costUsd: 0,
371 totalTokens: 0,
372 byProvider: new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(),
373 };
374 hour.costUsd += bucket.costUsd;
375 hour.totalTokens += tokens;
376 const hourProvider = hour.byProvider.get(bucket.provider) ?? {
377 costUsd: 0,
378 totalTokens: 0,
379 };
380 hourProvider.costUsd += bucket.costUsd;
381 hourProvider.totalTokens += tokens;
382 hour.byProvider.set(bucket.provider, hourProvider);
383 hourlyAccumulator.set(bucket.hourStart, hour);
384 }
385 }
386 }
387​
388 const totalTokens = uncachedInputTokens + cachedInputTokens + cacheCreationTokens + outputTokens;
389​
390 const providers: ProviderTotals[] = [...providerAccumulator.entries()]
391 .map(([provider, totals]) => ({
392 provider,
393 costUsd: totals.costUsd,
394 totalTokens: totals.totalTokens,
395 records: totals.records,
396 sessions: totals.sessions,
397 costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd,
398 tokenShare: totalTokens === 0 ? 0 : totals.totalTokens / totalTokens,
399 }))
400 .sort((a, b) => b.costUsd - a.costUsd);
401​
402 const models: ModelTotals[] = [...modelAccumulator.entries()]
403 .map(([key, totals]) => ({
404 model: key.slice(key.indexOf(" ") + 1),
405 provider: totals.provider,
406 costUsd: totals.costUsd,
407 totalTokens: totals.totalTokens,
408 records: totals.records,
409 unpricedRecords: totals.unpricedRecords,
410 costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd,
411 }))
412 .sort((a, b) => b.costUsd - a.costUsd || b.totalTokens - a.totalTokens);
413​
414 const daily: DailyTotals[] = [...dailyAccumulator.entries()]
415 .map(([day, totals]) => ({
416 day,
417 costUsd: totals.costUsd,
418 totalTokens: totals.totalTokens,
419 byProvider: totals.byProvider,
420 }))
421 .sort((a, b) => a.day.localeCompare(b.day));
422​
423 const hourly: HourlyTotals[] = [...hourlyAccumulator.values()].sort((a, b) =>
424 a.hourStart.localeCompare(b.hourStart),
425 );
426​
427 return {
428 costUsd,
429 uncachedInputTokens,
430 cachedInputTokens,
431 cacheCreationTokens,
432 outputTokens,
433 reasoningTokens,
434 totalTokens,
435 records,
436 sessions,
437 providers,
438 models,
439 daily,
440 hourly,
441 costQuality: {
442 providerReportedShare: records === 0 ? 0 : providerReportedRecords / records,
443 unpricedShare: records === 0 ? 0 : unpricedRecords / records,
444 modelPricedShare:
445 records === 0 ? 0 : (records - providerReportedRecords - unpricedRecords) / records,
446 cacheSavingsUsd,
447 },
448 duplicateSources: duplicates,
449 contributingEnvironments,
450 staleEnvironments,
451 };