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

usageScanCache.ts

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