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