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

usageScanCache.ts

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