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

usageScanCache.ts

384 lines13.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 { mergeUsageCopies } from "./usageAggregation.ts";
11import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts";
12​
13const USAGE_SCAN_CACHE_VERSION = 16 as const;
14const SPEED_COMPATIBLE_SINCE_VERSION = 4;
15​
16/**
17 * An older server sharing that directory cannot read a newer cache and would
18 * replace it, dropping saved usage for deleted transcripts. Separate files keep
19 * the newer one; older files are removed once it is saved.
20 */
21export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v16.json";
22export const LEGACY_SCAN_CACHE_FILE_NAMES = [
23 "usage-scan-cache-v15.json",
24 "usage-scan-cache-v14.json",
25 "usage-scan-cache-v13.json",
26 "usage-scan-cache-v12.json",
27 "usage-scan-cache-v11.json",
28 "usage-scan-cache-v10.json",
29 "usage-scan-cache-v9.json",
30 "usage-scan-cache-v8.json",
31 "usage-scan-cache-v7.json",
32 "usage-scan-cache-v6.json",
33 "usage-scan-cache-v5.json",
34 "usage-scan-cache.json",
35] as const;
36​
37const SPEEDS: readonly UsageSpeed[] = ["standard", "fast", "ultrafast"];
38​
39export interface CachedFile {
40 readonly size: number;
41 readonly mtimeMs: number;
42 readonly provider: UsageProviderKind;
43 readonly records: readonly UsageRecord[];
44 /** Unterminated tail records stay separate because incremental parsing rereads them. */
45 readonly tailRecords: readonly UsageRecord[];
46 /** Whole-file count, including diagnostics from the tentative tail. */
47 readonly malformedRecords: number;
48 readonly position: TranscriptParsePosition;
50​
51export type ScanCache = Map<string, CachedFile>;
52​
53type SerializedRecord = readonly [
54 timestampMs: number,
55 modelIndex: number,
56 sessionIndex: number,
57 uncachedInputTokens: number,
58 cachedInputTokens: number,
59 cacheCreationTokens: number,
60 outputTokens: number,
61 reasoningTokens: number,
62 dedupeKey: string | null,
63 reportedCostUsd: number | null,
64 speed: number,
65 rateModelIndex?: number | null,
66 unresolvedServiceTierTurnId?: string | null,
67 cacheCreation1hTokens?: number,
68];
69​
70interface SerializedFile {
71 readonly s: number;
72 readonly m: number;
73 readonly p: UsageProviderKind;
74 readonly r: readonly SerializedRecord[];
75 readonly t: readonly SerializedRecord[];
76 readonly mr: number;
77 readonly o: number;
78 readonly gl: number;
79 readonly gh: number;
80 readonly cs: unknown;
82​
83interface SerializedCache {
84 readonly version: number;
85 readonly models: readonly string[];
86 readonly sessions: readonly string[];
87 readonly files: Readonly<Record<string, SerializedFile>>;
89​
90interface InternTables {
91 readonly models: string[];
92 readonly sessions: string[];
93 readonly modelIndex: Map<string, number>;
94 readonly sessionIndex: Map<string, number>;
96​
97function makeInternTables(): InternTables {
98 return { models: [], sessions: [], modelIndex: new Map(), sessionIndex: new Map() };
100​
101function intern(table: string[], index: Map<string, number>, value: string): number {
102 const existing = index.get(value);
103 if (existing !== undefined) return existing;
104 const next = table.length;
105 table.push(value);
106 index.set(value, next);
107 return next;
109​
110function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile {
111 const serializeRecord = (record: UsageRecord): SerializedRecord => [
112 record.timestampMs,
113 intern(tables.models, tables.modelIndex, record.model),
114 intern(tables.sessions, tables.sessionIndex, record.sessionId),
115 record.totals.uncachedInputTokens,
116 record.totals.cachedInputTokens,
117 record.totals.cacheCreationTokens,
118 record.totals.outputTokens,
119 record.totals.reasoningTokens,
120 record.dedupeKey,
121 record.reportedCostUsd,
122 SPEEDS.indexOf(record.speed),
123 record.rateModel === undefined
124 ? null
125 : intern(tables.models, tables.modelIndex, record.rateModel),
126 ...(record.cacheCreation1hTokens !== undefined
127 ? ([record.unresolvedServiceTierTurnId ?? null, record.cacheCreation1hTokens] as const)
128 : record.unresolvedServiceTierTurnId !== undefined
129 ? ([record.unresolvedServiceTierTurnId] as const)
130 : ([] as const)),
131 ];
132 return {
133 s: entry.size,
134 m: entry.mtimeMs,
135 p: entry.provider,
136 r: entry.records.map(serializeRecord),
137 t: entry.tailRecords.map(serializeRecord),
138 mr: entry.malformedRecords,
139 o: entry.position.resumeOffset,
140 gl: entry.position.guardLength,
141 gh: entry.position.guardHash,
142 cs: entry.position.state,
143 };
145​
146/** Yields the document in pieces so large caches never become one string; growing intern tables preserve indexes, retaining unused strings until restart. */
147export function makeScanCacheWriter(): (
148 cache: ScanCache,
149 extra: Readonly<Record<string, unknown>>,
150) => Iterable<string> {
151 const tables = makeInternTables();
152 function* encode(entries: readonly (readonly [string, CachedFile])[], extra: object) {
153 yield '{"files":{';
154 for (const [index, [path, entry]] of entries.entries()) {
155 yield `${index === 0 ? "" : ","}${JSON.stringify(path)}:${JSON.stringify(serializeFile(entry, tables))}`;
156 }
157 // Encoded after the files, which may have added to the intern tables.
158 const tail = JSON.stringify({
159 ...extra,
160 version: USAGE_SCAN_CACHE_VERSION,
161 models: tables.models,
162 sessions: tables.sessions,
163 });
164 yield `},${tail.slice(1)}`;
165 }
166 // Snapshot now: the encoding runs later, while the file is written.
167 return (cache, extra) => encode([...cache], extra);
169​
170function isRecordArray(value: unknown): value is readonly unknown[] {
171 return Array.isArray(value);
173​
174export function decodeScanCache(
175 document: unknown,
176 formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
177): ScanCache {
178 const cache: ScanCache = new Map();
179 const isValidState = makeStateValidators(formats);
180 if (typeof document !== "object" || document === null) return cache;
181​
182 const root = document as Partial<SerializedCache>;
183 const version = root.version;
184 if (
185 typeof version !== "number" ||
186 version < SPEED_COMPATIBLE_SINCE_VERSION ||
187 version > USAGE_SCAN_CACHE_VERSION
188 ) {
189 return cache;
190 }
191 if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
192 if (typeof root.files !== "object" || root.files === null) return cache;
193​
194 if (!root.models.every((value) => typeof value === "string")) return cache;
195 if (!root.sessions.every((value) => typeof value === "string")) return cache;
196 const models = root.models as readonly string[];
197 const sessions = root.sessions as readonly string[];
198​
199 // Reject entire corrupt entries; partial survivors would appear warm and hide usage until the file changes.
200 const decodeRecords = (
201 rows: readonly unknown[],
202 provider: UsageProviderKind,
203 ): UsageRecord[] | null => {
204 const records: UsageRecord[] = [];
205 for (const row of rows) {
206 if (!isRecordArray(row) || row.length < 11) return null;
207 const [
208 timestampMs,
209 modelIndex,
210 sessionIndex,
211 uncached,
212 cached,
213 cacheCreation,
214 output,
215 reasoning,
216 dedupeKey,
217 reportedCostUsd,
218 speedIndex,
219 rateModelIndex,
220 unresolvedServiceTierTurnId,
221 cacheCreation1h = 0,
222 ] = row as SerializedRecord;
223 const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined;
224​
225 const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
226 const rateModel = typeof rateModelIndex === "number" ? models[rateModelIndex] : undefined;
227 if (
228 typeof timestampMs !== "number" ||
229 !Number.isFinite(timestampMs) ||
230 model === undefined ||
231 (unresolvedServiceTierTurnId != null && typeof unresolvedServiceTierTurnId !== "string") ||
232 !Number.isFinite(cacheCreation1h) ||
233 (rateModelIndex != null && rateModel === undefined) ||
234 !Number.isFinite(uncached) ||
235 !Number.isFinite(cached) ||
236 !Number.isFinite(cacheCreation) ||
237 !Number.isFinite(output) ||
238 !Number.isFinite(reasoning) ||
239 speed === undefined
240 ) {
241 return null;
242 }
243​
244 // Unchanged and deleted transcripts may only exist in the cache, so the
245 // parser cannot remove their previously saved local placeholders.
246 if (provider === "claude" && model === CLAUDE_SYNTHETIC_MODEL) continue;
247​
248 records.push({
249 provider,
250 timestampMs,
251 model,
252 ...(rateModel === undefined ? {} : { rateModel }),
253 sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "",
254 totals: {
255 uncachedInputTokens: uncached,
256 cachedInputTokens: cached,
257 cacheCreationTokens: cacheCreation,
258 outputTokens: output,
259 reasoningTokens: reasoning,
260 },
261 ...(cacheCreation1h > 0 ? { cacheCreation1hTokens: cacheCreation1h } : {}),
262 reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
263 speed,
264 ...(version >= 7 && unresolvedServiceTierTurnId != null
265 ? { unresolvedServiceTierTurnId }
266 : {}),
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 // Keep history for deleted rollouts, but re-parse incompatible reducer state.
302 // v13 adds Claude 1-hour cache writes; v14 uses Codex request ledgers.
303 // v15 repairs skipped Codex requests whose counters rewound; clean v14 entries stay served.
304 const legacy =
305 (entry.p === "claude" && version < 13) ||
306 (format.state !== undefined &&
307 (version < 6 ||
308 (entry.p === "codex" && (version < 14 || (version < 15 && malformedRecords > 0)))));
309 // A corrupt state disqualifies the entry: resuming with it would attach
310 // appended usage to the wrong model or replay fork-copied history.
311 if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue;
312 // Before v16 a Codex baseline can lack the time of its latest move, or carry an older one,
313 // and that time keeps a re-emitted older snapshot from billing twice. A grown file re-parses
314 // whole instead of resuming.
315 const resumable = !legacy && !(entry.p === "codex" && version < 16);
316​
317 const provider = entry.p;
318 const records = decodeRecords(entry.r, provider);
319 const tailRecords = decodeRecords(entry.t, provider);
320 if (records === null || tailRecords === null) continue;
321​
322 cache.set(path, {
323 size: legacy ? -1 : entry.s,
324 mtimeMs: entry.m,
325 provider,
326 records,
327 tailRecords,
328 malformedRecords,
329 position: resumable
330 ? {
331 resumeOffset: entry.o,
332 guardLength: entry.gl,
333 guardHash: entry.gh,
334 state: entry.cs,
335 }
336 : { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null },
337 });
338 }
339​
340 return cache;
342​
343function makeStateValidators(
344 formats: ReadonlyMap<UsageProviderKind, TranscriptUsageFormat<unknown>>,
345): ReadonlyMap<UsageProviderKind, (value: unknown) => boolean> {
346 return new Map(
347 [...formats].map(([provider, format]) => {
348 const isState = format.state === undefined ? undefined : Schema.is(format.state.schema);
349 return [
350 provider,
351 (value: unknown) => value === null || (isState !== undefined && isState(value)),
352 ] as const;
353 }),
354 );
356​
357export function pruneScanCache(cache: ScanCache, retentionCutoffMs: number): number {
358 let removed = 0;
359 for (const [path, entry] of cache) {
360 if (entry.mtimeMs < retentionCutoffMs) {
361 cache.delete(path);
362 removed += 1;
363 }
364 }
365 return removed;
367​
368/** Pass only newline-terminated records: an unterminated tail can still change, so the aggregator merges it per scan. */
369export function dedupeWithinFile(records: readonly UsageRecord[]): readonly UsageRecord[] {
370 const kept: UsageRecord[] = [];
371 const firstIndex = new Map<string, number>();
372 for (const record of records) {
373 if (record.dedupeKey !== null) {
374 const index = firstIndex.get(record.dedupeKey);
375 if (index !== undefined) {
376 kept[index] = mergeUsageCopies(kept[index]!, record);
377 continue;
378 }
379 firstIndex.set(record.dedupeKey, kept.length);
380 }
381 kept.push(record);
382 }
383 return kept;