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 } 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.
27const USAGE_SCAN_CACHE_VERSION = 4 as const;
28
29export interface CachedFile {
30 readonly size: number;
31 readonly mtimeMs: number;
32 readonly provider: UsageProviderKind;
33 /** Records from newline-terminated lines, up to `position.resumeOffset`. */
34 readonly records: readonly UsageRecord[];
35 /**
36 * Records from a trailing segment the writer had not newline-terminated at
37 * parse time. Kept apart from `records` because an incremental parse
38 * re-reads that segment and would otherwise double count it.
39 */
40 readonly tailRecords: readonly UsageRecord[];
41 readonly position: TranscriptParsePosition;
42}
43
44export type ScanCache = Map<string, CachedFile>;
45
46/**
47 * Row layout for the serialised form. Positional and interned rather than
48 * object-per-record: on a 30-day window that is the difference between a file
49 * measured in tens of megabytes and one under six.
50 */
51type SerializedRecord = readonly [
52 timestampMs: number,
53 modelIndex: number,
54 sessionIndex: number,
55 uncachedInputTokens: number,
56 cachedInputTokens: number,
57 cacheCreationTokens: number,
58 outputTokens: number,
59 reasoningTokens: number,
60 dedupeKey: string | null,
61 reportedCostUsd: number | null,
62 fast: 0 | 1,
63];
64
65interface SerializedFile {
66 readonly s: number;
67 readonly m: number;
68 readonly p: UsageProviderKind;
69 readonly r: readonly SerializedRecord[];
70 /** Tail records; see `CachedFile.tailRecords`. */
71 readonly t: readonly SerializedRecord[];
72 /** Parse position: resume offset, guard length, guard hash. */
73 readonly o: number;
74 readonly gl: number;
75 readonly gh: number;
76 /** Codex reducer state at `o`; `null` for stateless providers. */
77 readonly cs: CodexScanState | null;
78}
79
80interface SerializedCache {
81 readonly version: number;
82 readonly models: readonly string[];
83 readonly sessions: readonly string[];
84 readonly files: Readonly<Record<string, SerializedFile>>;
85}
86
87/** Serialises the cache, interning the repeated model and session strings. */
88export function encodeScanCache(cache: ScanCache): SerializedCache {
89 const models: string[] = [];
90 const sessions: string[] = [];
91 const modelIndex = new Map<string, number>();
92 const sessionIndex = new Map<string, number>();
93
94 const intern = (table: string[], index: Map<string, number>, value: string): number => {
95 const existing = index.get(value);
96 if (existing !== undefined) return existing;
97 const next = table.length;
98 table.push(value);
99 index.set(value, next);
100 return next;
101 };
102
103 const serializeRecord = (record: UsageRecord): SerializedRecord => [
104 record.timestampMs,
105 intern(models, modelIndex, record.model),
106 intern(sessions, sessionIndex, record.sessionId),
107 record.totals.uncachedInputTokens,
108 record.totals.cachedInputTokens,
109 record.totals.cacheCreationTokens,
110 record.totals.outputTokens,
111 record.totals.reasoningTokens,
112 record.dedupeKey,
113 record.reportedCostUsd,
114 record.fast ? 1 : 0,
115 ];
116
117 const files: Record<string, SerializedFile> = {};
118 for (const [path, entry] of cache) {
119 files[path] = {
120 s: entry.size,
121 m: entry.mtimeMs,
122 p: entry.provider,
123 r: entry.records.map(serializeRecord),
124 t: entry.tailRecords.map(serializeRecord),
125 o: entry.position.resumeOffset,
126 gl: entry.position.guardLength,
127 gh: entry.position.guardHash,
128 cs: entry.position.codexState,
129 };
130 }
131
132 return { version: USAGE_SCAN_CACHE_VERSION, models, sessions, files };
133}
134
135function isRecordArray(value: unknown): value is readonly unknown[] {
136 return Array.isArray(value);
137}
138
139/**
140 * Rebuilds the cache from a parsed document.
141 *
142 * Anything malformed yields an empty cache rather than an error: a corrupt
143 * cache should cost one cold scan, never a broken page.
144 */
145export function decodeScanCache(document: unknown): ScanCache {
146 const cache: ScanCache = new Map();
147 if (typeof document !== "object" || document === null) return cache;
148
149 const root = document as Partial<SerializedCache>;
150 if (root.version !== USAGE_SCAN_CACHE_VERSION) return cache;
151 if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
152 if (typeof root.files !== "object" || root.files === null) return cache;
153
154 // The intern tables must be all strings: a numeric entry would pass the
155 // undefined guard below, land in a record's model, and crash the aggregate
156 // at lookupRate. A corrupt table rejects the whole cache.
157 if (!root.models.every((value) => typeof value === "string")) return cache;
158 if (!root.sessions.every((value) => typeof value === "string")) return cache;
159 const models = root.models as readonly string[];
160 const sessions = root.sessions as readonly string[];
161
162 // Any corrupt row disqualifies the whole entry. Keeping the survivors
163 // under the original (size, mtime) would read as a valid warm hit and the
164 // file would never be re-parsed, silently losing the dropped rows' usage.
165 const decodeRecords = (
166 rows: readonly unknown[],
167 provider: UsageProviderKind,
168 ): UsageRecord[] | null => {
169 const records: UsageRecord[] = [];
170 for (const row of rows) {
171 if (!isRecordArray(row) || row.length < 11) return null;
172 const [
173 timestampMs,
174 modelIndex,
175 sessionIndex,
176 uncached,
177 cached,
178 cacheCreation,
179 output,
180 reasoning,
181 dedupeKey,
182 reportedCostUsd,
183 fast,
184 ] = row as SerializedRecord;
185
186 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
187 if (
188 typeof timestampMs !== "number" ||
189 !Number.isFinite(timestampMs) ||
190 model === undefined ||
191 !Number.isFinite(uncached) ||
192 !Number.isFinite(cached) ||
193 !Number.isFinite(cacheCreation) ||
194 !Number.isFinite(output) ||
195 !Number.isFinite(reasoning) ||
196 (fast !== 0 && fast !== 1)
197 ) {
198 return null;
199 }
200
201 records.push({
202 provider,
203 timestampMs,
204 model,
205 sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "",
206 totals: {
207 uncachedInputTokens: uncached,
208 cachedInputTokens: cached,
209 cacheCreationTokens: cacheCreation,
210 outputTokens: output,
211 reasoningTokens: reasoning,
212 },
213 reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
214 fast: fast === 1,
215 dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
216 });
217 }
218 return records;
219 };
220
221 for (const [path, raw] of Object.entries(root.files)) {
222 if (typeof raw !== "object" || raw === null) continue;
223 const entry = raw as Partial<SerializedFile>;
224 if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
225 if (entry.p !== "claude" && entry.p !== "codex" && entry.p !== "grok") continue;
226 if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
227 // Position fields feed byte offsets and a Buffer allocation in the reader,
228 // so anything outside their real ranges must reject the entry: a bogus
229 // guard length would otherwise fail every parse of the file, silently
230 // dropping its usage instead of costing the documented cold re-parse.
231 if (
232 typeof entry.o !== "number" ||
233 !Number.isSafeInteger(entry.o) ||
234 entry.o < 0 ||
235 typeof entry.gl !== "number" ||
236 !Number.isSafeInteger(entry.gl) ||
237 entry.gl < 0 ||
238 entry.gl > GUARD_LENGTH ||
239 entry.gl > entry.o ||
240 typeof entry.gh !== "number" ||
241 !Number.isFinite(entry.gh)
242 ) {
243 continue;
244 }
245 const codexState = decodeCodexState(entry.cs);
246 if (codexState === undefined) continue;
247
248 const provider: UsageProviderKind = entry.p;
249 const records = decodeRecords(entry.r, provider);
250 const tailRecords = decodeRecords(entry.t, provider);
251 if (records === null || tailRecords === null) continue;
252
253 cache.set(path, {
254 size: entry.s,
255 mtimeMs: entry.m,
256 provider,
257 records,
258 tailRecords,
259 position: {
260 resumeOffset: entry.o,
261 guardLength: entry.gl,
262 guardHash: entry.gh,
263 codexState,
264 },
265 });
266 }
267
268 return cache;
269}
270
271/**
272 * Validates a persisted Codex reducer state. Returns `undefined` for a corrupt
273 * value, which disqualifies the entry: resuming with a bad state would attach
274 * appended usage to the wrong model or replay fork-copied history.
275 */
276function decodeCodexState(value: unknown): CodexScanState | null | undefined {
277 if (value === null) return null;
278 if (typeof value !== "object") return undefined;
279 const state = value as Partial<CodexScanState>;
280 if (
281 typeof state.model !== "string" ||
282 typeof state.sessionId !== "string" ||
283 (state.lastUsageSignature !== null && typeof state.lastUsageSignature !== "string") ||
284 typeof state.sawSessionMeta !== "boolean" ||
285 typeof state.suppressingForkCopies !== "boolean" ||
286 typeof state.forkCopyAnchorMs !== "number" ||
287 !Number.isFinite(state.forkCopyAnchorMs)
288 ) {
289 return undefined;
290 }
291 return {
292 model: state.model,
293 sessionId: state.sessionId,
294 lastUsageSignature: state.lastUsageSignature ?? null,
295 sawSessionMeta: state.sawSessionMeta,
296 suppressingForkCopies: state.suppressingForkCopies,
297 forkCopyAnchorMs: state.forkCopyAnchorMs,
298 };
299}
300
301/** Keeps saved usage after transcript cleanup, until the reporting retention expires. */
302export function pruneScanCache(cache: ScanCache, retentionCutoffMs: number): number {
303 let removed = 0;
304 for (const [path, entry] of cache) {
305 if (entry.mtimeMs < retentionCutoffMs) {
306 cache.delete(path);
307 removed += 1;
308 }
309 }
310 return removed;
311}
312
313/**
314 * Within-file de-duplication, applied before an entry is cached.
315 *
316 * Callers stitching an incremental parse together pass one `seen` set across
317 * the line and tail record batches so the whole file stays deduplicated as a
318 * unit; the set is mutated in place.
319 */
320export function dedupeWithinFile(
321 records: readonly UsageRecord[],
322 seen: Set<string> = new Set(),
323): readonly UsageRecord[] {
324 const kept: UsageRecord[] = [];
325 for (const record of records) {
326 if (record.dedupeKey !== null) {
327 if (seen.has(record.dedupeKey)) continue;
328 seen.add(record.dedupeKey);
329 }
330 kept.push(record);
331 }
332 return kept;
333}