Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2
3import { UsageAggregator } from "./usageAggregation.ts";
4import type { RateTable } from "./usagePricing.ts";
5import type { UsageRecord } from "./usageTranscripts.ts";
6
7const rates: RateTable = new Map([
8 [
9 "claude-fable-5",
10 {
11 inputCostPerToken: 1e-5,
12 outputCostPerToken: 5e-5,
13 cacheReadCostPerToken: 1e-6,
14 cacheCreationCostPerToken: 1.25e-5,
15 },
16 ],
17]);
18
19function record(overrides: Partial<UsageRecord> = {}): UsageRecord {
20 return {
21 provider: "claude",
22 // 2026-08-07T04:05Z is still Aug 6 in Los Angeles.
23 timestampMs: Date.parse("2026-08-07T04:05:13.944Z"),
24 model: "claude-fable-5",
25 sessionId: "session-a",
26 totals: {
27 uncachedInputTokens: 100,
28 cachedInputTokens: 1000,
29 cacheCreationTokens: 10,
30 outputTokens: 50,
31 reasoningTokens: 0,
32 },
33 reportedCostUsd: null,
34 dedupeKey: null,
35 ...overrides,
36 };
37}
38
39function aggregate(
40 records: readonly UsageRecord[],
41 timeZone = "UTC",
42 resolution: "day" | "hour" = "day",
43) {
44 const hourlyBounds =
45 resolution === "hour"
46 ? {
47 sinceTimeMs: Date.parse("2026-08-06T04:37:00.000Z"),
48 untilTimeMs: Date.parse("2026-08-07T04:37:00.000Z"),
49 }
50 : {};
51 const aggregator = new UsageAggregator({
52 sourceIndex: 0,
53 timeZone,
54 sinceDay: "2026-08-01",
55 untilDay: "2026-08-31",
56 resolution,
57 ...hourlyBounds,
58 rates,
59 });
60 for (const item of records) aggregator.add(item);
61 return aggregator.finish();
62}
63
64describe("UsageAggregator", () => {
65 it("requires exact bounds for hourly aggregation", () => {
66 expect(
67 () =>
68 new UsageAggregator({
69 sourceIndex: 0,
70 timeZone: "UTC",
71 sinceDay: "2026-08-01",
72 untilDay: "2026-08-31",
73 resolution: "hour",
74 rates,
75 }),
76 ).toThrow("requires exact time bounds");
77 });
78
79 it("keeps only the first record for a repeated dedupe key", () => {
80 const result = aggregate([
81 record({ dedupeKey: "msg_1:" }),
82 record({ dedupeKey: "msg_1:" }),
83 record({ dedupeKey: "msg_1:" }),
84 ]);
85
86 expect(result.duplicatesDropped).toBe(2);
87 expect(result.buckets).toHaveLength(1);
88 expect(result.buckets[0]?.sourceIndex).toBe(0);
89 expect(result.buckets[0]?.records).toBe(1);
90 expect(result.buckets[0]?.totals.outputTokens).toBe(50);
91 });
92
93 it("deduplicates records across transcript sources in the same scan", () => {
94 const seenDedupeKeys = new Set<string>();
95 const options = {
96 timeZone: "UTC",
97 sinceDay: "2026-08-01",
98 untilDay: "2026-08-31",
99 rates,
100 };
101 const first = new UsageAggregator({ ...options, sourceIndex: 0 }, seenDedupeKeys);
102 const second = new UsageAggregator({ ...options, sourceIndex: 1 }, seenDedupeKeys);
103
104 expect(first.add(record({ dedupeKey: "msg_1:" }))).toBe(true);
105 expect(second.add(record({ dedupeKey: "msg_1:" }))).toBe(false);
106 expect(first.finish().buckets[0]?.records).toBe(1);
107 expect(second.finish()).toMatchObject({ buckets: [], duplicatesDropped: 1 });
108 });
109
110 it("still sums records that carry no dedupe key", () => {
111 const result = aggregate([record(), record()]);
112
113 expect(result.duplicatesDropped).toBe(0);
114 expect(result.buckets[0]?.totals.outputTokens).toBe(100);
115 });
116
117 it("buckets by the day in the requested time zone", () => {
118 const utc = aggregate([record()], "UTC");
119 const losAngeles = aggregate([record()], "America/Los_Angeles");
120
121 expect(utc.buckets[0]?.day).toBe("2026-08-07");
122 expect(losAngeles.buckets[0]?.day).toBe("2026-08-06");
123 });
124
125 it("splits an hourly request into fixed buckets anchored to its exact start", () => {
126 const result = aggregate(
127 [
128 record({ timestampMs: Date.parse("2026-08-07T02:40:13.944Z") }),
129 record({ timestampMs: Date.parse("2026-08-07T03:40:13.944Z") }),
130 ],
131 "America/Los_Angeles",
132 "hour",
133 );
134
135 expect(result.buckets.map((bucket) => [bucket.day, bucket.hourStart])).toEqual([
136 ["2026-08-06", "2026-08-07T02:37:00.000Z"],
137 ["2026-08-06", "2026-08-07T03:37:00.000Z"],
138 ]);
139 });
140
141 it("uses an inclusive start and exclusive end for rolling windows", () => {
142 const result = aggregate(
143 [
144 record({ timestampMs: Date.parse("2026-08-06T04:36:59.999Z") }),
145 record({ timestampMs: Date.parse("2026-08-06T04:37:00.000Z") }),
146 record({ timestampMs: Date.parse("2026-08-07T04:36:59.999Z") }),
147 record({ timestampMs: Date.parse("2026-08-07T04:37:00.000Z") }),
148 ],
149 "UTC",
150 "hour",
151 );
152
153 expect(result.outOfWindow).toBe(2);
154 expect(result.buckets.map((bucket) => bucket.hourStart)).toEqual([
155 "2026-08-06T04:37:00.000Z",
156 "2026-08-07T03:37:00.000Z",
157 ]);
158 });
159
160 it("keeps daily payloads collapsed when hourly resolution is not requested", () => {
161 const result = aggregate([
162 record({ timestampMs: Date.parse("2026-08-07T04:05:13.944Z") }),
163 record({ timestampMs: Date.parse("2026-08-07T05:05:13.944Z") }),
164 ]);
165
166 expect(result.buckets).toHaveLength(1);
167 expect(result.buckets[0]?.hourStart).toBeUndefined();
168 expect(result.buckets[0]?.records).toBe(2);
169 });
170
171 it("prices against the rate table", () => {
172 const result = aggregate([record()]);
173
174 // 100*1e-5 + 1000*1e-6 + 10*1.25e-5 + 50*5e-5
175 expect(result.buckets[0]?.costUsd).toBeCloseTo(0.004625, 9);
176 expect(result.buckets[0]?.costSource).toBe("modelPriced");
177 });
178
179 it("counts tokens but not cost for a model with no rate", () => {
180 const result = aggregate([record({ model: "kimi-k3" })]);
181
182 expect(result.buckets[0]?.costUsd).toBe(0);
183 expect(result.buckets[0]?.costSource).toBe("unpriced");
184 expect(result.buckets[0]?.unpricedRecords).toBe(1);
185 expect(result.buckets[0]?.totals.outputTokens).toBe(50);
186 });
187
188 it("prefers a reported cost over the rate table", () => {
189 const result = aggregate([record({ reportedCostUsd: 1.25 })]);
190
191 expect(result.buckets[0]?.costUsd).toBe(1.25);
192 expect(result.buckets[0]?.costSource).toBe("providerReported");
193 });
194
195 it("drops records outside the window", () => {
196 const result = aggregate([record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") })]);
197
198 expect(result.outOfWindow).toBe(1);
199 expect(result.buckets).toHaveLength(0);
200 });
201
202 it("reports whether a record contributed", () => {
203 const aggregator = new UsageAggregator({
204 sourceIndex: 0,
205 timeZone: "UTC",
206 sinceDay: "2026-08-01",
207 untilDay: "2026-08-31",
208 rates,
209 });
210
211 expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(true);
212 expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(false);
213 expect(aggregator.add(record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") }))).toBe(false);
214 });
215
216 it("separates providers and models into their own buckets", () => {
217 const result = aggregate([
218 record(),
219 record({ provider: "codex", model: "gpt-5.6-sol" }),
220 record({ model: "claude-opus-5" }),
221 ]);
222
223 expect(result.buckets).toHaveLength(3);
224 });
225});