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