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

usageAggregation.ts

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