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 fast: false,
28 dedupeKey: "msg_1:",
29 ...overrides,
30 };
31}
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 };
41}
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;
56}
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", fast: true })],
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: [record({ provider: "codex", model: "gpt-5.2-codex", dedupeKey: null })],
83 tailRecords: [],
84 position: position({
85 codexState: {
86 model: "gpt-5.2-codex",
87 sessionId: "session-c",
88 lastUsageSignature: '{"input_tokens":1}',
89 sawSessionMeta: true,
90 suppressingForkCopies: false,
91 forkCopyAnchorMs: 0,
92 },
93 }),
94 });
95
96 const restored = decodeScanCache(JSON.parse(JSON.stringify(encodeScanCache(original))));
97
98 expect(restored.size).toBe(4);
99 expect(restored.get("/a.jsonl")).toEqual(original.get("/a.jsonl"));
100 expect(restored.get("/b.jsonl")).toEqual(original.get("/b.jsonl"));
101 expect(restored.get("/grok.jsonl")).toEqual(original.get("/grok.jsonl"));
102 expect(restored.get("/codex.jsonl")).toEqual(original.get("/codex.jsonl"));
103 });
104
105 it("drops an entry whose persisted parse state is corrupt", () => {
106 // Resuming with a bad reducer state would attach appended usage to the
107 // wrong model or replay fork-copied history; that entry must cold parse.
108 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
109 const poisoned = {
110 ...encoded,
111 files: {
112 "/a.jsonl": { ...encoded.files["/a.jsonl"]!, cs: { model: 42 } },
113 },
114 };
115
116 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
117 });
118
119 it("drops an entry whose guard length is outside the supported range", () => {
120 // The guard length sizes a Buffer in the reader; a bogus value would make
121 // every parse of that file fail and silently drop its usage.
122 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
123 const poisoned = {
124 ...encoded,
125 files: { "/a.jsonl": { ...encoded.files["/a.jsonl"]!, gl: 1e20 } },
126 };
127
128 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
129 });
130
131 it("drops an entry whose fast flag is not 0 or 1", () => {
132 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record({ fast: true })]]]));
133 const row = encoded.files["/a.jsonl"]!.r[0]!;
134 const poisoned = {
135 ...encoded,
136 files: { "/a.jsonl": { ...encoded.files["/a.jsonl"]!, r: [[...row.slice(0, 10), true]] } },
137 };
138
139 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
140 });
141
142 it("rejects a document from the previous cache version", () => {
143 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
144 const previous = { ...encoded, version: 3 };
145
146 expect(decodeScanCache(JSON.parse(JSON.stringify(previous))).size).toBe(0);
147 });
148
149 it("interns repeated model and session strings", () => {
150 const encoded = encodeScanCache(
151 cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" }), record()]]]),
152 );
153
154 expect(encoded.models).toEqual(["claude-fable-5"]);
155 expect(encoded.sessions).toEqual(["session-a"]);
156 });
157
158 it("treats a corrupt or foreign document as an empty cache", () => {
159 // A bad cache should cost one cold scan, never a broken page.
160 expect(decodeScanCache(null).size).toBe(0);
161 expect(decodeScanCache("nonsense").size).toBe(0);
162 expect(decodeScanCache({ version: 999, models: [], sessions: [], files: {} }).size).toBe(0);
163 });
164
165 it("skips malformed file entries but keeps good ones", () => {
166 const encoded = encodeScanCache(cacheWith([["/good.jsonl", 100, [record()]]]));
167 const withJunk = {
168 ...encoded,
169 files: { ...encoded.files, "/bad.jsonl": { s: "nope", m: 1, p: "claude", r: [] } },
170 };
171
172 const restored = decodeScanCache(JSON.parse(JSON.stringify(withJunk)));
173 expect([...restored.keys()]).toEqual(["/good.jsonl"]);
174 });
175
176 it("rejects the whole cache when an intern table holds a non-string", () => {
177 // models: [1] would pass the undefined guard, put a number in a record's
178 // model, and crash lookupRate at aggregate time.
179 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
180 const poisoned = { ...encoded, models: [1] };
181
182 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).size).toBe(0);
183 });
184
185 it("drops the whole entry when any row is corrupt, forcing a cold re-parse", () => {
186 // Keeping the surviving rows under the original (size, mtime) would read
187 // as a valid warm hit and the file would never be re-parsed.
188 const encoded = encodeScanCache(
189 cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" })]]]),
190 );
191 const rows = encoded.files["/a.jsonl"]!.r;
192 const poisoned = {
193 ...encoded,
194 files: {
195 "/a.jsonl": {
196 ...encoded.files["/a.jsonl"]!,
197 r: [rows[0]!, [...rows[1]!.slice(0, 3), "not-a-number", ...rows[1]!.slice(4)]],
198 },
199 },
200 };
201
202 const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned)));
203 expect(restored.has("/a.jsonl")).toBe(false);
204 });
205});
206
207describe("pruneScanCache", () => {
208 const retentionCutoffMs = 1000;
209
210 it("drops entries older than retention", () => {
211 const cache = cacheWith([["/old.jsonl", 500, [record()]]]);
212
213 const removed = pruneScanCache(cache, retentionCutoffMs);
214
215 expect(removed).toBe(1);
216 expect(cache.size).toBe(0);
217 });
218
219 it("keeps entries whose file has disappeared", () => {
220 const cache = cacheWith([["/gone.jsonl", 5000, [record()]]]);
221
222 pruneScanCache(cache, retentionCutoffMs);
223
224 expect(cache.size).toBe(1);
225 });
226});
227
228describe("dedupeWithinFile", () => {
229 it("keeps the first record per dedupe key", () => {
230 const kept = dedupeWithinFile([
231 record({ totals: { ...record().totals, outputTokens: 1 } }),
232 record({ totals: { ...record().totals, outputTokens: 999 } }),
233 record({ dedupeKey: "msg_2:" }),
234 ]);
235
236 expect(kept).toHaveLength(2);
237 expect(kept[0]?.totals.outputTokens).toBe(1);
238 });
239
240 it("keeps every record that has no dedupe key", () => {
241 expect(
242 dedupeWithinFile([record({ dedupeKey: null }), record({ dedupeKey: null })]),
243 ).toHaveLength(2);
244 });
245});