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 { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts";
20import type { CodexScanState, UsageRecord, UsageSpeed } from "./usageTranscripts.ts";
21
22// v2: Codex fork-copy suppression changed what a file parses to, so v1
23// entries would keep serving double-counted records forever.
24// v3: entries carry the parse position and reducer state so a grown file
25// re-parses only its appended bytes instead of starting over.
26// v4: records carry Claude fast mode, which v3 rows never captured.
27// v5: Codex records carry their service tier. v4 rows store speed the same
28// way, so v4 entries still load; see `decodeScanCache` for v4 Codex entries.
29const USAGE_SCAN_CACHE_VERSION = 5 as const;
30const SPEED_COMPATIBLE_SINCE_VERSION = 4;
31
32/**
33 * Each cache version writes its own file in the state directory. An older
34 * server sharing that directory cannot read a newer cache and would replace
35 * it, dropping saved usage for deleted transcripts. Separate files keep both.
36 * A v5 server reads the legacy (v4) file once, when its own file is missing.
37 */
38export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v5.json";
39export const LEGACY_SCAN_CACHE_FILE_NAME = "usage-scan-cache.json";
40
41/** Serialised as the index into this list. */
42const SPEEDS: readonly UsageSpeed[] = ["standard", "fast", "ultrafast"];
43
44function isSpeed(value: unknown): value is UsageSpeed {
45 return SPEEDS.some((speed) => speed === value);
46}
47
48export interface CachedFile {
49 readonly size: number;
50 readonly mtimeMs: number;
51 readonly provider: UsageProviderKind;
52 /** Records from newline-terminated lines, up to `position.resumeOffset`. */
53 readonly records: readonly UsageRecord[];
54 /**
55 * Records from a trailing segment the writer had not newline-terminated at
56 * parse time. Kept apart from `records` because an incremental parse
57 * re-reads that segment and would otherwise double count it.
58 */
59 readonly tailRecords: readonly UsageRecord[];
60 readonly position: TranscriptParsePosition;
61}
62
63export type ScanCache = Map<string, CachedFile>;
64
65/**
66 * Row layout for the serialised form. Positional and interned rather than
67 * object-per-record: on a 30-day window that is the difference between a file
68 * measured in tens of megabytes and one under six.
69 */
70type SerializedRecord = readonly [
71 timestampMs: number,
72 modelIndex: number,
73 sessionIndex: number,
74 uncachedInputTokens: number,
75 cachedInputTokens: number,
76 cacheCreationTokens: number,
77 outputTokens: number,
78 reasoningTokens: number,
79 dedupeKey: string | null,
80 reportedCostUsd: number | null,
81 speed: number,
82];
83
84interface SerializedFile {
85 readonly s: number;
86 readonly m: number;
87 readonly p: UsageProviderKind;
88 readonly r: readonly SerializedRecord[];
89 /** Tail records; see `CachedFile.tailRecords`. */
90 readonly t: readonly SerializedRecord[];
91 /** Parse position: resume offset, guard length, guard hash. */
92 readonly o: number;
93 readonly gl: number;
94 readonly gh: number;
95 /** Codex reducer state at `o`; `null` for stateless providers. */
96 readonly cs: CodexScanState | null;
97}
98
99interface SerializedCache {
100 readonly version: number;
101 readonly models: readonly string[];
102 readonly sessions: readonly string[];
103 readonly files: Readonly<Record<string, SerializedFile>>;
104}
105
106/** Model and session strings, each stored once and referenced by index. */
107interface InternTables {
108 readonly models: string[];
109 readonly sessions: string[];
110 readonly modelIndex: Map<string, number>;
111 readonly sessionIndex: Map<string, number>;
112}
113
114function makeInternTables(): InternTables {
115 return { models: [], sessions: [], modelIndex: new Map(), sessionIndex: new Map() };
116}
117
118function intern(table: string[], index: Map<string, number>, value: string): number {
119 const existing = index.get(value);
120 if (existing !== undefined) return existing;
121 const next = table.length;
122 table.push(value);
123 index.set(value, next);
124 return next;
125}
126
127function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile {
128 const serializeRecord = (record: UsageRecord): SerializedRecord => [
129 record.timestampMs,
130 intern(tables.models, tables.modelIndex, record.model),
131 intern(tables.sessions, tables.sessionIndex, record.sessionId),
132 record.totals.uncachedInputTokens,
133 record.totals.cachedInputTokens,
134 record.totals.cacheCreationTokens,
135 record.totals.outputTokens,
136 record.totals.reasoningTokens,
137 record.dedupeKey,
138 record.reportedCostUsd,
139 SPEEDS.indexOf(record.speed),
140 ];
141 return {
142 s: entry.size,
143 m: entry.mtimeMs,
144 p: entry.provider,
145 r: entry.records.map(serializeRecord),
146 t: entry.tailRecords.map(serializeRecord),
147 o: entry.position.resumeOffset,
148 gl: entry.position.guardLength,
149 gh: entry.position.guardHash,
150 cs: entry.position.codexState,
151 };
152}
153
154/** Serialises the cache, interning the repeated model and session strings. */
155export function encodeScanCache(cache: ScanCache): SerializedCache {
156 const tables = makeInternTables();
157 const files: Record<string, SerializedFile> = {};
158 for (const [path, entry] of cache) files[path] = serializeFile(entry, tables);
159 return {
160 version: USAGE_SCAN_CACHE_VERSION,
161 models: tables.models,
162 sessions: tables.sessions,
163 files,
164 };
165}
166
167/**
168 * Returns a function that serialises the cache to JSON text, re-encoding only
169 * the entries that changed since its last call. Call it once per persist.
170 *
171 * Writes the same document as `encodeScanCache`. Most entries never change
172 * between scans, and encoding all of them made each persist cost close to a
173 * second on a large cache. Entries are replaced, never mutated, when their file
174 * changes, so an entry's JSON is memoised by identity. The intern tables only
175 * grow, so a memoised entry's indexes stay valid; a pruned entry can leave an
176 * unused string behind until the next process start.
177 */
178export function makeScanCacheWriter(): (
179 cache: ScanCache,
180 extra: Readonly<Record<string, unknown>>,
181) => string {
182 const tables = makeInternTables();
183 const fragments = new WeakMap<CachedFile, string>();
184 return (cache, extra) => {
185 const files: string[] = [];
186 for (const [path, entry] of cache) {
187 let fragment = fragments.get(entry);
188 if (fragment === undefined) {
189 fragment = JSON.stringify(serializeFile(entry, tables));
190 fragments.set(entry, fragment);
191 }
192 files.push(`${JSON.stringify(path)}:${fragment}`);
193 }
194 // Encoded after the files, which may have added to the intern tables.
195 const head = JSON.stringify({
196 ...extra,
197 version: USAGE_SCAN_CACHE_VERSION,
198 models: tables.models,
199 sessions: tables.sessions,
200 });
201 return `${head.slice(0, -1)},"files":{${files.join(",")}}}`;
202 };
203}
204
205function isRecordArray(value: unknown): value is readonly unknown[] {
206 return Array.isArray(value);
207}
208
209/**
210 * Rebuilds the cache from a parsed document.
211 *
212 * Anything malformed yields an empty cache rather than an error: a corrupt
213 * cache should cost one cold scan, never a broken page.
214 */
215export function decodeScanCache(document: unknown): ScanCache {
216 const cache: ScanCache = new Map();
217 if (typeof document !== "object" || document === null) return cache;
218
219 const root = document as Partial<SerializedCache>;
220 const version = root.version;
221 if (
222 typeof version !== "number" ||
223 version < SPEED_COMPATIBLE_SINCE_VERSION ||
224 version > USAGE_SCAN_CACHE_VERSION
225 ) {
226 return cache;
227 }
228 if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
229 if (typeof root.files !== "object" || root.files === null) return cache;
230
231 // The intern tables must be all strings: a numeric entry would pass the
232 // undefined guard below, land in a record's model, and crash the aggregate
233 // at lookupRate. A corrupt table rejects the whole cache.
234 if (!root.models.every((value) => typeof value === "string")) return cache;
235 if (!root.sessions.every((value) => typeof value === "string")) return cache;
236 const models = root.models as readonly string[];
237 const sessions = root.sessions as readonly string[];
238
239 // Any corrupt row disqualifies the whole entry. Keeping the survivors
240 // under the original (size, mtime) would read as a valid warm hit and the
241 // file would never be re-parsed, silently losing the dropped rows' usage.
242 const decodeRecords = (
243 rows: readonly unknown[],
244 provider: UsageProviderKind,
245 ): UsageRecord[] | null => {
246 const records: UsageRecord[] = [];
247 for (const row of rows) {
248 if (!isRecordArray(row) || row.length < 11) return null;
249 const [
250 timestampMs,
251 modelIndex,
252 sessionIndex,
253 uncached,
254 cached,
255 cacheCreation,
256 output,
257 reasoning,
258 dedupeKey,
259 reportedCostUsd,
260 speedIndex,
261 ] = row as SerializedRecord;
262 const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined;
263
264 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
265 if (
266 typeof timestampMs !== "number" ||
267 !Number.isFinite(timestampMs) ||
268 model === undefined ||
269 !Number.isFinite(uncached) ||
270 !Number.isFinite(cached) ||
271 !Number.isFinite(cacheCreation) ||
272 !Number.isFinite(output) ||
273 !Number.isFinite(reasoning) ||
274 speed === undefined
275 ) {
276 return null;
277 }
278
279 records.push({
280 provider,
281 timestampMs,
282 model,
283 sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "",
284 totals: {
285 uncachedInputTokens: uncached,
286 cachedInputTokens: cached,
287 cacheCreationTokens: cacheCreation,
288 outputTokens: output,
289 reasoningTokens: reasoning,
290 },
291 reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
292 speed,
293 dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
294 });
295 }
296 return records;
297 };
298
299 for (const [path, raw] of Object.entries(root.files)) {
300 if (typeof raw !== "object" || raw === null) continue;
301 const entry = raw as Partial<SerializedFile>;
302 if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
303 if (entry.p !== "claude" && entry.p !== "codex" && entry.p !== "grok") continue;
304 if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
305 // Position fields feed byte offsets and a Buffer allocation in the reader,
306 // so anything outside their real ranges must reject the entry: a bogus
307 // guard length would otherwise fail every parse of the file, silently
308 // dropping its usage instead of costing the documented cold re-parse.
309 if (
310 typeof entry.o !== "number" ||
311 !Number.isSafeInteger(entry.o) ||
312 entry.o < 0 ||
313 typeof entry.gl !== "number" ||
314 !Number.isSafeInteger(entry.gl) ||
315 entry.gl < 0 ||
316 entry.gl > GUARD_LENGTH ||
317 entry.gl > entry.o ||
318 typeof entry.gh !== "number" ||
319 !Number.isFinite(entry.gh)
320 ) {
321 continue;
322 }
323 // v4 Codex records predate service tiers, so they all priced as standard.
324 // Keep them, because the rollout may be gone, but make a live rollout
325 // re-parse whole: no file has size -1, and a zero position cannot resume.
326 const legacyCodex = entry.p === "codex" && version < USAGE_SCAN_CACHE_VERSION;
327 const codexState = legacyCodex ? null : decodeCodexState(entry.cs);
328 if (codexState === undefined) continue;
329
330 const provider: UsageProviderKind = entry.p;
331 const records = decodeRecords(entry.r, provider);
332 const tailRecords = decodeRecords(entry.t, provider);
333 if (records === null || tailRecords === null) continue;
334
335 cache.set(path, {
336 size: legacyCodex ? -1 : entry.s,
337 mtimeMs: entry.m,
338 provider,
339 records,
340 tailRecords,
341 position: legacyCodex
342 ? { resumeOffset: 0, guardLength: 0, guardHash: 0, codexState: null }
343 : { resumeOffset: entry.o, guardLength: entry.gl, guardHash: entry.gh, codexState },
344 });
345 }
346
347 return cache;
348}
349
350/**
351 * Validates a persisted Codex reducer state. Returns `undefined` for a corrupt
352 * value, which disqualifies the entry: resuming with a bad state would attach
353 * appended usage to the wrong model or replay fork-copied history.
354 */
355function decodeCodexState(value: unknown): CodexScanState | null | undefined {
356 if (value === null) return null;
357 if (typeof value !== "object") return undefined;
358 const state = value as Partial<CodexScanState>;
359 if (
360 typeof state.model !== "string" ||
361 !isSpeed(state.speed) ||
362 typeof state.sessionId !== "string" ||
363 (state.lastUsageSignature !== null && typeof state.lastUsageSignature !== "string") ||
364 typeof state.sawSessionMeta !== "boolean" ||
365 typeof state.suppressingForkCopies !== "boolean" ||
366 typeof state.forkCopyAnchorMs !== "number" ||
367 !Number.isFinite(state.forkCopyAnchorMs)
368 ) {
369 return undefined;
370 }
371 return {
372 model: state.model,
373 speed: state.speed,
374 sessionId: state.sessionId,
375 lastUsageSignature: state.lastUsageSignature ?? null,
376 sawSessionMeta: state.sawSessionMeta,
377 suppressingForkCopies: state.suppressingForkCopies,
378 forkCopyAnchorMs: state.forkCopyAnchorMs,
379 };
380}
381
382/** Keeps saved usage after transcript cleanup, until the reporting retention expires. */
383export function pruneScanCache(cache: ScanCache, retentionCutoffMs: number): number {
384 let removed = 0;
385 for (const [path, entry] of cache) {
386 if (entry.mtimeMs < retentionCutoffMs) {
387 cache.delete(path);
388 removed += 1;
389 }
390 }
391 return removed;
392}
393
394/**
395 * Within-file de-duplication, applied before an entry is cached.
396 *
397 * Callers stitching an incremental parse together pass one `seen` set across
398 * the line and tail record batches so the whole file stays deduplicated as a
399 * unit; the set is mutated in place.
400 */
401export function dedupeWithinFile(
402 records: readonly UsageRecord[],
403 seen: Set<string> = new Set(),
404): readonly UsageRecord[] {
405 const kept: UsageRecord[] = [];
406 for (const record of records) {
407 if (record.dedupeKey !== null) {
408 if (seen.has(record.dedupeKey)) continue;
409 seen.add(record.dedupeKey);
410 }
411 kept.push(record);
412 }
413 return kept;
414}