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 type {
10 EnvironmentId,
11 UsageBucket,
12 UsageProviderKind,
13 UsageSourceFingerprint,
14 UsageSummary,
15} from "@t3tools/contracts";
16
17export interface EnvironmentUsage {
18 readonly environmentId: EnvironmentId;
19 readonly label: string;
20 readonly summary: UsageSummary;
21}
22
23export interface ProviderTotals {
24 readonly provider: UsageProviderKind;
25 readonly costUsd: number;
26 readonly totalTokens: number;
27 readonly records: number;
28 readonly costShare: number;
29 readonly tokenShare: number;
30}
31
32export interface ModelTotals {
33 readonly model: string;
34 readonly provider: UsageProviderKind;
35 readonly costUsd: number;
36 readonly totalTokens: number;
37 readonly records: number;
38 readonly costShare: number;
39}
40
41export interface DailyTotals {
42 readonly day: string;
43 readonly costUsd: number;
44 readonly totalTokens: number;
45 readonly byProvider: ReadonlyMap<UsageProviderKind, { costUsd: number; totalTokens: number }>;
46}
47
48export interface CostQuality {
49 readonly providerReportedShare: number;
50 readonly modelPricedShare: number;
51 readonly unpricedShare: number;
52 readonly cacheSavingsUsd: number;
53}
54
55export interface MergedUsage {
56 readonly costUsd: number;
57 readonly uncachedInputTokens: number;
58 readonly cachedInputTokens: number;
59 readonly cacheCreationTokens: number;
60 readonly outputTokens: number;
61 readonly reasoningTokens: number;
62 readonly totalTokens: number;
63 readonly records: number;
64 readonly sessions: number;
65 readonly providers: readonly ProviderTotals[];
66 readonly models: readonly ModelTotals[];
67 readonly daily: readonly DailyTotals[];
68 readonly costQuality: CostQuality;
69 /** Environments whose data was dropped as a duplicate of another's. */
70 readonly duplicateSources: readonly string[];
71 readonly contributingEnvironments: readonly EnvironmentId[];
72 readonly staleEnvironments: readonly EnvironmentId[];
73}
74
75/**
76 * Two sources are the same physical transcript directory only when host,
77 * provider, path and filesystem identity all agree.
78 *
79 * `volumeId` is what stops two machines that happen to share a hostname and a
80 * home path, which is every Mac in a fleet, from collapsing into one source and
81 * having one of them silently dropped.
82 */
83function fingerprintKey(fingerprint: UsageSourceFingerprint): string {
84 return [
85 fingerprint.hostId,
86 fingerprint.provider,
87 fingerprint.resolvedHomePath,
88 fingerprint.volumeId,
89 ].join(" ");
90}
91
92/**
93 * Decides which environment owns each physical transcript directory.
94 *
95 * Several environments on one machine (worktree servers, for instance) resolve
96 * the same provider home and would otherwise double count every token. The
97 * first environment in a stable order claims a fingerprint; the rest have that
98 * provider's buckets dropped. Environments are sorted by id so the winner does
99 * not change between renders.
100 */
101function claimSources(environments: readonly EnvironmentUsage[]): {
102 readonly ownerByFingerprint: ReadonlyMap<string, EnvironmentId>;
103 readonly duplicates: readonly string[];
104} {
105 const ownerByFingerprint = new Map<string, EnvironmentId>();
106 const duplicates: string[] = [];
107
108 const ordered = [...environments].sort((a, b) => a.environmentId.localeCompare(b.environmentId));
109
110 for (const environment of ordered) {
111 for (const source of environment.summary.sources) {
112 if (source.status === "missing") continue;
113 const key = fingerprintKey(source.fingerprint);
114 if (ownerByFingerprint.has(key)) {
115 duplicates.push(`${environment.label}: ${source.fingerprint.resolvedHomePath}`);
116 continue;
117 }
118 ownerByFingerprint.set(key, environment.environmentId);
119 }
120 }
121
122 return { ownerByFingerprint, duplicates };
123}
124
125/** Sources this environment owns after fingerprint claims, plus their buckets. */
126function ownedContribution(
127 environment: EnvironmentUsage,
128 ownerByFingerprint: ReadonlyMap<string, EnvironmentId>,
129): { readonly buckets: readonly UsageBucket[]; readonly sessions: number } {
130 const ownedProviders = new Set<UsageProviderKind>();
131 let sessions = 0;
132 for (const source of environment.summary.sources) {
133 if (source.status === "missing") continue;
134 const key = fingerprintKey(source.fingerprint);
135 if (ownerByFingerprint.get(key) === environment.environmentId) {
136 ownedProviders.add(source.fingerprint.provider);
137 // Distinct within a directory. Summing per-bucket session counts instead
138 // would count a session once per day and model it spans.
139 sessions += source.distinctSessions;
140 }
141 }
142 return {
143 buckets: environment.summary.buckets.filter((bucket) => ownedProviders.has(bucket.provider)),
144 sessions,
145 };
146}
147
148function bucketTokens(bucket: UsageBucket): number {
149 // reasoningTokens is a subset of outputTokens and must not be added again.
150 return (
151 bucket.totals.uncachedInputTokens +
152 bucket.totals.cachedInputTokens +
153 bucket.totals.cacheCreationTokens +
154 bucket.totals.outputTokens
155 );
156}
157
158const EMPTY_MERGED: MergedUsage = {
159 costUsd: 0,
160 uncachedInputTokens: 0,
161 cachedInputTokens: 0,
162 cacheCreationTokens: 0,
163 outputTokens: 0,
164 reasoningTokens: 0,
165 totalTokens: 0,
166 records: 0,
167 sessions: 0,
168 providers: [],
169 models: [],
170 daily: [],
171 costQuality: {
172 providerReportedShare: 0,
173 modelPricedShare: 0,
174 unpricedShare: 0,
175 cacheSavingsUsd: 0,
176 },
177 duplicateSources: [],
178 contributingEnvironments: [],
179 staleEnvironments: [],
180};
181
182/**
183 * Merges every connected environment's summary.
184 *
185 * `expectedContractVersion` guards against an environment running older server
186 * code: rather than blocking the page, its data is excluded and its id is
187 * reported so the UI can say coverage is partial.
188 */
189export function mergeUsage(
190 environments: readonly EnvironmentUsage[],
191 expectedContractVersion: number,
192): MergedUsage {
193 if (environments.length === 0) return EMPTY_MERGED;
194
195 const current: EnvironmentUsage[] = [];
196 const staleEnvironments: EnvironmentId[] = [];
197 for (const environment of environments) {
198 if (environment.summary.contractVersion === expectedContractVersion) {
199 current.push(environment);
200 } else {
201 staleEnvironments.push(environment.environmentId);
202 }
203 }
204
205 const { ownerByFingerprint, duplicates } = claimSources(current);
206
207 let costUsd = 0;
208 let uncachedInputTokens = 0;
209 let cachedInputTokens = 0;
210 let cacheCreationTokens = 0;
211 let outputTokens = 0;
212 let reasoningTokens = 0;
213 let records = 0;
214 let sessions = 0;
215 let cacheSavingsUsd = 0;
216 let providerReportedRecords = 0;
217 let unpricedRecords = 0;
218
219 const providerAccumulator = new Map<
220 UsageProviderKind,
221 { costUsd: number; totalTokens: number; records: number }
222 >();
223 const modelAccumulator = new Map<
224 string,
225 { provider: UsageProviderKind; costUsd: number; totalTokens: number; records: number }
226 >();
227 const dailyAccumulator = new Map<
228 string,
229 {
230 costUsd: number;
231 totalTokens: number;
232 byProvider: Map<UsageProviderKind, { costUsd: number; totalTokens: number }>;
233 }
234 >();
235 const contributingEnvironments: EnvironmentId[] = [];
236
237 for (const environment of current) {
238 const { buckets, sessions: environmentSessions } = ownedContribution(
239 environment,
240 ownerByFingerprint,
241 );
242 if (buckets.length > 0) contributingEnvironments.push(environment.environmentId);
243 sessions += environmentSessions;
244
245 for (const bucket of buckets) {
246 const tokens = bucketTokens(bucket);
247
248 costUsd += bucket.costUsd;
249 cacheSavingsUsd += bucket.cacheSavingsUsd;
250 uncachedInputTokens += bucket.totals.uncachedInputTokens;
251 cachedInputTokens += bucket.totals.cachedInputTokens;
252 cacheCreationTokens += bucket.totals.cacheCreationTokens;
253 outputTokens += bucket.totals.outputTokens;
254 reasoningTokens += bucket.totals.reasoningTokens;
255 records += bucket.records;
256 unpricedRecords += bucket.unpricedRecords;
257 if (bucket.costSource === "providerReported") providerReportedRecords += bucket.records;
258
259 const provider = providerAccumulator.get(bucket.provider) ?? {
260 costUsd: 0,
261 totalTokens: 0,
262 records: 0,
263 };
264 provider.costUsd += bucket.costUsd;
265 provider.totalTokens += tokens;
266 provider.records += bucket.records;
267 providerAccumulator.set(bucket.provider, provider);
268
269 const modelKey = `${bucket.provider} ${bucket.model}`;
270 const model = modelAccumulator.get(modelKey) ?? {
271 provider: bucket.provider,
272 costUsd: 0,
273 totalTokens: 0,
274 records: 0,
275 };
276 model.costUsd += bucket.costUsd;
277 model.totalTokens += tokens;
278 model.records += bucket.records;
279 modelAccumulator.set(modelKey, model);
280
281 const day = dailyAccumulator.get(bucket.day) ?? {
282 costUsd: 0,
283 totalTokens: 0,
284 byProvider: new Map<UsageProviderKind, { costUsd: number; totalTokens: number }>(),
285 };
286 day.costUsd += bucket.costUsd;
287 day.totalTokens += tokens;
288 const dayProvider = day.byProvider.get(bucket.provider) ?? { costUsd: 0, totalTokens: 0 };
289 dayProvider.costUsd += bucket.costUsd;
290 dayProvider.totalTokens += tokens;
291 day.byProvider.set(bucket.provider, dayProvider);
292 dailyAccumulator.set(bucket.day, day);
293 }
294 }
295
296 const totalTokens = uncachedInputTokens + cachedInputTokens + cacheCreationTokens + outputTokens;
297
298 const providers: ProviderTotals[] = [...providerAccumulator.entries()]
299 .map(([provider, totals]) => ({
300 provider,
301 costUsd: totals.costUsd,
302 totalTokens: totals.totalTokens,
303 records: totals.records,
304 costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd,
305 tokenShare: totalTokens === 0 ? 0 : totals.totalTokens / totalTokens,
306 }))
307 .sort((a, b) => b.costUsd - a.costUsd);
308
309 const models: ModelTotals[] = [...modelAccumulator.entries()]
310 .map(([key, totals]) => ({
311 model: key.slice(key.indexOf(" ") + 1),
312 provider: totals.provider,
313 costUsd: totals.costUsd,
314 totalTokens: totals.totalTokens,
315 records: totals.records,
316 costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd,
317 }))
318 .sort((a, b) => b.costUsd - a.costUsd || b.totalTokens - a.totalTokens);
319
320 const daily: DailyTotals[] = [...dailyAccumulator.entries()]
321 .map(([day, totals]) => ({
322 day,
323 costUsd: totals.costUsd,
324 totalTokens: totals.totalTokens,
325 byProvider: totals.byProvider,
326 }))
327 .sort((a, b) => a.day.localeCompare(b.day));
328
329 return {
330 costUsd,
331 uncachedInputTokens,
332 cachedInputTokens,
333 cacheCreationTokens,
334 outputTokens,
335 reasoningTokens,
336 totalTokens,
337 records,
338 sessions,
339 providers,
340 models,
341 daily,
342 costQuality: {
343 providerReportedShare: records === 0 ? 0 : providerReportedRecords / records,
344 unpricedShare: records === 0 ? 0 : unpricedRecords / records,
345 modelPricedShare:
346 records === 0 ? 0 : (records - providerReportedRecords - unpricedRecords) / records,
347 cacheSavingsUsd,
348 },
349 duplicateSources: duplicates,
350 contributingEnvironments,
351 staleEnvironments,
352 };
353}