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

usageScanCache.ts

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