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

usageAggregation.ts

204 lines6.5 KB

1// @effect-diagnostics globalDate:off
2/**
3 * Folds parsed transcript records into `(day, provider, model, home)` buckets.
4 *
5 * `Intl.DateTimeFormat` is the only reliable way to resolve a wall-clock day in
6 * an arbitrary IANA zone, and it takes a `Date`. That is why the raw `Date`
7 * construction is allowed here; nothing in this module reads the clock.
8 *
9 * Pure, so the bucketing and de-duplication rules are testable without touching
10 * the filesystem or the network.
11 *
12 * @module usageAggregation
13 */
14import type { UsageBucket, UsageDay, UsageTokenTotals } from "@t3tools/contracts";
15​
16import { addTotals, EMPTY_TOTALS, type UsageRecord } from "./usageTranscripts.ts";
17import { cacheSavingsUsd, priceUsage, type RateTable } from "./usagePricing.ts";
18​
19/**
20 * Formats an instant as a `YYYY-MM-DD` day in `timeZone`.
21 *
22 * `en-CA` yields ISO-ordered parts, which is why it is used here rather than
23 * assembling the day from `Date` getters (those are host-local only).
24 */
25export function makeDayFormatter(timeZone: string): (timestampMs: number) => string {
26 let format: Intl.DateTimeFormat;
27 try {
28 format = new Intl.DateTimeFormat("en-CA", {
29 timeZone,
30 year: "numeric",
31 month: "2-digit",
32 day: "2-digit",
33 });
34 } catch {
35 // An unknown zone should degrade to UTC rather than fail the whole scan.
36 format = new Intl.DateTimeFormat("en-CA", {
37 timeZone: "UTC",
38 year: "numeric",
39 month: "2-digit",
40 day: "2-digit",
41 });
42 }
43 return (timestampMs) => format.format(new Date(timestampMs));
45​
46interface MutableBucket {
47 day: string;
48 provider: UsageRecord["provider"];
49 model: string;
50 homePath: string;
51 homeLabel: string | null;
52 totals: UsageTokenTotals;
53 costUsd: number;
54 cacheSavingsUsd: number;
55 records: number;
56 unpricedRecords: number;
57 providerReportedRecords: number;
58 sessions: Set<string>;
60​
61/** The transcript directory a record was read from, for bucket attribution. */
62export interface UsageHome {
63 readonly path: string;
64 readonly label: string | null;
66​
67export interface AggregateOptions {
68 readonly timeZone: string;
69 readonly sinceDay: string;
70 readonly untilDay: string;
71 readonly rates: RateTable;
73​
74export interface AggregateResult {
75 readonly buckets: readonly UsageBucket[];
76 /** Records dropped because an earlier record carried the same dedupe key. */
77 readonly duplicatesDropped: number;
78 /** Records whose day fell outside the requested window. */
79 readonly outOfWindow: number;
81​
82/**
83 * Accumulates records across many files.
84 *
85 * De-duplication is global across the whole scan, not per file: Claude Code
86 * copies a message's records forward when a session is resumed or forked, so
87 * the same `dedupeKey` legitimately appears in several transcripts.
88 */
89export class UsageAggregator {
90 readonly #buckets = new Map<string, MutableBucket>();
91 readonly #seen = new Set<string>();
92 readonly #toDay: (timestampMs: number) => string;
93 readonly #options: AggregateOptions;
94 #duplicatesDropped = 0;
95 #outOfWindow = 0;
96​
97 constructor(options: AggregateOptions) {
98 this.#options = options;
99 this.#toDay = makeDayFormatter(options.timeZone);
100 }
101​
102 /**
103 * Folds one record in. Returns whether it actually contributed, so callers
104 * can derive per-window facts (distinct sessions, for one) from the records
105 * that landed rather than everything the mtime prefilter happened to admit.
106 */
107 add(record: UsageRecord, home: UsageHome): boolean {
108 if (record.dedupeKey !== null) {
109 if (this.#seen.has(record.dedupeKey)) {
110 this.#duplicatesDropped += 1;
111 return false;
112 }
113 this.#seen.add(record.dedupeKey);
114 }
115​
116 const day = this.#toDay(record.timestampMs);
117 if (day < this.#options.sinceDay || day > this.#options.untilDay) {
118 this.#outOfWindow += 1;
119 return false;
120 }
121​
122 // JSON, not a delimiter-joined string: home paths can contain anything.
123 const key = JSON.stringify([day, record.provider, record.model, home.path]);
124 let bucket = this.#buckets.get(key);
125 if (bucket === undefined) {
126 bucket = {
127 day,
128 provider: record.provider,
129 model: record.model,
130 homePath: home.path,
131 homeLabel: home.label,
132 totals: EMPTY_TOTALS,
133 costUsd: 0,
134 cacheSavingsUsd: 0,
135 records: 0,
136 unpricedRecords: 0,
137 providerReportedRecords: 0,
138 sessions: new Set<string>(),
139 };
140 this.#buckets.set(key, bucket);
141 }
142​
143 const priced = priceUsage(
144 this.#options.rates,
145 record.model,
146 record.totals,
147 record.reportedCostUsd,
148 );
149​
150 bucket.totals = addTotals(bucket.totals, record.totals);
151 bucket.costUsd += priced.costUsd;
152 bucket.cacheSavingsUsd += cacheSavingsUsd(this.#options.rates, record.model, record.totals);
153 bucket.records += 1;
154 if (priced.costSource === "unpriced") bucket.unpricedRecords += 1;
155 if (priced.costSource === "providerReported") bucket.providerReportedRecords += 1;
156 if (record.sessionId.length > 0) bucket.sessions.add(record.sessionId);
157 return true;
158 }
159​
160 finish(): AggregateResult {
161 const buckets: UsageBucket[] = [];
162 for (const bucket of this.#buckets.values()) {
163 buckets.push({
164 day: bucket.day as UsageDay,
165 provider: bucket.provider,
166 homePath: bucket.homePath,
167 homeLabel: bucket.homeLabel,
168 model: bucket.model,
169 totals: bucket.totals,
170 costUsd: bucket.costUsd,
171 cacheSavingsUsd: bucket.cacheSavingsUsd,
172 costSource: resolveCostSource(bucket),
173 records: bucket.records,
174 unpricedRecords: bucket.unpricedRecords,
175 sessions: bucket.sessions.size,
176 });
177 }
178 // Stable ordering keeps payloads diffable and snapshot tests meaningful.
179 buckets.sort(
180 (a, b) =>
181 a.day.localeCompare(b.day) ||
182 a.provider.localeCompare(b.provider) ||
183 a.homePath.localeCompare(b.homePath) ||
184 a.model.localeCompare(b.model),
185 );
186​
187 return {
188 buckets,
189 duplicatesDropped: this.#duplicatesDropped,
190 outOfWindow: this.#outOfWindow,
191 };
192 }
194​
195/**
196 * A bucket mixes records from one model, but their cost provenance can differ
197 * when only some records carried a reported cost. The weakest provenance in the
198 * bucket wins so the UI never overstates confidence.
199 */
200function resolveCostSource(bucket: MutableBucket): UsageBucket["costSource"] {
201 if (bucket.unpricedRecords === bucket.records) return "unpriced";
202 if (bucket.providerReportedRecords === bucket.records) return "providerReported";
203 return "modelPriced";