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 { mergeUsageCopies } from "./usageAggregation.ts";
11import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts";
12
13const USAGE_SCAN_CACHE_VERSION = 18 as const;
14const SPEED_COMPATIBLE_SINCE_VERSION = 4;
15
16/**
17 * An older server sharing that directory cannot read a newer cache and would
18 * replace it, dropping saved usage for deleted transcripts. Separate files keep
19 * the newer one; older files are removed once it is saved.
20 */
21export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v18.json";
22export const LEGACY_SCAN_CACHE_FILE_NAMES = [
23 "usage-scan-cache-v17.json",
24 "usage-scan-cache-v16.json",
25 "usage-scan-cache-v15.json",
26 "usage-scan-cache-v14.json",
27 "usage-scan-cache-v13.json",
28 "usage-scan-cache-v12.json",
29 "usage-scan-cache-v11.json",
30 "usage-scan-cache-v10.json",
31 "usage-scan-cache-v9.json",
32 "usage-scan-cache-v8.json",
33 "usage-scan-cache-v7.json",
34 "usage-scan-cache-v6.json",
35 "usage-scan-cache-v5.json",
36 "usage-scan-cache.json",
37] as const;
38
39const SPEEDS: readonly UsageSpeed[] = ["standard", "fast", "ultrafast"];
40
41export interface CachedFile {
42 readonly size: number;
43 readonly mtimeMs: number;
44 readonly provider: UsageProviderKind;
45 readonly records: readonly UsageRecord[];
46 /** Unterminated tail records stay separate because incremental parsing rereads them. */
47 readonly tailRecords: readonly UsageRecord[];
48 /** Whole-file timestamps, including diagnostics from the tentative tail. */
49 readonly malformedRecords: readonly number[];
50 readonly position: TranscriptParsePosition;
51}
52
53export type ScanCache = Map<string, CachedFile>;
54
55type SerializedRecord = readonly [
56 timestampMs: number,
57 modelIndex: number,
58 sessionIndex: number,
59 uncachedInputTokens: number,
60 cachedInputTokens: number,
61 cacheCreationTokens: number,
62 outputTokens: number,
63 reasoningTokens: number,
64 dedupeKey: string | null,
65 reportedCostUsd: number | null,
66 speed: number,
67 rateModelIndex?: number | null,
68 unresolvedServiceTierTurnId?: string | null,
69 cacheCreation1hTokens?: number,
70 modelCalls?: number,
71];
72
73interface SerializedFile {
74 readonly s: number;
75 readonly m: number;
76 readonly p: UsageProviderKind;
77 readonly r: readonly SerializedRecord[];
78 readonly t: readonly SerializedRecord[];
79 readonly mr: number;
80 readonly mt?: readonly number[];
81 readonly fi?: string;
82 readonly o: number;
83 readonly gl: number;
84 readonly gh: number;
85 readonly cs: unknown;
86}
87
88interface SerializedCache {
89 readonly version: number;
90 readonly models: readonly string[];
91 readonly sessions: readonly string[];
92 readonly files: Readonly<Record<string, SerializedFile>>;
93}
94
95interface InternTables {
96 readonly models: string[];
97 readonly sessions: string[];
98 readonly modelIndex: Map<string, number>;
99 readonly sessionIndex: Map<string, number>;
100}
101
102function makeInternTables(): InternTables {
103 return { models: [], sessions: [], modelIndex: new Map(), sessionIndex: new Map() };
104}
105
106function intern(table: string[], index: Map<string, number>, value: string): number {
107 const existing = index.get(value);
108 if (existing !== undefined) return existing;
109 const next = table.length;
110 table.push(value);
111 index.set(value, next);
112 return next;
113}
114
115function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile {
116 const serializeRecord = (record: UsageRecord): SerializedRecord => [
117 record.timestampMs,
118 intern(tables.models, tables.modelIndex, record.model),
119 intern(tables.sessions, tables.sessionIndex, record.sessionId),
120 record.totals.uncachedInputTokens,
121 record.totals.cachedInputTokens,
122 record.totals.cacheCreationTokens,
123 record.totals.outputTokens,
124 record.totals.reasoningTokens,
125 record.dedupeKey,
126 record.reportedCostUsd,
127 SPEEDS.indexOf(record.speed),
128 record.rateModel === undefined
129 ? null
130 : intern(tables.models, tables.modelIndex, record.rateModel),
131 ...(record.modelCalls !== undefined && record.modelCalls > 1
132 ? ([
133 record.unresolvedServiceTierTurnId ?? null,
134 record.cacheCreation1hTokens ?? 0,
135 record.modelCalls,
136 ] as const)
137 : record.cacheCreation1hTokens !== undefined
138 ? ([record.unresolvedServiceTierTurnId ?? null, record.cacheCreation1hTokens] as const)
139 : record.unresolvedServiceTierTurnId !== undefined
140 ? ([record.unresolvedServiceTierTurnId] as const)
141 : ([] as const)),
142 ];
143 return {
144 s: entry.size,
145 m: entry.mtimeMs,
146 p: entry.provider,
147 r: entry.records.map(serializeRecord),
148 t: entry.tailRecords.map(serializeRecord),
149 mr: entry.malformedRecords.length,
150 ...(entry.malformedRecords.length === 0 ? {} : { mt: entry.malformedRecords }),
151 ...(entry.position.fileId === undefined ? {} : { fi: entry.position.fileId }),
152 o: entry.position.resumeOffset,
153 gl: entry.position.guardLength,
154 gh: entry.position.guardHash,
155 cs: entry.position.state,
156 };
157}
158
159/** Yields the document in pieces so large caches never become one string; growing intern tables preserve indexes, retaining unused strings until restart. */
160export function makeScanCacheWriter(): (
161 cache: ScanCache,
162 extra: Readonly<Record<string, unknown>>,
163) => Iterable<string> {
164 const tables = makeInternTables();
165 function* encode(entries: readonly (readonly [string, CachedFile])[], extra: object) {
166 yield '{"files":{';
167 for (const [index, [path, entry]] of entries.entries()) {
168 yield `${index === 0 ? "" : ","}${JSON.stringify(path)}:${JSON.stringify(serializeFile(entry, tables))}`;
169 }
170 // Encoded after the files, which may have added to the intern tables.
171 const tail = JSON.stringify({
172 ...extra,
173 version: USAGE_SCAN_CACHE_VERSION,
174 models: tables.models,
175 sessions: tables.sessions,
176 });
177 yield `},${tail.slice(1)}`;
178 }
179 // Snapshot now: the encoding runs later, while the file is written.
180 return (cache, extra) => encode([...cache], extra);
181}
182
183function isRecordArray(value: unknown): value is readonly unknown[] {
184 return Array.isArray(value);
185}
186
187export function decodeScanCache(
188 document: unknown,
189 formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
190): ScanCache {
191 const cache: ScanCache = new Map();
192 const isValidState = makeStateValidators(formats);
193 if (typeof document !== "object" || document === null) return cache;
194
195 const root = document as Partial<SerializedCache>;
196 const version = root.version;
197 if (
198 typeof version !== "number" ||
199 version < SPEED_COMPATIBLE_SINCE_VERSION ||
200 version > USAGE_SCAN_CACHE_VERSION
201 ) {
202 return cache;
203 }
204 if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
205 if (typeof root.files !== "object" || root.files === null) return cache;
206
207 if (!root.models.every((value) => typeof value === "string")) return cache;
208 if (!root.sessions.every((value) => typeof value === "string")) return cache;
209 const models = root.models as readonly string[];
210 const sessions = root.sessions as readonly string[];
211
212 // Reject entire corrupt entries; partial survivors would appear warm and hide usage until the file changes.
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 cacheCreation1h = 0,
235 modelCalls = 1,
236 ] = row as SerializedRecord;
237 const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined;
238
239 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
240 const rateModel = typeof rateModelIndex === "number" ? models[rateModelIndex] : undefined;
241 if (
242 typeof timestampMs !== "number" ||
243 !Number.isFinite(timestampMs) ||
244 model === undefined ||
245 (unresolvedServiceTierTurnId != null && typeof unresolvedServiceTierTurnId !== "string") ||
246 !Number.isFinite(cacheCreation1h) ||
247 typeof modelCalls !== "number" ||
248 !Number.isFinite(modelCalls) ||
249 modelCalls < 0 ||
250 (rateModelIndex != null && rateModel === undefined) ||
251 !Number.isFinite(uncached) ||
252 !Number.isFinite(cached) ||
253 !Number.isFinite(cacheCreation) ||
254 !Number.isFinite(output) ||
255 !Number.isFinite(reasoning) ||
256 speed === undefined
257 ) {
258 return null;
259 }
260
261 // Unchanged and deleted transcripts may only exist in the cache, so the
262 // parser cannot remove their previously saved local placeholders.
263 if (provider === "claude" && model === CLAUDE_SYNTHETIC_MODEL) continue;
264
265 const calls = Math.trunc(modelCalls);
266 records.push({
267 provider,
268 timestampMs,
269 model,
270 ...(rateModel === undefined ? {} : { rateModel }),
271 sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "",
272 totals: {
273 uncachedInputTokens: uncached,
274 cachedInputTokens: cached,
275 cacheCreationTokens: cacheCreation,
276 outputTokens: output,
277 reasoningTokens: reasoning,
278 },
279 ...(cacheCreation1h > 0 ? { cacheCreation1hTokens: cacheCreation1h } : {}),
280 reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
281 speed,
282 ...(calls > 1 ? { modelCalls: calls } : {}),
283 ...(version >= 7 && unresolvedServiceTierTurnId != null
284 ? { unresolvedServiceTierTurnId }
285 : {}),
286 dedupeKey:
287 typeof dedupeKey !== "string"
288 ? null
289 : // Saved copies of moved transcripts must still match the re-parsed v17 key.
290 provider === "grok" &&
291 version < 17 &&
292 dedupeKey.endsWith(`:${model}`) &&
293 !dedupeKey.endsWith(`:${timestampMs}:${model}`)
294 ? `${dedupeKey.slice(0, -model.length)}${timestampMs}:${model}`
295 : dedupeKey,
296 });
297 }
298 return records;
299 };
300
301 for (const [path, raw] of Object.entries(root.files)) {
302 if (typeof raw !== "object" || raw === null) continue;
303 const entry = raw as Partial<SerializedFile>;
304 if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
305 if (entry.p === undefined) continue;
306 const format = formats.get(entry.p);
307 if (format === undefined) continue;
308 if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
309 const malformedCount = entry.mr === undefined ? 0 : entry.mr;
310 if (!Number.isSafeInteger(malformedCount) || malformedCount < 0) continue;
311 const malformedRecords = entry.mt ?? (malformedCount === 0 ? [] : undefined);
312 if (
313 malformedRecords !== undefined &&
314 (!Array.isArray(malformedRecords) ||
315 malformedRecords.length !== malformedCount ||
316 !malformedRecords.every(Number.isFinite))
317 )
318 continue;
319 // A count saved without dates cannot be limited to a window, so the file re-parses whole.
320 const undated = malformedRecords === undefined;
321 // Position fields feed byte offsets and a Buffer allocation in the reader,
322 // so anything outside their real ranges must reject the entry: a bogus
323 // guard length would otherwise fail every parse of the file, silently
324 // dropping its usage instead of costing the documented cold re-parse.
325 if (
326 typeof entry.o !== "number" ||
327 !Number.isSafeInteger(entry.o) ||
328 entry.o < 0 ||
329 typeof entry.gl !== "number" ||
330 !Number.isSafeInteger(entry.gl) ||
331 entry.gl < 0 ||
332 entry.gl > GUARD_LENGTH ||
333 entry.gl > entry.o ||
334 typeof entry.gh !== "number" ||
335 !Number.isFinite(entry.gh)
336 ) {
337 continue;
338 }
339 // Keep history for deleted rollouts, but re-parse incompatible reducer state:
340 // v13 1h cache writes, v14 Codex ledgers, v15 rewound Codex counters,
341 // v17 time-keyed Grok turns, v18 Grok modelCalls for per-call context tiers.
342 const legacy =
343 (entry.p === "claude" && version < 13) ||
344 (entry.p === "grok" && version < 18) ||
345 (format.state !== undefined &&
346 (version < 6 ||
347 (entry.p === "codex" && (version < 14 || (version < 15 && malformedCount > 0)))));
348 // A corrupt state disqualifies the entry: resuming with it would attach
349 // appended usage to the wrong model or replay fork-copied history.
350 if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue;
351 // Before v16 a Codex baseline can lack the time of its latest move, or carry an older one,
352 // and that time keeps a re-emitted older snapshot from billing twice. A grown file re-parses
353 // whole instead of resuming.
354 const resumable = !legacy && !undated && !(entry.p === "codex" && version < 16);
355
356 const provider = entry.p;
357 const records = decodeRecords(entry.r, provider);
358 const tailRecords = decodeRecords(entry.t, provider);
359 if (records === null || tailRecords === null) continue;
360
361 cache.set(path, {
362 size: legacy || undated ? -1 : entry.s,
363 mtimeMs: entry.m,
364 provider,
365 records,
366 tailRecords,
367 malformedRecords: malformedRecords ?? [],
368 position: resumable
369 ? {
370 ...(typeof entry.fi === "string" ? { fileId: entry.fi } : {}),
371 resumeOffset: entry.o,
372 guardLength: entry.gl,
373 guardHash: entry.gh,
374 state: entry.cs,
375 }
376 : { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null },
377 });
378 }
379
380 return cache;
381}
382
383function makeStateValidators(
384 formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
385): ReadonlyMap<UsageProviderKind, (value: unknown) => boolean> {
386 return new Map(
387 [...formats].map(([provider, format]) => {
388 const isState = format.state === undefined ? undefined : Schema.is(format.state.schema);
389 return [
390 provider,
391 (value: unknown) => value === null || (isState !== undefined && isState(value)),
392 ] as const;
393 }),
394 );
395}
396
397export function pruneScanCache(cache: ScanCache, retentionCutoffMs: number): number {
398 let removed = 0;
399 for (const [path, entry] of cache) {
400 if (entry.mtimeMs < retentionCutoffMs) {
401 cache.delete(path);
402 removed += 1;
403 }
404 }
405 return removed;
406}
407
408/** Pass only newline-terminated records: an unterminated tail can still change, so the aggregator merges it per scan. */
409export function dedupeWithinFile(records: readonly UsageRecord[]): readonly UsageRecord[] {
410 const kept: UsageRecord[] = [];
411 const firstIndex = new Map<string, number>();
412 for (const record of records) {
413 if (record.dedupeKey !== null) {
414 const index = firstIndex.get(record.dedupeKey);
415 if (index !== undefined) {
416 kept[index] = mergeUsageCopies(kept[index]!, record);
417 continue;
418 }
419 firstIndex.set(record.dedupeKey, kept.length);
420 }
421 kept.push(record);
422 }
423 return kept;
424}