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

usageScanCache.test.ts

254 lines7.8 KB

1import { describe, expect, it } from "@effect/vitest";
2​
3import {
4 decodeScanCache,
5 dedupeWithinFile,
6 encodeScanCache,
7 pruneScanCache,
8 type ScanCache,
9} from "./usageScanCache.ts";
10import type { UsageRecord } from "./usageTranscripts.ts";
11​
12function record(overrides: Partial<UsageRecord> = {}): UsageRecord {
13 return {
14 provider: "claude",
15 timestampMs: 1_786_000_000_000,
16 model: "claude-fable-5",
17 sessionId: "session-a",
18 totals: {
19 uncachedInputTokens: 2,
20 cachedInputTokens: 1000,
21 cacheCreationTokens: 10,
22 outputTokens: 50,
23 reasoningTokens: 0,
24 },
25 reportedCostUsd: null,
26 dedupeKey: "msg_1:",
27 ...overrides,
28 };
30​
31function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][]): ScanCache {
32 const cache: ScanCache = new Map();
33 for (const [path, mtimeMs, records] of entries) {
34 cache.set(path, { size: records.length * 10, mtimeMs, provider: "claude", records });
35 }
36 return cache;
38​
39describe("scan cache round trip", () => {
40 it("restores records unchanged", () => {
41 const original = cacheWith([
42 ["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5" })]],
43 ["/b.jsonl", 200, [record({ sessionId: "session-b", reportedCostUsd: 1.5 })]],
44 ]);
45​
46 const restored = decodeScanCache(JSON.parse(JSON.stringify(encodeScanCache(original))));
47​
48 expect(restored.size).toBe(2);
49 expect(restored.get("/a.jsonl")).toEqual(original.get("/a.jsonl"));
50 expect(restored.get("/b.jsonl")).toEqual(original.get("/b.jsonl"));
51 });
52​
53 it("interns repeated model and session strings", () => {
54 const encoded = encodeScanCache(
55 cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" }), record()]]]),
56 );
57​
58 expect(encoded.models).toEqual(["claude-fable-5"]);
59 expect(encoded.sessions).toEqual(["session-a"]);
60 });
61​
62 it("round-trips an opencode store entry with its WAL identity", () => {
63 const cache: ScanCache = new Map();
64 cache.set("/opencode.db", {
65 size: 1024,
66 mtimeMs: 200,
67 provider: "opencode",
68 wal: { size: 64, mtimeMs: 210 },
69 records: [
70 record({
71 provider: "opencode",
72 model: "opencode-go/deepseek-v4-flash",
73 reportedCostUsd: 0.25,
74 dedupeKey: null,
75 }),
76 ],
77 });
78​
79 const restored = decodeScanCache(JSON.parse(JSON.stringify(encodeScanCache(cache))));
80​
81 expect(restored.get("/opencode.db")).toEqual(cache.get("/opencode.db"));
82 });
83​
84 it("rejects an opencode entry whose WAL identity is malformed", () => {
85 const encoded = encodeScanCache(
86 (() => {
87 const cache: ScanCache = new Map();
88 cache.set("/opencode.db", {
89 size: 1024,
90 mtimeMs: 200,
91 provider: "opencode",
92 records: [
93 record({ provider: "opencode", model: "opencode-go/gpt-5.6-luna", dedupeKey: null }),
94 ],
95 });
96 return cache;
97 })(),
98 );
99 const poisoned = {
100 ...encoded,
101 files: {
102 "/opencode.db": { ...encoded.files["/opencode.db"]!, w: ["nope", 1] },
103 },
104 };
105​
106 const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned)));
107 expect(restored.has("/opencode.db")).toBe(false);
108 });
109​
110 it("treats a corrupt or foreign document as an empty cache", () => {
111 // A bad cache should cost one cold scan, never a broken page.
112 expect(decodeScanCache(null).size).toBe(0);
113 expect(decodeScanCache("nonsense").size).toBe(0);
114 expect(decodeScanCache({ version: 999, models: [], sessions: [], files: {} }).size).toBe(0);
115 });
116​
117 it("skips malformed file entries but keeps good ones", () => {
118 const encoded = encodeScanCache(cacheWith([["/good.jsonl", 100, [record()]]]));
119 const withJunk = {
120 ...encoded,
121 files: { ...encoded.files, "/bad.jsonl": { s: "nope", m: 1, p: "claude", r: [] } },
122 };
123​
124 const restored = decodeScanCache(JSON.parse(JSON.stringify(withJunk)));
125 expect([...restored.keys()]).toEqual(["/good.jsonl"]);
126 });
127​
128 it("rejects the whole cache when an intern table holds a non-string", () => {
129 // models: [1] would pass the undefined guard, put a number in a record's
130 // model, and crash normalizeModelName at aggregate time.
131 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
132 const poisoned = { ...encoded, models: [1] };
133​
134 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).size).toBe(0);
135 });
136​
137 it("drops the whole entry when any row is corrupt, forcing a cold re-parse", () => {
138 // Keeping the surviving rows under the original (size, mtime) would read
139 // as a valid warm hit and the file would never be re-parsed.
140 const encoded = encodeScanCache(
141 cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" })]]]),
142 );
143 const rows = encoded.files["/a.jsonl"]!.r;
144 const poisoned = {
145 ...encoded,
146 files: {
147 "/a.jsonl": {
148 ...encoded.files["/a.jsonl"]!,
149 r: [rows[0]!, [...rows[1]!.slice(0, 3), "not-a-number", ...rows[1]!.slice(4)]],
150 },
151 },
152 };
153​
154 const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned)));
155 expect(restored.has("/a.jsonl")).toBe(false);
156 });
157});
158​
159describe("pruneScanCache", () => {
160 const retentionCutoffMs = 1000;
161​
162 it("drops entries older than retention", () => {
163 const cache = cacheWith([["/old.jsonl", 500, [record()]]]);
164​
165 const removed = pruneScanCache(cache, {
166 livePaths: new Set(),
167 walkedRoots: ["/"],
168 windowStartMs: 400,
169 retentionCutoffMs,
170 });
171​
172 expect(removed).toBe(1);
173 expect(cache.size).toBe(0);
174 });
175​
176 it("drops in-window entries whose file has disappeared", () => {
177 const cache = cacheWith([["/gone.jsonl", 5000, [record()]]]);
178​
179 pruneScanCache(cache, {
180 livePaths: new Set(),
181 walkedRoots: ["/"],
182 windowStartMs: 4000,
183 retentionCutoffMs,
184 });
185​
186 expect(cache.size).toBe(0);
187 });
188​
189 it("keeps entries outside the walked window that are still within retention", () => {
190 // Viewing 7 days must not evict the 30-day entries, which that walk never
191 // looked for and so cannot prove are gone.
192 const cache = cacheWith([["/older-but-valid.jsonl", 2000, [record()]]]);
193​
194 const removed = pruneScanCache(cache, {
195 livePaths: new Set(),
196 walkedRoots: ["/"],
197 windowStartMs: 4000,
198 retentionCutoffMs,
199 });
200​
201 expect(removed).toBe(0);
202 expect(cache.size).toBe(1);
203 });
204​
205 it("keeps entries the walk saw", () => {
206 const cache = cacheWith([["/live.jsonl", 5000, [record()]]]);
207​
208 pruneScanCache(cache, {
209 livePaths: new Set(["/live.jsonl"]),
210 walkedRoots: ["/"],
211 windowStartMs: 4000,
212 retentionCutoffMs,
213 });
214​
215 expect(cache.size).toBe(1);
216 });
217});
218​
219describe("pruneScanCache with an unwalked root", () => {
220 it("keeps in-window entries for a provider whose directory was not walked", () => {
221 // A missing provider root or failed settings read leaves livePaths without
222 // that provider's files. Its warm entries must survive the pass.
223 const cache = cacheWith([["/codex/sessions/a.jsonl", 5000, [record()]]]);
224​
225 const removed = pruneScanCache(cache, {
226 livePaths: new Set(),
227 walkedRoots: ["/claude/projects"],
228 windowStartMs: 4000,
229 retentionCutoffMs: 1000,
230 });
231​
232 expect(removed).toBe(0);
233 expect(cache.size).toBe(1);
234 });
235});
236​
237describe("dedupeWithinFile", () => {
238 it("keeps the first record per dedupe key", () => {
239 const kept = dedupeWithinFile([
240 record({ totals: { ...record().totals, outputTokens: 1 } }),
241 record({ totals: { ...record().totals, outputTokens: 999 } }),
242 record({ dedupeKey: "msg_2:" }),
243 ]);
244​
245 expect(kept).toHaveLength(2);
246 expect(kept[0]?.totals.outputTokens).toBe(1);
247 });
248​
249 it("keeps every record that has no dedupe key", () => {
250 expect(
251 dedupeWithinFile([record({ dedupeKey: null }), record({ dedupeKey: null })]),
252 ).toHaveLength(2);
253 });
254});