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

usageMerge.ts

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