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

usageScanCache.ts

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