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

usageScanCache.test.ts

229 lines7.6 KB

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 };
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 };
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;
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, retentionCutoffMs);
198​
199 expect(removed).toBe(1);
200 expect(cache.size).toBe(0);
201 });
202​
203 it("keeps entries whose file has disappeared", () => {
204 const cache = cacheWith([["/gone.jsonl", 5000, [record()]]]);
205​
206 pruneScanCache(cache, retentionCutoffMs);
207​
208 expect(cache.size).toBe(1);
209 });
210});
211​
212describe("dedupeWithinFile", () => {
213 it("keeps the first record per dedupe key", () => {
214 const kept = dedupeWithinFile([
215 record({ totals: { ...record().totals, outputTokens: 1 } }),
216 record({ totals: { ...record().totals, outputTokens: 999 } }),
217 record({ dedupeKey: "msg_2:" }),
218 ]);
219​
220 expect(kept).toHaveLength(2);
221 expect(kept[0]?.totals.outputTokens).toBe(1);
222 });
223​
224 it("keeps every record that has no dedupe key", () => {
225 expect(
226 dedupeWithinFile([record({ dedupeKey: null }), record({ dedupeKey: null })]),
227 ).toHaveLength(2);
228 });
229});