Open History to see the last commit
1/**
2 * Durable per-file scan cache.
3 *
4 * Transcripts are append-only and a file that has not changed can never yield
5 * different usage, so parsed records are keyed by `(size, mtime)` and reused.
6 * Without this every server restart re-parses the whole window: roughly 3.5s
7 * for a 30-day scan here, against ~11ms to reload this cache.
8 *
9 * Caching *per file* rather than per day is deliberate. It is timezone
10 * independent, so changing the reporting zone does not invalidate anything, and
11 * it keeps cross-file de-duplication exact: cached entries are de-duplicated
12 * within their own file only, and the aggregator still applies the global
13 * dedupe pass over the small surviving key set.
14 *
15 * @module usageScanCache
16 */
17import type { UsageProviderKind } from "@t3tools/contracts";
18
19import type { UsageRecord } from "./usageTranscripts.ts";
20
21// v2: Codex fork-copy suppression changed what a file parses to, so v1
22// entries would keep serving double-counted records forever.
23// v3: OpenCode's WAL sidecar joined the cache identity.
24export const USAGE_SCAN_CACHE_VERSION = 3 as const;
25
26export interface CachedFile {
27 readonly size: number;
28 readonly mtimeMs: number;
29 readonly provider: UsageProviderKind;
30 readonly records: readonly UsageRecord[];
31 /**
32 * OpenCode's store runs in WAL mode, so its live tail lives in a sidecar
33 * file that is part of the cache identity. `undefined` for transcript
34 * directories, which are fully described by `size` and `mtimeMs`.
35 */
36 readonly wal?: { readonly size: number; readonly mtimeMs: number } | undefined;
37}
38
39export type ScanCache = Map<string, CachedFile>;
40
41/**
42 * Row layout for the serialised form. Positional and interned rather than
43 * object-per-record: on a 30-day window that is the difference between a file
44 * measured in tens of megabytes and one under six.
45 */
46type SerializedRecord = readonly [
47 timestampMs: number,
48 modelIndex: number,
49 sessionIndex: number,
50 uncachedInputTokens: number,
51 cachedInputTokens: number,
52 cacheCreationTokens: number,
53 outputTokens: number,
54 reasoningTokens: number,
55 dedupeKey: string | null,
56 reportedCostUsd: number | null,
57];
58
59interface SerializedFile {
60 readonly s: number;
61 readonly m: number;
62 readonly p: UsageProviderKind;
63 readonly w?: [number, number] | undefined;
64 readonly r: readonly SerializedRecord[];
65}
66
67interface SerializedCache {
68 readonly version: number;
69 readonly models: readonly string[];
70 readonly sessions: readonly string[];
71 readonly files: Readonly<Record<string, SerializedFile>>;
72}
73
74/** Serialises the cache, interning the repeated model and session strings. */
75export function encodeScanCache(cache: ScanCache): SerializedCache {
76 const models: string[] = [];
77 const sessions: string[] = [];
78 const modelIndex = new Map<string, number>();
79 const sessionIndex = new Map<string, number>();
80
81 const intern = (table: string[], index: Map<string, number>, value: string): number => {
82 const existing = index.get(value);
83 if (existing !== undefined) return existing;
84 const next = table.length;
85 table.push(value);
86 index.set(value, next);
87 return next;
88 };
89
90 const files: Record<string, SerializedFile> = {};
91 for (const [path, entry] of cache) {
92 files[path] = {
93 s: entry.size,
94 m: entry.mtimeMs,
95 p: entry.provider,
96 ...(entry.wal === undefined ? {} : { w: [entry.wal.size, entry.wal.mtimeMs] as const }),
97 r: entry.records.map((record) => [
98 record.timestampMs,
99 intern(models, modelIndex, record.model),
100 intern(sessions, sessionIndex, record.sessionId),
101 record.totals.uncachedInputTokens,
102 record.totals.cachedInputTokens,
103 record.totals.cacheCreationTokens,
104 record.totals.outputTokens,
105 record.totals.reasoningTokens,
106 record.dedupeKey,
107 record.reportedCostUsd,
108 ]),
109 };
110 }
111
112 return { version: USAGE_SCAN_CACHE_VERSION, models, sessions, files };
113}
114
115function isRecordArray(value: unknown): value is readonly unknown[] {
116 return Array.isArray(value);
117}
118
119/**
120 * Rebuilds the cache from a parsed document.
121 *
122 * Anything malformed yields an empty cache rather than an error: a corrupt
123 * cache should cost one cold scan, never a broken page.
124 */
125export function decodeScanCache(document: unknown): ScanCache {
126 const cache: ScanCache = new Map();
127 if (typeof document !== "object" || document === null) return cache;
128
129 const root = document as Partial<SerializedCache>;
130 if (root.version !== USAGE_SCAN_CACHE_VERSION) return cache;
131 if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
132 if (typeof root.files !== "object" || root.files === null) return cache;
133
134 // The intern tables must be all strings: a numeric entry would pass the
135 // undefined guard below, land in a record's model, and crash the aggregate
136 // at normalizeModelName. A corrupt table rejects the whole cache.
137 if (!root.models.every((value) => typeof value === "string")) return cache;
138 if (!root.sessions.every((value) => typeof value === "string")) return cache;
139 const models = root.models as readonly string[];
140 const sessions = root.sessions as readonly string[];
141
142 for (const [path, raw] of Object.entries(root.files)) {
143 if (typeof raw !== "object" || raw === null) continue;
144 const entry = raw as Partial<SerializedFile>;
145 if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
146 if (entry.p !== "claude" && entry.p !== "codex" && entry.p !== "opencode") continue;
147 if (!isRecordArray(entry.r)) continue;
148
149 const wal =
150 entry.w === undefined
151 ? undefined
152 : isRecordArray(entry.w) &&
153 entry.w.length === 2 &&
154 typeof entry.w[0] === "number" &&
155 typeof entry.w[1] === "number"
156 ? { size: entry.w[0], mtimeMs: entry.w[1] }
157 : null;
158 // A malformed WAL identity must not ride a warm hit: drop the whole entry
159 // so the store is re-parsed and the correct identity re-serialised. (`wal`
160 // is only ever `null` when `entry.w` was present.)
161 if (wal === null) continue;
162
163 const provider: UsageProviderKind = entry.p;
164 const records: UsageRecord[] = [];
165 // Any corrupt row disqualifies the whole entry. Keeping the survivors
166 // under the original (size, mtime) would read as a valid warm hit and the
167 // file would never be re-parsed, silently losing the dropped rows' usage.
168 let corrupt = false;
169 for (const row of entry.r) {
170 if (!isRecordArray(row) || row.length < 10) {
171 corrupt = true;
172 break;
173 }
174 const [
175 timestampMs,
176 modelIndex,
177 sessionIndex,
178 uncached,
179 cached,
180 cacheCreation,
181 output,
182 reasoning,
183 dedupeKey,
184 reportedCostUsd,
185 ] = row as SerializedRecord;
186
187 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
188 if (
189 typeof timestampMs !== "number" ||
190 !Number.isFinite(timestampMs) ||
191 model === undefined ||
192 !Number.isFinite(uncached) ||
193 !Number.isFinite(cached) ||
194 !Number.isFinite(cacheCreation) ||
195 !Number.isFinite(output) ||
196 !Number.isFinite(reasoning)
197 ) {
198 corrupt = true;
199 break;
200 }
201
202 records.push({
203 provider,
204 timestampMs,
205 model,
206 sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "",
207 totals: {
208 uncachedInputTokens: uncached,
209 cachedInputTokens: cached,
210 cacheCreationTokens: cacheCreation,
211 outputTokens: output,
212 reasoningTokens: reasoning,
213 },
214 reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
215 dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
216 });
217 }
218
219 if (corrupt) continue;
220 cache.set(path, {
221 size: entry.s,
222 mtimeMs: entry.m,
223 provider,
224 ...(wal === undefined ? {} : { wal }),
225 records,
226 });
227 }
228
229 return cache;
230}
231
232export interface PruneOptions {
233 /** Files the walk just saw. Only meaningful inside the walked window. */
234 readonly livePaths: ReadonlySet<string>;
235 /**
236 * Roots the walk actually completed. Absence from `livePaths` only proves a
237 * file is gone when its root was walked: a provider whose directory failed to
238 * resolve this pass must not have its warm entries purged.
239 */
240 readonly walkedRoots: readonly string[];
241 /** Start of the walked window; entries older than this were not looked for. */
242 readonly windowStartMs: number;
243 /** Entries older than this are dropped regardless. */
244 readonly retentionCutoffMs: number;
245}
246
247/**
248 * Drops aged-out entries, and entries for files that have disappeared.
249 *
250 * The walk only covers the requested window, so absence from `livePaths` only
251 * proves deletion for entries *inside* that window. Pruning everything the walk
252 * missed would evict the 30-day entries every time someone looked at 7 days.
253 *
254 * Replaces an earlier record cap that cleared the whole cache once exceeded,
255 * which meant a large enough window never warmed up at all.
256 */
257export function pruneScanCache(cache: ScanCache, options: PruneOptions): number {
258 let removed = 0;
259 for (const [path, entry] of cache) {
260 const agedOut = entry.mtimeMs < options.retentionCutoffMs;
261 const underWalkedRoot = options.walkedRoots.some((root) => path.startsWith(root));
262 const deleted =
263 underWalkedRoot && entry.mtimeMs >= options.windowStartMs && !options.livePaths.has(path);
264 if (agedOut || deleted) {
265 cache.delete(path);
266 removed += 1;
267 }
268 }
269 return removed;
270}
271
272/** Within-file de-duplication, applied before an entry is cached. */
273export function dedupeWithinFile(records: readonly UsageRecord[]): readonly UsageRecord[] {
274 const seen = new Set<string>();
275 const kept: UsageRecord[] = [];
276 for (const record of records) {
277 if (record.dedupeKey !== null) {
278 if (seen.has(record.dedupeKey)) continue;
279 seen.add(record.dedupeKey);
280 }
281 kept.push(record);
282 }
283 return kept;
284}