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

usageScanCache.ts

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