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 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 };
29}
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;
37}
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("treats a corrupt or foreign document as an empty cache", () => {
63 // A bad cache should cost one cold scan, never a broken page.
64 expect(decodeScanCache(null).size).toBe(0);
65 expect(decodeScanCache("nonsense").size).toBe(0);
66 expect(decodeScanCache({ version: 999, models: [], sessions: [], files: {} }).size).toBe(0);
67 });
68
69 it("skips malformed file entries but keeps good ones", () => {
70 const encoded = encodeScanCache(cacheWith([["/good.jsonl", 100, [record()]]]));
71 const withJunk = {
72 ...encoded,
73 files: { ...encoded.files, "/bad.jsonl": { s: "nope", m: 1, p: "claude", r: [] } },
74 };
75
76 const restored = decodeScanCache(JSON.parse(JSON.stringify(withJunk)));
77 expect([...restored.keys()]).toEqual(["/good.jsonl"]);
78 });
79
80 it("rejects the whole cache when an intern table holds a non-string", () => {
81 // models: [1] would pass the undefined guard, put a number in a record's
82 // model, and crash normalizeModelName at aggregate time.
83 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
84 const poisoned = { ...encoded, models: [1] };
85
86 expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).size).toBe(0);
87 });
88
89 it("drops the whole entry when any row is corrupt, forcing a cold re-parse", () => {
90 // Keeping the surviving rows under the original (size, mtime) would read
91 // as a valid warm hit and the file would never be re-parsed.
92 const encoded = encodeScanCache(
93 cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" })]]]),
94 );
95 const rows = encoded.files["/a.jsonl"]!.r;
96 const poisoned = {
97 ...encoded,
98 files: {
99 "/a.jsonl": {
100 ...encoded.files["/a.jsonl"]!,
101 r: [rows[0]!, [...rows[1]!.slice(0, 3), "not-a-number", ...rows[1]!.slice(4)]],
102 },
103 },
104 };
105
106 const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned)));
107 expect(restored.has("/a.jsonl")).toBe(false);
108 });
109});
110
111describe("pruneScanCache", () => {
112 const retentionCutoffMs = 1000;
113
114 it("drops entries older than retention", () => {
115 const cache = cacheWith([["/old.jsonl", 500, [record()]]]);
116
117 const removed = pruneScanCache(cache, {
118 livePaths: new Set(),
119 walkedRoots: ["/"],
120 windowStartMs: 400,
121 retentionCutoffMs,
122 });
123
124 expect(removed).toBe(1);
125 expect(cache.size).toBe(0);
126 });
127
128 it("drops in-window entries whose file has disappeared", () => {
129 const cache = cacheWith([["/gone.jsonl", 5000, [record()]]]);
130
131 pruneScanCache(cache, {
132 livePaths: new Set(),
133 walkedRoots: ["/"],
134 windowStartMs: 4000,
135 retentionCutoffMs,
136 });
137
138 expect(cache.size).toBe(0);
139 });
140
141 it("keeps entries outside the walked window that are still within retention", () => {
142 // Viewing 7 days must not evict the 30-day entries, which that walk never
143 // looked for and so cannot prove are gone.
144 const cache = cacheWith([["/older-but-valid.jsonl", 2000, [record()]]]);
145
146 const removed = pruneScanCache(cache, {
147 livePaths: new Set(),
148 walkedRoots: ["/"],
149 windowStartMs: 4000,
150 retentionCutoffMs,
151 });
152
153 expect(removed).toBe(0);
154 expect(cache.size).toBe(1);
155 });
156
157 it("keeps entries the walk saw", () => {
158 const cache = cacheWith([["/live.jsonl", 5000, [record()]]]);
159
160 pruneScanCache(cache, {
161 livePaths: new Set(["/live.jsonl"]),
162 walkedRoots: ["/"],
163 windowStartMs: 4000,
164 retentionCutoffMs,
165 });
166
167 expect(cache.size).toBe(1);
168 });
169});
170
171describe("pruneScanCache with an unwalked root", () => {
172 it("keeps in-window entries for a provider whose directory was not walked", () => {
173 // A missing provider root or failed settings read leaves livePaths without
174 // that provider's files. Its warm entries must survive the pass.
175 const cache = cacheWith([["/codex/sessions/a.jsonl", 5000, [record()]]]);
176
177 const removed = pruneScanCache(cache, {
178 livePaths: new Set(),
179 walkedRoots: ["/claude/projects"],
180 windowStartMs: 4000,
181 retentionCutoffMs: 1000,
182 });
183
184 expect(removed).toBe(0);
185 expect(cache.size).toBe(1);
186 });
187});
188
189describe("dedupeWithinFile", () => {
190 it("keeps the first record per dedupe key", () => {
191 const kept = dedupeWithinFile([
192 record({ totals: { ...record().totals, outputTokens: 1 } }),
193 record({ totals: { ...record().totals, outputTokens: 999 } }),
194 record({ dedupeKey: "msg_2:" }),
195 ]);
196
197 expect(kept).toHaveLength(2);
198 expect(kept[0]?.totals.outputTokens).toBe(1);
199 });
200
201 it("keeps every record that has no dedupe key", () => {
202 expect(
203 dedupeWithinFile([record({ dedupeKey: null }), record({ dedupeKey: null })]),
204 ).toHaveLength(2);
205 });
206});