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

usageAggregation.ts

231 lines7.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 { 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 */
26function 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 priceOverrides?: RateTable;
65 readonly resolution?: UsageResolution;
66 readonly sinceTimeMs?: number;
67 readonly untilTimeMs?: number;
69​
70export interface AggregateResult {
71 readonly buckets: readonly UsageBucket[];
72 /** Records dropped because an earlier record carried the same dedupe key. */
73 readonly duplicatesDropped: number;
74 /** Records whose day fell outside the requested window. */
75 readonly outOfWindow: number;
77​
78/**
79 * Accumulates records across many files.
80 *
81 * De-duplication is global across the whole scan, not per file: Claude Code
82 * copies a message's records forward when a session is resumed or forked, so
83 * the same `dedupeKey` legitimately appears in several transcripts.
84 */
85export class UsageAggregator {
86 readonly #buckets = new Map<string, MutableBucket>();
87 readonly #seen = new Set<string>();
88 readonly #toDay: (timestampMs: number) => string;
89 readonly #hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null;
90 readonly #options: AggregateOptions;
91 #duplicatesDropped = 0;
92 #outOfWindow = 0;
93​
94 constructor(options: AggregateOptions) {
95 this.#options = options;
96 this.#toDay = makeDayFormatter(options.timeZone);
97 if (options.resolution === "hour") {
98 if (options.sinceTimeMs === undefined || options.untilTimeMs === undefined) {
99 throw new Error("Hourly usage aggregation requires exact time bounds");
100 }
101 this.#hourlyWindow = {
102 sinceTimeMs: options.sinceTimeMs,
103 untilTimeMs: options.untilTimeMs,
104 };
105 } else {
106 this.#hourlyWindow = null;
107 }
108 }
109​
110 /**
111 * Folds one record in. Returns whether it actually contributed, so callers
112 * can derive per-window facts (distinct sessions, for one) from the records
113 * that landed rather than everything the mtime prefilter happened to admit.
114 */
115 add(record: UsageRecord): boolean {
116 if (record.dedupeKey !== null) {
117 if (this.#seen.has(record.dedupeKey)) {
118 this.#duplicatesDropped += 1;
119 return false;
120 }
121 this.#seen.add(record.dedupeKey);
122 }
123​
124 if (
125 this.#hourlyWindow !== null &&
126 (record.timestampMs < this.#hourlyWindow.sinceTimeMs ||
127 record.timestampMs >= this.#hourlyWindow.untilTimeMs)
128 ) {
129 this.#outOfWindow += 1;
130 return false;
131 }
132​
133 const day = this.#toDay(record.timestampMs);
134 if (
135 this.#hourlyWindow === null &&
136 (day < this.#options.sinceDay || day > this.#options.untilDay)
137 ) {
138 this.#outOfWindow += 1;
139 return false;
140 }
141​
142 const hourStart =
143 this.#hourlyWindow === null
144 ? ""
145 : new Date(
146 this.#hourlyWindow.sinceTimeMs +
147 Math.floor((record.timestampMs - this.#hourlyWindow.sinceTimeMs) / HOUR_MS) * HOUR_MS,
148 ).toISOString();
149 const key = `${day}\u0000${hourStart}\u0000${record.provider}\u0000${record.model}`;
150 let bucket = this.#buckets.get(key);
151 if (bucket === undefined) {
152 bucket = {
153 totals: EMPTY_TOTALS,
154 costUsd: 0,
155 cacheSavingsUsd: 0,
156 records: 0,
157 unpricedRecords: 0,
158 providerReportedRecords: 0,
159 sessions: new Set<string>(),
160 };
161 this.#buckets.set(key, bucket);
162 }
163​
164 const priced = priceUsage(
165 this.#options.rates,
166 record.model,
167 record.totals,
168 record.reportedCostUsd,
169 this.#options.priceOverrides,
170 );
171​
172 bucket.totals = addTotals(bucket.totals, record.totals);
173 bucket.costUsd += priced.costUsd;
174 bucket.cacheSavingsUsd += cacheSavingsUsd(
175 this.#options.rates,
176 record.model,
177 record.totals,
178 this.#options.priceOverrides,
179 );
180 bucket.records += 1;
181 if (priced.costSource === "unpriced") bucket.unpricedRecords += 1;
182 if (priced.costSource === "providerReported") bucket.providerReportedRecords += 1;
183 if (record.sessionId.length > 0) bucket.sessions.add(record.sessionId);
184 return true;
185 }
186​
187 finish(): AggregateResult {
188 const buckets: UsageBucket[] = [];
189 for (const [key, bucket] of this.#buckets) {
190 const [day = "", hourStart = "", provider = "", model = ""] = key.split("\u0000");
191 buckets.push({
192 day: day as UsageDay,
193 ...(hourStart === "" ? {} : { hourStart }),
194 provider: provider as UsageBucket["provider"],
195 model,
196 totals: bucket.totals,
197 costUsd: bucket.costUsd,
198 cacheSavingsUsd: bucket.cacheSavingsUsd,
199 costSource: resolveCostSource(bucket),
200 records: bucket.records,
201 unpricedRecords: bucket.unpricedRecords,
202 sessions: bucket.sessions.size,
203 });
204 }
205 // Stable ordering keeps payloads diffable and snapshot tests meaningful.
206 buckets.sort(
207 (a, b) =>
208 a.day.localeCompare(b.day) ||
209 (a.hourStart ?? "").localeCompare(b.hourStart ?? "") ||
210 a.provider.localeCompare(b.provider) ||
211 a.model.localeCompare(b.model),
212 );
213​
214 return {
215 buckets,
216 duplicatesDropped: this.#duplicatesDropped,
217 outOfWindow: this.#outOfWindow,
218 };
219 }
221​
222/**
223 * A bucket mixes records from one model, but their cost provenance can differ
224 * when only some records carried a reported cost. The weakest provenance in the
225 * bucket wins so the UI never overstates confidence.
226 */
227function resolveCostSource(bucket: MutableBucket): UsageBucket["costSource"] {
228 if (bucket.unpricedRecords === bucket.records) return "unpriced";
229 if (bucket.providerReportedRecords === bucket.records) return "providerReported";
230 return "modelPriced";