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

+179 -24
View File
@@ -4,16 +4,19 @@
*
* Isolated here so the rest of the usage code stays on Effect's `FileSystem`.
* The direct `node:fs` streaming is deliberate: a cold 30-day window is ~1.4 GB
* across ~1,500 files, and `readline` over a read stream is roughly an order of
* across ~1,500 files, and buffer-level streaming is roughly an order of
* magnitude cheaper than materialising each file. The equivalent Effect stream
* pipeline is idiomatic but not fast enough to sit behind a page load.
*
* Transcripts are append-only, so a parse also reports the byte position it
* stopped at. A later scan of the same file resumes from that position and
* parses only the appended bytes, which is what keeps a warm scan cheap while a
* session is actively writing a multi-hundred-megabyte rollout.
*
* @module usageTranscriptReader
*/
import * as NodeFS from "node:fs";
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
import * as NodeReadline from "node:readline";
import type { UsageProviderKind } from "@t3tools/contracts";
@@ -23,6 +26,7 @@ import {
parseClaudeLine,
parseCodexLine,
parseGrokLine,
type CodexScanState,
type UsageRecord,
} from "./usageTranscripts.ts";
@@ -32,6 +36,56 @@ export interface TranscriptFile {
readonly mtimeMs: number;
}
/**
* Where a parse stopped, with enough state to continue from there.
*
* The guard hash fingerprints the bytes immediately before `resumeOffset`. A
* resume only proceeds when those bytes still match: transcripts are
* append-only by design, but a rotated or rewritten file silently mis-parsed
* from the middle would corrupt usage totals. The window is a cheap tripwire
* for those realistic failure shapes, all of which disturb the file's tail at
* that exact offset; it deliberately does not hash the whole prefix, which
* would cost the full re-read the resume exists to avoid.
*/
export interface TranscriptParsePosition {
/** Byte offset just past the last newline-terminated line consumed. */
readonly resumeOffset: number;
/** Length of the fingerprinted window ending at `resumeOffset`. */
readonly guardLength: number;
/** FNV-1a hash of that window. */
readonly guardHash: number;
/** Codex reducer state as of `resumeOffset`; `null` for stateless providers. */
readonly codexState: CodexScanState | null;
}
export interface TranscriptParseResult {
/** Records from newline-terminated lines at or after the parse start. */
readonly records: readonly UsageRecord[];
/**
* Records from a trailing segment the writer has not newline-terminated yet.
* Kept out of `records` because `position` deliberately excludes that
* segment: the next scan re-reads it once the writer finishes the line.
*/
readonly tailRecords: readonly UsageRecord[];
readonly position: TranscriptParsePosition;
/** Whether the parse continued from `resumeFrom` rather than byte 0. */
readonly resumed: boolean;
}
/** 64 bytes of JSONL tail is ample to distinguish a replaced file. */
export const GUARD_LENGTH = 64;
const NEWLINE = 0x0a;
const CARRIAGE_RETURN = 0x0d;
function fnv1a(buffer: Buffer): number {
let hash = 0x811c9dc5;
for (let index = 0; index < buffer.length; index += 1) {
hash ^= buffer[index]!;
hash = Math.imul(hash, 0x01000193);
}
return hash >>> 0;
}
/**
* Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`.
*
@@ -100,6 +154,25 @@ export async function readDirectoryVolumeId(path: string): Promise<string> {
}
}
async function guardMatches(
handle: NodeFSP.FileHandle,
position: TranscriptParsePosition,
): Promise<boolean> {
if (position.guardLength <= 0 || position.guardLength > GUARD_LENGTH) return false;
try {
const window = Buffer.alloc(position.guardLength);
const { bytesRead } = await handle.read(
window,
0,
position.guardLength,
position.resumeOffset - position.guardLength,
);
return bytesRead === position.guardLength && fnv1a(window) === position.guardHash;
} catch {
return false;
}
}
/**
* Streams one transcript and returns the usage records it contains, or `null`
* when the file could not be read.
@@ -109,6 +182,10 @@ export async function readDirectoryVolumeId(path: string): Promise<string> {
* under the same `(size, mtime)` key would silently drop that file's usage
* until the file next changes.
*
* With `resumeFrom`, parsing continues from that position when its guard bytes
* still match, so only appended lines are read; otherwise the whole file is
* re-parsed from the start and `resumed` reports `false`.
*
* Codex carries the active model on `turn_context` lines that hold no usage of
* their own, so those still have to pass through the reducer to keep model
* attribution correct.
@@ -116,43 +193,121 @@ export async function readDirectoryVolumeId(path: string): Promise<string> {
export async function readTranscriptRecords(
filePath: string,
provider: UsageProviderKind,
): Promise<readonly UsageRecord[] | null> {
const records: UsageRecord[] = [];
const codexState = initialCodexScanState();
resumeFrom?: TranscriptParsePosition,
): Promise<TranscriptParseResult | null> {
let handle: NodeFSP.FileHandle;
try {
handle = await NodeFSP.open(filePath, "r");
} catch {
return null;
}
try {
const lines = NodeReadline.createInterface({
input: NodeFS.createReadStream(filePath, { encoding: "utf8" }),
crlfDelay: Infinity,
});
let codexState = initialCodexScanState();
let resumed = false;
let start = 0;
if (
resumeFrom !== undefined &&
resumeFrom.resumeOffset > 0 &&
(provider !== "codex" || resumeFrom.codexState !== null) &&
(await guardMatches(handle, resumeFrom))
) {
if (resumeFrom.codexState !== null) codexState = { ...resumeFrom.codexState };
start = resumeFrom.resumeOffset;
resumed = true;
}
for await (const line of lines) {
const parseLine = (line: string, state: CodexScanState, out: UsageRecord[]): void => {
if (provider === "codex") {
if (
!mightCarryUsage(line, provider) &&
!line.includes('"turn_context"') &&
!line.includes('"session_meta"')
) {
continue;
return;
}
const record = parseCodexLine(line, codexState);
if (record !== null) records.push(record);
continue;
const record = parseCodexLine(line, state);
if (record !== null) out.push(record);
return;
}
if (!mightCarryUsage(line, provider)) return;
if (provider === "grok") {
if (!mightCarryUsage(line, provider)) continue;
for (const grokRecord of parseGrokLine(line)) records.push(grokRecord);
for (const grokRecord of parseGrokLine(line)) out.push(grokRecord);
return;
}
const record = parseClaudeLine(line);
if (record !== null) out.push(record);
};
const toLineString = (lineBuffer: Buffer): string => {
const content =
lineBuffer.length > 0 && lineBuffer[lineBuffer.length - 1] === CARRIAGE_RETURN
? lineBuffer.subarray(0, -1)
: lineBuffer;
return content.toString("utf8");
};
const records: UsageRecord[] = [];
// Buffer-level line splitting rather than `readline`, because resuming
// needs byte-exact offsets and decoded strings cannot provide them.
// Newline-free chunks are collected rather than concatenated as they
// arrive, so a single huge line costs one copy instead of one per chunk.
let resumeOffset = start;
let pendingChunks: Buffer[] = [];
const stream = handle.createReadStream({
start,
autoClose: false,
}) as AsyncIterable<Buffer>;
for await (const chunk of stream) {
if (!chunk.includes(NEWLINE)) {
pendingChunks.push(chunk);
continue;
}
if (!mightCarryUsage(line, provider)) continue;
const record = parseClaudeLine(line);
if (record !== null) records.push(record);
const buffer: Buffer =
pendingChunks.length === 0 ? chunk : Buffer.concat([...pendingChunks, chunk]);
pendingChunks = [];
let lineStart = 0;
for (;;) {
const newlineIndex = buffer.indexOf(NEWLINE, lineStart);
if (newlineIndex === -1) break;
parseLine(toLineString(buffer.subarray(lineStart, newlineIndex)), codexState, records);
lineStart = newlineIndex + 1;
}
resumeOffset += lineStart;
if (lineStart < buffer.length) pendingChunks.push(buffer.subarray(lineStart));
}
// A trailing segment without its newline is parsed for this result but not
// consumed: a writer may still be appending to it, and counting a half
// record now and its full form later would double count.
const tailRecords: UsageRecord[] = [];
if (pendingChunks.length > 0) {
const pending = pendingChunks.length === 1 ? pendingChunks[0]! : Buffer.concat(pendingChunks);
if (pending.length > 0) parseLine(toLineString(pending), { ...codexState }, tailRecords);
}
const guardLength = Math.min(GUARD_LENGTH, resumeOffset);
let guardHash = 0;
if (guardLength > 0) {
const window = Buffer.alloc(guardLength);
await handle.read(window, 0, guardLength, resumeOffset - guardLength);
guardHash = fnv1a(window);
}
return {
records,
tailRecords,
position: {
resumeOffset,
guardLength,
guardHash,
codexState: provider === "codex" ? codexState : null,
},
resumed,
};
} catch {
return null;
} finally {
await handle.close().catch(() => undefined);
}
return records;
}