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

usageAggregation.test.ts

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