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

usageScanCache.ts

370 lines12.3 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 = 10 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-v10.json";
21export const LEGACY_SCAN_CACHE_FILE_NAMES = [
22 "usage-scan-cache-v9.json",
23 "usage-scan-cache-v8.json",
24 "usage-scan-cache-v7.json",
25 "usage-scan-cache-v6.json",
26 "usage-scan-cache-v5.json",
27 "usage-scan-cache.json",
28] as const;
29​
30const SPEEDS: readonly UsageSpeed[] = ["standard", "fast", "ultrafast"];
31​
32export interface CachedFile {
33 readonly size: number;
34 readonly mtimeMs: number;
35 readonly provider: UsageProviderKind;
36 readonly records: readonly UsageRecord[];
37 /** Unterminated tail records stay separate because incremental parsing rereads them. */
38 readonly tailRecords: readonly UsageRecord[];
39 /** Whole-file count, including diagnostics from the tentative tail. */
40 readonly malformedRecords: number;
41 readonly position: TranscriptParsePosition;
43​
44export type ScanCache = Map<string, CachedFile>;
45​
46type SerializedRecord = readonly [
47 timestampMs: number,
48 modelIndex: number,
49 sessionIndex: number,
50 uncachedInputTokens: number,
51 cachedInputTokens: number,
52 cacheCreationTokens: number,
53 outputTokens: number,
54 reasoningTokens: number,
55 dedupeKey: string | null,
56 reportedCostUsd: number | null,
57 speed: number,
58 rateModelIndex?: number | null,
59 unresolvedServiceTierTurnId?: string,
60];
61​
62interface SerializedFile {
63 readonly s: number;
64 readonly m: number;
65 readonly p: UsageProviderKind;
66 readonly r: readonly SerializedRecord[];
67 readonly t: readonly SerializedRecord[];
68 readonly mr: number;
69 readonly o: number;
70 readonly gl: number;
71 readonly gh: number;
72 readonly cs: unknown;
74​
75interface SerializedCache {
76 readonly version: number;
77 readonly models: readonly string[];
78 readonly sessions: readonly string[];
79 readonly files: Readonly<Record<string, SerializedFile>>;
81​
82interface InternTables {
83 readonly models: string[];
84 readonly sessions: string[];
85 readonly modelIndex: Map<string, number>;
86 readonly sessionIndex: Map<string, number>;
88​
89function makeInternTables(): InternTables {
90 return { models: [], sessions: [], modelIndex: new Map(), sessionIndex: new Map() };
92​
93function intern(table: string[], index: Map<string, number>, value: string): number {
94 const existing = index.get(value);
95 if (existing !== undefined) return existing;
96 const next = table.length;
97 table.push(value);
98 index.set(value, next);
99 return next;
101​
102function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile {
103 const serializeRecord = (record: UsageRecord): SerializedRecord => [
104 record.timestampMs,
105 intern(tables.models, tables.modelIndex, record.model),
106 intern(tables.sessions, tables.sessionIndex, record.sessionId),
107 record.totals.uncachedInputTokens,
108 record.totals.cachedInputTokens,
109 record.totals.cacheCreationTokens,
110 record.totals.outputTokens,
111 record.totals.reasoningTokens,
112 record.dedupeKey,
113 record.reportedCostUsd,
114 SPEEDS.indexOf(record.speed),
115 record.rateModel === undefined
116 ? null
117 : intern(tables.models, tables.modelIndex, record.rateModel),
118 ...(record.unresolvedServiceTierTurnId === undefined
119 ? ([] as const)
120 : ([record.unresolvedServiceTierTurnId] as const)),
121 ];
122 return {
123 s: entry.size,
124 m: entry.mtimeMs,
125 p: entry.provider,
126 r: entry.records.map(serializeRecord),
127 t: entry.tailRecords.map(serializeRecord),
128 mr: entry.malformedRecords,
129 o: entry.position.resumeOffset,
130 gl: entry.position.guardLength,
131 gh: entry.position.guardHash,
132 cs: entry.position.state,
133 };
135​
136/** Memoizes immutable entries by identity; growing intern tables preserve indexes, retaining unused strings until restart. */
137export function makeScanCacheWriter(): (
138 cache: ScanCache,
139 extra: Readonly<Record<string, unknown>>,
140) => string {
141 const tables = makeInternTables();
142 const fragments = new WeakMap<CachedFile, string>();
143 return (cache, extra) => {
144 const files: string[] = [];
145 for (const [path, entry] of cache) {
146 let fragment = fragments.get(entry);
147 if (fragment === undefined) {
148 fragment = JSON.stringify(serializeFile(entry, tables));
149 fragments.set(entry, fragment);
150 }
151 files.push(`${JSON.stringify(path)}:${fragment}`);
152 }
153 // Encoded after the files, which may have added to the intern tables.
154 const head = JSON.stringify({
155 ...extra,
156 version: USAGE_SCAN_CACHE_VERSION,
157 models: tables.models,
158 sessions: tables.sessions,
159 });
160 return `${head.slice(0, -1)},"files":{${files.join(",")}}}`;
161 };
163​
164function isRecordArray(value: unknown): value is readonly unknown[] {
165 return Array.isArray(value);
167​
168export function decodeScanCache(
169 document: unknown,
170 formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
171): ScanCache {
172 const cache: ScanCache = new Map();
173 const isValidState = makeStateValidators(formats);
174 if (typeof document !== "object" || document === null) return cache;
175​
176 const root = document as Partial<SerializedCache>;
177 const version = root.version;
178 if (
179 typeof version !== "number" ||
180 version < SPEED_COMPATIBLE_SINCE_VERSION ||
181 version > USAGE_SCAN_CACHE_VERSION
182 ) {
183 return cache;
184 }
185 if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
186 if (typeof root.files !== "object" || root.files === null) return cache;
187​
188 if (!root.models.every((value) => typeof value === "string")) return cache;
189 if (!root.sessions.every((value) => typeof value === "string")) return cache;
190 const models = root.models as readonly string[];
191 const sessions = root.sessions as readonly string[];
192​
193 // Reject entire corrupt entries; partial survivors would appear warm and hide usage until the file changes.
194 const decodeRecords = (
195 rows: readonly unknown[],
196 provider: UsageProviderKind,
197 ): UsageRecord[] | null => {
198 const records: UsageRecord[] = [];
199 for (const row of rows) {
200 if (!isRecordArray(row) || row.length < 11) return null;
201 const [
202 timestampMs,
203 modelIndex,
204 sessionIndex,
205 uncached,
206 cached,
207 cacheCreation,
208 output,
209 reasoning,
210 dedupeKey,
211 reportedCostUsd,
212 speedIndex,
213 rateModelIndex,
214 unresolvedServiceTierTurnId,
215 ] = row as SerializedRecord;
216 const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined;
217​
218 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
219 const rateModel = typeof rateModelIndex === "number" ? models[rateModelIndex] : undefined;
220 if (
221 typeof timestampMs !== "number" ||
222 !Number.isFinite(timestampMs) ||
223 model === undefined ||
224 (unresolvedServiceTierTurnId !== undefined &&
225 typeof unresolvedServiceTierTurnId !== "string") ||
226 (rateModelIndex != null && rateModel === undefined) ||
227 !Number.isFinite(uncached) ||
228 !Number.isFinite(cached) ||
229 !Number.isFinite(cacheCreation) ||
230 !Number.isFinite(output) ||
231 !Number.isFinite(reasoning) ||
232 speed === undefined
233 ) {
234 return null;
235 }
236​
237 // Unchanged and deleted transcripts may only exist in the cache, so the
238 // parser cannot remove their previously saved local placeholders.
239 if (provider === "claude" && model === CLAUDE_SYNTHETIC_MODEL) continue;
240​
241 records.push({
242 provider,
243 timestampMs,
244 model,
245 ...(rateModel === undefined ? {} : { rateModel }),
246 sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "",
247 totals: {
248 uncachedInputTokens: uncached,
249 cachedInputTokens: cached,
250 cacheCreationTokens: cacheCreation,
251 outputTokens: output,
252 reasoningTokens: reasoning,
253 },
254 reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
255 speed,
256 ...(version >= 7 && unresolvedServiceTierTurnId !== undefined
257 ? { unresolvedServiceTierTurnId }
258 : {}),
259 dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
260 });
261 }
262 return records;
263 };
264​
265 for (const [path, raw] of Object.entries(root.files)) {
266 if (typeof raw !== "object" || raw === null) continue;
267 const entry = raw as Partial<SerializedFile>;
268 if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
269 if (entry.p === undefined) continue;
270 const format = formats.get(entry.p);
271 if (format === undefined) continue;
272 if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
273 const malformedRecords = entry.mr === undefined ? 0 : entry.mr;
274 if (!Number.isSafeInteger(malformedRecords) || malformedRecords < 0) continue;
275 // Position fields feed byte offsets and a Buffer allocation in the reader,
276 // so anything outside their real ranges must reject the entry: a bogus
277 // guard length would otherwise fail every parse of the file, silently
278 // dropping its usage instead of costing the documented cold re-parse.
279 if (
280 typeof entry.o !== "number" ||
281 !Number.isSafeInteger(entry.o) ||
282 entry.o < 0 ||
283 typeof entry.gl !== "number" ||
284 !Number.isSafeInteger(entry.gl) ||
285 entry.gl < 0 ||
286 entry.gl > GUARD_LENGTH ||
287 entry.gl > entry.o ||
288 typeof entry.gh !== "number" ||
289 !Number.isFinite(entry.gh)
290 ) {
291 continue;
292 }
293 // Keep history for deleted rollouts, but re-parse incompatible reducer state.
294 // v9 repairs skipped initial Codex requests; clean v8 entries can still resume.
295 // v10 adds Claude advisor calls, which no older Claude entry holds.
296 const legacy =
297 (entry.p === "claude" && version < 10) ||
298 (format.state !== undefined &&
299 (version < 6 ||
300 (entry.p === "codex" && (version < 8 || (version < 9 && malformedRecords > 0)))));
301 // A corrupt state disqualifies the entry: resuming with it would attach
302 // appended usage to the wrong model or replay fork-copied history.
303 if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue;
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: legacy
318 ? { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }
319 : {
320 resumeOffset: entry.o,
321 guardLength: entry.gl,
322 guardHash: entry.gh,
323 state: entry.cs,
324 },
325 });
326 }
327​
328 return cache;
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 );
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;
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;