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

usageMerge.ts

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