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

usageAggregation.ts

233 lines7.5 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 { UsageBucket, UsageDay, UsageResolution, UsageTokenTotals } from "@t3tools/contracts";
16​
17import { addTotals, EMPTY_TOTALS, type UsageRecord } from "./usageTranscripts.ts";
18import { cacheSavingsUsd, priceUsage, type RateTable } from "./usagePricing.ts";
19​
20/**
21 * Formats an instant as a `YYYY-MM-DD` day in `timeZone`.
22 *
23 * `en-CA` yields ISO-ordered parts, which is why it is used here rather than
24 * assembling the day from `Date` getters (those are host-local only).
25 */
26export function makeDayFormatter(timeZone: string): (timestampMs: number) => string {
27 let format: Intl.DateTimeFormat;
28 try {
29 format = new Intl.DateTimeFormat("en-CA", {
30 timeZone,
31 year: "numeric",
32 month: "2-digit",
33 day: "2-digit",
34 });
35 } catch {
36 // An unknown zone should degrade to UTC rather than fail the whole scan.
37 format = new Intl.DateTimeFormat("en-CA", {
38 timeZone: "UTC",
39 year: "numeric",
40 month: "2-digit",
41 day: "2-digit",
42 });
43 }
44 return (timestampMs) => format.format(new Date(timestampMs));
46​
47const HOUR_MS = 60 * 60 * 1000;
48​
49interface MutableBucket {
50 totals: UsageTokenTotals;
51 costUsd: number;
52 cacheSavingsUsd: number;
53 records: number;
54 unpricedRecords: number;
55 providerReportedRecords: number;
56 sessions: Set<string>;
58​
59export interface AggregateOptions {
60 readonly timeZone: string;
61 readonly sinceDay: string;
62 readonly untilDay: string;
63 readonly rates: RateTable;
64 readonly providerRates?: Partial<Readonly<Record<UsageRecord["provider"], RateTable>>>;
65 readonly priceOverrides?: RateTable;
66 readonly resolution?: UsageResolution;
67 readonly sinceTimeMs?: number;
68 readonly untilTimeMs?: number;
70​
71export interface AggregateResult {
72 readonly buckets: readonly UsageBucket[];
73 /** Records dropped because an earlier record carried the same dedupe key. */
74 readonly duplicatesDropped: number;
75 /** Records whose day fell outside the requested window. */
76 readonly outOfWindow: number;
78​
79/**
80 * Accumulates records across many files.
81 *
82 * De-duplication is global across the whole scan, not per file: Claude Code
83 * copies a message's records forward when a session is resumed or forked, so
84 * the same `dedupeKey` legitimately appears in several transcripts.
85 */
86export class UsageAggregator {
87 readonly #buckets = new Map<string, MutableBucket>();
88 readonly #seen = new Set<string>();
89 readonly #toDay: (timestampMs: number) => string;
90 readonly #hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null;
91 readonly #options: AggregateOptions;
92 #duplicatesDropped = 0;
93 #outOfWindow = 0;
94​
95 constructor(options: AggregateOptions) {
96 this.#options = options;
97 this.#toDay = makeDayFormatter(options.timeZone);
98 if (options.resolution === "hour") {
99 if (options.sinceTimeMs === undefined || options.untilTimeMs === undefined) {
100 throw new Error("Hourly usage aggregation requires exact time bounds");
101 }
102 this.#hourlyWindow = {
103 sinceTimeMs: options.sinceTimeMs,
104 untilTimeMs: options.untilTimeMs,
105 };
106 } else {
107 this.#hourlyWindow = null;
108 }
109 }
110​
111 /**
112 * Folds one record in. Returns whether it actually contributed, so callers
113 * can derive per-window facts (distinct sessions, for one) from the records
114 * that landed rather than everything the mtime prefilter happened to admit.
115 */
116 add(record: UsageRecord): boolean {
117 if (record.dedupeKey !== null) {
118 if (this.#seen.has(record.dedupeKey)) {
119 this.#duplicatesDropped += 1;
120 return false;
121 }
122 this.#seen.add(record.dedupeKey);
123 }
124​
125 if (
126 this.#hourlyWindow !== null &&
127 (record.timestampMs < this.#hourlyWindow.sinceTimeMs ||
128 record.timestampMs >= this.#hourlyWindow.untilTimeMs)
129 ) {
130 this.#outOfWindow += 1;
131 return false;
132 }
133​
134 const day = this.#toDay(record.timestampMs);
135 if (
136 this.#hourlyWindow === null &&
137 (day < this.#options.sinceDay || day > this.#options.untilDay)
138 ) {
139 this.#outOfWindow += 1;
140 return false;
141 }
142​
143 const hourStart =
144 this.#hourlyWindow === null
145 ? ""
146 : new Date(
147 this.#hourlyWindow.sinceTimeMs +
148 Math.floor((record.timestampMs - this.#hourlyWindow.sinceTimeMs) / HOUR_MS) * HOUR_MS,
149 ).toISOString();
150 const key = `${day}\u0000${hourStart}\u0000${record.provider}\u0000${record.model}`;
151 let bucket = this.#buckets.get(key);
152 if (bucket === undefined) {
153 bucket = {
154 totals: EMPTY_TOTALS,
155 costUsd: 0,
156 cacheSavingsUsd: 0,
157 records: 0,
158 unpricedRecords: 0,
159 providerReportedRecords: 0,
160 sessions: new Set<string>(),
161 };
162 this.#buckets.set(key, bucket);
163 }
164​
165 const rates = this.#options.providerRates?.[record.provider] ?? this.#options.rates;
166 const priced = priceUsage(
167 rates,
168 record.model,
169 record.totals,
170 record.reportedCostUsd,
171 this.#options.priceOverrides,
172 );
173​
174 bucket.totals = addTotals(bucket.totals, record.totals);
175 bucket.costUsd += priced.costUsd;
176 bucket.cacheSavingsUsd += cacheSavingsUsd(
177 rates,
178 record.model,
179 record.totals,
180 this.#options.priceOverrides,
181 );
182 bucket.records += 1;
183 if (priced.costSource === "unpriced") bucket.unpricedRecords += 1;
184 if (priced.costSource === "providerReported") bucket.providerReportedRecords += 1;
185 if (record.sessionId.length > 0) bucket.sessions.add(record.sessionId);
186 return true;
187 }
188​
189 finish(): AggregateResult {
190 const buckets: UsageBucket[] = [];
191 for (const [key, bucket] of this.#buckets) {
192 const [day = "", hourStart = "", provider = "", model = ""] = key.split("\u0000");
193 buckets.push({
194 day: day as UsageDay,
195 ...(hourStart === "" ? {} : { hourStart }),
196 provider: provider as UsageBucket["provider"],
197 model,
198 totals: bucket.totals,
199 costUsd: bucket.costUsd,
200 cacheSavingsUsd: bucket.cacheSavingsUsd,
201 costSource: resolveCostSource(bucket),
202 records: bucket.records,
203 unpricedRecords: bucket.unpricedRecords,
204 sessions: bucket.sessions.size,
205 });
206 }
207 // Stable ordering keeps payloads diffable and snapshot tests meaningful.
208 buckets.sort(
209 (a, b) =>
210 a.day.localeCompare(b.day) ||
211 (a.hourStart ?? "").localeCompare(b.hourStart ?? "") ||
212 a.provider.localeCompare(b.provider) ||
213 a.model.localeCompare(b.model),
214 );
215​
216 return {
217 buckets,
218 duplicatesDropped: this.#duplicatesDropped,
219 outOfWindow: this.#outOfWindow,
220 };
221 }
223​
224/**
225 * A bucket mixes records from one model, but their cost provenance can differ
226 * when only some records carried a reported cost. The weakest provenance in the
227 * bucket wins so the UI never overstates confidence.
228 */
229function resolveCostSource(bucket: MutableBucket): UsageBucket["costSource"] {
230 if (bucket.unpricedRecords === bucket.records) return "unpriced";
231 if (bucket.providerReportedRecords === bucket.records) return "providerReported";
232 return "modelPriced";