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
135/** Memoizes immutable entries by identity; growing intern tables preserve indexes, retaining unused strings until restart. */
136export function makeScanCacheWriter(): (
137 cache: ScanCache,
138 extra: Readonly<Record<string, unknown>>,
139) => string {
140 const tables = makeInternTables();
141 const fragments = new WeakMap<CachedFile, string>();
142 return (cache, extra) => {
143 const files: string[] = [];
144 for (const [path, entry] of cache) {
145 let fragment = fragments.get(entry);
146 if (fragment === undefined) {
147 fragment = JSON.stringify(serializeFile(entry, tables));
148 fragments.set(entry, fragment);
149 }
150 files.push(`${JSON.stringify(path)}:${fragment}`);
151 }
152 // Encoded after the files, which may have added to the intern tables.
153 const head = JSON.stringify({
154 ...extra,
155 version: USAGE_SCAN_CACHE_VERSION,
156 models: tables.models,
157 sessions: tables.sessions,
158 });
159 return `${head.slice(0, -1)},"files":{${files.join(",")}}}`;
160 };
161}
162
163function isRecordArray(value: unknown): value is readonly unknown[] {
164 return Array.isArray(value);
165}
166
167export function decodeScanCache(
168 document: unknown,
169 formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
170): ScanCache {
171 const cache: ScanCache = new Map();
172 const isValidState = makeStateValidators(formats);
173 if (typeof document !== "object" || document === null) return cache;
174
175 const root = document as Partial<SerializedCache>;
176 const version = root.version;
177 if (
178 typeof version !== "number" ||
179 version < SPEED_COMPATIBLE_SINCE_VERSION ||
180 version > USAGE_SCAN_CACHE_VERSION
181 ) {
182 return cache;
183 }
184 if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
185 if (typeof root.files !== "object" || root.files === null) return cache;
186
187 if (!root.models.every((value) => typeof value === "string")) return cache;
188 if (!root.sessions.every((value) => typeof value === "string")) return cache;
189 const models = root.models as readonly string[];
190 const sessions = root.sessions as readonly string[];
191
192 // Reject entire corrupt entries; partial survivors would appear warm and hide usage until the file changes.
193 const decodeRecords = (
194 rows: readonly unknown[],
195 provider: UsageProviderKind,
196 ): UsageRecord[] | null => {
197 const records: UsageRecord[] = [];
198 for (const row of rows) {
199 if (!isRecordArray(row) || row.length < 11) return null;
200 const [
201 timestampMs,
202 modelIndex,
203 sessionIndex,
204 uncached,
205 cached,
206 cacheCreation,
207 output,
208 reasoning,
209 dedupeKey,
210 reportedCostUsd,
211 speedIndex,
212 rateModelIndex,
213 unresolvedServiceTierTurnId,
214 ] = row as SerializedRecord;
215 const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined;
216
217 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
218 const rateModel = typeof rateModelIndex === "number" ? models[rateModelIndex] : undefined;
219 if (
220 typeof timestampMs !== "number" ||
221 !Number.isFinite(timestampMs) ||
222 model === undefined ||
223 (unresolvedServiceTierTurnId !== undefined &&
224 typeof unresolvedServiceTierTurnId !== "string") ||
225 (rateModelIndex != null && rateModel === undefined) ||
226 !Number.isFinite(uncached) ||
227 !Number.isFinite(cached) ||
228 !Number.isFinite(cacheCreation) ||
229 !Number.isFinite(output) ||
230 !Number.isFinite(reasoning) ||
231 speed === undefined
232 ) {
233 return null;
234 }
235
236 // Unchanged and deleted transcripts may only exist in the cache, so the
237 // parser cannot remove their previously saved local placeholders.
238 if (provider === "claude" && model === CLAUDE_SYNTHETIC_MODEL) continue;
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 ...(version >= 7 && unresolvedServiceTierTurnId !== undefined
256 ? { unresolvedServiceTierTurnId }
257 : {}),
258 dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
259 });
260 }
261 return records;
262 };
263
264 for (const [path, raw] of Object.entries(root.files)) {
265 if (typeof raw !== "object" || raw === null) continue;
266 const entry = raw as Partial<SerializedFile>;
267 if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
268 if (entry.p === undefined) continue;
269 const format = formats.get(entry.p);
270 if (format === undefined) continue;
271 if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
272 const malformedRecords = entry.mr === undefined ? 0 : entry.mr;
273 if (!Number.isSafeInteger(malformedRecords) || malformedRecords < 0) continue;
274 // Position fields feed byte offsets and a Buffer allocation in the reader,
275 // so anything outside their real ranges must reject the entry: a bogus
276 // guard length would otherwise fail every parse of the file, silently
277 // dropping its usage instead of costing the documented cold re-parse.
278 if (
279 typeof entry.o !== "number" ||
280 !Number.isSafeInteger(entry.o) ||
281 entry.o < 0 ||
282 typeof entry.gl !== "number" ||
283 !Number.isSafeInteger(entry.gl) ||
284 entry.gl < 0 ||
285 entry.gl > GUARD_LENGTH ||
286 entry.gl > entry.o ||
287 typeof entry.gh !== "number" ||
288 !Number.isFinite(entry.gh)
289 ) {
290 continue;
291 }
292 // Keep history for deleted rollouts, but re-parse incompatible reducer state.
293 // v9 repairs skipped initial Codex requests; clean v8 entries can still resume.
294 const legacy =
295 format.state !== undefined &&
296 (version < 6 ||
297 (entry.p === "codex" && (version < 8 || (version < 9 && malformedRecords > 0))));
298 // A corrupt state disqualifies the entry: resuming with it would attach
299 // appended usage to the wrong model or replay fork-copied history.
300 if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue;
301
302 const provider = entry.p;
303 const records = decodeRecords(entry.r, provider);
304 const tailRecords = decodeRecords(entry.t, provider);
305 if (records === null || tailRecords === null) continue;
306
307 cache.set(path, {
308 size: legacy ? -1 : entry.s,
309 mtimeMs: entry.m,
310 provider,
311 records,
312 tailRecords,
313 malformedRecords,
314 position: legacy
315 ? { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }
316 : {
317 resumeOffset: entry.o,
318 guardLength: entry.gl,
319 guardHash: entry.gh,
320 state: entry.cs,
321 },
322 });
323 }
324
325 return cache;
326}
327
328function makeStateValidators(
329 formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
330): ReadonlyMap<UsageProviderKind, (value: unknown) => boolean> {
331 return new Map(
332 [...formats].map(([provider, format]) => {
333 const isState = format.state === undefined ? undefined : Schema.is(format.state.schema);
334 return [
335 provider,
336 (value: unknown) => value === null || (isState !== undefined && isState(value)),
337 ] as const;
338 }),
339 );
340}
341
342export function pruneScanCache(cache: ScanCache, retentionCutoffMs: number): number {
343 let removed = 0;
344 for (const [path, entry] of cache) {
345 if (entry.mtimeMs < retentionCutoffMs) {
346 cache.delete(path);
347 removed += 1;
348 }
349 }
350 return removed;
351}
352
353/** Mutates seen; share it across incremental line/tail batches to deduplicate the whole file. */
354export function dedupeWithinFile(
355 records: readonly UsageRecord[],
356 seen: Set<string> = new Set(),
357): readonly UsageRecord[] {
358 const kept: UsageRecord[] = [];
359 for (const record of records) {
360 if (record.dedupeKey !== null) {
361 if (seen.has(record.dedupeKey)) continue;
362 seen.add(record.dedupeKey);
363 }
364 kept.push(record);
365 }
366 return kept;
367}