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