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