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

usageScanCache.ts

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