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

usageAggregation.ts

282 lines9.3 KB

1// @effect-diagnostics globalDate:off
2/**
3 * Folds parsed transcript records into `(day, hourStart?, provider, model)`
4 * buckets.
5 *
6 * `Intl.DateTimeFormat` is the only reliable way to resolve a wall-clock day in
7 * an arbitrary IANA zone, and it takes a `Date`. That is why the raw `Date`
8 * construction is allowed here; nothing in this module reads the clock.
9 *
10 * Pure, so the bucketing and de-duplication rules are testable without touching
11 * the filesystem or the network.
12 *
13 * @module usageAggregation
14 */
15import type {
16 UsageBucket,
17 UsageCategoryCost,
18 UsageDay,
19 UsageResolution,
20 UsageTokenTotals,
21} from "@t3tools/contracts";
22​
23import { addTotals, EMPTY_TOTALS, type UsageRecord } from "./usageTranscripts.ts";
24import { cacheSavingsUsd, priceUsage, type RateTable } from "./usagePricing.ts";
25​
26/**
27 * Formats an instant as a `YYYY-MM-DD` day in `timeZone`.
28 *
29 * `en-CA` yields ISO-ordered parts, which is why it is used here rather than
30 * assembling the day from `Date` getters (those are host-local only).
31 */
32function makeDayFormatter(timeZone: string): (timestampMs: number) => string {
33 let format: Intl.DateTimeFormat;
34 try {
35 format = new Intl.DateTimeFormat("en-CA", {
36 timeZone,
37 year: "numeric",
38 month: "2-digit",
39 day: "2-digit",
40 });
41 } catch {
42 // An unknown zone should degrade to UTC rather than fail the whole scan.
43 format = new Intl.DateTimeFormat("en-CA", {
44 timeZone: "UTC",
45 year: "numeric",
46 month: "2-digit",
47 day: "2-digit",
48 });
49 }
50 return (timestampMs) => format.format(new Date(timestampMs));
52​
53const HOUR_MS = 60 * 60 * 1000;
54​
55interface MutableBucket {
56 totals: UsageTokenTotals;
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 providerReportedRecords: number;
66 sessions: Set<string>;
68​
69export interface AggregateOptions {
70 readonly timeZone: string;
71 readonly sinceDay: string;
72 readonly untilDay: string;
73 readonly rates: RateTable;
74 readonly priceOverrides?: RateTable;
75 readonly resolution?: UsageResolution;
76 readonly sinceTimeMs?: number;
77 readonly untilTimeMs?: number;
79​
80export interface AggregateResult {
81 readonly buckets: readonly UsageBucket[];
82 /** Records dropped because an earlier record carried the same dedupe key. */
83 readonly duplicatesDropped: number;
84 /** Records whose day fell outside the requested window. */
85 readonly outOfWindow: number;
87​
88/**
89 * Accumulates records across many files.
90 *
91 * De-duplication is global across the whole scan, not per file: Claude Code
92 * copies a message's records forward when a session is resumed or forked, so
93 * the same `dedupeKey` legitimately appears in several transcripts.
94 */
95export class UsageAggregator {
96 readonly #buckets = new Map<string, MutableBucket>();
97 readonly #seen = new Set<string>();
98 readonly #toDay: (timestampMs: number) => string;
99 readonly #hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null;
100 readonly #options: AggregateOptions;
101 #duplicatesDropped = 0;
102 #outOfWindow = 0;
103​
104 constructor(options: AggregateOptions) {
105 this.#options = options;
106 this.#toDay = makeDayFormatter(options.timeZone);
107 if (options.resolution === "hour") {
108 if (options.sinceTimeMs === undefined || options.untilTimeMs === undefined) {
109 throw new Error("Hourly usage aggregation requires exact time bounds");
110 }
111 this.#hourlyWindow = {
112 sinceTimeMs: options.sinceTimeMs,
113 untilTimeMs: options.untilTimeMs,
114 };
115 } else {
116 this.#hourlyWindow = null;
117 }
118 }
119​
120 /**
121 * Folds one record in. Returns whether it actually contributed, so callers
122 * can derive per-window facts (distinct sessions, for one) from the records
123 * that landed rather than everything the mtime prefilter happened to admit.
124 */
125 add(record: UsageRecord, sourcePath?: string): boolean {
126 if (record.dedupeKey !== null) {
127 if (this.#seen.has(record.dedupeKey)) {
128 this.#duplicatesDropped += 1;
129 return false;
130 }
131 this.#seen.add(record.dedupeKey);
132 }
133​
134 if (
135 this.#hourlyWindow !== null &&
136 (record.timestampMs < this.#hourlyWindow.sinceTimeMs ||
137 record.timestampMs >= this.#hourlyWindow.untilTimeMs)
138 ) {
139 this.#outOfWindow += 1;
140 return false;
141 }
142​
143 const day = this.#toDay(record.timestampMs);
144 if (
145 this.#hourlyWindow === null &&
146 (day < this.#options.sinceDay || day > this.#options.untilDay)
147 ) {
148 this.#outOfWindow += 1;
149 return false;
150 }
151​
152 const hourStart =
153 this.#hourlyWindow === null
154 ? ""
155 : new Date(
156 this.#hourlyWindow.sinceTimeMs +
157 Math.floor((record.timestampMs - this.#hourlyWindow.sinceTimeMs) / HOUR_MS) * HOUR_MS,
158 ).toISOString();
159 const key = `${day}\u0000${hourStart}\u0000${record.provider}\u0000${record.model}\u0000${sourcePath ?? ""}`;
160 let bucket = this.#buckets.get(key);
161 if (bucket === undefined) {
162 bucket = {
163 totals: EMPTY_TOTALS,
164 costUsd: 0,
165 cacheSavingsUsd: 0,
166 categoryCostUsd: null,
167 fastCostUsd: 0,
168 ultrafastCostUsd: 0,
169 speedPremiumUsd: 0,
170 records: 0,
171 unpricedRecords: 0,
172 providerReportedRecords: 0,
173 sessions: new Set<string>(),
174 };
175 this.#buckets.set(key, bucket);
176 }
177​
178 const priced = priceUsage(this.#options.rates, record, this.#options.priceOverrides);
179​
180 bucket.totals = addTotals(bucket.totals, record.totals);
181 bucket.costUsd += priced.costUsd;
182 if (priced.categoryCostUsd !== null) {
183 const sum = bucket.categoryCostUsd;
184 const add = priced.categoryCostUsd;
185 bucket.categoryCostUsd =
186 sum === null
187 ? add
188 : {
189 input: sum.input + add.input,
190 cacheRead: sum.cacheRead + add.cacheRead,
191 cacheWrite: sum.cacheWrite + add.cacheWrite,
192 output: sum.output + add.output,
193 };
194 }
195 if (record.speed === "fast") bucket.fastCostUsd += priced.costUsd;
196 if (record.speed === "ultrafast") bucket.ultrafastCostUsd += priced.costUsd;
197 bucket.speedPremiumUsd += priced.speedPremiumUsd;
198 bucket.cacheSavingsUsd += cacheSavingsUsd(
199 this.#options.rates,
200 record,
201 this.#options.priceOverrides,
202 );
203 bucket.records += 1;
204 if (priced.costSource === "unpriced") bucket.unpricedRecords += 1;
205 if (priced.costSource === "providerReported") bucket.providerReportedRecords += 1;
206 if (record.sessionId.length > 0) bucket.sessions.add(record.sessionId);
207 return true;
208 }
209​
210 finish(): AggregateResult {
211 const buckets: UsageBucket[] = [];
212 for (const [key, bucket] of this.#buckets) {
213 const [day = "", hourStart = "", provider = "", model = "", sourcePath = ""] =
214 key.split("\u0000");
215 const category = bucket.categoryCostUsd;
216 const fastCostUsd = roundUsd(bucket.fastCostUsd);
217 const ultrafastCostUsd = roundUsd(bucket.ultrafastCostUsd);
218 const speedPremiumUsd = roundUsd(bucket.speedPremiumUsd);
219 buckets.push({
220 day: day as UsageDay,
221 ...(hourStart === "" ? {} : { hourStart }),
222 provider: provider as UsageBucket["provider"],
223 model,
224 ...(sourcePath === "" ? {} : { sourcePath }),
225 totals: bucket.totals,
226 costUsd: bucket.costUsd,
227 cacheSavingsUsd: bucket.cacheSavingsUsd,
228 // Zero and unknown figures are omitted to keep payloads small.
229 ...(category === null
230 ? {}
231 : {
232 categoryCostUsd: {
233 input: roundUsd(category.input),
234 cacheRead: roundUsd(category.cacheRead),
235 cacheWrite: roundUsd(category.cacheWrite),
236 output: roundUsd(category.output),
237 },
238 }),
239 ...(fastCostUsd === 0 ? {} : { fastCostUsd }),
240 ...(ultrafastCostUsd === 0 ? {} : { ultrafastCostUsd }),
241 ...(speedPremiumUsd === 0 ? {} : { speedPremiumUsd }),
242 costSource: resolveCostSource(bucket),
243 records: bucket.records,
244 unpricedRecords: bucket.unpricedRecords,
245 sessions: bucket.sessions.size,
246 });
247 }
248 // Stable ordering keeps payloads diffable and snapshot tests meaningful.
249 buckets.sort(
250 (a, b) =>
251 a.day.localeCompare(b.day) ||
252 (a.hourStart ?? "").localeCompare(b.hourStart ?? "") ||
253 a.provider.localeCompare(b.provider) ||
254 a.model.localeCompare(b.model),
255 );
256​
257 return {
258 buckets,
259 duplicatesDropped: this.#duplicatesDropped,
260 outOfWindow: this.#outOfWindow,
261 };
262 }
264​
265/**
266 * Rounds to micro-dollars. The split and speed figures need no more precision,
267 * and shorter numbers keep them cheap on the wire.
268 */
269function roundUsd(value: number): number {
270 return Math.round(value * 1e6) / 1e6;
272​
273/**
274 * A bucket mixes records from one model, but their cost provenance can differ
275 * when only some records carried a reported cost. The weakest provenance in the
276 * bucket wins so the UI never overstates confidence.
277 */
278function resolveCostSource(bucket: MutableBucket): UsageBucket["costSource"] {
279 if (bucket.unpricedRecords === bucket.records) return "unpriced";
280 if (bucket.providerReportedRecords === bucket.records) return "providerReported";
281 return "modelPriced";