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

usageScanCache.test.ts

299 lines9.2 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 "@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 };
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 };
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;
60​
61describe("scan cache round trip", () => {
62 it("restores cached history unchanged except for Claude local placeholders", () => {
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 [
70 "/b.jsonl",
71 200,
72 [
73 record({
74 sessionId: "session-b",
75 reportedCostUsd: 1.5,
76 totals: {
77 uncachedInputTokens: 0,
78 cachedInputTokens: 0,
79 cacheCreationTokens: 0,
80 outputTokens: 0,
81 reasoningTokens: 0,
82 },
83 }),
84 ],
85 ],
86 ]);
87 original.set("/grok.jsonl", {
88 size: 40,
89 mtimeMs: 300,
90 provider: "grok",
91 records: [
92 record({ provider: "grok", model: "grok-4.5-build", dedupeKey: "s:p:grok-4.5-build" }),
93 record({ provider: "grok", model: "<synthetic>", dedupeKey: "s:p:<synthetic>" }),
94 ],
95 tailRecords: [record({ provider: "grok", model: "<synthetic>", dedupeKey: null })],
96 position: position({ resumeOffset: 30, guardLength: 30, guardHash: 123 }),
97 });
98 original.set("/codex.jsonl", {
99 size: 80,
100 mtimeMs: 400,
101 provider: "codex",
102 records: [
103 record({ provider: "codex", model: "gpt-6-astra", dedupeKey: null, speed: "ultrafast" }),
104 ],
105 tailRecords: [],
106 position: position({
107 state: {
108 model: "gpt-6-astra",
109 speed: "ultrafast",
110 sessionId: "session-c",
111 lastUsageSignature: '{"input_tokens":1}',
112 sawSessionMeta: true,
113 suppressingForkCopies: false,
114 forkCopyAnchorMs: 0,
115 },
116 }),
117 });
118​
119 original.set("/a.jsonl", {
120 ...original.get("/a.jsonl")!,
121 tailRecords: [record({ dedupeKey: "msg_tail:" })],
122 });
123 const claude = original.get("/a.jsonl")!;
124 const cached = new Map(original);
125 cached.set("/a.jsonl", {
126 ...claude,
127 records: [...claude.records, record({ model: "<synthetic>" })],
128 tailRecords: [
129 ...claude.tailRecords,
130 record({ model: "<synthetic>", dedupeKey: "msg_tail:" }),
131 ],
132 });
133 const restored = decodeScanCache(
134 JSON.parse(JSON.stringify(encodeScanCache(cached))),
135 TEST_FORMAT_MAP,
136 );
137​
138 expect(restored).toEqual(original);
139 });
140​
141 it("drops an entry whose persisted parse state is corrupt", () => {
142 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
143 const poisoned = {
144 ...encoded,
145 files: {
146 "/a.jsonl": { ...encoded.files["/a.jsonl"]!, cs: { model: 42 } },
147 },
148 };
149​
150 expect(
151 decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP).has("/a.jsonl"),
152 ).toBe(false);
153 });
154​
155 it("drops an entry whose guard length is outside the supported range", () => {
156 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
157 const poisoned = {
158 ...encoded,
159 files: { "/a.jsonl": { ...encoded.files["/a.jsonl"]!, gl: 1e20 } },
160 };
161​
162 expect(
163 decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP).has("/a.jsonl"),
164 ).toBe(false);
165 });
166​
167 it("drops an entry whose speed is not a known index", () => {
168 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record({ speed: "fast" })]]]));
169 const row = encoded.files["/a.jsonl"]!.r[0]!;
170 const poisoned = {
171 ...encoded,
172 files: { "/a.jsonl": { ...encoded.files["/a.jsonl"]!, r: [[...row.slice(0, 10), true]] } },
173 };
174​
175 expect(
176 decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP).has("/a.jsonl"),
177 ).toBe(false);
178 });
179​
180 it("rejects a document from before records carried a speed", () => {
181 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
182 const previous = { ...encoded, version: 3 };
183​
184 expect(decodeScanCache(JSON.parse(JSON.stringify(previous)), TEST_FORMAT_MAP).size).toBe(0);
185 });
186​
187 it("rewrites only changed entries and still restores the whole cache", () => {
188 const write = makeScanCacheWriter();
189 const cache = cacheWith([
190 ["/a.jsonl", 100, [record()]],
191 ["/b.jsonl", 200, [record({ sessionId: "session-b" })]],
192 ]);
193 const sources = { "claude\u0000/projects": { dir: "/projects", volumeId: "1:2" } };
194 expect(decodeScanCache(JSON.parse(write(cache, { sources })), TEST_FORMAT_MAP)).toEqual(cache);
195​
196 cache.set("/b.jsonl", {
197 ...cache.get("/b.jsonl")!,
198 size: 30,
199 records: [record({ sessionId: "session-c", model: "claude-opus-5-5", dedupeKey: "msg_3:" })],
200 });
201 const document = JSON.parse(write(cache, { sources }));
202 expect(decodeScanCache(document, TEST_FORMAT_MAP)).toEqual(cache);
203 expect(document.sources).toEqual(sources);
204 });
205​
206 it("interns repeated model and session strings", () => {
207 const encoded = encodeScanCache(
208 cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" }), record()]]]),
209 );
210​
211 expect(encoded.models).toEqual(["claude-fable-5"]);
212 expect(encoded.sessions).toEqual(["session-a"]);
213 });
214​
215 it("treats a corrupt or foreign document as an empty cache", () => {
216 expect(decodeScanCache(null, TEST_FORMAT_MAP).size).toBe(0);
217 expect(decodeScanCache("nonsense", TEST_FORMAT_MAP).size).toBe(0);
218 expect(
219 decodeScanCache({ version: 999, models: [], sessions: [], files: {} }, TEST_FORMAT_MAP).size,
220 ).toBe(0);
221 });
222​
223 it("skips malformed file entries but keeps good ones", () => {
224 const encoded = encodeScanCache(cacheWith([["/good.jsonl", 100, [record()]]]));
225 const withJunk = {
226 ...encoded,
227 files: { ...encoded.files, "/bad.jsonl": { s: "nope", m: 1, p: "claude", r: [] } },
228 };
229​
230 const restored = decodeScanCache(JSON.parse(JSON.stringify(withJunk)), TEST_FORMAT_MAP);
231 expect([...restored.keys()]).toEqual(["/good.jsonl"]);
232 });
233​
234 it("rejects the whole cache when an intern table holds a non-string", () => {
235 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
236 const poisoned = { ...encoded, models: [1] };
237​
238 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP).size).toBe(0);
239 });
240​
241 it("drops the whole entry when any row is corrupt, forcing a cold re-parse", () => {
242 const encoded = encodeScanCache(
243 cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" })]]]),
244 );
245 const rows = encoded.files["/a.jsonl"]!.r;
246 const poisoned = {
247 ...encoded,
248 files: {
249 "/a.jsonl": {
250 ...encoded.files["/a.jsonl"]!,
251 r: [rows[0]!, [...rows[1]!.slice(0, 3), "not-a-number", ...rows[1]!.slice(4)]],
252 },
253 },
254 };
255​
256 const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP);
257 expect(restored.has("/a.jsonl")).toBe(false);
258 });
259});
260​
261describe("pruneScanCache", () => {
262 const retentionCutoffMs = 1000;
263​
264 it("drops entries older than retention", () => {
265 const cache = cacheWith([["/old.jsonl", 500, [record()]]]);
266​
267 const removed = pruneScanCache(cache, retentionCutoffMs);
268​
269 expect(removed).toBe(1);
270 expect(cache.size).toBe(0);
271 });
272​
273 it("keeps entries whose file has disappeared", () => {
274 const cache = cacheWith([["/gone.jsonl", 5000, [record()]]]);
275​
276 pruneScanCache(cache, retentionCutoffMs);
277​
278 expect(cache.size).toBe(1);
279 });
280});
281​
282describe("dedupeWithinFile", () => {
283 it("keeps the first record per dedupe key", () => {
284 const kept = dedupeWithinFile([
285 record({ totals: { ...record().totals, outputTokens: 1 } }),
286 record({ totals: { ...record().totals, outputTokens: 999 } }),
287 record({ dedupeKey: "msg_2:" }),
288 ]);
289​
290 expect(kept).toHaveLength(2);
291 expect(kept[0]?.totals.outputTokens).toBe(1);
292 });
293​
294 it("keeps every record that has no dedupe key", () => {
295 expect(
296 dedupeWithinFile([record({ dedupeKey: null }), record({ dedupeKey: null })]),
297 ).toHaveLength(2);
298 });
299});