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

usageScanCache.ts

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