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 */
17// @effect-diagnostics nodeBuiltinImport:off
18import * as NodePath from "node:path";
19
20import type { UsageProviderKind } from "@t3tools/contracts";
21
22import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts";
23import type { CodexScanState, UsageRecord } from "./usageTranscripts.ts";
24
25// v2: Codex fork-copy suppression changed what a file parses to, so v1
26// entries would keep serving double-counted records forever.
27// v3: entries carry the parse position and reducer state so a grown file
28// re-parses only its appended bytes instead of starting over.
29// v3: Devin ACP event-log records were added and the provider set is part of
30// the cache schema. Invalidating older entries also ensures a previously
31// flattened provider snapshot cannot mask the new model/session attribution.
32export const USAGE_SCAN_CACHE_VERSION = 3 as const;
33
34export interface CachedFile {
35 readonly size: number;
36 readonly mtimeMs: number;
37 readonly provider: UsageProviderKind;
38 /** Records from newline-terminated lines, up to `position.resumeOffset`. */
39 readonly records: readonly UsageRecord[];
40 /**
41 * Records from a trailing segment the writer had not newline-terminated at
42 * parse time. Kept apart from `records` because an incremental parse
43 * re-reads that segment and would otherwise double count it.
44 */
45 readonly tailRecords: readonly UsageRecord[];
46 readonly position: TranscriptParsePosition;
47}
48
49export type ScanCache = Map<string, CachedFile>;
50
51/**
52 * Row layout for the serialised form. Positional and interned rather than
53 * object-per-record: on a 30-day window that is the difference between a file
54 * measured in tens of megabytes and one under six.
55 */
56type SerializedRecord = readonly [
57 timestampMs: number,
58 modelIndex: number,
59 sessionIndex: number,
60 uncachedInputTokens: number,
61 cachedInputTokens: number,
62 cacheCreationTokens: number,
63 outputTokens: number,
64 reasoningTokens: number,
65 dedupeKey: string | null,
66 reportedCostUsd: number | null,
67];
68
69interface SerializedFile {
70 readonly s: number;
71 readonly m: number;
72 readonly p: UsageProviderKind;
73 readonly r: readonly SerializedRecord[];
74 /** Tail records; see `CachedFile.tailRecords`. */
75 readonly t: readonly SerializedRecord[];
76 /** Parse position: resume offset, guard length, guard hash. */
77 readonly o: number;
78 readonly gl: number;
79 readonly gh: number;
80 /** Codex reducer state at `o`; `null` for stateless providers. */
81 readonly cs: CodexScanState | null;
82}
83
84interface SerializedCache {
85 readonly version: number;
86 readonly models: readonly string[];
87 readonly sessions: readonly string[];
88 readonly files: Readonly<Record<string, SerializedFile>>;
89}
90
91/** Serialises the cache, interning the repeated model and session strings. */
92export function encodeScanCache(cache: ScanCache): SerializedCache {
93 const models: string[] = [];
94 const sessions: string[] = [];
95 const modelIndex = new Map<string, number>();
96 const sessionIndex = new Map<string, number>();
97
98 const intern = (table: string[], index: Map<string, number>, value: string): number => {
99 const existing = index.get(value);
100 if (existing !== undefined) return existing;
101 const next = table.length;
102 table.push(value);
103 index.set(value, next);
104 return next;
105 };
106
107 const serializeRecord = (record: UsageRecord): SerializedRecord => [
108 record.timestampMs,
109 intern(models, modelIndex, record.model),
110 intern(sessions, sessionIndex, record.sessionId),
111 record.totals.uncachedInputTokens,
112 record.totals.cachedInputTokens,
113 record.totals.cacheCreationTokens,
114 record.totals.outputTokens,
115 record.totals.reasoningTokens,
116 record.dedupeKey,
117 record.reportedCostUsd,
118 ];
119
120 const files: Record<string, SerializedFile> = {};
121 for (const [path, entry] of cache) {
122 files[path] = {
123 s: entry.size,
124 m: entry.mtimeMs,
125 p: entry.provider,
126 r: entry.records.map(serializeRecord),
127 t: entry.tailRecords.map(serializeRecord),
128 o: entry.position.resumeOffset,
129 gl: entry.position.guardLength,
130 gh: entry.position.guardHash,
131 cs: entry.position.codexState,
132 };
133 }
134
135 return { version: USAGE_SCAN_CACHE_VERSION, models, sessions, files };
136}
137
138function isRecordArray(value: unknown): value is readonly unknown[] {
139 return Array.isArray(value);
140}
141
142/**
143 * Rebuilds the cache from a parsed document.
144 *
145 * Anything malformed yields an empty cache rather than an error: a corrupt
146 * cache should cost one cold scan, never a broken page.
147 */
148export function decodeScanCache(document: unknown): ScanCache {
149 const cache: ScanCache = new Map();
150 if (typeof document !== "object" || document === null) return cache;
151
152 const root = document as Partial<SerializedCache>;
153 if (root.version !== USAGE_SCAN_CACHE_VERSION) return cache;
154 if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
155 if (typeof root.files !== "object" || root.files === null) return cache;
156
157 // The intern tables must be all strings: a numeric entry would pass the
158 // undefined guard below, land in a record's model, and crash the aggregate
159 // at lookupRate. A corrupt table rejects the whole cache.
160 if (!root.models.every((value) => typeof value === "string")) return cache;
161 if (!root.sessions.every((value) => typeof value === "string")) return cache;
162 const models = root.models as readonly string[];
163 const sessions = root.sessions as readonly string[];
164
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 const decodeRecords = (
169 rows: readonly unknown[],
170 provider: UsageProviderKind,
171 ): UsageRecord[] | null => {
172 const records: UsageRecord[] = [];
173 for (const row of rows) {
174 if (!isRecordArray(row) || row.length < 10) return null;
175 const [
176 timestampMs,
177 modelIndex,
178 sessionIndex,
179 uncached,
180 cached,
181 cacheCreation,
182 output,
183 reasoning,
184 dedupeKey,
185 reportedCostUsd,
186 ] = row as SerializedRecord;
187
188 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
189 if (
190 typeof timestampMs !== "number" ||
191 !Number.isFinite(timestampMs) ||
192 model === undefined ||
193 !Number.isFinite(uncached) ||
194 !Number.isFinite(cached) ||
195 !Number.isFinite(cacheCreation) ||
196 !Number.isFinite(output) ||
197 !Number.isFinite(reasoning)
198 ) {
199 return null;
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 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" && entry.p !== "devin")
226 continue;
227 if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
228 // Position fields feed byte offsets and a Buffer allocation in the reader,
229 // so anything outside their real ranges must reject the entry: a bogus
230 // guard length would otherwise fail every parse of the file, silently
231 // dropping its usage instead of costing the documented cold re-parse.
232 if (
233 typeof entry.o !== "number" ||
234 !Number.isSafeInteger(entry.o) ||
235 entry.o < 0 ||
236 typeof entry.gl !== "number" ||
237 !Number.isSafeInteger(entry.gl) ||
238 entry.gl < 0 ||
239 entry.gl > GUARD_LENGTH ||
240 entry.gl > entry.o ||
241 typeof entry.gh !== "number" ||
242 !Number.isFinite(entry.gh)
243 ) {
244 continue;
245 }
246 const codexState = decodeCodexState(entry.cs);
247 if (codexState === undefined) continue;
248
249 const provider: UsageProviderKind = entry.p;
250 const records = decodeRecords(entry.r, provider);
251 const tailRecords = decodeRecords(entry.t, provider);
252 if (records === null || tailRecords === null) continue;
253
254 cache.set(path, {
255 size: entry.s,
256 mtimeMs: entry.m,
257 provider,
258 records,
259 tailRecords,
260 position: {
261 resumeOffset: entry.o,
262 guardLength: entry.gl,
263 guardHash: entry.gh,
264 codexState,
265 },
266 });
267 }
268
269 return cache;
270}
271
272/**
273 * Validates a persisted Codex reducer state. Returns `undefined` for a corrupt
274 * value, which disqualifies the entry: resuming with a bad state would attach
275 * appended usage to the wrong model or replay fork-copied history.
276 */
277function decodeCodexState(value: unknown): CodexScanState | null | undefined {
278 if (value === null) return null;
279 if (typeof value !== "object") return undefined;
280 const state = value as Partial<CodexScanState>;
281 if (
282 typeof state.model !== "string" ||
283 typeof state.sessionId !== "string" ||
284 (state.lastUsageSignature !== null && typeof state.lastUsageSignature !== "string") ||
285 typeof state.sawSessionMeta !== "boolean" ||
286 typeof state.suppressingForkCopies !== "boolean" ||
287 typeof state.forkCopyAnchorMs !== "number" ||
288 !Number.isFinite(state.forkCopyAnchorMs)
289 ) {
290 return undefined;
291 }
292 return {
293 model: state.model,
294 sessionId: state.sessionId,
295 lastUsageSignature: state.lastUsageSignature ?? null,
296 sawSessionMeta: state.sawSessionMeta,
297 suppressingForkCopies: state.suppressingForkCopies,
298 forkCopyAnchorMs: state.forkCopyAnchorMs,
299 };
300}
301
302export interface PruneOptions {
303 /** Files the walk just saw. Only meaningful inside the walked window. */
304 readonly livePaths: ReadonlySet<string>;
305 /**
306 * Roots the walk actually completed. Absence from `livePaths` only proves a
307 * file is gone when its root was walked: a provider whose directory failed to
308 * resolve this pass must not have its warm entries purged.
309 */
310 readonly walkedRoots: readonly string[];
311 /** Start of the walked window; entries older than this were not looked for. */
312 readonly windowStartMs: number;
313 /** Entries older than this are dropped regardless. */
314 readonly retentionCutoffMs: number;
315}
316
317/**
318 * Drops aged-out entries, and entries for files that have disappeared.
319 *
320 * The walk only covers the requested window, so absence from `livePaths` only
321 * proves deletion for entries *inside* that window. Pruning everything the walk
322 * missed would evict the 30-day entries every time someone looked at 7 days.
323 *
324 * Replaces an earlier record cap that cleared the whole cache once exceeded,
325 * which meant a large enough window never warmed up at all.
326 */
327export function pruneScanCache(cache: ScanCache, options: PruneOptions): number {
328 let removed = 0;
329 for (const [path, entry] of cache) {
330 const agedOut = entry.mtimeMs < options.retentionCutoffMs;
331 const underWalkedRoot = options.walkedRoots.some((root) => {
332 const relative = NodePath.relative(root, path);
333 return (
334 relative === "" ||
335 (relative !== ".." &&
336 !relative.startsWith(`..${NodePath.sep}`) &&
337 !NodePath.isAbsolute(relative))
338 );
339 });
340 const deleted =
341 underWalkedRoot && entry.mtimeMs >= options.windowStartMs && !options.livePaths.has(path);
342 if (agedOut || deleted) {
343 cache.delete(path);
344 removed += 1;
345 }
346 }
347 return removed;
348}
349
350/**
351 * Within-file de-duplication, applied before an entry is cached.
352 *
353 * Callers stitching an incremental parse together pass one `seen` set across
354 * the line and tail record batches so the whole file stays deduplicated as a
355 * unit; the set is mutated in place.
356 */
357export function dedupeWithinFile(
358 records: readonly UsageRecord[],
359 seen: Set<string> = new Set(),
360): readonly UsageRecord[] {
361 const kept: UsageRecord[] = [];
362 for (const record of records) {
363 if (record.dedupeKey !== null) {
364 if (seen.has(record.dedupeKey)) continue;
365 seen.add(record.dedupeKey);
366 }
367 kept.push(record);
368 }
369 return kept;
370}