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

usageAggregation.ts

227 lines7.4 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 sourceIndex: number;
61 readonly timeZone: string;
62 readonly sinceDay: string;
63 readonly untilDay: string;
64 readonly rates: 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: 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, seenDedupeKeys: Set<string> = new Set()) {
95 this.#options = options;
96 this.#seen = seenDedupeKeys;
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 priced = priceUsage(
166 this.#options.rates,
167 record.model,
168 record.totals,
169 record.reportedCostUsd,
170 );
171​
172 bucket.totals = addTotals(bucket.totals, record.totals);
173 bucket.costUsd += priced.costUsd;
174 bucket.cacheSavingsUsd += cacheSavingsUsd(this.#options.rates, record.model, record.totals);
175 bucket.records += 1;
176 if (priced.costSource === "unpriced") bucket.unpricedRecords += 1;
177 if (priced.costSource === "providerReported") bucket.providerReportedRecords += 1;
178 if (record.sessionId.length > 0) bucket.sessions.add(record.sessionId);
179 return true;
180 }
181​
182 finish(): AggregateResult {
183 const buckets: UsageBucket[] = [];
184 for (const [key, bucket] of this.#buckets) {
185 const [day = "", hourStart = "", provider = "", model = ""] = key.split("\u0000");
186 buckets.push({
187 sourceIndex: this.#options.sourceIndex,
188 day: day as UsageDay,
189 ...(hourStart === "" ? {} : { hourStart }),
190 provider: provider as UsageBucket["provider"],
191 model,
192 totals: bucket.totals,
193 costUsd: bucket.costUsd,
194 cacheSavingsUsd: bucket.cacheSavingsUsd,
195 costSource: resolveCostSource(bucket),
196 records: bucket.records,
197 unpricedRecords: bucket.unpricedRecords,
198 sessions: bucket.sessions.size,
199 });
200 }
201 // Stable ordering keeps payloads diffable and snapshot tests meaningful.
202 buckets.sort(
203 (a, b) =>
204 a.day.localeCompare(b.day) ||
205 (a.hourStart ?? "").localeCompare(b.hourStart ?? "") ||
206 a.provider.localeCompare(b.provider) ||
207 a.model.localeCompare(b.model),
208 );
209​
210 return {
211 buckets,
212 duplicatesDropped: this.#duplicatesDropped,
213 outOfWindow: this.#outOfWindow,
214 };
215 }
217​
218/**
219 * A bucket mixes records from one model, but their cost provenance can differ
220 * when only some records carried a reported cost. The weakest provenance in the
221 * bucket wins so the UI never overstates confidence.
222 */
223function resolveCostSource(bucket: MutableBucket): UsageBucket["costSource"] {
224 if (bucket.unpricedRecords === bucket.records) return "unpriced";
225 if (bucket.providerReportedRecords === bucket.records) return "providerReported";
226 return "modelPriced";