perf(server): scan only appended transcript bytes for usage summaries (#9024)

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-09-01 02:59:16 -07:00
1 parent 0bfb6df34b
commit 8f1ef8b9eb
6 files changed
+964 -91

No files matched your search

+138 -38
View File
@@ -19,17 +19,28 @@ import * as NodePath from "node:path";
import type { UsageProviderKind } from "@t3tools/contracts";
import type { UsageRecord } from "./usageTranscripts.ts";
import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts";
import type { CodexScanState, UsageRecord } from "./usageTranscripts.ts";
// v2: Codex fork-copy suppression changed what a file parses to, so v1
// entries would keep serving double-counted records forever.
export const USAGE_SCAN_CACHE_VERSION = 2 as const;
// v3: entries carry the parse position and reducer state so a grown file
// re-parses only its appended bytes instead of starting over.
export const USAGE_SCAN_CACHE_VERSION = 3 as const;
export interface CachedFile {
readonly size: number;
readonly mtimeMs: number;
readonly provider: UsageProviderKind;
/** Records from newline-terminated lines, up to `position.resumeOffset`. */
readonly records: readonly UsageRecord[];
/**
* Records from a trailing segment the writer had not newline-terminated at
* parse time. Kept apart from `records` because an incremental parse
* re-reads that segment and would otherwise double count it.
*/
readonly tailRecords: readonly UsageRecord[];
readonly position: TranscriptParsePosition;
}
export type ScanCache = Map<string, CachedFile>;
@@ -57,6 +68,14 @@ interface SerializedFile {
readonly m: number;
readonly p: UsageProviderKind;
readonly r: readonly SerializedRecord[];
/** Tail records; see `CachedFile.tailRecords`. */
readonly t: readonly SerializedRecord[];
/** Parse position: resume offset, guard length, guard hash. */
readonly o: number;
readonly gl: number;
readonly gh: number;
/** Codex reducer state at `o`; `null` for stateless providers. */
readonly cs: CodexScanState | null;
}
interface SerializedCache {
@@ -82,24 +101,31 @@ export function encodeScanCache(cache: ScanCache): SerializedCache {
return next;
};
const serializeRecord = (record: UsageRecord): SerializedRecord => [
record.timestampMs,
intern(models, modelIndex, record.model),
intern(sessions, sessionIndex, record.sessionId),
record.totals.uncachedInputTokens,
record.totals.cachedInputTokens,
record.totals.cacheCreationTokens,
record.totals.outputTokens,
record.totals.reasoningTokens,
record.dedupeKey,
record.reportedCostUsd,
];
const files: Record<string, SerializedFile> = {};
for (const [path, entry] of cache) {
files[path] = {
s: entry.size,
m: entry.mtimeMs,
p: entry.provider,
r: entry.records.map((record) => [
record.timestampMs,
intern(models, modelIndex, record.model),
intern(sessions, sessionIndex, record.sessionId),
record.totals.uncachedInputTokens,
record.totals.cachedInputTokens,
record.totals.cacheCreationTokens,
record.totals.outputTokens,
record.totals.reasoningTokens,
record.dedupeKey,
record.reportedCostUsd,
]),
r: entry.records.map(serializeRecord),
t: entry.tailRecords.map(serializeRecord),
o: entry.position.resumeOffset,
gl: entry.position.guardLength,
gh: entry.position.guardHash,
cs: entry.position.codexState,
};
}
@@ -133,24 +159,16 @@ export function decodeScanCache(document: unknown): ScanCache {
const models = root.models as readonly string[];
const sessions = root.sessions as readonly string[];
for (const [path, raw] of Object.entries(root.files)) {
if (typeof raw !== "object" || raw === null) continue;
const entry = raw as Partial<SerializedFile>;
if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
if (entry.p !== "claude" && entry.p !== "codex" && entry.p !== "grok") continue;
if (!isRecordArray(entry.r)) continue;
const provider: UsageProviderKind = entry.p;
// Any corrupt row disqualifies the whole entry. Keeping the survivors
// under the original (size, mtime) would read as a valid warm hit and the
// file would never be re-parsed, silently losing the dropped rows' usage.
const decodeRecords = (
rows: readonly unknown[],
provider: UsageProviderKind,
): UsageRecord[] | null => {
const records: UsageRecord[] = [];
// Any corrupt row disqualifies the whole entry. Keeping the survivors
// under the original (size, mtime) would read as a valid warm hit and the
// file would never be re-parsed, silently losing the dropped rows' usage.
let corrupt = false;
for (const row of entry.r) {
if (!isRecordArray(row) || row.length < 10) {
corrupt = true;
break;
}
for (const row of rows) {
if (!isRecordArray(row) || row.length < 10) return null;
const [
timestampMs,
modelIndex,
@@ -175,8 +193,7 @@ export function decodeScanCache(document: unknown): ScanCache {
!Number.isFinite(output) ||
!Number.isFinite(reasoning)
) {
corrupt = true;
break;
return null;
}
records.push({
@@ -195,14 +212,89 @@ export function decodeScanCache(document: unknown): ScanCache {
dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
});
}
return records;
};
if (corrupt) continue;
cache.set(path, { size: entry.s, mtimeMs: entry.m, provider, records });
for (const [path, raw] of Object.entries(root.files)) {
if (typeof raw !== "object" || raw === null) continue;
const entry = raw as Partial<SerializedFile>;
if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
if (entry.p !== "claude" && entry.p !== "codex" && entry.p !== "grok") continue;
if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
// Position fields feed byte offsets and a Buffer allocation in the reader,
// so anything outside their real ranges must reject the entry: a bogus
// guard length would otherwise fail every parse of the file, silently
// dropping its usage instead of costing the documented cold re-parse.
if (
typeof entry.o !== "number" ||
!Number.isSafeInteger(entry.o) ||
entry.o < 0 ||
typeof entry.gl !== "number" ||
!Number.isSafeInteger(entry.gl) ||
entry.gl < 0 ||
entry.gl > GUARD_LENGTH ||
entry.gl > entry.o ||
typeof entry.gh !== "number" ||
!Number.isFinite(entry.gh)
) {
continue;
}
const codexState = decodeCodexState(entry.cs);
if (codexState === undefined) continue;
const provider: UsageProviderKind = entry.p;
const records = decodeRecords(entry.r, provider);
const tailRecords = decodeRecords(entry.t, provider);
if (records === null || tailRecords === null) continue;
cache.set(path, {
size: entry.s,
mtimeMs: entry.m,
provider,
records,
tailRecords,
position: {
resumeOffset: entry.o,
guardLength: entry.gl,
guardHash: entry.gh,
codexState,
},
});
}
return cache;
}
/**
* Validates a persisted Codex reducer state. Returns `undefined` for a corrupt
* value, which disqualifies the entry: resuming with a bad state would attach
* appended usage to the wrong model or replay fork-copied history.
*/
function decodeCodexState(value: unknown): CodexScanState | null | undefined {
if (value === null) return null;
if (typeof value !== "object") return undefined;
const state = value as Partial<CodexScanState>;
if (
typeof state.model !== "string" ||
typeof state.sessionId !== "string" ||
(state.lastUsageSignature !== null && typeof state.lastUsageSignature !== "string") ||
typeof state.sawSessionMeta !== "boolean" ||
typeof state.suppressingForkCopies !== "boolean" ||
typeof state.forkCopyAnchorMs !== "number" ||
!Number.isFinite(state.forkCopyAnchorMs)
) {
return undefined;
}
return {
model: state.model,
sessionId: state.sessionId,
lastUsageSignature: state.lastUsageSignature ?? null,
sawSessionMeta: state.sawSessionMeta,
suppressingForkCopies: state.suppressingForkCopies,
forkCopyAnchorMs: state.forkCopyAnchorMs,
};
}
export interface PruneOptions {
/** Files the walk just saw. Only meaningful inside the walked window. */
readonly livePaths: ReadonlySet<string>;
@@ -251,9 +343,17 @@ export function pruneScanCache(cache: ScanCache, options: PruneOptions): number
return removed;
}
/** Within-file de-duplication, applied before an entry is cached. */
export function dedupeWithinFile(records: readonly UsageRecord[]): readonly UsageRecord[] {
const seen = new Set<string>();
/**
* Within-file de-duplication, applied before an entry is cached.
*
* Callers stitching an incremental parse together pass one `seen` set across
* the line and tail record batches so the whole file stays deduplicated as a
* unit; the set is mutated in place.
*/
export function dedupeWithinFile(
records: readonly UsageRecord[],
seen: Set<string> = new Set(),
): readonly UsageRecord[] {
const kept: UsageRecord[] = [];
for (const record of records) {
if (record.dedupeKey !== null) {