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

usageScanCache.ts

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