Open History to see the last commit
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 dedupeKey: "msg_1:",
28 ...overrides,
29 };
30}
31
32function position(overrides: Partial<CachedFile["position"]> = {}): CachedFile["position"] {
33 return {
34 resumeOffset: 120,
35 guardLength: 64,
36 guardHash: 0xdeadbeef,
37 codexState: null,
38 ...overrides,
39 };
40}
41
42function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][]): ScanCache {
43 const cache: ScanCache = new Map();
44 for (const [path, mtimeMs, records] of entries) {
45 cache.set(path, {
46 size: records.length * 10,
47 mtimeMs,
48 provider: "claude",
49 records,
50 tailRecords: [],
51 position: position(),
52 });
53 }
54 return cache;
55}
56
57describe("scan cache round trip", () => {
58 it("restores records unchanged", () => {
59 const original = cacheWith([
60 ["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5" })]],
61 ["/b.jsonl", 200, [record({ sessionId: "session-b", reportedCostUsd: 1.5 })]],
62 ]);
63 original.set("/grok.jsonl", {
64 size: 40,
65 mtimeMs: 300,
66 provider: "grok",
67 records: [
68 record({ provider: "grok", model: "grok-4.5-build", dedupeKey: "s:p:grok-4.5-build" }),
69 ],
70 tailRecords: [record({ provider: "grok", model: "grok-4.5-build", dedupeKey: null })],
71 position: position({ resumeOffset: 30, guardLength: 30, guardHash: 123 }),
72 });
73 original.set("/codex.jsonl", {
74 size: 80,
75 mtimeMs: 400,
76 provider: "codex",
77 records: [record({ provider: "codex", model: "gpt-5.2-codex", dedupeKey: null })],
78 tailRecords: [],
79 position: position({
80 codexState: {
81 model: "gpt-5.2-codex",
82 sessionId: "session-c",
83 lastUsageSignature: '{"input_tokens":1}',
84 sawSessionMeta: true,
85 suppressingForkCopies: false,
86 forkCopyAnchorMs: 0,
87 },
88 }),
89 });
90
91 const restored = decodeScanCache(JSON.parse(JSON.stringify(encodeScanCache(original))));
92
93 expect(restored.size).toBe(4);
94 expect(restored.get("/a.jsonl")).toEqual(original.get("/a.jsonl"));
95 expect(restored.get("/b.jsonl")).toEqual(original.get("/b.jsonl"));
96 expect(restored.get("/grok.jsonl")).toEqual(original.get("/grok.jsonl"));
97 expect(restored.get("/codex.jsonl")).toEqual(original.get("/codex.jsonl"));
98 });
99
100 it("drops an entry whose persisted parse state is corrupt", () => {
101 // Resuming with a bad reducer state would attach appended usage to the
102 // wrong model or replay fork-copied history; that entry must cold parse.
103 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
104 const poisoned = {
105 ...encoded,
106 files: {
107 "/a.jsonl": { ...encoded.files["/a.jsonl"]!, cs: { model: 42 } },
108 },
109 };
110
111 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
112 });
113
114 it("drops an entry whose guard length is outside the supported range", () => {
115 // The guard length sizes a Buffer in the reader; a bogus value would make
116 // every parse of that file fail and silently drop its usage.
117 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
118 const poisoned = {
119 ...encoded,
120 files: { "/a.jsonl": { ...encoded.files["/a.jsonl"]!, gl: 1e20 } },
121 };
122
123 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
124 });
125
126 it("rejects a document from the previous cache version", () => {
127 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
128 const previous = { ...encoded, version: 2 };
129
130 expect(decodeScanCache(JSON.parse(JSON.stringify(previous))).size).toBe(0);
131 });
132
133 it("interns repeated model and session strings", () => {
134 const encoded = encodeScanCache(
135 cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" }), record()]]]),
136 );
137
138 expect(encoded.models).toEqual(["claude-fable-5"]);
139 expect(encoded.sessions).toEqual(["session-a"]);
140 });
141
142 it("treats a corrupt or foreign document as an empty cache", () => {
143 // A bad cache should cost one cold scan, never a broken page.
144 expect(decodeScanCache(null).size).toBe(0);
145 expect(decodeScanCache("nonsense").size).toBe(0);
146 expect(decodeScanCache({ version: 999, models: [], sessions: [], files: {} }).size).toBe(0);
147 });
148
149 it("skips malformed file entries but keeps good ones", () => {
150 const encoded = encodeScanCache(cacheWith([["/good.jsonl", 100, [record()]]]));
151 const withJunk = {
152 ...encoded,
153 files: { ...encoded.files, "/bad.jsonl": { s: "nope", m: 1, p: "claude", r: [] } },
154 };
155
156 const restored = decodeScanCache(JSON.parse(JSON.stringify(withJunk)));
157 expect([...restored.keys()]).toEqual(["/good.jsonl"]);
158 });
159
160 it("rejects the whole cache when an intern table holds a non-string", () => {
161 // models: [1] would pass the undefined guard, put a number in a record's
162 // model, and crash lookupRate at aggregate time.
163 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
164 const poisoned = { ...encoded, models: [1] };
165
166 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).size).toBe(0);
167 });
168
169 it("drops the whole entry when any row is corrupt, forcing a cold re-parse", () => {
170 // Keeping the surviving rows under the original (size, mtime) would read
171 // as a valid warm hit and the file would never be re-parsed.
172 const encoded = encodeScanCache(
173 cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" })]]]),
174 );
175 const rows = encoded.files["/a.jsonl"]!.r;
176 const poisoned = {
177 ...encoded,
178 files: {
179 "/a.jsonl": {
180 ...encoded.files["/a.jsonl"]!,
181 r: [rows[0]!, [...rows[1]!.slice(0, 3), "not-a-number", ...rows[1]!.slice(4)]],
182 },
183 },
184 };
185
186 const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned)));
187 expect(restored.has("/a.jsonl")).toBe(false);
188 });
189});
190
191describe("pruneScanCache", () => {
192 const retentionCutoffMs = 1000;
193
194 it("drops entries older than retention", () => {
195 const cache = cacheWith([["/old.jsonl", 500, [record()]]]);
196
197 const removed = pruneScanCache(cache, {
198 livePaths: new Set(),
199 walkedRoots: ["/"],
200 windowStartMs: 400,
201 retentionCutoffMs,
202 });
203
204 expect(removed).toBe(1);
205 expect(cache.size).toBe(0);
206 });
207
208 it("drops in-window entries whose file has disappeared", () => {
209 const cache = cacheWith([["/gone.jsonl", 5000, [record()]]]);
210
211 pruneScanCache(cache, {
212 livePaths: new Set(),
213 walkedRoots: ["/"],
214 windowStartMs: 4000,
215 retentionCutoffMs,
216 });
217
218 expect(cache.size).toBe(0);
219 });
220
221 it("keeps entries outside the walked window that are still within retention", () => {
222 // Viewing 7 days must not evict the 30-day entries, which that walk never
223 // looked for and so cannot prove are gone.
224 const cache = cacheWith([["/older-but-valid.jsonl", 2000, [record()]]]);
225
226 const removed = pruneScanCache(cache, {
227 livePaths: new Set(),
228 walkedRoots: ["/"],
229 windowStartMs: 4000,
230 retentionCutoffMs,
231 });
232
233 expect(removed).toBe(0);
234 expect(cache.size).toBe(1);
235 });
236
237 it("keeps entries the walk saw", () => {
238 const cache = cacheWith([["/live.jsonl", 5000, [record()]]]);
239
240 pruneScanCache(cache, {
241 livePaths: new Set(["/live.jsonl"]),
242 walkedRoots: ["/"],
243 windowStartMs: 4000,
244 retentionCutoffMs,
245 });
246
247 expect(cache.size).toBe(1);
248 });
249});
250
251describe("pruneScanCache with an unwalked root", () => {
252 it("keeps in-window entries for a provider whose directory was not walked", () => {
253 // A missing provider root or failed settings read leaves livePaths without
254 // that provider's files. Its warm entries must survive the pass.
255 const cache = cacheWith([["/codex/sessions/a.jsonl", 5000, [record()]]]);
256
257 const removed = pruneScanCache(cache, {
258 livePaths: new Set(),
259 walkedRoots: ["/claude/projects"],
260 windowStartMs: 4000,
261 retentionCutoffMs: 1000,
262 });
263
264 expect(removed).toBe(0);
265 expect(cache.size).toBe(1);
266 });
267
268 it("keeps entries under a sibling path that only shares the walked root prefix", () => {
269 const cache = cacheWith([["/claude/projects-copy/a.jsonl", 5000, [record()]]]);
270
271 const removed = pruneScanCache(cache, {
272 livePaths: new Set(),
273 walkedRoots: ["/claude/projects"],
274 windowStartMs: 4000,
275 retentionCutoffMs: 1000,
276 });
277
278 expect(removed).toBe(0);
279 expect(cache.size).toBe(1);
280 });
281});
282
283describe("dedupeWithinFile", () => {
284 it("keeps the first record per dedupe key", () => {
285 const kept = dedupeWithinFile([
286 record({ totals: { ...record().totals, outputTokens: 1 } }),
287 record({ totals: { ...record().totals, outputTokens: 999 } }),
288 record({ dedupeKey: "msg_2:" }),
289 ]);
290
291 expect(kept).toHaveLength(2);
292 expect(kept[0]?.totals.outputTokens).toBe(1);
293 });
294
295 it("keeps every record that has no dedupe key", () => {
296 expect(
297 dedupeWithinFile([record({ dedupeKey: null }), record({ dedupeKey: null })]),
298 ).toHaveLength(2);
299 });
300});