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

usageScanCache.ts

255 lines8.8 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 type { UsageRecord } from "./usageTranscripts.ts";
20​
21// v2: Codex fork-copy suppression changed what a file parses to, so v1
22// entries would keep serving double-counted records forever.
23export const USAGE_SCAN_CACHE_VERSION = 2 as const;
24​
25export interface CachedFile {
26 readonly size: number;
27 readonly mtimeMs: number;
28 readonly provider: UsageProviderKind;
29 readonly records: readonly UsageRecord[];
31​
32export type ScanCache = Map<string, CachedFile>;
33​
34/**
35 * Row layout for the serialised form. Positional and interned rather than
36 * object-per-record: on a 30-day window that is the difference between a file
37 * measured in tens of megabytes and one under six.
38 */
39type SerializedRecord = readonly [
40 timestampMs: number,
41 modelIndex: number,
42 sessionIndex: number,
43 uncachedInputTokens: number,
44 cachedInputTokens: number,
45 cacheCreationTokens: number,
46 outputTokens: number,
47 reasoningTokens: number,
48 dedupeKey: string | null,
49 reportedCostUsd: number | null,
50];
51​
52interface SerializedFile {
53 readonly s: number;
54 readonly m: number;
55 readonly p: UsageProviderKind;
56 readonly r: readonly SerializedRecord[];
58​
59interface SerializedCache {
60 readonly version: number;
61 readonly models: readonly string[];
62 readonly sessions: readonly string[];
63 readonly files: Readonly<Record<string, SerializedFile>>;
65​
66/** Serialises the cache, interning the repeated model and session strings. */
67export function encodeScanCache(cache: ScanCache): SerializedCache {
68 const models: string[] = [];
69 const sessions: string[] = [];
70 const modelIndex = new Map<string, number>();
71 const sessionIndex = new Map<string, number>();
72​
73 const intern = (table: string[], index: Map<string, number>, value: string): number => {
74 const existing = index.get(value);
75 if (existing !== undefined) return existing;
76 const next = table.length;
77 table.push(value);
78 index.set(value, next);
79 return next;
80 };
81​
82 const files: Record<string, SerializedFile> = {};
83 for (const [path, entry] of cache) {
84 files[path] = {
85 s: entry.size,
86 m: entry.mtimeMs,
87 p: entry.provider,
88 r: entry.records.map((record) => [
89 record.timestampMs,
90 intern(models, modelIndex, record.model),
91 intern(sessions, sessionIndex, record.sessionId),
92 record.totals.uncachedInputTokens,
93 record.totals.cachedInputTokens,
94 record.totals.cacheCreationTokens,
95 record.totals.outputTokens,
96 record.totals.reasoningTokens,
97 record.dedupeKey,
98 record.reportedCostUsd,
99 ]),
100 };
101 }
102​
103 return { version: USAGE_SCAN_CACHE_VERSION, models, sessions, files };
105​
106function isRecordArray(value: unknown): value is readonly unknown[] {
107 return Array.isArray(value);
109​
110/**
111 * Rebuilds the cache from a parsed document.
112 *
113 * Anything malformed yields an empty cache rather than an error: a corrupt
114 * cache should cost one cold scan, never a broken page.
115 */
116export function decodeScanCache(document: unknown): ScanCache {
117 const cache: ScanCache = new Map();
118 if (typeof document !== "object" || document === null) return cache;
119​
120 const root = document as Partial<SerializedCache>;
121 if (root.version !== USAGE_SCAN_CACHE_VERSION) return cache;
122 if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
123 if (typeof root.files !== "object" || root.files === null) return cache;
124​
125 // The intern tables must be all strings: a numeric entry would pass the
126 // undefined guard below, land in a record's model, and crash the aggregate
127 // at lookupRate. A corrupt table rejects the whole cache.
128 if (!root.models.every((value) => typeof value === "string")) return cache;
129 if (!root.sessions.every((value) => typeof value === "string")) return cache;
130 const models = root.models as readonly string[];
131 const sessions = root.sessions as readonly string[];
132​
133 for (const [path, raw] of Object.entries(root.files)) {
134 if (typeof raw !== "object" || raw === null) continue;
135 const entry = raw as Partial<SerializedFile>;
136 if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
137 if (entry.p !== "claude" && entry.p !== "codex" && entry.p !== "grok") continue;
138 if (!isRecordArray(entry.r)) continue;
139​
140 const provider: UsageProviderKind = entry.p;
141 const records: UsageRecord[] = [];
142 // Any corrupt row disqualifies the whole entry. Keeping the survivors
143 // under the original (size, mtime) would read as a valid warm hit and the
144 // file would never be re-parsed, silently losing the dropped rows' usage.
145 let corrupt = false;
146 for (const row of entry.r) {
147 if (!isRecordArray(row) || row.length < 10) {
148 corrupt = true;
149 break;
150 }
151 const [
152 timestampMs,
153 modelIndex,
154 sessionIndex,
155 uncached,
156 cached,
157 cacheCreation,
158 output,
159 reasoning,
160 dedupeKey,
161 reportedCostUsd,
162 ] = row as SerializedRecord;
163​
164 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
165 if (
166 typeof timestampMs !== "number" ||
167 !Number.isFinite(timestampMs) ||
168 model === undefined ||
169 !Number.isFinite(uncached) ||
170 !Number.isFinite(cached) ||
171 !Number.isFinite(cacheCreation) ||
172 !Number.isFinite(output) ||
173 !Number.isFinite(reasoning)
174 ) {
175 corrupt = true;
176 break;
177 }
178​
179 records.push({
180 provider,
181 timestampMs,
182 model,
183 sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "",
184 totals: {
185 uncachedInputTokens: uncached,
186 cachedInputTokens: cached,
187 cacheCreationTokens: cacheCreation,
188 outputTokens: output,
189 reasoningTokens: reasoning,
190 },
191 reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
192 dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
193 });
194 }
195​
196 if (corrupt) continue;
197 cache.set(path, { size: entry.s, mtimeMs: entry.m, provider, records });
198 }
199​
200 return cache;
202​
203export interface PruneOptions {
204 /** Files the walk just saw. Only meaningful inside the walked window. */
205 readonly livePaths: ReadonlySet<string>;
206 /**
207 * Roots the walk actually completed. Absence from `livePaths` only proves a
208 * file is gone when its root was walked: a provider whose directory failed to
209 * resolve this pass must not have its warm entries purged.
210 */
211 readonly walkedRoots: readonly string[];
212 /** Start of the walked window; entries older than this were not looked for. */
213 readonly windowStartMs: number;
214 /** Entries older than this are dropped regardless. */
215 readonly retentionCutoffMs: number;
217​
218/**
219 * Drops aged-out entries, and entries for files that have disappeared.
220 *
221 * The walk only covers the requested window, so absence from `livePaths` only
222 * proves deletion for entries *inside* that window. Pruning everything the walk
223 * missed would evict the 30-day entries every time someone looked at 7 days.
224 *
225 * Replaces an earlier record cap that cleared the whole cache once exceeded,
226 * which meant a large enough window never warmed up at all.
227 */
228export function pruneScanCache(cache: ScanCache, options: PruneOptions): number {
229 let removed = 0;
230 for (const [path, entry] of cache) {
231 const agedOut = entry.mtimeMs < options.retentionCutoffMs;
232 const underWalkedRoot = options.walkedRoots.some((root) => path.startsWith(root));
233 const deleted =
234 underWalkedRoot && entry.mtimeMs >= options.windowStartMs && !options.livePaths.has(path);
235 if (agedOut || deleted) {
236 cache.delete(path);
237 removed += 1;
238 }
239 }
240 return removed;
242​
243/** Within-file de-duplication, applied before an entry is cached. */
244export function dedupeWithinFile(records: readonly UsageRecord[]): readonly UsageRecord[] {
245 const seen = new Set<string>();
246 const kept: UsageRecord[] = [];
247 for (const record of records) {
248 if (record.dedupeKey !== null) {
249 if (seen.has(record.dedupeKey)) continue;
250 seen.add(record.dedupeKey);
251 }
252 kept.push(record);
253 }
254 return kept;