Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2
3import { resolveModelAliases, UsageAggregator } from "./usageAggregation.ts";
4import type { RateTable } from "./usagePricing.ts";
5import type { UsageRecord } from "@t3tools/provider-core/server/usage";
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 timestampMs: Date.parse("2026-08-07T04:05:13.944Z"),
30 model: "claude-fable-5",
31 sessionId: "session-a",
32 totals: {
33 uncachedInputTokens: 100,
34 cachedInputTokens: 1000,
35 cacheCreationTokens: 10,
36 outputTokens: 50,
37 reasoningTokens: 0,
38 },
39 reportedCostUsd: null,
40 speed: "standard",
41 dedupeKey: null,
42 ...overrides,
43 };
44}
45
46function aggregate(
47 records: readonly UsageRecord[],
48 timeZone = "UTC",
49 resolution: "day" | "hour" = "day",
50) {
51 const hourlyBounds =
52 resolution === "hour"
53 ? {
54 sinceTimeMs: Date.parse("2026-08-06T04:37:00.000Z"),
55 untilTimeMs: Date.parse("2026-08-07T04:37:00.000Z"),
56 }
57 : {};
58 const aggregator = new UsageAggregator({
59 timeZone,
60 sinceDay: "2026-08-01",
61 untilDay: "2026-08-31",
62 resolution,
63 ...hourlyBounds,
64 rates,
65 });
66 for (const item of records) aggregator.add(item);
67 return aggregator.finish();
68}
69
70describe("UsageAggregator", () => {
71 it("requires exact bounds for hourly aggregation", () => {
72 expect(
73 () =>
74 new UsageAggregator({
75 timeZone: "UTC",
76 sinceDay: "2026-08-01",
77 untilDay: "2026-08-31",
78 resolution: "hour",
79 rates,
80 }),
81 ).toThrow("requires exact time bounds");
82 });
83
84 it("splits a bucket's cost by category and speed", () => {
85 const [bucket] = aggregate([record(), record({ speed: "fast" })]).buckets;
86
87 expect(bucket).toMatchObject({
88 costUsd: expect.closeTo(0.016875),
89 categoryCostUsd: {
90 input: expect.closeTo(0.003),
91 cacheRead: expect.closeTo(0.003),
92 cacheWrite: expect.closeTo(0.000375),
93 output: expect.closeTo(0.0075),
94 },
95 fastCostUsd: expect.closeTo(0.01125),
96 speedPremiumUsd: expect.closeTo(0.005625),
97 });
98 expect(bucket).not.toHaveProperty("ultrafastCostUsd");
99 });
100
101 it("keeps only the first record for a repeated dedupe key", () => {
102 const result = aggregate([
103 record({ dedupeKey: "msg_1:" }),
104 record({ dedupeKey: "msg_1:" }),
105 record({ dedupeKey: "msg_1:" }),
106 ]);
107
108 expect(result.duplicatesDropped).toBe(2);
109 expect(result.buckets).toHaveLength(1);
110 expect(result.buckets[0]?.records).toBe(1);
111 expect(result.buckets[0]?.totals.outputTokens).toBe(50);
112 });
113
114 it("still sums records that carry no dedupe key", () => {
115 const result = aggregate([record(), record()]);
116
117 expect(result.duplicatesDropped).toBe(0);
118 expect(result.buckets[0]?.totals.outputTokens).toBe(100);
119 });
120
121 it("buckets by the day in the requested time zone", () => {
122 const utc = aggregate([record()], "UTC");
123 const losAngeles = aggregate([record()], "America/Los_Angeles");
124
125 expect(utc.buckets[0]?.day).toBe("2026-08-07");
126 expect(losAngeles.buckets[0]?.day).toBe("2026-08-06");
127 });
128
129 it("finds the day at a quarter-hour zone's midnight across interleaved buckets", () => {
130 const result = aggregate(
131 [
132 record({ timestampMs: Date.parse("2026-08-01T18:14:59.999Z") }),
133 record({ timestampMs: Date.parse("2026-08-01T18:15:00.000Z") }),
134 record({ timestampMs: Date.parse("2026-08-01T18:15:00.000Z"), model: "claude-opus-5" }),
135 record({ timestampMs: Date.parse("2026-08-01T18:16:00.000Z") }),
136 ],
137 "Asia/Kathmandu",
138 );
139
140 expect(result.buckets.map((bucket) => [bucket.day, bucket.model, bucket.records])).toEqual([
141 ["2026-08-01", "claude-fable-5", 1],
142 ["2026-08-02", "claude-fable-5", 2],
143 ["2026-08-02", "claude-opus-5", 1],
144 ]);
145 });
146
147 it("finds the day at a fixed offset's midnight between quarter hours", () => {
148 const result = aggregate(
149 [
150 record({ timestampMs: Date.parse("2026-08-01T23:58:59.999Z") }),
151 record({ timestampMs: Date.parse("2026-08-01T23:59:00.000Z") }),
152 ],
153 "+00:01",
154 );
155
156 expect(result.buckets.map((bucket) => [bucket.day, bucket.records])).toEqual([
157 ["2026-08-01", 1],
158 ["2026-08-02", 1],
159 ]);
160 });
161
162 it("splits an hourly request into fixed buckets anchored to its exact start", () => {
163 const result = aggregate(
164 [
165 record({ timestampMs: Date.parse("2026-08-07T02:40:13.944Z") }),
166 record({ timestampMs: Date.parse("2026-08-07T03:40:13.944Z") }),
167 ],
168 "America/Los_Angeles",
169 "hour",
170 );
171
172 expect(result.buckets.map((bucket) => [bucket.day, bucket.hourStart])).toEqual([
173 ["2026-08-06", "2026-08-07T02:37:00.000Z"],
174 ["2026-08-06", "2026-08-07T03:37:00.000Z"],
175 ]);
176 });
177
178 it("uses an inclusive start and exclusive end for rolling windows", () => {
179 const result = aggregate(
180 [
181 record({ timestampMs: Date.parse("2026-08-06T04:36:59.999Z") }),
182 record({ timestampMs: Date.parse("2026-08-06T04:37:00.000Z") }),
183 record({ timestampMs: Date.parse("2026-08-07T04:36:59.999Z") }),
184 record({ timestampMs: Date.parse("2026-08-07T04:37:00.000Z") }),
185 ],
186 "UTC",
187 "hour",
188 );
189
190 expect(result.outOfWindow).toBe(2);
191 expect(result.buckets.map((bucket) => bucket.hourStart)).toEqual([
192 "2026-08-06T04:37:00.000Z",
193 "2026-08-07T03:37:00.000Z",
194 ]);
195 });
196
197 it("keeps daily payloads collapsed when hourly resolution is not requested", () => {
198 const result = aggregate([
199 record({ timestampMs: Date.parse("2026-08-07T04:05:13.944Z") }),
200 record({ timestampMs: Date.parse("2026-08-07T05:05:13.944Z") }),
201 ]);
202
203 expect(result.buckets).toHaveLength(1);
204 expect(result.buckets[0]?.hourStart).toBeUndefined();
205 expect(result.buckets[0]?.records).toBe(2);
206 });
207
208 it("prices against the rate table", () => {
209 const result = aggregate([record()]);
210
211 expect(result.buckets[0]?.costUsd).toBeCloseTo(0.004625, 9);
212 expect(result.buckets[0]?.costSource).toBe("modelPriced");
213 });
214
215 it("counts tokens but not cost for a model with no rate", () => {
216 const result = aggregate([record({ model: "kimi-k3" })]);
217
218 expect(result.buckets[0]?.costUsd).toBe(0);
219 expect(result.buckets[0]?.costSource).toBe("unpriced");
220 expect(result.buckets[0]?.unpricedRecords).toBe(1);
221 expect(result.buckets[0]?.totals.outputTokens).toBe(50);
222 });
223
224 it("prefers a reported cost over the rate table", () => {
225 const result = aggregate([record({ reportedCostUsd: 1.25 })]);
226
227 expect(result.buckets[0]?.costUsd).toBe(1.25);
228 expect(result.buckets[0]?.costSource).toBe("providerReported");
229 });
230
231 it("drops records outside the window", () => {
232 const result = aggregate([record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") })]);
233
234 expect(result.outOfWindow).toBe(1);
235 expect(result.buckets).toHaveLength(0);
236 });
237
238 it("reports whether a record contributed", () => {
239 const aggregator = new UsageAggregator({
240 timeZone: "UTC",
241 sinceDay: "2026-08-01",
242 untilDay: "2026-08-31",
243 rates,
244 });
245
246 expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(true);
247 expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(false);
248 expect(aggregator.add(record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") }))).toBe(false);
249 });
250
251 it("folds a mapped model into its target and prices it there", () => {
252 const aggregator = new UsageAggregator({
253 timeZone: "UTC",
254 sinceDay: "2026-08-01",
255 untilDay: "2026-08-31",
256 rates,
257 modelAliases: resolveModelAliases({ "example-preview": "claude-fable-5" }),
258 });
259 aggregator.add(record());
260 aggregator.add(record({ model: "example-preview", rateModel: "example-preview-high" }));
261 const result = aggregator.finish();
262
263 expect(result.buckets).toHaveLength(1);
264 expect(result.buckets[0]?.model).toBe("claude-fable-5");
265 expect(result.buckets[0]?.records).toBe(2);
266 expect(result.buckets[0]?.costUsd).toBeCloseTo(0.00925, 9);
267 expect(result.buckets[0]?.unpricedRecords).toBe(0);
268 });
269
270 it("separates providers and models into their own buckets", () => {
271 const result = aggregate([
272 record(),
273 record({ provider: "codex", model: "gpt-5.6-sol" }),
274 record({ model: "claude-opus-5" }),
275 ]);
276
277 expect(result.buckets).toHaveLength(3);
278 });
279});
280
281describe("resolveModelAliases", () => {
282 it("follows chains to the final model and drops chains that enter a loop", () => {
283 expect(
284 resolveModelAliases({
285 "preview[1m]": "preview",
286 preview: "example-model",
287 loop: "back",
288 back: "loop",
289 intoLoop: "loop",
290 self: "self",
291 }),
292 ).toEqual(
293 new Map([
294 ["preview[1m]", "example-model"],
295 ["preview", "example-model"],
296 ]),
297 );
298 });
299});