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("round-trips Devin ACP event-log records", () => {
134 const original: ScanCache = new Map([
135 [
136 "events.thread-1.log",
137 {
138 size: 128,
139 mtimeMs: 300,
140 provider: "devin",
141 records: [
142 record({
143 provider: "devin",
144 model: "gpt-5-6-luna-medium",
145 sessionId: "acp-session-1",
146 reportedCostUsd: 0.0125,
147 dedupeKey: "event-1",
148 }),
149 ],
150 tailRecords: [],
151 position: position(),
152 },
153 ],
154 ]);
155
156 const restored = decodeScanCache(JSON.parse(JSON.stringify(encodeScanCache(original))));
157 expect(restored.get("events.thread-1.log")).toEqual(original.get("events.thread-1.log"));
158 });
159
160 it("interns repeated model and session strings", () => {
161 const encoded = encodeScanCache(
162 cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" }), record()]]]),
163 );
164
165 expect(encoded.models).toEqual(["claude-fable-5"]);
166 expect(encoded.sessions).toEqual(["session-a"]);
167 });
168
169 it("treats a corrupt or foreign document as an empty cache", () => {
170 // A bad cache should cost one cold scan, never a broken page.
171 expect(decodeScanCache(null).size).toBe(0);
172 expect(decodeScanCache("nonsense").size).toBe(0);
173 expect(decodeScanCache({ version: 999, models: [], sessions: [], files: {} }).size).toBe(0);
174 });
175
176 it("skips malformed file entries but keeps good ones", () => {
177 const encoded = encodeScanCache(cacheWith([["/good.jsonl", 100, [record()]]]));
178 const withJunk = {
179 ...encoded,
180 files: { ...encoded.files, "/bad.jsonl": { s: "nope", m: 1, p: "claude", r: [] } },
181 };
182
183 const restored = decodeScanCache(JSON.parse(JSON.stringify(withJunk)));
184 expect([...restored.keys()]).toEqual(["/good.jsonl"]);
185 });
186
187 it("rejects the whole cache when an intern table holds a non-string", () => {
188 // models: [1] would pass the undefined guard, put a number in a record's
189 // model, and crash lookupRate at aggregate time.
190 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
191 const poisoned = { ...encoded, models: [1] };
192
193 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).size).toBe(0);
194 });
195
196 it("drops the whole entry when any row is corrupt, forcing a cold re-parse", () => {
197 // Keeping the surviving rows under the original (size, mtime) would read
198 // as a valid warm hit and the file would never be re-parsed.
199 const encoded = encodeScanCache(
200 cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" })]]]),
201 );
202 const rows = encoded.files["/a.jsonl"]!.r;
203 const poisoned = {
204 ...encoded,
205 files: {
206 "/a.jsonl": {
207 ...encoded.files["/a.jsonl"]!,
208 r: [rows[0]!, [...rows[1]!.slice(0, 3), "not-a-number", ...rows[1]!.slice(4)]],
209 },
210 },
211 };
212
213 const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned)));
214 expect(restored.has("/a.jsonl")).toBe(false);
215 });
216});
217
218describe("pruneScanCache", () => {
219 const retentionCutoffMs = 1000;
220
221 it("drops entries older than retention", () => {
222 const cache = cacheWith([["/old.jsonl", 500, [record()]]]);
223
224 const removed = pruneScanCache(cache, {
225 livePaths: new Set(),
226 walkedRoots: ["/"],
227 windowStartMs: 400,
228 retentionCutoffMs,
229 });
230
231 expect(removed).toBe(1);
232 expect(cache.size).toBe(0);
233 });
234
235 it("drops in-window entries whose file has disappeared", () => {
236 const cache = cacheWith([["/gone.jsonl", 5000, [record()]]]);
237
238 pruneScanCache(cache, {
239 livePaths: new Set(),
240 walkedRoots: ["/"],
241 windowStartMs: 4000,
242 retentionCutoffMs,
243 });
244
245 expect(cache.size).toBe(0);
246 });
247
248 it("keeps entries outside the walked window that are still within retention", () => {
249 // Viewing 7 days must not evict the 30-day entries, which that walk never
250 // looked for and so cannot prove are gone.
251 const cache = cacheWith([["/older-but-valid.jsonl", 2000, [record()]]]);
252
253 const removed = pruneScanCache(cache, {
254 livePaths: new Set(),
255 walkedRoots: ["/"],
256 windowStartMs: 4000,
257 retentionCutoffMs,
258 });
259
260 expect(removed).toBe(0);
261 expect(cache.size).toBe(1);
262 });
263
264 it("keeps entries the walk saw", () => {
265 const cache = cacheWith([["/live.jsonl", 5000, [record()]]]);
266
267 pruneScanCache(cache, {
268 livePaths: new Set(["/live.jsonl"]),
269 walkedRoots: ["/"],
270 windowStartMs: 4000,
271 retentionCutoffMs,
272 });
273
274 expect(cache.size).toBe(1);
275 });
276});
277
278describe("pruneScanCache with an unwalked root", () => {
279 it("keeps in-window entries for a provider whose directory was not walked", () => {
280 // A missing provider root or failed settings read leaves livePaths without
281 // that provider's files. Its warm entries must survive the pass.
282 const cache = cacheWith([["/codex/sessions/a.jsonl", 5000, [record()]]]);
283
284 const removed = pruneScanCache(cache, {
285 livePaths: new Set(),
286 walkedRoots: ["/claude/projects"],
287 windowStartMs: 4000,
288 retentionCutoffMs: 1000,
289 });
290
291 expect(removed).toBe(0);
292 expect(cache.size).toBe(1);
293 });
294
295 it("keeps entries under a sibling path that only shares the walked root prefix", () => {
296 const cache = cacheWith([["/claude/projects-copy/a.jsonl", 5000, [record()]]]);
297
298 const removed = pruneScanCache(cache, {
299 livePaths: new Set(),
300 walkedRoots: ["/claude/projects"],
301 windowStartMs: 4000,
302 retentionCutoffMs: 1000,
303 });
304
305 expect(removed).toBe(0);
306 expect(cache.size).toBe(1);
307 });
308});
309
310describe("dedupeWithinFile", () => {
311 it("keeps the first record per dedupe key", () => {
312 const kept = dedupeWithinFile([
313 record({ totals: { ...record().totals, outputTokens: 1 } }),
314 record({ totals: { ...record().totals, outputTokens: 999 } }),
315 record({ dedupeKey: "msg_2:" }),
316 ]);
317
318 expect(kept).toHaveLength(2);
319 expect(kept[0]?.totals.outputTokens).toBe(1);
320 });
321
322 it("keeps every record that has no dedupe key", () => {
323 expect(
324 dedupeWithinFile([record({ dedupeKey: null }), record({ dedupeKey: null })]),
325 ).toHaveLength(2);
326 });
327});