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

usageScanCache.ts

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