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

usageMerge.ts

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