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/** Serialises the cache, interning the repeated model and session strings. */
107export function encodeScanCache(cache: ScanCache): SerializedCache {
108 const models: string[] = [];
109 const sessions: string[] = [];
110 const modelIndex = new Map<string, number>();
111 const sessionIndex = new Map<string, number>();
112
113 const intern = (table: string[], index: Map<string, number>, value: string): number => {
114 const existing = index.get(value);
115 if (existing !== undefined) return existing;
116 const next = table.length;
117 table.push(value);
118 index.set(value, next);
119 return next;
120 };
121
122 const serializeRecord = (record: UsageRecord): SerializedRecord => [
123 record.timestampMs,
124 intern(models, modelIndex, record.model),
125 intern(sessions, sessionIndex, record.sessionId),
126 record.totals.uncachedInputTokens,
127 record.totals.cachedInputTokens,
128 record.totals.cacheCreationTokens,
129 record.totals.outputTokens,
130 record.totals.reasoningTokens,
131 record.dedupeKey,
132 record.reportedCostUsd,
133 SPEEDS.indexOf(record.speed),
134 ];
135
136 const files: Record<string, SerializedFile> = {};
137 for (const [path, entry] of cache) {
138 files[path] = {
139 s: entry.size,
140 m: entry.mtimeMs,
141 p: entry.provider,
142 r: entry.records.map(serializeRecord),
143 t: entry.tailRecords.map(serializeRecord),
144 o: entry.position.resumeOffset,
145 gl: entry.position.guardLength,
146 gh: entry.position.guardHash,
147 cs: entry.position.codexState,
148 };
149 }
150
151 return { version: USAGE_SCAN_CACHE_VERSION, models, sessions, files };
152}
153
154function isRecordArray(value: unknown): value is readonly unknown[] {
155 return Array.isArray(value);
156}
157
158/**
159 * Rebuilds the cache from a parsed document.
160 *
161 * Anything malformed yields an empty cache rather than an error: a corrupt
162 * cache should cost one cold scan, never a broken page.
163 */
164export function decodeScanCache(document: unknown): ScanCache {
165 const cache: ScanCache = new Map();
166 if (typeof document !== "object" || document === null) return cache;
167
168 const root = document as Partial<SerializedCache>;
169 const version = root.version;
170 if (
171 typeof version !== "number" ||
172 version < SPEED_COMPATIBLE_SINCE_VERSION ||
173 version > USAGE_SCAN_CACHE_VERSION
174 ) {
175 return cache;
176 }
177 if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
178 if (typeof root.files !== "object" || root.files === null) return cache;
179
180 // The intern tables must be all strings: a numeric entry would pass the
181 // undefined guard below, land in a record's model, and crash the aggregate
182 // at lookupRate. A corrupt table rejects the whole cache.
183 if (!root.models.every((value) => typeof value === "string")) return cache;
184 if (!root.sessions.every((value) => typeof value === "string")) return cache;
185 const models = root.models as readonly string[];
186 const sessions = root.sessions as readonly string[];
187
188 // Any corrupt row disqualifies the whole entry. Keeping the survivors
189 // under the original (size, mtime) would read as a valid warm hit and the
190 // file would never be re-parsed, silently losing the dropped rows' usage.
191 const decodeRecords = (
192 rows: readonly unknown[],
193 provider: UsageProviderKind,
194 ): UsageRecord[] | null => {
195 const records: UsageRecord[] = [];
196 for (const row of rows) {
197 if (!isRecordArray(row) || row.length < 11) return null;
198 const [
199 timestampMs,
200 modelIndex,
201 sessionIndex,
202 uncached,
203 cached,
204 cacheCreation,
205 output,
206 reasoning,
207 dedupeKey,
208 reportedCostUsd,
209 speedIndex,
210 ] = row as SerializedRecord;
211 const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined;
212
213 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
214 if (
215 typeof timestampMs !== "number" ||
216 !Number.isFinite(timestampMs) ||
217 model === undefined ||
218 !Number.isFinite(uncached) ||
219 !Number.isFinite(cached) ||
220 !Number.isFinite(cacheCreation) ||
221 !Number.isFinite(output) ||
222 !Number.isFinite(reasoning) ||
223 speed === undefined
224 ) {
225 return null;
226 }
227
228 records.push({
229 provider,
230 timestampMs,
231 model,
232 sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "",
233 totals: {
234 uncachedInputTokens: uncached,
235 cachedInputTokens: cached,
236 cacheCreationTokens: cacheCreation,
237 outputTokens: output,
238 reasoningTokens: reasoning,
239 },
240 reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
241 speed,
242 dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
243 });
244 }
245 return records;
246 };
247
248 for (const [path, raw] of Object.entries(root.files)) {
249 if (typeof raw !== "object" || raw === null) continue;
250 const entry = raw as Partial<SerializedFile>;
251 if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
252 if (entry.p !== "claude" && entry.p !== "codex" && entry.p !== "grok") continue;
253 if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
254 // Position fields feed byte offsets and a Buffer allocation in the reader,
255 // so anything outside their real ranges must reject the entry: a bogus
256 // guard length would otherwise fail every parse of the file, silently
257 // dropping its usage instead of costing the documented cold re-parse.
258 if (
259 typeof entry.o !== "number" ||
260 !Number.isSafeInteger(entry.o) ||
261 entry.o < 0 ||
262 typeof entry.gl !== "number" ||
263 !Number.isSafeInteger(entry.gl) ||
264 entry.gl < 0 ||
265 entry.gl > GUARD_LENGTH ||
266 entry.gl > entry.o ||
267 typeof entry.gh !== "number" ||
268 !Number.isFinite(entry.gh)
269 ) {
270 continue;
271 }
272 // v4 Codex records predate service tiers, so they all priced as standard.
273 // Keep them, because the rollout may be gone, but make a live rollout
274 // re-parse whole: no file has size -1, and a zero position cannot resume.
275 const legacyCodex = entry.p === "codex" && version < USAGE_SCAN_CACHE_VERSION;
276 const codexState = legacyCodex ? null : decodeCodexState(entry.cs);
277 if (codexState === undefined) continue;
278
279 const provider: UsageProviderKind = entry.p;
280 const records = decodeRecords(entry.r, provider);
281 const tailRecords = decodeRecords(entry.t, provider);
282 if (records === null || tailRecords === null) continue;
283
284 cache.set(path, {
285 size: legacyCodex ? -1 : entry.s,
286 mtimeMs: entry.m,
287 provider,
288 records,
289 tailRecords,
290 position: legacyCodex
291 ? { resumeOffset: 0, guardLength: 0, guardHash: 0, codexState: null }
292 : { resumeOffset: entry.o, guardLength: entry.gl, guardHash: entry.gh, codexState },
293 });
294 }
295
296 return cache;
297}
298
299/**
300 * Validates a persisted Codex reducer state. Returns `undefined` for a corrupt
301 * value, which disqualifies the entry: resuming with a bad state would attach
302 * appended usage to the wrong model or replay fork-copied history.
303 */
304function decodeCodexState(value: unknown): CodexScanState | null | undefined {
305 if (value === null) return null;
306 if (typeof value !== "object") return undefined;
307 const state = value as Partial<CodexScanState>;
308 if (
309 typeof state.model !== "string" ||
310 !isSpeed(state.speed) ||
311 typeof state.sessionId !== "string" ||
312 (state.lastUsageSignature !== null && typeof state.lastUsageSignature !== "string") ||
313 typeof state.sawSessionMeta !== "boolean" ||
314 typeof state.suppressingForkCopies !== "boolean" ||
315 typeof state.forkCopyAnchorMs !== "number" ||
316 !Number.isFinite(state.forkCopyAnchorMs)
317 ) {
318 return undefined;
319 }
320 return {
321 model: state.model,
322 speed: state.speed,
323 sessionId: state.sessionId,
324 lastUsageSignature: state.lastUsageSignature ?? null,
325 sawSessionMeta: state.sawSessionMeta,
326 suppressingForkCopies: state.suppressingForkCopies,
327 forkCopyAnchorMs: state.forkCopyAnchorMs,
328 };
329}
330
331/** Keeps saved usage after transcript cleanup, until the reporting retention expires. */
332export function pruneScanCache(cache: ScanCache, retentionCutoffMs: number): number {
333 let removed = 0;
334 for (const [path, entry] of cache) {
335 if (entry.mtimeMs < retentionCutoffMs) {
336 cache.delete(path);
337 removed += 1;
338 }
339 }
340 return removed;
341}
342
343/**
344 * Within-file de-duplication, applied before an entry is cached.
345 *
346 * Callers stitching an incremental parse together pass one `seen` set across
347 * the line and tail record batches so the whole file stays deduplicated as a
348 * unit; the set is mutated in place.
349 */
350export function dedupeWithinFile(
351 records: readonly UsageRecord[],
352 seen: Set<string> = new Set(),
353): readonly UsageRecord[] {
354 const kept: UsageRecord[] = [];
355 for (const record of records) {
356 if (record.dedupeKey !== null) {
357 if (seen.has(record.dedupeKey)) continue;
358 seen.add(record.dedupeKey);
359 }
360 kept.push(record);
361 }
362 return kept;
363}