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