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 = 7 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-v7.json";
21export const LEGACY_SCAN_CACHE_FILE_NAMES = [
22 "usage-scan-cache-v6.json",
23 "usage-scan-cache-v5.json",
24 "usage-scan-cache.json",
25] as const;
26
27const SPEEDS: readonly UsageSpeed[] = ["standard", "fast", "ultrafast"];
28
29export interface CachedFile {
30 readonly size: number;
31 readonly mtimeMs: number;
32 readonly provider: UsageProviderKind;
33 readonly records: readonly UsageRecord[];
34 /**
35 * Records from a trailing segment the writer had not newline-terminated at
36 * parse time. Kept apart from `records` because an incremental parse
37 * re-reads that segment and would otherwise double count it.
38 */
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
137export function encodeScanCache(cache: ScanCache): SerializedCache {
138 const tables = makeInternTables();
139 const files: Record<string, SerializedFile> = {};
140 for (const [path, entry] of cache) files[path] = serializeFile(entry, tables);
141 return {
142 version: USAGE_SCAN_CACHE_VERSION,
143 models: tables.models,
144 sessions: tables.sessions,
145 files,
146 };
147}
148
149/**
150 * Entries are replaced, never mutated, when their file changes, so an entry's JSON is memoised by
151 * identity. The intern tables only grow, so a memoised entry's indexes stay valid; a pruned entry
152 * can leave an unused string behind until the next process start.
153 */
154export function makeScanCacheWriter(): (
155 cache: ScanCache,
156 extra: Readonly<Record<string, unknown>>,
157) => string {
158 const tables = makeInternTables();
159 const fragments = new WeakMap<CachedFile, string>();
160 return (cache, extra) => {
161 const files: string[] = [];
162 for (const [path, entry] of cache) {
163 let fragment = fragments.get(entry);
164 if (fragment === undefined) {
165 fragment = JSON.stringify(serializeFile(entry, tables));
166 fragments.set(entry, fragment);
167 }
168 files.push(`${JSON.stringify(path)}:${fragment}`);
169 }
170 // Encoded after the files, which may have added to the intern tables.
171 const head = JSON.stringify({
172 ...extra,
173 version: USAGE_SCAN_CACHE_VERSION,
174 models: tables.models,
175 sessions: tables.sessions,
176 });
177 return `${head.slice(0, -1)},"files":{${files.join(",")}}}`;
178 };
179}
180
181function isRecordArray(value: unknown): value is readonly unknown[] {
182 return Array.isArray(value);
183}
184
185export function decodeScanCache(
186 document: unknown,
187 formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
188): ScanCache {
189 const cache: ScanCache = new Map();
190 const isValidState = makeStateValidators(formats);
191 if (typeof document !== "object" || document === null) return cache;
192
193 const root = document as Partial<SerializedCache>;
194 const version = root.version;
195 if (
196 typeof version !== "number" ||
197 version < SPEED_COMPATIBLE_SINCE_VERSION ||
198 version > USAGE_SCAN_CACHE_VERSION
199 ) {
200 return cache;
201 }
202 if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
203 if (typeof root.files !== "object" || root.files === null) return cache;
204
205 if (!root.models.every((value) => typeof value === "string")) return cache;
206 if (!root.sessions.every((value) => typeof value === "string")) return cache;
207 const models = root.models as readonly string[];
208 const sessions = root.sessions as readonly string[];
209
210 // Any corrupt row disqualifies the whole entry. Keeping the survivors
211 // under the original (size, mtime) would read as a valid warm hit and the
212 // file would never be re-parsed, silently losing the dropped rows' usage.
213 const decodeRecords = (
214 rows: readonly unknown[],
215 provider: UsageProviderKind,
216 ): UsageRecord[] | null => {
217 const records: UsageRecord[] = [];
218 for (const row of rows) {
219 if (!isRecordArray(row) || row.length < 11) return null;
220 const [
221 timestampMs,
222 modelIndex,
223 sessionIndex,
224 uncached,
225 cached,
226 cacheCreation,
227 output,
228 reasoning,
229 dedupeKey,
230 reportedCostUsd,
231 speedIndex,
232 rateModelIndex,
233 unresolvedServiceTierTurnId,
234 ] = row as SerializedRecord;
235 const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined;
236
237 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
238 const rateModel = typeof rateModelIndex === "number" ? models[rateModelIndex] : undefined;
239 if (
240 typeof timestampMs !== "number" ||
241 !Number.isFinite(timestampMs) ||
242 model === undefined ||
243 (unresolvedServiceTierTurnId !== undefined &&
244 typeof unresolvedServiceTierTurnId !== "string") ||
245 (rateModelIndex != null && rateModel === undefined) ||
246 !Number.isFinite(uncached) ||
247 !Number.isFinite(cached) ||
248 !Number.isFinite(cacheCreation) ||
249 !Number.isFinite(output) ||
250 !Number.isFinite(reasoning) ||
251 speed === undefined
252 ) {
253 return null;
254 }
255
256 // Unchanged and deleted transcripts may only exist in the cache, so the
257 // parser cannot remove their previously saved local placeholders.
258 if (provider === "claude" && model === CLAUDE_SYNTHETIC_MODEL) continue;
259
260 records.push({
261 provider,
262 timestampMs,
263 model,
264 ...(rateModel === undefined ? {} : { rateModel }),
265 sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "",
266 totals: {
267 uncachedInputTokens: uncached,
268 cachedInputTokens: cached,
269 cacheCreationTokens: cacheCreation,
270 outputTokens: output,
271 reasoningTokens: reasoning,
272 },
273 reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
274 speed,
275 ...(version >= 7 && unresolvedServiceTierTurnId !== undefined
276 ? { unresolvedServiceTierTurnId }
277 : {}),
278 dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
279 });
280 }
281 return records;
282 };
283
284 for (const [path, raw] of Object.entries(root.files)) {
285 if (typeof raw !== "object" || raw === null) continue;
286 const entry = raw as Partial<SerializedFile>;
287 if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
288 if (entry.p === undefined) continue;
289 const format = formats.get(entry.p);
290 if (format === undefined) continue;
291 if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
292 const malformedRecords = entry.mr === undefined ? 0 : entry.mr;
293 if (!Number.isSafeInteger(malformedRecords) || malformedRecords < 0) continue;
294 // Position fields feed byte offsets and a Buffer allocation in the reader,
295 // so anything outside their real ranges must reject the entry: a bogus
296 // guard length would otherwise fail every parse of the file, silently
297 // dropping its usage instead of costing the documented cold re-parse.
298 if (
299 typeof entry.o !== "number" ||
300 !Number.isSafeInteger(entry.o) ||
301 entry.o < 0 ||
302 typeof entry.gl !== "number" ||
303 !Number.isSafeInteger(entry.gl) ||
304 entry.gl < 0 ||
305 entry.gl > GUARD_LENGTH ||
306 entry.gl > entry.o ||
307 typeof entry.gh !== "number" ||
308 !Number.isFinite(entry.gh)
309 ) {
310 continue;
311 }
312 // Keep history for deleted rollouts, but re-parse incompatible reducer state.
313 // Only Codex requires new provenance state in v7.
314 const legacy =
315 format.state !== undefined && (version < 6 || (entry.p === "codex" && version < 7));
316 // A corrupt state disqualifies the entry: resuming with it would attach
317 // appended usage to the wrong model or replay fork-copied history.
318 if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue;
319
320 const provider = entry.p;
321 const records = decodeRecords(entry.r, provider);
322 const tailRecords = decodeRecords(entry.t, provider);
323 if (records === null || tailRecords === null) continue;
324
325 cache.set(path, {
326 size: legacy ? -1 : entry.s,
327 mtimeMs: entry.m,
328 provider,
329 records,
330 tailRecords,
331 malformedRecords,
332 position: legacy
333 ? { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }
334 : {
335 resumeOffset: entry.o,
336 guardLength: entry.gl,
337 guardHash: entry.gh,
338 state: entry.cs,
339 },
340 });
341 }
342
343 return cache;
344}
345
346function makeStateValidators(
347 formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
348): ReadonlyMap<UsageProviderKind, (value: unknown) => boolean> {
349 return new Map(
350 [...formats].map(([provider, format]) => {
351 const isState = format.state === undefined ? undefined : Schema.is(format.state.schema);
352 return [
353 provider,
354 (value: unknown) => value === null || (isState !== undefined && isState(value)),
355 ] as const;
356 }),
357 );
358}
359
360export function pruneScanCache(cache: ScanCache, retentionCutoffMs: number): number {
361 let removed = 0;
362 for (const [path, entry] of cache) {
363 if (entry.mtimeMs < retentionCutoffMs) {
364 cache.delete(path);
365 removed += 1;
366 }
367 }
368 return removed;
369}
370
371/**
372 * Callers stitching an incremental parse together pass one `seen` set across the line and tail
373 * record batches so the whole file stays deduplicated as a unit; the set is mutated in place.
374 */
375export function dedupeWithinFile(
376 records: readonly UsageRecord[],
377 seen: Set<string> = new Set(),
378): readonly UsageRecord[] {
379 const kept: UsageRecord[] = [];
380 for (const record of records) {
381 if (record.dedupeKey !== null) {
382 if (seen.has(record.dedupeKey)) continue;
383 seen.add(record.dedupeKey);
384 }
385 kept.push(record);
386 }
387 return kept;
388}