Open History to see the last commit
1import type { UsageProviderKind } from "@t3tools/contracts";
2import type {
3 TranscriptUsageFormat,
4 UsageRecord,
5 UsageSpeed,
6} from "@t3tools/provider-core/server/usage";
7import * as Schema from "effect/Schema";
8
9import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts";
10
11const USAGE_SCAN_CACHE_VERSION = 5 as const;
12const SPEED_COMPATIBLE_SINCE_VERSION = 4;
13
14/**
15 * An older server sharing that directory cannot read a newer cache and would
16 * replace it, dropping saved usage for deleted transcripts. Separate files keep
17 * both.
18 */
19export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v5.json";
20export const LEGACY_SCAN_CACHE_FILE_NAME = "usage-scan-cache.json";
21
22const SPEEDS: readonly UsageSpeed[] = ["standard", "fast", "ultrafast"];
23
24export interface CachedFile {
25 readonly size: number;
26 readonly mtimeMs: number;
27 readonly provider: UsageProviderKind;
28 readonly records: readonly UsageRecord[];
29 /**
30 * Records from a trailing segment the writer had not newline-terminated at
31 * parse time. Kept apart from `records` because an incremental parse
32 * re-reads that segment and would otherwise double count it.
33 */
34 readonly tailRecords: readonly UsageRecord[];
35 readonly position: TranscriptParsePosition;
36}
37
38export type ScanCache = Map<string, CachedFile>;
39
40type SerializedRecord = readonly [
41 timestampMs: number,
42 modelIndex: number,
43 sessionIndex: number,
44 uncachedInputTokens: number,
45 cachedInputTokens: number,
46 cacheCreationTokens: number,
47 outputTokens: number,
48 reasoningTokens: number,
49 dedupeKey: string | null,
50 reportedCostUsd: number | null,
51 speed: number,
52 rateModelIndex?: number | null,
53];
54
55interface SerializedFile {
56 readonly s: number;
57 readonly m: number;
58 readonly p: UsageProviderKind;
59 readonly r: readonly SerializedRecord[];
60 readonly t: readonly SerializedRecord[];
61 readonly o: number;
62 readonly gl: number;
63 readonly gh: number;
64 readonly cs: unknown;
65}
66
67interface SerializedCache {
68 readonly version: number;
69 readonly models: readonly string[];
70 readonly sessions: readonly string[];
71 readonly files: Readonly<Record<string, SerializedFile>>;
72}
73
74interface InternTables {
75 readonly models: string[];
76 readonly sessions: string[];
77 readonly modelIndex: Map<string, number>;
78 readonly sessionIndex: Map<string, number>;
79}
80
81function makeInternTables(): InternTables {
82 return { models: [], sessions: [], modelIndex: new Map(), sessionIndex: new Map() };
83}
84
85function intern(table: string[], index: Map<string, number>, value: string): number {
86 const existing = index.get(value);
87 if (existing !== undefined) return existing;
88 const next = table.length;
89 table.push(value);
90 index.set(value, next);
91 return next;
92}
93
94function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile {
95 const serializeRecord = (record: UsageRecord): SerializedRecord => [
96 record.timestampMs,
97 intern(tables.models, tables.modelIndex, record.model),
98 intern(tables.sessions, tables.sessionIndex, record.sessionId),
99 record.totals.uncachedInputTokens,
100 record.totals.cachedInputTokens,
101 record.totals.cacheCreationTokens,
102 record.totals.outputTokens,
103 record.totals.reasoningTokens,
104 record.dedupeKey,
105 record.reportedCostUsd,
106 SPEEDS.indexOf(record.speed),
107 record.rateModel === undefined
108 ? null
109 : intern(tables.models, tables.modelIndex, record.rateModel),
110 ];
111 return {
112 s: entry.size,
113 m: entry.mtimeMs,
114 p: entry.provider,
115 r: entry.records.map(serializeRecord),
116 t: entry.tailRecords.map(serializeRecord),
117 o: entry.position.resumeOffset,
118 gl: entry.position.guardLength,
119 gh: entry.position.guardHash,
120 cs: entry.position.state,
121 };
122}
123
124export function encodeScanCache(cache: ScanCache): SerializedCache {
125 const tables = makeInternTables();
126 const files: Record<string, SerializedFile> = {};
127 for (const [path, entry] of cache) files[path] = serializeFile(entry, tables);
128 return {
129 version: USAGE_SCAN_CACHE_VERSION,
130 models: tables.models,
131 sessions: tables.sessions,
132 files,
133 };
134}
135
136/**
137 * Entries are replaced, never mutated, when their file changes, so an entry's JSON is memoised by
138 * identity. The intern tables only grow, so a memoised entry's indexes stay valid; a pruned entry
139 * can leave an unused string behind until the next process start.
140 */
141export function makeScanCacheWriter(): (
142 cache: ScanCache,
143 extra: Readonly<Record<string, unknown>>,
144) => string {
145 const tables = makeInternTables();
146 const fragments = new WeakMap<CachedFile, string>();
147 return (cache, extra) => {
148 const files: string[] = [];
149 for (const [path, entry] of cache) {
150 let fragment = fragments.get(entry);
151 if (fragment === undefined) {
152 fragment = JSON.stringify(serializeFile(entry, tables));
153 fragments.set(entry, fragment);
154 }
155 files.push(`${JSON.stringify(path)}:${fragment}`);
156 }
157 // Encoded after the files, which may have added to the intern tables.
158 const head = JSON.stringify({
159 ...extra,
160 version: USAGE_SCAN_CACHE_VERSION,
161 models: tables.models,
162 sessions: tables.sessions,
163 });
164 return `${head.slice(0, -1)},"files":{${files.join(",")}}}`;
165 };
166}
167
168function isRecordArray(value: unknown): value is readonly unknown[] {
169 return Array.isArray(value);
170}
171
172export function decodeScanCache(
173 document: unknown,
174 formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
175): ScanCache {
176 const cache: ScanCache = new Map();
177 const isValidState = makeStateValidators(formats);
178 if (typeof document !== "object" || document === null) return cache;
179
180 const root = document as Partial<SerializedCache>;
181 const version = root.version;
182 if (
183 typeof version !== "number" ||
184 version < SPEED_COMPATIBLE_SINCE_VERSION ||
185 version > USAGE_SCAN_CACHE_VERSION
186 ) {
187 return cache;
188 }
189 if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
190 if (typeof root.files !== "object" || root.files === null) return cache;
191
192 if (!root.models.every((value) => typeof value === "string")) return cache;
193 if (!root.sessions.every((value) => typeof value === "string")) return cache;
194 const models = root.models as readonly string[];
195 const sessions = root.sessions as readonly string[];
196
197 // Any corrupt row disqualifies the whole entry. Keeping the survivors
198 // under the original (size, mtime) would read as a valid warm hit and the
199 // file would never be re-parsed, silently losing the dropped rows' usage.
200 const decodeRecords = (
201 rows: readonly unknown[],
202 provider: UsageProviderKind,
203 ): UsageRecord[] | null => {
204 const records: UsageRecord[] = [];
205 for (const row of rows) {
206 if (!isRecordArray(row) || row.length < 11) return null;
207 const [
208 timestampMs,
209 modelIndex,
210 sessionIndex,
211 uncached,
212 cached,
213 cacheCreation,
214 output,
215 reasoning,
216 dedupeKey,
217 reportedCostUsd,
218 speedIndex,
219 rateModelIndex,
220 ] = row as SerializedRecord;
221 const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined;
222
223 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
224 const rateModel = typeof rateModelIndex === "number" ? models[rateModelIndex] : undefined;
225 if (
226 typeof timestampMs !== "number" ||
227 !Number.isFinite(timestampMs) ||
228 model === undefined ||
229 (rateModelIndex != null && rateModel === undefined) ||
230 !Number.isFinite(uncached) ||
231 !Number.isFinite(cached) ||
232 !Number.isFinite(cacheCreation) ||
233 !Number.isFinite(output) ||
234 !Number.isFinite(reasoning) ||
235 speed === undefined
236 ) {
237 return null;
238 }
239
240 records.push({
241 provider,
242 timestampMs,
243 model,
244 ...(rateModel === undefined ? {} : { rateModel }),
245 sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "",
246 totals: {
247 uncachedInputTokens: uncached,
248 cachedInputTokens: cached,
249 cacheCreationTokens: cacheCreation,
250 outputTokens: output,
251 reasoningTokens: reasoning,
252 },
253 reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
254 speed,
255 dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
256 });
257 }
258 return records;
259 };
260
261 for (const [path, raw] of Object.entries(root.files)) {
262 if (typeof raw !== "object" || raw === null) continue;
263 const entry = raw as Partial<SerializedFile>;
264 if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
265 if (entry.p === undefined) continue;
266 const format = formats.get(entry.p);
267 if (format === undefined) continue;
268 if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
269 // Position fields feed byte offsets and a Buffer allocation in the reader,
270 // so anything outside their real ranges must reject the entry: a bogus
271 // guard length would otherwise fail every parse of the file, silently
272 // dropping its usage instead of costing the documented cold re-parse.
273 if (
274 typeof entry.o !== "number" ||
275 !Number.isSafeInteger(entry.o) ||
276 entry.o < 0 ||
277 typeof entry.gl !== "number" ||
278 !Number.isSafeInteger(entry.gl) ||
279 entry.gl < 0 ||
280 entry.gl > GUARD_LENGTH ||
281 entry.gl > entry.o ||
282 typeof entry.gh !== "number" ||
283 !Number.isFinite(entry.gh)
284 ) {
285 continue;
286 }
287 // v4 records of stateful formats (Codex) predate service tiers, so they
288 // all priced as standard. Keep them, because the rollout may be gone, but
289 // make a live rollout re-parse whole: no file has size -1, and a zero
290 // position cannot resume.
291 const legacy = format.state !== undefined && version < USAGE_SCAN_CACHE_VERSION;
292 // A corrupt state disqualifies the entry: resuming with it would attach
293 // appended usage to the wrong model or replay fork-copied history.
294 if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue;
295
296 const provider = entry.p;
297 const records = decodeRecords(entry.r, provider);
298 const tailRecords = decodeRecords(entry.t, provider);
299 if (records === null || tailRecords === null) continue;
300
301 cache.set(path, {
302 size: legacy ? -1 : entry.s,
303 mtimeMs: entry.m,
304 provider,
305 records,
306 tailRecords,
307 position: legacy
308 ? { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }
309 : {
310 resumeOffset: entry.o,
311 guardLength: entry.gl,
312 guardHash: entry.gh,
313 state: entry.cs,
314 },
315 });
316 }
317
318 return cache;
319}
320
321function makeStateValidators(
322 formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
323): ReadonlyMap<UsageProviderKind, (value: unknown) => boolean> {
324 return new Map(
325 [...formats].map(([provider, format]) => {
326 const isState = format.state === undefined ? undefined : Schema.is(format.state.schema);
327 return [
328 provider,
329 (value: unknown) => value === null || (isState !== undefined && isState(value)),
330 ] as const;
331 }),
332 );
333}
334
335export function pruneScanCache(cache: ScanCache, retentionCutoffMs: number): number {
336 let removed = 0;
337 for (const [path, entry] of cache) {
338 if (entry.mtimeMs < retentionCutoffMs) {
339 cache.delete(path);
340 removed += 1;
341 }
342 }
343 return removed;
344}
345
346/**
347 * Callers stitching an incremental parse together pass one `seen` set across the line and tail
348 * record batches so the whole file stays deduplicated as a unit; the set is mutated in place.
349 */
350export function dedupeWithinFile(
351 records: readonly UsageRecord[],
352 seen: Set<string> = new Set(),
353): readonly UsageRecord[] {
354 const kept: UsageRecord[] = [];
355 for (const record of records) {
356 if (record.dedupeKey !== null) {
357 if (seen.has(record.dedupeKey)) continue;
358 seen.add(record.dedupeKey);
359 }
360 kept.push(record);
361 }
362 return kept;
363}