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("splits a bucket's cost by category and speed", () => {
72 const [bucket] = aggregate([record(), record({ speed: "fast" })]).buckets;
73
74 expect(bucket).toMatchObject({
75 costUsd: expect.closeTo(0.016875),
76 categoryCostUsd: {
77 input: expect.closeTo(0.003),
78 cacheRead: expect.closeTo(0.003),
79 cacheWrite: expect.closeTo(0.000375),
80 output: expect.closeTo(0.0075),
81 },
82 fastCostUsd: expect.closeTo(0.01125),
83 speedPremiumUsd: expect.closeTo(0.005625),
84 });
85 expect(bucket).not.toHaveProperty("ultrafastCostUsd");
86 });
87
88 it("merges partial copies of a key by channel maximum in the first copy's bucket", () => {
89 const zeroTotals = {
90 uncachedInputTokens: 0,
91 cachedInputTokens: 0,
92 cacheCreationTokens: 0,
93 outputTokens: 0,
94 reasoningTokens: 0,
95 };
96 const partial = record({
97 dedupeKey: "msg_1:",
98 speed: "fast",
99 reportedCostUsd: 1,
100 totals: { ...record().totals, cachedInputTokens: 1200, outputTokens: 3, reasoningTokens: 5 },
101 });
102 const complete = record({
103 dedupeKey: "msg_1:",
104 model: "claude-fable-5[1m]",
105 timestampMs: Date.parse("2026-08-08T12:00:00Z"),
106 sessionId: "session-fork",
107 reportedCostUsd: 2,
108 totals: {
109 uncachedInputTokens: 2,
110 cachedInputTokens: 1000,
111 cacheCreationTokens: 40,
112 outputTokens: 264,
113 reasoningTokens: 135,
114 },
115 });
116 const zero = { ...partial, totals: zeroTotals, reportedCostUsd: null };
117 const merged = {
118 reportedCostUsd: 2,
119 totals: { ...complete.totals, uncachedInputTokens: 100, cachedInputTokens: 1200 },
120 };
121
122 for (const copies of [
123 [zero, partial, complete, complete],
124 [complete, partial, zero, zero],
125 ]) {
126 const aggregator = new UsageAggregator({
127 timeZone: "UTC",
128 sinceDay: "2026-08-01",
129 untilDay: "2026-08-31",
130 rates,
131 });
132 copies.forEach((copy, index) => aggregator.add(copy, `${index}.jsonl`));
133 const result = aggregator.finish();
134 const expected = aggregate([{ ...copies[0]!, ...merged }]).buckets[0];
135
136 expect(result.duplicatesDropped).toBe(3);
137 expect(result.buckets).toEqual([{ ...expected, sourcePath: "0.jsonl" }]);
138 }
139 });
140
141 it("does not count a key whose first copy fell outside the window", () => {
142 const result = aggregate([
143 record({ dedupeKey: "msg_1:", timestampMs: Date.parse("2026-07-01T12:00:00Z") }),
144 record({ dedupeKey: "msg_1:", totals: { ...record().totals, outputTokens: 500 } }),
145 ]);
146
147 expect(result.duplicatesDropped).toBe(1);
148 expect(result.outOfWindow).toBe(1);
149 expect(result.buckets).toHaveLength(0);
150 });
151
152 it("buckets by the day in the requested time zone", () => {
153 const utc = aggregate([record()], "UTC");
154 const losAngeles = aggregate([record()], "America/Los_Angeles");
155
156 expect(utc.buckets[0]?.day).toBe("2026-08-07");
157 expect(losAngeles.buckets[0]?.day).toBe("2026-08-06");
158 });
159
160 it("finds the day at a quarter-hour zone's midnight across interleaved buckets", () => {
161 const result = aggregate(
162 [
163 record({ timestampMs: Date.parse("2026-08-01T18:14:59.999Z") }),
164 record({ timestampMs: Date.parse("2026-08-01T18:15:00.000Z") }),
165 record({ timestampMs: Date.parse("2026-08-01T18:15:00.000Z"), model: "claude-opus-5" }),
166 record({ timestampMs: Date.parse("2026-08-01T18:16:00.000Z") }),
167 ],
168 "Asia/Kathmandu",
169 );
170
171 expect(result.buckets.map((bucket) => [bucket.day, bucket.model, bucket.records])).toEqual([
172 ["2026-08-01", "claude-fable-5", 1],
173 ["2026-08-02", "claude-fable-5", 2],
174 ["2026-08-02", "claude-opus-5", 1],
175 ]);
176 });
177
178 it("finds the day at a fixed offset's midnight between quarter hours", () => {
179 const result = aggregate(
180 [
181 record({ timestampMs: Date.parse("2026-08-01T23:58:59.999Z") }),
182 record({ timestampMs: Date.parse("2026-08-01T23:59:00.000Z") }),
183 ],
184 "+00:01",
185 );
186
187 expect(result.buckets.map((bucket) => [bucket.day, bucket.records])).toEqual([
188 ["2026-08-01", 1],
189 ["2026-08-02", 1],
190 ]);
191 });
192
193 it("splits an hourly request into fixed buckets anchored to its exact start", () => {
194 const result = aggregate(
195 [
196 record({ timestampMs: Date.parse("2026-08-07T02:40:13.944Z") }),
197 record({ timestampMs: Date.parse("2026-08-07T03:40:13.944Z") }),
198 ],
199 "America/Los_Angeles",
200 "hour",
201 );
202
203 expect(result.buckets.map((bucket) => [bucket.day, bucket.hourStart])).toEqual([
204 ["2026-08-06", "2026-08-07T02:37:00.000Z"],
205 ["2026-08-06", "2026-08-07T03:37:00.000Z"],
206 ]);
207 });
208
209 it("uses an inclusive start and exclusive end for rolling windows", () => {
210 const result = aggregate(
211 [
212 record({ timestampMs: Date.parse("2026-08-06T04:36:59.999Z") }),
213 record({ timestampMs: Date.parse("2026-08-06T04:37:00.000Z") }),
214 record({ timestampMs: Date.parse("2026-08-07T04:36:59.999Z") }),
215 record({ timestampMs: Date.parse("2026-08-07T04:37:00.000Z") }),
216 ],
217 "UTC",
218 "hour",
219 );
220
221 expect(result.outOfWindow).toBe(2);
222 expect(result.buckets.map((bucket) => bucket.hourStart)).toEqual([
223 "2026-08-06T04:37:00.000Z",
224 "2026-08-07T03:37:00.000Z",
225 ]);
226 });
227
228 it("counts tokens but not cost for a model with no rate", () => {
229 const result = aggregate([record({ model: "kimi-k3" })]);
230
231 expect(result.buckets[0]?.costUsd).toBe(0);
232 expect(result.buckets[0]?.costSource).toBe("unpriced");
233 expect(result.buckets[0]?.unpricedRecords).toBe(1);
234 expect(result.buckets[0]?.totals.outputTokens).toBe(50);
235 });
236
237 it("prefers a reported cost over the rate table", () => {
238 const result = aggregate([record({ reportedCostUsd: 1.25 })]);
239
240 expect(result.buckets[0]?.costUsd).toBe(1.25);
241 expect(result.buckets[0]?.costSource).toBe("providerReported");
242 });
243
244 it("folds a mapped model into its target and prices it there", () => {
245 const aggregator = new UsageAggregator({
246 timeZone: "UTC",
247 sinceDay: "2026-08-01",
248 untilDay: "2026-08-31",
249 rates,
250 modelAliases: resolveModelAliases({ "example-preview": "claude-fable-5" }),
251 });
252 aggregator.add(record());
253 aggregator.add(record({ model: "example-preview", rateModel: "example-preview-high" }));
254 const result = aggregator.finish();
255
256 expect(result.buckets).toHaveLength(1);
257 expect(result.buckets[0]?.model).toBe("claude-fable-5");
258 expect(result.buckets[0]?.records).toBe(2);
259 expect(result.buckets[0]?.costUsd).toBeCloseTo(0.00925, 9);
260 expect(result.buckets[0]?.unpricedRecords).toBe(0);
261 });
262});
263
264describe("resolveModelAliases", () => {
265 it("follows chains to the final model and drops chains that enter a loop", () => {
266 expect(
267 resolveModelAliases({
268 "preview[1m]": "preview",
269 preview: "example-model",
270 loop: "back",
271 back: "loop",
272 intoLoop: "loop",
273 self: "self",
274 }),
275 ).toEqual(
276 new Map([
277 ["preview[1m]", "example-model"],
278 ["preview", "example-model"],
279 ]),
280 );
281 });
282});