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

usageScanCache.test.ts

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