Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usageAggregation.test.ts

242 lines7.3 KB

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 };
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();
62​
63describe("UsageAggregator", () => {
64 it("uses provider catalog rates for both cost and cache savings without affecting other providers", () => {
65 const aggregator = new UsageAggregator({
66 timeZone: "UTC",
67 sinceDay: "2026-08-01",
68 untilDay: "2026-08-31",
69 rates,
70 providerRates: {
71 devin: new Map([
72 [
73 "claude-fable-5",
74 {
75 inputCostPerToken: 2e-5,
76 outputCostPerToken: 8e-5,
77 cacheReadCostPerToken: 2e-6,
78 cacheCreationCostPerToken: 3e-5,
79 },
80 ],
81 ]),
82 },
83 });
84 aggregator.add(record());
85 aggregator.add(record({ provider: "devin" }));
86 const buckets = aggregator.finish().buckets;
87 expect(buckets.find((bucket) => bucket.provider === "claude")?.costUsd).toBeCloseTo(
88 0.004625,
89 9,
90 );
91 expect(buckets.find((bucket) => bucket.provider === "claude")?.cacheSavingsUsd).toBeCloseTo(
92 0.009,
93 9,
94 );
95 expect(buckets.find((bucket) => bucket.provider === "devin")?.costUsd).toBeCloseTo(0.0083, 9);
96 expect(buckets.find((bucket) => bucket.provider === "devin")?.cacheSavingsUsd).toBeCloseTo(
97 0.018,
98 9,
99 );
100 });
101​
102 it("requires exact bounds for hourly aggregation", () => {
103 expect(
104 () =>
105 new UsageAggregator({
106 timeZone: "UTC",
107 sinceDay: "2026-08-01",
108 untilDay: "2026-08-31",
109 resolution: "hour",
110 rates,
111 }),
112 ).toThrow("requires exact time bounds");
113 });
114​
115 it("keeps only the first record for a repeated dedupe key", () => {
116 const result = aggregate([
117 record({ dedupeKey: "msg_1:" }),
118 record({ dedupeKey: "msg_1:" }),
119 record({ dedupeKey: "msg_1:" }),
120 ]);
121​
122 expect(result.duplicatesDropped).toBe(2);
123 expect(result.buckets).toHaveLength(1);
124 expect(result.buckets[0]?.records).toBe(1);
125 expect(result.buckets[0]?.totals.outputTokens).toBe(50);
126 });
127​
128 it("still sums records that carry no dedupe key", () => {
129 const result = aggregate([record(), record()]);
130​
131 expect(result.duplicatesDropped).toBe(0);
132 expect(result.buckets[0]?.totals.outputTokens).toBe(100);
133 });
134​
135 it("buckets by the day in the requested time zone", () => {
136 const utc = aggregate([record()], "UTC");
137 const losAngeles = aggregate([record()], "America/Los_Angeles");
138​
139 expect(utc.buckets[0]?.day).toBe("2026-08-07");
140 expect(losAngeles.buckets[0]?.day).toBe("2026-08-06");
141 });
142​
143 it("splits an hourly request into fixed buckets anchored to its exact start", () => {
144 const result = aggregate(
145 [
146 record({ timestampMs: Date.parse("2026-08-07T02:40:13.944Z") }),
147 record({ timestampMs: Date.parse("2026-08-07T03:40:13.944Z") }),
148 ],
149 "America/Los_Angeles",
150 "hour",
151 );
152​
153 expect(result.buckets.map((bucket) => [bucket.day, bucket.hourStart])).toEqual([
154 ["2026-08-06", "2026-08-07T02:37:00.000Z"],
155 ["2026-08-06", "2026-08-07T03:37:00.000Z"],
156 ]);
157 });
158​
159 it("uses an inclusive start and exclusive end for rolling windows", () => {
160 const result = aggregate(
161 [
162 record({ timestampMs: Date.parse("2026-08-06T04:36:59.999Z") }),
163 record({ timestampMs: Date.parse("2026-08-06T04:37:00.000Z") }),
164 record({ timestampMs: Date.parse("2026-08-07T04:36:59.999Z") }),
165 record({ timestampMs: Date.parse("2026-08-07T04:37:00.000Z") }),
166 ],
167 "UTC",
168 "hour",
169 );
170​
171 expect(result.outOfWindow).toBe(2);
172 expect(result.buckets.map((bucket) => bucket.hourStart)).toEqual([
173 "2026-08-06T04:37:00.000Z",
174 "2026-08-07T03:37:00.000Z",
175 ]);
176 });
177​
178 it("keeps daily payloads collapsed when hourly resolution is not requested", () => {
179 const result = aggregate([
180 record({ timestampMs: Date.parse("2026-08-07T04:05:13.944Z") }),
181 record({ timestampMs: Date.parse("2026-08-07T05:05:13.944Z") }),
182 ]);
183​
184 expect(result.buckets).toHaveLength(1);
185 expect(result.buckets[0]?.hourStart).toBeUndefined();
186 expect(result.buckets[0]?.records).toBe(2);
187 });
188​
189 it("prices against the rate table", () => {
190 const result = aggregate([record()]);
191​
192 // 100*1e-5 + 1000*1e-6 + 10*1.25e-5 + 50*5e-5
193 expect(result.buckets[0]?.costUsd).toBeCloseTo(0.004625, 9);
194 expect(result.buckets[0]?.costSource).toBe("modelPriced");
195 });
196​
197 it("counts tokens but not cost for a model with no rate", () => {
198 const result = aggregate([record({ model: "kimi-k3" })]);
199​
200 expect(result.buckets[0]?.costUsd).toBe(0);
201 expect(result.buckets[0]?.costSource).toBe("unpriced");
202 expect(result.buckets[0]?.unpricedRecords).toBe(1);
203 expect(result.buckets[0]?.totals.outputTokens).toBe(50);
204 });
205​
206 it("prefers a reported cost over the rate table", () => {
207 const result = aggregate([record({ reportedCostUsd: 1.25 })]);
208​
209 expect(result.buckets[0]?.costUsd).toBe(1.25);
210 expect(result.buckets[0]?.costSource).toBe("providerReported");
211 });
212​
213 it("drops records outside the window", () => {
214 const result = aggregate([record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") })]);
215​
216 expect(result.outOfWindow).toBe(1);
217 expect(result.buckets).toHaveLength(0);
218 });
219​
220 it("reports whether a record contributed", () => {
221 const aggregator = new UsageAggregator({
222 timeZone: "UTC",
223 sinceDay: "2026-08-01",
224 untilDay: "2026-08-31",
225 rates,
226 });
227​
228 expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(true);
229 expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(false);
230 expect(aggregator.add(record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") }))).toBe(false);
231 });
232​
233 it("separates providers and models into their own buckets", () => {
234 const result = aggregate([
235 record(),
236 record({ provider: "codex", model: "gpt-5.6-sol" }),
237 record({ model: "claude-opus-5" }),
238 ]);
239​
240 expect(result.buckets).toHaveLength(3);
241 });
242});