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

usageAggregation.ts

494 lines17.5 KB

1// @effect-diagnostics globalDate:off
2import type {
3 UsageBucket,
4 UsageCategoryCost,
5 UsageDay,
6 UsageModelFilter,
7 UsageModelSelector,
8 UsageResolution,
9 UsageTokenTotals,
10} from "@t3tools/contracts";
11​
12import { EMPTY_TOTALS, type UsageRecord } from "@t3tools/provider-core/server/usage";
13import { cacheSavingsUsd, lookupRate, priceUsage, type RateTable } from "./usagePricing.ts";
14​
15// en-CA gives ISO-ordered parts in the requested zone; Date getters are host-local.
16function makeDayFormatter(timeZone: string): (timestampMs: number) => string {
17 let format: Intl.DateTimeFormat;
18 try {
19 format = new Intl.DateTimeFormat("en-CA", {
20 timeZone,
21 year: "numeric",
22 month: "2-digit",
23 day: "2-digit",
24 });
25 } catch {
26 format = new Intl.DateTimeFormat("en-CA", {
27 timeZone: "UTC",
28 year: "numeric",
29 month: "2-digit",
30 day: "2-digit",
31 });
32 }
33 // Cache quarter-hour slots to avoid per-record Intl calls; fixed-offset midnight can split slots and needs exact formatting.
34 const days = new Map<number, string | null>();
35 return (timestampMs) => {
36 const slot = Math.floor(timestampMs / QUARTER_HOUR_MS);
37 let day = days.get(slot);
38 if (day === undefined) {
39 const first = format.format(new Date(slot * QUARTER_HOUR_MS));
40 const last = format.format(new Date((slot + 1) * QUARTER_HOUR_MS - 1));
41 day = first === last ? first : null;
42 days.set(slot, day);
43 }
44 return day ?? format.format(new Date(timestampMs));
45 };
47​
48const QUARTER_HOUR_MS = 15 * 60 * 1000;
49const HOUR_MS = 60 * 60 * 1000;
50​
51interface MutableBucket {
52 totals: { -readonly [K in keyof UsageTokenTotals]: number };
53 costUsd: number;
54 cacheSavingsUsd: number;
55 categoryCostUsd: UsageCategoryCost | null;
56 fastCostUsd: number;
57 ultrafastCostUsd: number;
58 speedPremiumUsd: number;
59 records: number;
60 unpricedRecords: number;
61 unpricedTokens: number;
62 providerReportedRecords: number;
63 sessions: Set<string>;
65​
66export interface AggregateOptions {
67 readonly timeZone: string;
68 readonly sinceDay: string;
69 readonly untilDay: string;
70 readonly rates: RateTable;
71 readonly priceOverrides?: RateTable;
72 readonly modelAliases?: ReadonlyMap<string, string>;
73 readonly rateModel?: (provider: UsageRecord["provider"], model: string) => string | undefined;
74 readonly modelFilter?: UsageModelFilter;
75 readonly resolution?: UsageResolution;
76 readonly sinceTimeMs?: number;
77 readonly untilTimeMs?: number;
79​
80export function usageTimestampFilter(
81 options: Pick<
82 AggregateOptions,
83 "timeZone" | "sinceDay" | "untilDay" | "sinceTimeMs" | "untilTimeMs"
84 >,
85) {
86 const toDay = makeDayFormatter(options.timeZone);
87 return (timestampMs: number) => {
88 if (options.sinceTimeMs !== undefined && options.untilTimeMs !== undefined) {
89 return timestampMs >= options.sinceTimeMs && timestampMs < options.untilTimeMs;
90 }
91 const day = toDay(timestampMs);
92 return day >= options.sinceDay && day <= options.untilDay;
93 };
95​
96export function resolveModelAliases(
97 aliases: Readonly<Record<string, string>>,
98): ReadonlyMap<string, string> {
99 const models = Object.keys(aliases);
100 const memo = new Map<string, string | null>();
101 for (const model of models) {
102 if (memo.has(model)) continue;
103 const path: string[] = [];
104 let target = model;
105 while (Object.hasOwn(aliases, target) && !memo.has(target)) {
106 path.push(target);
107 // Null marks both the active walk and paths that end in a cycle.
108 memo.set(target, null);
109 target = aliases[target]!;
110 }
111 const terminal = Object.hasOwn(aliases, target) ? (memo.get(target) ?? null) : target;
112 for (const alias of path) memo.set(alias, terminal);
113 }
114​
115 const resolved = new Map<string, string>();
116 for (const model of models) {
117 const target = memo.get(model);
118 if (target !== null && target !== undefined) resolved.set(model, target);
119 }
120 return resolved;
122​
123/** Matches original IDs, so an alias cannot pull excluded usage into a kept model. */
124function keepsUsageRecord(filter: UsageModelFilter | undefined, record: UsageRecord): boolean {
125 if (filter === undefined) return true;
126 const model = record.model.trim();
127 const matches = (selector: UsageModelSelector) =>
128 selector.model === model &&
129 (selector.provider === undefined || selector.provider === record.provider);
130 return (filter.include?.some(matches) ?? true) && !(filter.exclude?.some(matches) ?? false);
132​
133const selectorKey = (selector: UsageModelSelector) =>
134 JSON.stringify([selector.provider ?? null, selector.model]);
135​
136const canonicalSelectors = (selectors: readonly UsageModelSelector[]) =>
137 [...new Map(selectors.map((selector) => [selectorKey(selector), selector]))]
138 // Code-unit order, so servers in different locales echo the same form.
139 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
140 .map(([, selector]) => selector);
141​
142/** Equal filters get one form, so they share scans and clients can compare echoed filters. */
143export function canonicalModelFilter(
144 filter: UsageModelFilter | undefined,
145): UsageModelFilter | undefined {
146 if (filter === undefined) return undefined;
147 const exclude = filter.exclude?.length ? canonicalSelectors(filter.exclude) : undefined;
148 if (filter.include === undefined && exclude === undefined) return undefined;
149 return {
150 ...(filter.include === undefined ? {} : { include: canonicalSelectors(filter.include) }),
151 ...(exclude === undefined ? {} : { exclude }),
152 };
154​
155export interface AggregateResult {
156 readonly buckets: readonly UsageBucket[];
157 readonly duplicatesDropped: number;
158 readonly outOfWindow: number;
160​
161/**
162 * Partial copies share a billed message's key: keep each token channel's maximum and the larger
163 * reported cost, and the first copy's time, model, session and speed so it stays in its bucket.
164 */
165export function mergeUsageCopies(held: UsageRecord, copy: UsageRecord): UsageRecord {
166 const a = held.totals;
167 const b = copy.totals;
168 const reportedCostUsd =
169 held.reportedCostUsd === null || copy.reportedCostUsd === null
170 ? (held.reportedCostUsd ?? copy.reportedCostUsd)
171 : Math.max(held.reportedCostUsd, copy.reportedCostUsd);
172 const heldModelCalls = held.modelCalls ?? 0;
173 const copyModelCalls = copy.modelCalls ?? 0;
174 const modelCalls = Math.max(heldModelCalls, copyModelCalls);
175 if (
176 b.uncachedInputTokens <= a.uncachedInputTokens &&
177 b.cachedInputTokens <= a.cachedInputTokens &&
178 b.cacheCreationTokens <= a.cacheCreationTokens &&
179 b.outputTokens <= a.outputTokens &&
180 b.reasoningTokens <= a.reasoningTokens &&
181 (copy.cacheCreation1hTokens ?? 0) <= (held.cacheCreation1hTokens ?? 0) &&
182 copyModelCalls <= heldModelCalls &&
183 reportedCostUsd === held.reportedCostUsd
184 ) {
185 return held;
186 }
187 const cacheCreation1hTokens = Math.max(
188 held.cacheCreation1hTokens ?? 0,
189 copy.cacheCreation1hTokens ?? 0,
190 );
191 return {
192 ...held,
193 ...(cacheCreation1hTokens > 0 ? { cacheCreation1hTokens } : {}),
194 ...(modelCalls > 1 ? { modelCalls } : {}),
195 totals: {
196 uncachedInputTokens: Math.max(a.uncachedInputTokens, b.uncachedInputTokens),
197 cachedInputTokens: Math.max(a.cachedInputTokens, b.cachedInputTokens),
198 cacheCreationTokens: Math.max(a.cacheCreationTokens, b.cacheCreationTokens),
199 outputTokens: Math.max(a.outputTokens, b.outputTokens),
200 reasoningTokens: Math.max(a.reasoningTokens, b.reasoningTokens),
201 },
202 reportedCostUsd,
203 };
205​
206/**
207 * Grok reports each turn once, complete, so real copies are equal. A larger one is a deleted
208 * transcript's pre-v17 maximum over turns that shared a prompt id, whichever source it came from.
209 */
210function smallestGrokCopy(held: UsageRecord, copy: UsageRecord): UsageRecord {
211 const a = held.totals;
212 const b = copy.totals;
213 const reportedCostUsd =
214 held.reportedCostUsd === null || copy.reportedCostUsd === null
215 ? (held.reportedCostUsd ?? copy.reportedCostUsd)
216 : Math.min(held.reportedCostUsd, copy.reportedCostUsd);
217 const modelCalls =
218 held.modelCalls !== undefined && copy.modelCalls !== undefined
219 ? Math.min(held.modelCalls, copy.modelCalls)
220 : (held.modelCalls ?? copy.modelCalls);
221 return {
222 ...held,
223 ...(modelCalls !== undefined && modelCalls > 1 ? { modelCalls } : {}),
224 totals: {
225 uncachedInputTokens: Math.min(a.uncachedInputTokens, b.uncachedInputTokens),
226 cachedInputTokens: Math.min(a.cachedInputTokens, b.cachedInputTokens),
227 cacheCreationTokens: Math.min(a.cacheCreationTokens, b.cacheCreationTokens),
228 outputTokens: Math.min(a.outputTokens, b.outputTokens),
229 reasoningTokens: Math.min(a.reasoningTokens, b.reasoningTokens),
230 },
231 reportedCostUsd,
232 };
234​
235interface Contribution {
236 record: UsageRecord;
237 /** Null when the first copy fell outside the window. */
238 readonly bucket: MutableBucket | null;
240​
241/** Deduplicates across the whole scan; Claude copies records into resumed/forked transcripts. */
242export class UsageAggregator {
243 readonly #buckets = new Map<string, MutableBucket>();
244 readonly #seen = new Map<string, Contribution>();
245 readonly #toDay: (timestampMs: number) => string;
246 readonly #hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null;
247 readonly #options: AggregateOptions;
248 #lastBucket: {
249 readonly day: string;
250 readonly hourIndex: number;
251 readonly provider: string;
252 readonly model: string;
253 readonly source: string;
254 readonly bucket: MutableBucket;
255 } | null = null;
256 #duplicatesDropped = 0;
257 #outOfWindow = 0;
258​
259 constructor(options: AggregateOptions) {
260 this.#options = options;
261 this.#toDay = makeDayFormatter(options.timeZone);
262 if (options.resolution === "hour") {
263 if (options.sinceTimeMs === undefined || options.untilTimeMs === undefined) {
264 throw new Error("Hourly usage aggregation requires exact time bounds");
265 }
266 this.#hourlyWindow = {
267 sinceTimeMs: options.sinceTimeMs,
268 untilTimeMs: options.untilTimeMs,
269 };
270 } else {
271 this.#hourlyWindow = null;
272 }
273 }
274​
275 add(input: UsageRecord, sourcePath?: string): boolean {
276 if (!keepsUsageRecord(this.#options.modelFilter, input)) return false;
277 const record = this.#mapModel(input);
278 if (record.dedupeKey !== null) {
279 const held = this.#seen.get(record.dedupeKey);
280 if (held !== undefined) {
281 this.#duplicatesDropped += 1;
282 if (held.bucket !== null) {
283 held.record =
284 record.provider === "grok"
285 ? smallestGrokCopy(held.record, record)
286 : mergeUsageCopies(held.record, record);
287 }
288 return false;
289 }
290 }
291​
292 const bucket = this.#placeInWindow(record, sourcePath ?? "");
293 if (record.dedupeKey !== null) this.#seen.set(record.dedupeKey, { record, bucket });
294 if (bucket === null) {
295 this.#outOfWindow += 1;
296 return false;
297 }
298 // Keyed usage is counted in finish(), once all its copies are merged.
299 if (record.dedupeKey === null) this.#accumulate(bucket, record);
300 if (record.sessionId.length > 0) bucket.sessions.add(record.sessionId);
301 return true;
302 }
303​
304 #placeInWindow(record: UsageRecord, source: string): MutableBucket | null {
305 if (
306 this.#hourlyWindow !== null &&
307 (record.timestampMs < this.#hourlyWindow.sinceTimeMs ||
308 record.timestampMs >= this.#hourlyWindow.untilTimeMs)
309 ) {
310 return null;
311 }
312​
313 const day = this.#toDay(record.timestampMs);
314 if (
315 this.#hourlyWindow === null &&
316 (day < this.#options.sinceDay || day > this.#options.untilDay)
317 ) {
318 return null;
319 }
320​
321 const hourIndex =
322 this.#hourlyWindow === null
323 ? -1
324 : Math.floor((record.timestampMs - this.#hourlyWindow.sinceTimeMs) / HOUR_MS);
325 return this.#bucketFor(day, hourIndex, record.provider, record.model, source);
326 }
327​
328 #accumulate(bucket: MutableBucket, record: UsageRecord): void {
329 const priced = priceUsage(this.#options.rates, record, this.#options.priceOverrides);
330​
331 const totals = bucket.totals;
332 totals.uncachedInputTokens += record.totals.uncachedInputTokens;
333 totals.cachedInputTokens += record.totals.cachedInputTokens;
334 totals.cacheCreationTokens += record.totals.cacheCreationTokens;
335 totals.outputTokens += record.totals.outputTokens;
336 totals.reasoningTokens += record.totals.reasoningTokens;
337 bucket.costUsd += priced.costUsd;
338 if (priced.categoryCostUsd !== null) {
339 const sum = bucket.categoryCostUsd;
340 const add = priced.categoryCostUsd;
341 bucket.categoryCostUsd =
342 sum === null
343 ? add
344 : {
345 input: sum.input + add.input,
346 cacheRead: sum.cacheRead + add.cacheRead,
347 cacheWrite: sum.cacheWrite + add.cacheWrite,
348 output: sum.output + add.output,
349 };
350 }
351 if (record.speed === "fast") bucket.fastCostUsd += priced.costUsd;
352 if (record.speed === "ultrafast") bucket.ultrafastCostUsd += priced.costUsd;
353 bucket.speedPremiumUsd += priced.speedPremiumUsd;
354 bucket.cacheSavingsUsd += cacheSavingsUsd(
355 this.#options.rates,
356 record,
357 this.#options.priceOverrides,
358 );
359 bucket.records += 1;
360 if (priced.costSource === "unpriced") {
361 bucket.unpricedRecords += 1;
362 bucket.unpricedTokens +=
363 record.totals.uncachedInputTokens +
364 record.totals.cachedInputTokens +
365 record.totals.cacheCreationTokens +
366 record.totals.outputTokens;
367 }
368 if (priced.costSource === "providerReported") bucket.providerReportedRecords += 1;
369 }
370​
371 // Aliases use the target's rate. Only an unpriced target goes through the provider's own rate naming.
372 #mapModel(record: UsageRecord): UsageRecord {
373 const model = this.#options.modelAliases?.get(record.model);
374 if (model === undefined) return record;
375 const { rateModel: _rateModel, ...rest } = record;
376 const rateModel =
377 lookupRate(this.#options.rates, model) === null
378 ? this.#options.rateModel?.(record.provider, model)
379 : undefined;
380 return rateModel === undefined ? { ...rest, model } : { ...rest, model, rateModel };
381 }
382​
383 // Time-ordered records usually reuse the previous bucket; avoid rebuilding its key.
384 #bucketFor(
385 day: string,
386 hourIndex: number,
387 provider: string,
388 model: string,
389 source: string,
390 ): MutableBucket {
391 const last = this.#lastBucket;
392 if (
393 last !== null &&
394 last.day === day &&
395 last.hourIndex === hourIndex &&
396 last.provider === provider &&
397 last.model === model &&
398 last.source === source
399 ) {
400 return last.bucket;
401 }
402 const window = this.#hourlyWindow;
403 const hourStart =
404 window === null ? "" : new Date(window.sinceTimeMs + hourIndex * HOUR_MS).toISOString();
405 const key = `${day}\u0000${hourStart}\u0000${provider}\u0000${model}\u0000${source}`;
406 let bucket = this.#buckets.get(key);
407 if (bucket === undefined) {
408 bucket = {
409 totals: { ...EMPTY_TOTALS },
410 costUsd: 0,
411 cacheSavingsUsd: 0,
412 categoryCostUsd: null,
413 fastCostUsd: 0,
414 ultrafastCostUsd: 0,
415 speedPremiumUsd: 0,
416 records: 0,
417 unpricedRecords: 0,
418 unpricedTokens: 0,
419 providerReportedRecords: 0,
420 sessions: new Set<string>(),
421 };
422 this.#buckets.set(key, bucket);
423 }
424 this.#lastBucket = { day, hourIndex, provider, model, source, bucket };
425 return bucket;
426 }
427​
428 finish(): AggregateResult {
429 for (const { record, bucket } of this.#seen.values()) {
430 if (bucket !== null) this.#accumulate(bucket, record);
431 }
432 this.#seen.clear();
433 const buckets: UsageBucket[] = [];
434 for (const [key, bucket] of this.#buckets) {
435 const [day = "", hourStart = "", provider = "", model = "", sourcePath = ""] =
436 key.split("\u0000");
437 const category = bucket.categoryCostUsd;
438 const fastCostUsd = roundUsd(bucket.fastCostUsd);
439 const ultrafastCostUsd = roundUsd(bucket.ultrafastCostUsd);
440 const speedPremiumUsd = roundUsd(bucket.speedPremiumUsd);
441 buckets.push({
442 day: day as UsageDay,
443 ...(hourStart === "" ? {} : { hourStart }),
444 provider: provider as UsageBucket["provider"],
445 model,
446 ...(sourcePath === "" ? {} : { sourcePath }),
447 totals: { ...bucket.totals },
448 costUsd: bucket.costUsd,
449 cacheSavingsUsd: bucket.cacheSavingsUsd,
450 ...(category === null
451 ? {}
452 : {
453 categoryCostUsd: {
454 input: roundUsd(category.input),
455 cacheRead: roundUsd(category.cacheRead),
456 cacheWrite: roundUsd(category.cacheWrite),
457 output: roundUsd(category.output),
458 },
459 }),
460 ...(fastCostUsd === 0 ? {} : { fastCostUsd }),
461 ...(ultrafastCostUsd === 0 ? {} : { ultrafastCostUsd }),
462 ...(speedPremiumUsd === 0 ? {} : { speedPremiumUsd }),
463 costSource: resolveCostSource(bucket),
464 records: bucket.records,
465 unpricedRecords: bucket.unpricedRecords,
466 unpricedTokens: bucket.unpricedTokens,
467 sessions: bucket.sessions.size,
468 });
469 }
470 buckets.sort(
471 (a, b) =>
472 a.day.localeCompare(b.day) ||
473 (a.hourStart ?? "").localeCompare(b.hourStart ?? "") ||
474 a.provider.localeCompare(b.provider) ||
475 a.model.localeCompare(b.model),
476 );
477​
478 return {
479 buckets,
480 duplicatesDropped: this.#duplicatesDropped,
481 outOfWindow: this.#outOfWindow,
482 };
483 }
485​
486function roundUsd(value: number): number {
487 return Math.round(value * 1e6) / 1e6;
489​
490function resolveCostSource(bucket: MutableBucket): UsageBucket["costSource"] {
491 if (bucket.unpricedRecords === bucket.records) return "unpriced";
492 if (bucket.providerReportedRecords === bucket.records) return "providerReported";
493 return "modelPriced";