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