Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usageScanCache.ts

366 lines12.7 KB

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.
29const USAGE_SCAN_CACHE_VERSION = 3 as const;
30​
31export interface CachedFile {
32 readonly size: number;
33 readonly mtimeMs: number;
34 readonly provider: UsageProviderKind;
35 /** Records from newline-terminated lines, up to `position.resumeOffset`. */
36 readonly records: readonly UsageRecord[];
37 /**
38 * Records from a trailing segment the writer had not newline-terminated at
39 * parse time. Kept apart from `records` because an incremental parse
40 * re-reads that segment and would otherwise double count it.
41 */
42 readonly tailRecords: readonly UsageRecord[];
43 readonly position: TranscriptParsePosition;
45​
46export type ScanCache = Map<string, CachedFile>;
47​
48/**
49 * Row layout for the serialised form. Positional and interned rather than
50 * object-per-record: on a 30-day window that is the difference between a file
51 * measured in tens of megabytes and one under six.
52 */
53type SerializedRecord = readonly [
54 timestampMs: number,
55 modelIndex: number,
56 sessionIndex: number,
57 uncachedInputTokens: number,
58 cachedInputTokens: number,
59 cacheCreationTokens: number,
60 outputTokens: number,
61 reasoningTokens: number,
62 dedupeKey: string | null,
63 reportedCostUsd: number | null,
64];
65​
66interface SerializedFile {
67 readonly s: number;
68 readonly m: number;
69 readonly p: UsageProviderKind;
70 readonly r: readonly SerializedRecord[];
71 /** Tail records; see `CachedFile.tailRecords`. */
72 readonly t: readonly SerializedRecord[];
73 /** Parse position: resume offset, guard length, guard hash. */
74 readonly o: number;
75 readonly gl: number;
76 readonly gh: number;
77 /** Codex reducer state at `o`; `null` for stateless providers. */
78 readonly cs: CodexScanState | null;
80​
81interface SerializedCache {
82 readonly version: number;
83 readonly models: readonly string[];
84 readonly sessions: readonly string[];
85 readonly files: Readonly<Record<string, SerializedFile>>;
87​
88/** Serialises the cache, interning the repeated model and session strings. */
89export function encodeScanCache(cache: ScanCache): SerializedCache {
90 const models: string[] = [];
91 const sessions: string[] = [];
92 const modelIndex = new Map<string, number>();
93 const sessionIndex = new Map<string, number>();
94​
95 const intern = (table: string[], index: Map<string, number>, value: string): number => {
96 const existing = index.get(value);
97 if (existing !== undefined) return existing;
98 const next = table.length;
99 table.push(value);
100 index.set(value, next);
101 return next;
102 };
103​
104 const serializeRecord = (record: UsageRecord): SerializedRecord => [
105 record.timestampMs,
106 intern(models, modelIndex, record.model),
107 intern(sessions, sessionIndex, record.sessionId),
108 record.totals.uncachedInputTokens,
109 record.totals.cachedInputTokens,
110 record.totals.cacheCreationTokens,
111 record.totals.outputTokens,
112 record.totals.reasoningTokens,
113 record.dedupeKey,
114 record.reportedCostUsd,
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 };
134​
135function isRecordArray(value: unknown): value is readonly unknown[] {
136 return Array.isArray(value);
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 < 10) 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 ] = row as SerializedRecord;
184​
185 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
186 if (
187 typeof timestampMs !== "number" ||
188 !Number.isFinite(timestampMs) ||
189 model === undefined ||
190 !Number.isFinite(uncached) ||
191 !Number.isFinite(cached) ||
192 !Number.isFinite(cacheCreation) ||
193 !Number.isFinite(output) ||
194 !Number.isFinite(reasoning)
195 ) {
196 return null;
197 }
198​
199 records.push({
200 provider,
201 timestampMs,
202 model,
203 sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "",
204 totals: {
205 uncachedInputTokens: uncached,
206 cachedInputTokens: cached,
207 cacheCreationTokens: cacheCreation,
208 outputTokens: output,
209 reasoningTokens: reasoning,
210 },
211 reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
212 dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
213 });
214 }
215 return records;
216 };
217​
218 for (const [path, raw] of Object.entries(root.files)) {
219 if (typeof raw !== "object" || raw === null) continue;
220 const entry = raw as Partial<SerializedFile>;
221 if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
222 if (entry.p !== "claude" && entry.p !== "codex" && entry.p !== "grok") continue;
223 if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
224 // Position fields feed byte offsets and a Buffer allocation in the reader,
225 // so anything outside their real ranges must reject the entry: a bogus
226 // guard length would otherwise fail every parse of the file, silently
227 // dropping its usage instead of costing the documented cold re-parse.
228 if (
229 typeof entry.o !== "number" ||
230 !Number.isSafeInteger(entry.o) ||
231 entry.o < 0 ||
232 typeof entry.gl !== "number" ||
233 !Number.isSafeInteger(entry.gl) ||
234 entry.gl < 0 ||
235 entry.gl > GUARD_LENGTH ||
236 entry.gl > entry.o ||
237 typeof entry.gh !== "number" ||
238 !Number.isFinite(entry.gh)
239 ) {
240 continue;
241 }
242 const codexState = decodeCodexState(entry.cs);
243 if (codexState === undefined) continue;
244​
245 const provider: UsageProviderKind = entry.p;
246 const records = decodeRecords(entry.r, provider);
247 const tailRecords = decodeRecords(entry.t, provider);
248 if (records === null || tailRecords === null) continue;
249​
250 cache.set(path, {
251 size: entry.s,
252 mtimeMs: entry.m,
253 provider,
254 records,
255 tailRecords,
256 position: {
257 resumeOffset: entry.o,
258 guardLength: entry.gl,
259 guardHash: entry.gh,
260 codexState,
261 },
262 });
263 }
264​
265 return cache;
267​
268/**
269 * Validates a persisted Codex reducer state. Returns `undefined` for a corrupt
270 * value, which disqualifies the entry: resuming with a bad state would attach
271 * appended usage to the wrong model or replay fork-copied history.
272 */
273function decodeCodexState(value: unknown): CodexScanState | null | undefined {
274 if (value === null) return null;
275 if (typeof value !== "object") return undefined;
276 const state = value as Partial<CodexScanState>;
277 if (
278 typeof state.model !== "string" ||
279 typeof state.sessionId !== "string" ||
280 (state.lastUsageSignature !== null && typeof state.lastUsageSignature !== "string") ||
281 typeof state.sawSessionMeta !== "boolean" ||
282 typeof state.suppressingForkCopies !== "boolean" ||
283 typeof state.forkCopyAnchorMs !== "number" ||
284 !Number.isFinite(state.forkCopyAnchorMs)
285 ) {
286 return undefined;
287 }
288 return {
289 model: state.model,
290 sessionId: state.sessionId,
291 lastUsageSignature: state.lastUsageSignature ?? null,
292 sawSessionMeta: state.sawSessionMeta,
293 suppressingForkCopies: state.suppressingForkCopies,
294 forkCopyAnchorMs: state.forkCopyAnchorMs,
295 };
297​
298export interface PruneOptions {
299 /** Files the walk just saw. Only meaningful inside the walked window. */
300 readonly livePaths: ReadonlySet<string>;
301 /**
302 * Roots the walk actually completed. Absence from `livePaths` only proves a
303 * file is gone when its root was walked: a provider whose directory failed to
304 * resolve this pass must not have its warm entries purged.
305 */
306 readonly walkedRoots: readonly string[];
307 /** Start of the walked window; entries older than this were not looked for. */
308 readonly windowStartMs: number;
309 /** Entries older than this are dropped regardless. */
310 readonly retentionCutoffMs: number;
312​
313/**
314 * Drops aged-out entries, and entries for files that have disappeared.
315 *
316 * The walk only covers the requested window, so absence from `livePaths` only
317 * proves deletion for entries *inside* that window. Pruning everything the walk
318 * missed would evict the 30-day entries every time someone looked at 7 days.
319 *
320 * Replaces an earlier record cap that cleared the whole cache once exceeded,
321 * which meant a large enough window never warmed up at all.
322 */
323export function pruneScanCache(cache: ScanCache, options: PruneOptions): number {
324 let removed = 0;
325 for (const [path, entry] of cache) {
326 const agedOut = entry.mtimeMs < options.retentionCutoffMs;
327 const underWalkedRoot = options.walkedRoots.some((root) => {
328 const relative = NodePath.relative(root, path);
329 return (
330 relative === "" ||
331 (relative !== ".." &&
332 !relative.startsWith(`..${NodePath.sep}`) &&
333 !NodePath.isAbsolute(relative))
334 );
335 });
336 const deleted =
337 underWalkedRoot && entry.mtimeMs >= options.windowStartMs && !options.livePaths.has(path);
338 if (agedOut || deleted) {
339 cache.delete(path);
340 removed += 1;
341 }
342 }
343 return removed;
345​
346/**
347 * Within-file de-duplication, applied before an entry is cached.
348 *
349 * Callers stitching an incremental parse together pass one `seen` set across
350 * the line and tail record batches so the whole file stays deduplicated as a
351 * unit; the set is mutated in place.
352 */
353export function dedupeWithinFile(
354 records: readonly UsageRecord[],
355 seen: Set<string> = new Set(),
356): readonly UsageRecord[] {
357 const kept: UsageRecord[] = [];
358 for (const record of records) {
359 if (record.dedupeKey !== null) {
360 if (seen.has(record.dedupeKey)) continue;
361 seen.add(record.dedupeKey);
362 }
363 kept.push(record);
364 }
365 return kept;