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

usageScanCache.test.ts

248 lines8.1 KB

1import { describe, expect, it } from "@effect/vitest";
2​
3import {
4 decodeScanCache,
5 dedupeWithinFile,
6 encodeScanCache,
7 pruneScanCache,
8 type CachedFile,
9 type ScanCache,
10} from "./usageScanCache.ts";
11import type { UsageRecord } from "./usageTranscripts.ts";
12​
13function record(overrides: Partial<UsageRecord> = {}): UsageRecord {
14 return {
15 provider: "claude",
16 timestampMs: 1_786_000_000_000,
17 model: "claude-fable-5",
18 sessionId: "session-a",
19 totals: {
20 uncachedInputTokens: 2,
21 cachedInputTokens: 1000,
22 cacheCreationTokens: 10,
23 outputTokens: 50,
24 reasoningTokens: 0,
25 },
26 reportedCostUsd: null,
27 speed: "standard",
28 dedupeKey: "msg_1:",
29 ...overrides,
30 };
32​
33function position(overrides: Partial<CachedFile["position"]> = {}): CachedFile["position"] {
34 return {
35 resumeOffset: 120,
36 guardLength: 64,
37 guardHash: 0xdeadbeef,
38 codexState: null,
39 ...overrides,
40 };
42​
43function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][]): ScanCache {
44 const cache: ScanCache = new Map();
45 for (const [path, mtimeMs, records] of entries) {
46 cache.set(path, {
47 size: records.length * 10,
48 mtimeMs,
49 provider: "claude",
50 records,
51 tailRecords: [],
52 position: position(),
53 });
54 }
55 return cache;
57​
58describe("scan cache round trip", () => {
59 it("restores records unchanged", () => {
60 const original = cacheWith([
61 [
62 "/a.jsonl",
63 100,
64 [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5-5", speed: "fast" })],
65 ],
66 ["/b.jsonl", 200, [record({ sessionId: "session-b", reportedCostUsd: 1.5 })]],
67 ]);
68 original.set("/grok.jsonl", {
69 size: 40,
70 mtimeMs: 300,
71 provider: "grok",
72 records: [
73 record({ provider: "grok", model: "grok-4.5-build", dedupeKey: "s:p:grok-4.5-build" }),
74 ],
75 tailRecords: [record({ provider: "grok", model: "grok-4.5-build", dedupeKey: null })],
76 position: position({ resumeOffset: 30, guardLength: 30, guardHash: 123 }),
77 });
78 original.set("/codex.jsonl", {
79 size: 80,
80 mtimeMs: 400,
81 provider: "codex",
82 records: [
83 record({ provider: "codex", model: "gpt-6-astra", dedupeKey: null, speed: "ultrafast" }),
84 ],
85 tailRecords: [],
86 position: position({
87 codexState: {
88 model: "gpt-6-astra",
89 speed: "ultrafast",
90 sessionId: "session-c",
91 lastUsageSignature: '{"input_tokens":1}',
92 sawSessionMeta: true,
93 suppressingForkCopies: false,
94 forkCopyAnchorMs: 0,
95 },
96 }),
97 });
98​
99 const restored = decodeScanCache(JSON.parse(JSON.stringify(encodeScanCache(original))));
100​
101 expect(restored.size).toBe(4);
102 expect(restored.get("/a.jsonl")).toEqual(original.get("/a.jsonl"));
103 expect(restored.get("/b.jsonl")).toEqual(original.get("/b.jsonl"));
104 expect(restored.get("/grok.jsonl")).toEqual(original.get("/grok.jsonl"));
105 expect(restored.get("/codex.jsonl")).toEqual(original.get("/codex.jsonl"));
106 });
107​
108 it("drops an entry whose persisted parse state is corrupt", () => {
109 // Resuming with a bad reducer state would attach appended usage to the
110 // wrong model or replay fork-copied history; that entry must cold parse.
111 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
112 const poisoned = {
113 ...encoded,
114 files: {
115 "/a.jsonl": { ...encoded.files["/a.jsonl"]!, cs: { model: 42 } },
116 },
117 };
118​
119 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
120 });
121​
122 it("drops an entry whose guard length is outside the supported range", () => {
123 // The guard length sizes a Buffer in the reader; a bogus value would make
124 // every parse of that file fail and silently drop its usage.
125 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
126 const poisoned = {
127 ...encoded,
128 files: { "/a.jsonl": { ...encoded.files["/a.jsonl"]!, gl: 1e20 } },
129 };
130​
131 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
132 });
133​
134 it("drops an entry whose speed is not a known index", () => {
135 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record({ speed: "fast" })]]]));
136 const row = encoded.files["/a.jsonl"]!.r[0]!;
137 const poisoned = {
138 ...encoded,
139 files: { "/a.jsonl": { ...encoded.files["/a.jsonl"]!, r: [[...row.slice(0, 10), true]] } },
140 };
141​
142 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
143 });
144​
145 it("rejects a document from before records carried a speed", () => {
146 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
147 const previous = { ...encoded, version: 3 };
148​
149 expect(decodeScanCache(JSON.parse(JSON.stringify(previous))).size).toBe(0);
150 });
151​
152 it("interns repeated model and session strings", () => {
153 const encoded = encodeScanCache(
154 cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" }), record()]]]),
155 );
156​
157 expect(encoded.models).toEqual(["claude-fable-5"]);
158 expect(encoded.sessions).toEqual(["session-a"]);
159 });
160​
161 it("treats a corrupt or foreign document as an empty cache", () => {
162 // A bad cache should cost one cold scan, never a broken page.
163 expect(decodeScanCache(null).size).toBe(0);
164 expect(decodeScanCache("nonsense").size).toBe(0);
165 expect(decodeScanCache({ version: 999, models: [], sessions: [], files: {} }).size).toBe(0);
166 });
167​
168 it("skips malformed file entries but keeps good ones", () => {
169 const encoded = encodeScanCache(cacheWith([["/good.jsonl", 100, [record()]]]));
170 const withJunk = {
171 ...encoded,
172 files: { ...encoded.files, "/bad.jsonl": { s: "nope", m: 1, p: "claude", r: [] } },
173 };
174​
175 const restored = decodeScanCache(JSON.parse(JSON.stringify(withJunk)));
176 expect([...restored.keys()]).toEqual(["/good.jsonl"]);
177 });
178​
179 it("rejects the whole cache when an intern table holds a non-string", () => {
180 // models: [1] would pass the undefined guard, put a number in a record's
181 // model, and crash lookupRate at aggregate time.
182 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
183 const poisoned = { ...encoded, models: [1] };
184​
185 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).size).toBe(0);
186 });
187​
188 it("drops the whole entry when any row is corrupt, forcing a cold re-parse", () => {
189 // Keeping the surviving rows under the original (size, mtime) would read
190 // as a valid warm hit and the file would never be re-parsed.
191 const encoded = encodeScanCache(
192 cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" })]]]),
193 );
194 const rows = encoded.files["/a.jsonl"]!.r;
195 const poisoned = {
196 ...encoded,
197 files: {
198 "/a.jsonl": {
199 ...encoded.files["/a.jsonl"]!,
200 r: [rows[0]!, [...rows[1]!.slice(0, 3), "not-a-number", ...rows[1]!.slice(4)]],
201 },
202 },
203 };
204​
205 const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned)));
206 expect(restored.has("/a.jsonl")).toBe(false);
207 });
208});
209​
210describe("pruneScanCache", () => {
211 const retentionCutoffMs = 1000;
212​
213 it("drops entries older than retention", () => {
214 const cache = cacheWith([["/old.jsonl", 500, [record()]]]);
215​
216 const removed = pruneScanCache(cache, retentionCutoffMs);
217​
218 expect(removed).toBe(1);
219 expect(cache.size).toBe(0);
220 });
221​
222 it("keeps entries whose file has disappeared", () => {
223 const cache = cacheWith([["/gone.jsonl", 5000, [record()]]]);
224​
225 pruneScanCache(cache, retentionCutoffMs);
226​
227 expect(cache.size).toBe(1);
228 });
229});
230​
231describe("dedupeWithinFile", () => {
232 it("keeps the first record per dedupe key", () => {
233 const kept = dedupeWithinFile([
234 record({ totals: { ...record().totals, outputTokens: 1 } }),
235 record({ totals: { ...record().totals, outputTokens: 999 } }),
236 record({ dedupeKey: "msg_2:" }),
237 ]);
238​
239 expect(kept).toHaveLength(2);
240 expect(kept[0]?.totals.outputTokens).toBe(1);
241 });
242​
243 it("keeps every record that has no dedupe key", () => {
244 expect(
245 dedupeWithinFile([record({ dedupeKey: null }), record({ dedupeKey: null })]),
246 ).toHaveLength(2);
247 });
248});