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

usageScanCache.test.ts

269 lines9.0 KB

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