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 { CLAUDE_SYNTHETIC_MODEL } from "../provider/Drivers/claudeUsage.ts";
10import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts";
11
12const USAGE_SCAN_CACHE_VERSION = 9 as const;
13const SPEED_COMPATIBLE_SINCE_VERSION = 4;
14
15/**
16 * An older server sharing that directory cannot read a newer cache and would
17 * replace it, dropping saved usage for deleted transcripts. Separate files keep
18 * both.
19 */
20export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v9.json";
21export const LEGACY_SCAN_CACHE_FILE_NAMES = [
22 "usage-scan-cache-v8.json",
23 "usage-scan-cache-v7.json",
24 "usage-scan-cache-v6.json",
25 "usage-scan-cache-v5.json",
26 "usage-scan-cache.json",
27] as const;
28
29const SPEEDS: readonly UsageSpeed[] = ["standard", "fast", "ultrafast"];
30
31export interface CachedFile {
32 readonly size: number;
33 readonly mtimeMs: number;
34 readonly provider: UsageProviderKind;
35 readonly records: readonly UsageRecord[];
36 /** Unterminated tail records stay separate because incremental parsing rereads them. */
37 readonly tailRecords: readonly UsageRecord[];
38 /** Whole-file count, including diagnostics from the tentative tail. */
39 readonly malformedRecords: number;
40 readonly position: TranscriptParsePosition;
41}
42
43export type ScanCache = Map<string, CachedFile>;
44
45type SerializedRecord = readonly [
46 timestampMs: number,
47 modelIndex: number,
48 sessionIndex: number,
49 uncachedInputTokens: number,
50 cachedInputTokens: number,
51 cacheCreationTokens: number,
52 outputTokens: number,
53 reasoningTokens: number,
54 dedupeKey: string | null,
55 reportedCostUsd: number | null,
56 speed: number,
57 rateModelIndex?: number | null,
58 unresolvedServiceTierTurnId?: string,
59];
60
61interface SerializedFile {
62 readonly s: number;
63 readonly m: number;
64 readonly p: UsageProviderKind;
65 readonly r: readonly SerializedRecord[];
66 readonly t: readonly SerializedRecord[];
67 readonly mr: number;
68 readonly o: number;
69 readonly gl: number;
70 readonly gh: number;
71 readonly cs: unknown;
72}
73
74interface SerializedCache {
75 readonly version: number;
76 readonly models: readonly string[];
77 readonly sessions: readonly string[];
78 readonly files: Readonly<Record<string, SerializedFile>>;
79}
80
81interface InternTables {
82 readonly models: string[];
83 readonly sessions: string[];
84 readonly modelIndex: Map<string, number>;
85 readonly sessionIndex: Map<string, number>;
86}
87
88function makeInternTables(): InternTables {
89 return { models: [], sessions: [], modelIndex: new Map(), sessionIndex: new Map() };
90}
91
92function 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
101function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile {
102 const serializeRecord = (record: UsageRecord): SerializedRecord => [
103 record.timestampMs,
104 intern(tables.models, tables.modelIndex, record.model),
105 intern(tables.sessions, tables.sessionIndex, record.sessionId),
106 record.totals.uncachedInputTokens,
107 record.totals.cachedInputTokens,
108 record.totals.cacheCreationTokens,
109 record.totals.outputTokens,
110 record.totals.reasoningTokens,
111 record.dedupeKey,
112 record.reportedCostUsd,
113 SPEEDS.indexOf(record.speed),
114 record.rateModel === undefined
115 ? null
116 : intern(tables.models, tables.modelIndex, record.rateModel),
117 ...(record.unresolvedServiceTierTurnId === undefined
118 ? ([] as const)
119 : ([record.unresolvedServiceTierTurnId] as const)),
120 ];
121 return {
122 s: entry.size,
123 m: entry.mtimeMs,
124 p: entry.provider,
125 r: entry.records.map(serializeRecord),
126 t: entry.tailRecords.map(serializeRecord),
127 mr: entry.malformedRecords,
128 o: entry.position.resumeOffset,
129 gl: entry.position.guardLength,
130 gh: entry.position.guardHash,
131 cs: entry.position.state,
132 };
133}
134
135export function encodeScanCache(cache: ScanCache): SerializedCache {
136 const tables = makeInternTables();
137 const files: Record<string, SerializedFile> = {};
138 for (const [path, entry] of cache) files[path] = serializeFile(entry, tables);
139 return {
140 version: USAGE_SCAN_CACHE_VERSION,
141 models: tables.models,
142 sessions: tables.sessions,
143 files,
144 };
145}
146
147/** Memoizes immutable entries by identity; growing intern tables preserve indexes, retaining unused strings until restart. */
148export function makeScanCacheWriter(): (
149 cache: ScanCache,
150 extra: Readonly<Record<string, unknown>>,
151) => string {
152 const tables = makeInternTables();
153 const fragments = new WeakMap<CachedFile, string>();
154 return (cache, extra) => {
155 const files: string[] = [];
156 for (const [path, entry] of cache) {
157 let fragment = fragments.get(entry);
158 if (fragment === undefined) {
159 fragment = JSON.stringify(serializeFile(entry, tables));
160 fragments.set(entry, fragment);
161 }
162 files.push(`${JSON.stringify(path)}:${fragment}`);
163 }
164 // Encoded after the files, which may have added to the intern tables.
165 const head = JSON.stringify({
166 ...extra,
167 version: USAGE_SCAN_CACHE_VERSION,
168 models: tables.models,
169 sessions: tables.sessions,
170 });
171 return `${head.slice(0, -1)},"files":{${files.join(",")}}}`;
172 };
173}
174
175function isRecordArray(value: unknown): value is readonly unknown[] {
176 return Array.isArray(value);
177}
178
179export function decodeScanCache(
180 document: unknown,
181 formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
182): ScanCache {
183 const cache: ScanCache = new Map();
184 const isValidState = makeStateValidators(formats);
185 if (typeof document !== "object" || document === null) return cache;
186
187 const root = document as Partial<SerializedCache>;
188 const version = root.version;
189 if (
190 typeof version !== "number" ||
191 version < SPEED_COMPATIBLE_SINCE_VERSION ||
192 version > USAGE_SCAN_CACHE_VERSION
193 ) {
194 return cache;
195 }
196 if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
197 if (typeof root.files !== "object" || root.files === null) return cache;
198
199 if (!root.models.every((value) => typeof value === "string")) return cache;
200 if (!root.sessions.every((value) => typeof value === "string")) return cache;
201 const models = root.models as readonly string[];
202 const sessions = root.sessions as readonly string[];
203
204 // Reject entire corrupt entries; partial survivors would appear warm and hide usage until the file changes.
205 const decodeRecords = (
206 rows: readonly unknown[],
207 provider: UsageProviderKind,
208 ): UsageRecord[] | null => {
209 const records: UsageRecord[] = [];
210 for (const row of rows) {
211 if (!isRecordArray(row) || row.length < 11) return null;
212 const [
213 timestampMs,
214 modelIndex,
215 sessionIndex,
216 uncached,
217 cached,
218 cacheCreation,
219 output,
220 reasoning,
221 dedupeKey,
222 reportedCostUsd,
223 speedIndex,
224 rateModelIndex,
225 unresolvedServiceTierTurnId,
226 ] = row as SerializedRecord;
227 const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined;
228
229 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
230 const rateModel = typeof rateModelIndex === "number" ? models[rateModelIndex] : undefined;
231 if (
232 typeof timestampMs !== "number" ||
233 !Number.isFinite(timestampMs) ||
234 model === undefined ||
235 (unresolvedServiceTierTurnId !== undefined &&
236 typeof unresolvedServiceTierTurnId !== "string") ||
237 (rateModelIndex != null && rateModel === undefined) ||
238 !Number.isFinite(uncached) ||
239 !Number.isFinite(cached) ||
240 !Number.isFinite(cacheCreation) ||
241 !Number.isFinite(output) ||
242 !Number.isFinite(reasoning) ||
243 speed === undefined
244 ) {
245 return null;
246 }
247
248 // Unchanged and deleted transcripts may only exist in the cache, so the
249 // parser cannot remove their previously saved local placeholders.
250 if (provider === "claude" && model === CLAUDE_SYNTHETIC_MODEL) continue;
251
252 records.push({
253 provider,
254 timestampMs,
255 model,
256 ...(rateModel === undefined ? {} : { rateModel }),
257 sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "",
258 totals: {
259 uncachedInputTokens: uncached,
260 cachedInputTokens: cached,
261 cacheCreationTokens: cacheCreation,
262 outputTokens: output,
263 reasoningTokens: reasoning,
264 },
265 reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
266 speed,
267 ...(version >= 7 && unresolvedServiceTierTurnId !== undefined
268 ? { unresolvedServiceTierTurnId }
269 : {}),
270 dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
271 });
272 }
273 return records;
274 };
275
276 for (const [path, raw] of Object.entries(root.files)) {
277 if (typeof raw !== "object" || raw === null) continue;
278 const entry = raw as Partial<SerializedFile>;
279 if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
280 if (entry.p === undefined) continue;
281 const format = formats.get(entry.p);
282 if (format === undefined) continue;
283 if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
284 const malformedRecords = entry.mr === undefined ? 0 : entry.mr;
285 if (!Number.isSafeInteger(malformedRecords) || malformedRecords < 0) continue;
286 // Position fields feed byte offsets and a Buffer allocation in the reader,
287 // so anything outside their real ranges must reject the entry: a bogus
288 // guard length would otherwise fail every parse of the file, silently
289 // dropping its usage instead of costing the documented cold re-parse.
290 if (
291 typeof entry.o !== "number" ||
292 !Number.isSafeInteger(entry.o) ||
293 entry.o < 0 ||
294 typeof entry.gl !== "number" ||
295 !Number.isSafeInteger(entry.gl) ||
296 entry.gl < 0 ||
297 entry.gl > GUARD_LENGTH ||
298 entry.gl > entry.o ||
299 typeof entry.gh !== "number" ||
300 !Number.isFinite(entry.gh)
301 ) {
302 continue;
303 }
304 // Keep history for deleted rollouts, but re-parse incompatible reducer state.
305 // v9 repairs skipped initial Codex requests; clean v8 entries can still resume.
306 const legacy =
307 format.state !== undefined &&
308 (version < 6 ||
309 (entry.p === "codex" && (version < 8 || (version < 9 && malformedRecords > 0))));
310 // A corrupt state disqualifies the entry: resuming with it would attach
311 // appended usage to the wrong model or replay fork-copied history.
312 if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue;
313
314 const provider = entry.p;
315 const records = decodeRecords(entry.r, provider);
316 const tailRecords = decodeRecords(entry.t, provider);
317 if (records === null || tailRecords === null) continue;
318
319 cache.set(path, {
320 size: legacy ? -1 : entry.s,
321 mtimeMs: entry.m,
322 provider,
323 records,
324 tailRecords,
325 malformedRecords,
326 position: legacy
327 ? { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }
328 : {
329 resumeOffset: entry.o,
330 guardLength: entry.gl,
331 guardHash: entry.gh,
332 state: entry.cs,
333 },
334 });
335 }
336
337 return cache;
338}
339
340function makeStateValidators(
341 formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
342): ReadonlyMap<UsageProviderKind, (value: unknown) => boolean> {
343 return new Map(
344 [...formats].map(([provider, format]) => {
345 const isState = format.state === undefined ? undefined : Schema.is(format.state.schema);
346 return [
347 provider,
348 (value: unknown) => value === null || (isState !== undefined && isState(value)),
349 ] as const;
350 }),
351 );
352}
353
354export function pruneScanCache(cache: ScanCache, retentionCutoffMs: number): number {
355 let removed = 0;
356 for (const [path, entry] of cache) {
357 if (entry.mtimeMs < retentionCutoffMs) {
358 cache.delete(path);
359 removed += 1;
360 }
361 }
362 return removed;
363}
364
365/** Mutates seen; share it across incremental line/tail batches to deduplicate the whole file. */
366export function dedupeWithinFile(
367 records: readonly UsageRecord[],
368 seen: Set<string> = new Set(),
369): readonly UsageRecord[] {
370 const kept: UsageRecord[] = [];
371 for (const record of records) {
372 if (record.dedupeKey !== null) {
373 if (seen.has(record.dedupeKey)) continue;
374 seen.add(record.dedupeKey);
375 }
376 kept.push(record);
377 }
378 return kept;
379}