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

usageAggregation.ts

484 lines17.0 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 if (
173 b.uncachedInputTokens <= a.uncachedInputTokens &&
174 b.cachedInputTokens <= a.cachedInputTokens &&
175 b.cacheCreationTokens <= a.cacheCreationTokens &&
176 b.outputTokens <= a.outputTokens &&
177 b.reasoningTokens <= a.reasoningTokens &&
178 (copy.cacheCreation1hTokens ?? 0) <= (held.cacheCreation1hTokens ?? 0) &&
179 reportedCostUsd === held.reportedCostUsd
180 ) {
181 return held;
182 }
183 const cacheCreation1hTokens = Math.max(
184 held.cacheCreation1hTokens ?? 0,
185 copy.cacheCreation1hTokens ?? 0,
186 );
187 return {
188 ...held,
189 ...(cacheCreation1hTokens > 0 ? { cacheCreation1hTokens } : {}),
190 totals: {
191 uncachedInputTokens: Math.max(a.uncachedInputTokens, b.uncachedInputTokens),
192 cachedInputTokens: Math.max(a.cachedInputTokens, b.cachedInputTokens),
193 cacheCreationTokens: Math.max(a.cacheCreationTokens, b.cacheCreationTokens),
194 outputTokens: Math.max(a.outputTokens, b.outputTokens),
195 reasoningTokens: Math.max(a.reasoningTokens, b.reasoningTokens),
196 },
197 reportedCostUsd,
198 };
200​
201/**
202 * Grok reports each turn once, complete, so real copies are equal. A larger one is a deleted
203 * transcript's pre-v17 maximum over turns that shared a prompt id, whichever source it came from.
204 */
205function smallestGrokCopy(held: UsageRecord, copy: UsageRecord): UsageRecord {
206 const a = held.totals;
207 const b = copy.totals;
208 const reportedCostUsd =
209 held.reportedCostUsd === null || copy.reportedCostUsd === null
210 ? (held.reportedCostUsd ?? copy.reportedCostUsd)
211 : Math.min(held.reportedCostUsd, copy.reportedCostUsd);
212 return {
213 ...held,
214 totals: {
215 uncachedInputTokens: Math.min(a.uncachedInputTokens, b.uncachedInputTokens),
216 cachedInputTokens: Math.min(a.cachedInputTokens, b.cachedInputTokens),
217 cacheCreationTokens: Math.min(a.cacheCreationTokens, b.cacheCreationTokens),
218 outputTokens: Math.min(a.outputTokens, b.outputTokens),
219 reasoningTokens: Math.min(a.reasoningTokens, b.reasoningTokens),
220 },
221 reportedCostUsd,
222 };
224​
225interface Contribution {
226 record: UsageRecord;
227 /** Null when the first copy fell outside the window. */
228 readonly bucket: MutableBucket | null;
230​
231/** Deduplicates across the whole scan; Claude copies records into resumed/forked transcripts. */
232export class UsageAggregator {
233 readonly #buckets = new Map<string, MutableBucket>();
234 readonly #seen = new Map<string, Contribution>();
235 readonly #toDay: (timestampMs: number) => string;
236 readonly #hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null;
237 readonly #options: AggregateOptions;
238 #lastBucket: {
239 readonly day: string;
240 readonly hourIndex: number;
241 readonly provider: string;
242 readonly model: string;
243 readonly source: string;
244 readonly bucket: MutableBucket;
245 } | null = null;
246 #duplicatesDropped = 0;
247 #outOfWindow = 0;
248​
249 constructor(options: AggregateOptions) {
250 this.#options = options;
251 this.#toDay = makeDayFormatter(options.timeZone);
252 if (options.resolution === "hour") {
253 if (options.sinceTimeMs === undefined || options.untilTimeMs === undefined) {
254 throw new Error("Hourly usage aggregation requires exact time bounds");
255 }
256 this.#hourlyWindow = {
257 sinceTimeMs: options.sinceTimeMs,
258 untilTimeMs: options.untilTimeMs,
259 };
260 } else {
261 this.#hourlyWindow = null;
262 }
263 }
264​
265 add(input: UsageRecord, sourcePath?: string): boolean {
266 if (!keepsUsageRecord(this.#options.modelFilter, input)) return false;
267 const record = this.#mapModel(input);
268 if (record.dedupeKey !== null) {
269 const held = this.#seen.get(record.dedupeKey);
270 if (held !== undefined) {
271 this.#duplicatesDropped += 1;
272 if (held.bucket !== null) {
273 held.record =
274 record.provider === "grok"
275 ? smallestGrokCopy(held.record, record)
276 : mergeUsageCopies(held.record, record);
277 }
278 return false;
279 }
280 }
281​
282 const bucket = this.#placeInWindow(record, sourcePath ?? "");
283 if (record.dedupeKey !== null) this.#seen.set(record.dedupeKey, { record, bucket });
284 if (bucket === null) {
285 this.#outOfWindow += 1;
286 return false;
287 }
288 // Keyed usage is counted in finish(), once all its copies are merged.
289 if (record.dedupeKey === null) this.#accumulate(bucket, record);
290 if (record.sessionId.length > 0) bucket.sessions.add(record.sessionId);
291 return true;
292 }
293​
294 #placeInWindow(record: UsageRecord, source: string): MutableBucket | null {
295 if (
296 this.#hourlyWindow !== null &&
297 (record.timestampMs < this.#hourlyWindow.sinceTimeMs ||
298 record.timestampMs >= this.#hourlyWindow.untilTimeMs)
299 ) {
300 return null;
301 }
302​
303 const day = this.#toDay(record.timestampMs);
304 if (
305 this.#hourlyWindow === null &&
306 (day < this.#options.sinceDay || day > this.#options.untilDay)
307 ) {
308 return null;
309 }
310​
311 const hourIndex =
312 this.#hourlyWindow === null
313 ? -1
314 : Math.floor((record.timestampMs - this.#hourlyWindow.sinceTimeMs) / HOUR_MS);
315 return this.#bucketFor(day, hourIndex, record.provider, record.model, source);
316 }
317​
318 #accumulate(bucket: MutableBucket, record: UsageRecord): void {
319 const priced = priceUsage(this.#options.rates, record, this.#options.priceOverrides);
320​
321 const totals = bucket.totals;
322 totals.uncachedInputTokens += record.totals.uncachedInputTokens;
323 totals.cachedInputTokens += record.totals.cachedInputTokens;
324 totals.cacheCreationTokens += record.totals.cacheCreationTokens;
325 totals.outputTokens += record.totals.outputTokens;
326 totals.reasoningTokens += record.totals.reasoningTokens;
327 bucket.costUsd += priced.costUsd;
328 if (priced.categoryCostUsd !== null) {
329 const sum = bucket.categoryCostUsd;
330 const add = priced.categoryCostUsd;
331 bucket.categoryCostUsd =
332 sum === null
333 ? add
334 : {
335 input: sum.input + add.input,
336 cacheRead: sum.cacheRead + add.cacheRead,
337 cacheWrite: sum.cacheWrite + add.cacheWrite,
338 output: sum.output + add.output,
339 };
340 }
341 if (record.speed === "fast") bucket.fastCostUsd += priced.costUsd;
342 if (record.speed === "ultrafast") bucket.ultrafastCostUsd += priced.costUsd;
343 bucket.speedPremiumUsd += priced.speedPremiumUsd;
344 bucket.cacheSavingsUsd += cacheSavingsUsd(
345 this.#options.rates,
346 record,
347 this.#options.priceOverrides,
348 );
349 bucket.records += 1;
350 if (priced.costSource === "unpriced") {
351 bucket.unpricedRecords += 1;
352 bucket.unpricedTokens +=
353 record.totals.uncachedInputTokens +
354 record.totals.cachedInputTokens +
355 record.totals.cacheCreationTokens +
356 record.totals.outputTokens;
357 }
358 if (priced.costSource === "providerReported") bucket.providerReportedRecords += 1;
359 }
360​
361 // Aliases use the target's rate. Only an unpriced target goes through the provider's own rate naming.
362 #mapModel(record: UsageRecord): UsageRecord {
363 const model = this.#options.modelAliases?.get(record.model);
364 if (model === undefined) return record;
365 const { rateModel: _rateModel, ...rest } = record;
366 const rateModel =
367 lookupRate(this.#options.rates, model) === null
368 ? this.#options.rateModel?.(record.provider, model)
369 : undefined;
370 return rateModel === undefined ? { ...rest, model } : { ...rest, model, rateModel };
371 }
372​
373 // Time-ordered records usually reuse the previous bucket; avoid rebuilding its key.
374 #bucketFor(
375 day: string,
376 hourIndex: number,
377 provider: string,
378 model: string,
379 source: string,
380 ): MutableBucket {
381 const last = this.#lastBucket;
382 if (
383 last !== null &&
384 last.day === day &&
385 last.hourIndex === hourIndex &&
386 last.provider === provider &&
387 last.model === model &&
388 last.source === source
389 ) {
390 return last.bucket;
391 }
392 const window = this.#hourlyWindow;
393 const hourStart =
394 window === null ? "" : new Date(window.sinceTimeMs + hourIndex * HOUR_MS).toISOString();
395 const key = `${day}\u0000${hourStart}\u0000${provider}\u0000${model}\u0000${source}`;
396 let bucket = this.#buckets.get(key);
397 if (bucket === undefined) {
398 bucket = {
399 totals: { ...EMPTY_TOTALS },
400 costUsd: 0,
401 cacheSavingsUsd: 0,
402 categoryCostUsd: null,
403 fastCostUsd: 0,
404 ultrafastCostUsd: 0,
405 speedPremiumUsd: 0,
406 records: 0,
407 unpricedRecords: 0,
408 unpricedTokens: 0,
409 providerReportedRecords: 0,
410 sessions: new Set<string>(),
411 };
412 this.#buckets.set(key, bucket);
413 }
414 this.#lastBucket = { day, hourIndex, provider, model, source, bucket };
415 return bucket;
416 }
417​
418 finish(): AggregateResult {
419 for (const { record, bucket } of this.#seen.values()) {
420 if (bucket !== null) this.#accumulate(bucket, record);
421 }
422 this.#seen.clear();
423 const buckets: UsageBucket[] = [];
424 for (const [key, bucket] of this.#buckets) {
425 const [day = "", hourStart = "", provider = "", model = "", sourcePath = ""] =
426 key.split("\u0000");
427 const category = bucket.categoryCostUsd;
428 const fastCostUsd = roundUsd(bucket.fastCostUsd);
429 const ultrafastCostUsd = roundUsd(bucket.ultrafastCostUsd);
430 const speedPremiumUsd = roundUsd(bucket.speedPremiumUsd);
431 buckets.push({
432 day: day as UsageDay,
433 ...(hourStart === "" ? {} : { hourStart }),
434 provider: provider as UsageBucket["provider"],
435 model,
436 ...(sourcePath === "" ? {} : { sourcePath }),
437 totals: { ...bucket.totals },
438 costUsd: bucket.costUsd,
439 cacheSavingsUsd: bucket.cacheSavingsUsd,
440 ...(category === null
441 ? {}
442 : {
443 categoryCostUsd: {
444 input: roundUsd(category.input),
445 cacheRead: roundUsd(category.cacheRead),
446 cacheWrite: roundUsd(category.cacheWrite),
447 output: roundUsd(category.output),
448 },
449 }),
450 ...(fastCostUsd === 0 ? {} : { fastCostUsd }),
451 ...(ultrafastCostUsd === 0 ? {} : { ultrafastCostUsd }),
452 ...(speedPremiumUsd === 0 ? {} : { speedPremiumUsd }),
453 costSource: resolveCostSource(bucket),
454 records: bucket.records,
455 unpricedRecords: bucket.unpricedRecords,
456 unpricedTokens: bucket.unpricedTokens,
457 sessions: bucket.sessions.size,
458 });
459 }
460 buckets.sort(
461 (a, b) =>
462 a.day.localeCompare(b.day) ||
463 (a.hourStart ?? "").localeCompare(b.hourStart ?? "") ||
464 a.provider.localeCompare(b.provider) ||
465 a.model.localeCompare(b.model),
466 );
467​
468 return {
469 buckets,
470 duplicatesDropped: this.#duplicatesDropped,
471 outOfWindow: this.#outOfWindow,
472 };
473 }
475​
476function roundUsd(value: number): number {
477 return Math.round(value * 1e6) / 1e6;
479​
480function resolveCostSource(bucket: MutableBucket): UsageBucket["costSource"] {
481 if (bucket.unpricedRecords === bucket.records) return "unpriced";
482 if (bucket.providerReportedRecords === bucket.records) return "providerReported";
483 return "modelPriced";