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

usageAggregation.ts

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