Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usageScanCache.ts

374 lines12.6 KB

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