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

usageMerge.ts

448 lines14.3 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 * first environment in a stable order claims a fingerprint; the rest have that
122 * provider's buckets dropped. Environments are sorted by id so the winner does
123 * not change between renders.
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((a, b) => a.environmentId.localeCompare(b.environmentId));
133​
134 for (const environment of ordered) {
135 for (const source of environment.summary.sources) {
136 if (source.status === "missing") continue;
137 const key = fingerprintKey(source.fingerprint);
138 if (ownerByFingerprint.has(key)) {
139 duplicates.push(`${environment.label}: ${source.fingerprint.resolvedHomePath}`);
140 continue;
141 }
142 ownerByFingerprint.set(key, environment.environmentId);
143 }
144 }
145​
146 return { ownerByFingerprint, duplicates };
148​
149/** Sources this environment owns after fingerprint claims, plus their buckets. */
150function ownedContribution(
151 environment: EnvironmentUsage,
152 ownerByFingerprint: ReadonlyMap<string, EnvironmentId>,
153): {
154 readonly buckets: readonly UsageBucket[];
155 readonly sessionsByProvider: ReadonlyMap<UsageProviderKind, number>;
156} {
157 const ownedProviders = new Set<UsageProviderKind>();
158 const sessionsByProvider = new Map<UsageProviderKind, number>();
159 for (const source of environment.summary.sources) {
160 if (source.status === "missing") continue;
161 const key = fingerprintKey(source.fingerprint);
162 if (ownerByFingerprint.get(key) === environment.environmentId) {
163 const provider = source.fingerprint.provider;
164 ownedProviders.add(provider);
165 // Distinct within a directory. Summing per-bucket session counts instead
166 // would count a session once per day and model it spans.
167 sessionsByProvider.set(
168 provider,
169 (sessionsByProvider.get(provider) ?? 0) + source.distinctSessions,
170 );
171 }
172 }
173 return {
174 buckets: environment.summary.buckets.filter((bucket) => ownedProviders.has(bucket.provider)),
175 sessionsByProvider,
176 };
178​
179function bucketTokens(bucket: UsageBucket): number {
180 // reasoningTokens is a subset of outputTokens and must not be added again.
181 return (
182 bucket.totals.uncachedInputTokens +
183 bucket.totals.cachedInputTokens +
184 bucket.totals.cacheCreationTokens +
185 bucket.totals.outputTokens
186 );
188​
189export function isCompatibleUsageContractVersion(version: number, expected: number): boolean {
190 return version >= USAGE_MERGE_COMPATIBLE_SINCE && version <= expected;
192​
193const EMPTY_MERGED: MergedUsage = {
194 costUsd: 0,
195 uncachedInputTokens: 0,
196 cachedInputTokens: 0,
197 cacheCreationTokens: 0,
198 outputTokens: 0,
199 reasoningTokens: 0,
200 totalTokens: 0,
201 records: 0,
202 sessions: 0,
203 providers: [],
204 models: [],
205 daily: [],
206 hourly: [],
207 costQuality: {
208 providerReportedShare: 0,
209 modelPricedShare: 0,
210 unpricedShare: 0,
211 cacheSavingsUsd: 0,
212 },
213 duplicateSources: [],
214 contributingEnvironments: [],
215 staleEnvironments: [],
216};
217​
218/**
219 * Merges every connected environment's summary.
220 *
221 * `expectedContractVersion` guards against an environment running older server
222 * code: rather than blocking the page, incompatible data is excluded and its
223 * id is reported so the UI can say coverage is partial. Versions in
224 * [{@link USAGE_MERGE_COMPATIBLE_SINCE}, expected] still merge, so an additive
225 * provider expansion does not drop Claude/Codex totals from older servers.
226 */
227export function mergeUsage(
228 environments: readonly EnvironmentUsage[],
229 expectedContractVersion: number,
230): MergedUsage {
231 if (environments.length === 0) return EMPTY_MERGED;
232​
233 const current: EnvironmentUsage[] = [];
234 const staleEnvironments: EnvironmentId[] = [];
235 for (const environment of environments) {
236 if (
237 isCompatibleUsageContractVersion(environment.summary.contractVersion, expectedContractVersion)
238 ) {
239 current.push(environment);
240 } else {
241 staleEnvironments.push(environment.environmentId);
242 }
243 }
244​
245 const { ownerByFingerprint, duplicates } = claimSources(current);
246​
247 let costUsd = 0;
248 let uncachedInputTokens = 0;
249 let cachedInputTokens = 0;
250 let cacheCreationTokens = 0;
251 let outputTokens = 0;
252 let reasoningTokens = 0;
253 let records = 0;
254 let sessions = 0;
255 let cacheSavingsUsd = 0;
256 let providerReportedRecords = 0;
257 let unpricedRecords = 0;
258​
259 const providerAccumulator = new Map<
260 UsageProviderKind,
261 { costUsd: number; totalTokens: number; records: number; sessions: number }
262 >();
263 const modelAccumulator = new Map<
264 string,
265 {
266 provider: UsageProviderKind;
267 costUsd: number;
268 totalTokens: number;
269 records: number;
270 unpricedRecords: number;
271 }
272 >();
273 const dailyAccumulator = new Map<
274 string,
275 {
276 costUsd: number;
277 totalTokens: number;
278 byProvider: Map<UsageProviderKind, { costUsd: number; totalTokens: number }>;
279 }
280 >();
281 const hourlyAccumulator = new Map<
282 string,
283 {
284 day: string;
285 hourStart: string;
286 costUsd: number;
287 totalTokens: number;
288 byProvider: Map<UsageProviderKind, { costUsd: number; totalTokens: number }>;
289 }
290 >();
291 const contributingEnvironments: EnvironmentId[] = [];
292​
293 for (const environment of current) {
294 const { buckets, sessionsByProvider } = ownedContribution(environment, ownerByFingerprint);
295 if (buckets.length > 0) contributingEnvironments.push(environment.environmentId);
296​
297 for (const [providerKind, providerSessions] of sessionsByProvider) {
298 sessions += providerSessions;
299 if (providerSessions === 0) continue;
300 const provider = providerAccumulator.get(providerKind) ?? {
301 costUsd: 0,
302 totalTokens: 0,
303 records: 0,
304 sessions: 0,
305 };
306 provider.sessions += providerSessions;
307 providerAccumulator.set(providerKind, provider);
308 }
309​
310 for (const bucket of buckets) {
311 const tokens = bucketTokens(bucket);
312​
313 costUsd += bucket.costUsd;
314 cacheSavingsUsd += bucket.cacheSavingsUsd;
315 uncachedInputTokens += bucket.totals.uncachedInputTokens;
316 cachedInputTokens += bucket.totals.cachedInputTokens;
317 cacheCreationTokens += bucket.totals.cacheCreationTokens;
318 outputTokens += bucket.totals.outputTokens;
319 reasoningTokens += bucket.totals.reasoningTokens;
320 records += bucket.records;
321 unpricedRecords += bucket.unpricedRecords;
322 if (bucket.costSource === "providerReported") providerReportedRecords += bucket.records;
323​
324 const provider = providerAccumulator.get(bucket.provider) ?? {
325 costUsd: 0,
326 totalTokens: 0,
327 records: 0,
328 sessions: 0,
329 };
330 provider.costUsd += bucket.costUsd;
331 provider.totalTokens += tokens;
332 provider.records += bucket.records;
333 providerAccumulator.set(bucket.provider, provider);
334​
335 const modelKey = `${bucket.provider} ${bucket.model}`;
336 const model = modelAccumulator.get(modelKey) ?? {
337 provider: bucket.provider,
338 costUsd: 0,
339 totalTokens: 0,
340 records: 0,
341 unpricedRecords: 0,
342 };
343 model.costUsd += bucket.costUsd;
344 model.totalTokens += tokens;
345 model.records += bucket.records;
346 model.unpricedRecords += bucket.unpricedRecords;
347 modelAccumulator.set(modelKey, model);
348​
349 const day = dailyAccumulator.get(bucket.day) ?? {
350 costUsd: 0,
351 totalTokens: 0,
352 byProvider: new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(),
353 };
354 day.costUsd += bucket.costUsd;
355 day.totalTokens += tokens;
356 const dayProvider = day.byProvider.get(bucket.provider) ?? { costUsd: 0, totalTokens: 0 };
357 dayProvider.costUsd += bucket.costUsd;
358 dayProvider.totalTokens += tokens;
359 day.byProvider.set(bucket.provider, dayProvider);
360 dailyAccumulator.set(bucket.day, day);
361​
362 if (bucket.hourStart !== undefined) {
363 const hour = hourlyAccumulator.get(bucket.hourStart) ?? {
364 day: bucket.day,
365 hourStart: bucket.hourStart,
366 costUsd: 0,
367 totalTokens: 0,
368 byProvider: new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(),
369 };
370 hour.costUsd += bucket.costUsd;
371 hour.totalTokens += tokens;
372 const hourProvider = hour.byProvider.get(bucket.provider) ?? {
373 costUsd: 0,
374 totalTokens: 0,
375 };
376 hourProvider.costUsd += bucket.costUsd;
377 hourProvider.totalTokens += tokens;
378 hour.byProvider.set(bucket.provider, hourProvider);
379 hourlyAccumulator.set(bucket.hourStart, hour);
380 }
381 }
382 }
383​
384 const totalTokens = uncachedInputTokens + cachedInputTokens + cacheCreationTokens + outputTokens;
385​
386 const providers: ProviderTotals[] = [...providerAccumulator.entries()]
387 .map(([provider, totals]) => ({
388 provider,
389 costUsd: totals.costUsd,
390 totalTokens: totals.totalTokens,
391 records: totals.records,
392 sessions: totals.sessions,
393 costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd,
394 tokenShare: totalTokens === 0 ? 0 : totals.totalTokens / totalTokens,
395 }))
396 .sort((a, b) => b.costUsd - a.costUsd);
397​
398 const models: ModelTotals[] = [...modelAccumulator.entries()]
399 .map(([key, totals]) => ({
400 model: key.slice(key.indexOf(" ") + 1),
401 provider: totals.provider,
402 costUsd: totals.costUsd,
403 totalTokens: totals.totalTokens,
404 records: totals.records,
405 unpricedRecords: totals.unpricedRecords,
406 costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd,
407 }))
408 .sort((a, b) => b.costUsd - a.costUsd || b.totalTokens - a.totalTokens);
409​
410 const daily: DailyTotals[] = [...dailyAccumulator.entries()]
411 .map(([day, totals]) => ({
412 day,
413 costUsd: totals.costUsd,
414 totalTokens: totals.totalTokens,
415 byProvider: totals.byProvider,
416 }))
417 .sort((a, b) => a.day.localeCompare(b.day));
418​
419 const hourly: HourlyTotals[] = [...hourlyAccumulator.values()].sort((a, b) =>
420 a.hourStart.localeCompare(b.hourStart),
421 );
422​
423 return {
424 costUsd,
425 uncachedInputTokens,
426 cachedInputTokens,
427 cacheCreationTokens,
428 outputTokens,
429 reasoningTokens,
430 totalTokens,
431 records,
432 sessions,
433 providers,
434 models,
435 daily,
436 hourly,
437 costQuality: {
438 providerReportedShare: records === 0 ? 0 : providerReportedRecords / records,
439 unpricedShare: records === 0 ? 0 : unpricedRecords / records,
440 modelPricedShare:
441 records === 0 ? 0 : (records - providerReportedRecords - unpricedRecords) / records,
442 cacheSavingsUsd,
443 },
444 duplicateSources: duplicates,
445 contributingEnvironments,
446 staleEnvironments,
447 };