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

usageMerge.ts

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