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("keeps only the first record for a repeated dedupe key", () => {
89 const result = aggregate([
90 record({ dedupeKey: "msg_1:" }),
91 record({ dedupeKey: "msg_1:" }),
92 record({ dedupeKey: "msg_1:" }),
93 ]);
94
95 expect(result.duplicatesDropped).toBe(2);
96 expect(result.buckets).toHaveLength(1);
97 expect(result.buckets[0]?.records).toBe(1);
98 expect(result.buckets[0]?.totals.outputTokens).toBe(50);
99 });
100
101 it("buckets by the day in the requested time zone", () => {
102 const utc = aggregate([record()], "UTC");
103 const losAngeles = aggregate([record()], "America/Los_Angeles");
104
105 expect(utc.buckets[0]?.day).toBe("2026-08-07");
106 expect(losAngeles.buckets[0]?.day).toBe("2026-08-06");
107 });
108
109 it("finds the day at a quarter-hour zone's midnight across interleaved buckets", () => {
110 const result = aggregate(
111 [
112 record({ timestampMs: Date.parse("2026-08-01T18:14:59.999Z") }),
113 record({ timestampMs: Date.parse("2026-08-01T18:15:00.000Z") }),
114 record({ timestampMs: Date.parse("2026-08-01T18:15:00.000Z"), model: "claude-opus-5" }),
115 record({ timestampMs: Date.parse("2026-08-01T18:16:00.000Z") }),
116 ],
117 "Asia/Kathmandu",
118 );
119
120 expect(result.buckets.map((bucket) => [bucket.day, bucket.model, bucket.records])).toEqual([
121 ["2026-08-01", "claude-fable-5", 1],
122 ["2026-08-02", "claude-fable-5", 2],
123 ["2026-08-02", "claude-opus-5", 1],
124 ]);
125 });
126
127 it("finds the day at a fixed offset's midnight between quarter hours", () => {
128 const result = aggregate(
129 [
130 record({ timestampMs: Date.parse("2026-08-01T23:58:59.999Z") }),
131 record({ timestampMs: Date.parse("2026-08-01T23:59:00.000Z") }),
132 ],
133 "+00:01",
134 );
135
136 expect(result.buckets.map((bucket) => [bucket.day, bucket.records])).toEqual([
137 ["2026-08-01", 1],
138 ["2026-08-02", 1],
139 ]);
140 });
141
142 it("splits an hourly request into fixed buckets anchored to its exact start", () => {
143 const result = aggregate(
144 [
145 record({ timestampMs: Date.parse("2026-08-07T02:40:13.944Z") }),
146 record({ timestampMs: Date.parse("2026-08-07T03:40:13.944Z") }),
147 ],
148 "America/Los_Angeles",
149 "hour",
150 );
151
152 expect(result.buckets.map((bucket) => [bucket.day, bucket.hourStart])).toEqual([
153 ["2026-08-06", "2026-08-07T02:37:00.000Z"],
154 ["2026-08-06", "2026-08-07T03:37:00.000Z"],
155 ]);
156 });
157
158 it("uses an inclusive start and exclusive end for rolling windows", () => {
159 const result = aggregate(
160 [
161 record({ timestampMs: Date.parse("2026-08-06T04:36:59.999Z") }),
162 record({ timestampMs: Date.parse("2026-08-06T04:37:00.000Z") }),
163 record({ timestampMs: Date.parse("2026-08-07T04:36:59.999Z") }),
164 record({ timestampMs: Date.parse("2026-08-07T04:37:00.000Z") }),
165 ],
166 "UTC",
167 "hour",
168 );
169
170 expect(result.outOfWindow).toBe(2);
171 expect(result.buckets.map((bucket) => bucket.hourStart)).toEqual([
172 "2026-08-06T04:37:00.000Z",
173 "2026-08-07T03:37:00.000Z",
174 ]);
175 });
176
177 it("counts tokens but not cost for a model with no rate", () => {
178 const result = aggregate([record({ model: "kimi-k3" })]);
179
180 expect(result.buckets[0]?.costUsd).toBe(0);
181 expect(result.buckets[0]?.costSource).toBe("unpriced");
182 expect(result.buckets[0]?.unpricedRecords).toBe(1);
183 expect(result.buckets[0]?.totals.outputTokens).toBe(50);
184 });
185
186 it("prefers a reported cost over the rate table", () => {
187 const result = aggregate([record({ reportedCostUsd: 1.25 })]);
188
189 expect(result.buckets[0]?.costUsd).toBe(1.25);
190 expect(result.buckets[0]?.costSource).toBe("providerReported");
191 });
192
193 it("folds a mapped model into its target and prices it there", () => {
194 const aggregator = new UsageAggregator({
195 timeZone: "UTC",
196 sinceDay: "2026-08-01",
197 untilDay: "2026-08-31",
198 rates,
199 modelAliases: resolveModelAliases({ "example-preview": "claude-fable-5" }),
200 });
201 aggregator.add(record());
202 aggregator.add(record({ model: "example-preview", rateModel: "example-preview-high" }));
203 const result = aggregator.finish();
204
205 expect(result.buckets).toHaveLength(1);
206 expect(result.buckets[0]?.model).toBe("claude-fable-5");
207 expect(result.buckets[0]?.records).toBe(2);
208 expect(result.buckets[0]?.costUsd).toBeCloseTo(0.00925, 9);
209 expect(result.buckets[0]?.unpricedRecords).toBe(0);
210 });
211});
212
213describe("resolveModelAliases", () => {
214 it("follows chains to the final model and drops chains that enter a loop", () => {
215 expect(
216 resolveModelAliases({
217 "preview[1m]": "preview",
218 preview: "example-model",
219 loop: "back",
220 back: "loop",
221 intoLoop: "loop",
222 self: "self",
223 }),
224 ).toEqual(
225 new Map([
226 ["preview[1m]", "example-model"],
227 ["preview", "example-model"],
228 ]),
229 );
230 });
231});