Skip to content
TypeScript

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

Wout Stiens8f1ef8b9eb72
diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts
new file mode 100644
index 00000000000..8fc86ee3d46
--- /dev/null
+++ b/apps/server/src/usage/UsageService.test.ts
@@ -0,0 +1,226 @@
+// @effect-diagnostics nodeBuiltinImport:off - the suite seeds and grows real
+// transcript trees on disk, outside the service's Effect FileSystem.
+import * as NodeFSP from "node:fs/promises";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+
+import { assert, describe, it } from "@effect/vitest";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
+import { UsageDay, type UsageSummaryInput } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
+import * as Fiber from "effect/Fiber";
+import * as Layer from "effect/Layer";
+import * as Scheduler from "effect/Scheduler";
+import { HttpClient, HttpClientResponse } from "effect/unstable/http";
+
+import * as ServerConfig from "../config.ts";
+import * as ServerSettings from "../serverSettings.ts";
+import * as UsageService from "./UsageService.ts";
+
+function claudeLine(id: number, outputTokens: number): string {
+ return `${JSON.stringify({
+ type: "assistant",
+ timestamp: "2026-08-01T10:00:00Z",
+ requestId: `req_${id}`,
+ sessionId: "session-1",
+ message: {
+ id: `msg_${id}`,
+ model: "claude-fable-5",
+ usage: { input_tokens: 10, output_tokens: outputTokens },
+ },
+ })}\n`;
+}
+
+const WINDOW: UsageSummaryInput = {
+ timeZone: "UTC",
+ sinceDay: UsageDay.make("2026-07-31"),
+ untilDay: UsageDay.make("2026-08-02"),
+};
+
+const setup = Effect.gen(function* () {
+ const home = yield* Effect.promise(() =>
+ NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "usage-service-test-")),
+ );
+ yield* Effect.addFinalizer(() =>
+ Effect.promise(() => NodeFSP.rm(home, { recursive: true, force: true })),
+ );
+ const transcriptDir = NodePath.join(home, "claude", "projects", "proj");
+ yield* Effect.promise(() => NodeFSP.mkdir(transcriptDir, { recursive: true }));
+ return {
+ home,
+ transcript: NodePath.join(transcriptDir, "session.jsonl"),
+ settings: {
+ providers: {
+ claudeAgent: { homePath: NodePath.join(home, "claude") },
+ codex: { homePath: NodePath.join(home, "codex") },
+ },
+ },
+ };
+});
+
+const serviceLayers = (input: {
+ readonly prefix: string;
+ readonly home: string;
+ readonly settings: Parameters<typeof ServerSettings.layerTest>[0];
+ readonly onRatesFetch?: () => void;
+}) =>
+ ServerConfig.layerTest(process.cwd(), { prefix: input.prefix }).pipe(
+ Layer.provideMerge(NodeServices.layer),
+ Layer.provideMerge(ServerSettings.layerTest(input.settings)),
+ Layer.provideMerge(
+ Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make((request) =>
+ Effect.sync(() => {
+ input.onRatesFetch?.();
+ // Unparsable rates: every scan retries the fetch, which makes the
+ // fetch count a boundary-level observation of how many scans ran.
+ return HttpClientResponse.fromWeb(request, Response.json({}));
+ }),
+ ),
+ ),
+ ),
+ Layer.provideMerge(
+ Layer.succeed(HostProcessEnvironment, { GROK_HOME: NodePath.join(input.home, "grok") }),
+ ),
+ );
+
+function totalOutputTokens(summary: { buckets: readonly { totals: { outputTokens: number } }[] }) {
+ return summary.buckets.reduce((sum, bucket) => sum + bucket.totals.outputTokens, 0);
+}
+
+describe("UsageService", () => {
+ it.live("counts appended usage on a rescan of a grown transcript", () =>
+ Effect.gen(function* () {
+ const { transcript, settings, home } = yield* setup;
+ yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5)));
+
+ const service = yield* UsageService.make.pipe(
+ Effect.provide(serviceLayers({ prefix: "usage-service-grow-test", home, settings })),
+ );
+
+ const first = yield* service.readSummary(WINDOW);
+ assert.strictEqual(totalOutputTokens(first), 5);
+
+ yield* Effect.promise(() => NodeFSP.appendFile(transcript, claudeLine(2, 7)));
+ const second = yield* service.readSummary(WINDOW);
+ assert.strictEqual(totalOutputTokens(second), 12);
+ }).pipe(Effect.scoped),
+ );
+
+ it.live("shares one scan between concurrent identical requests", () =>
+ Effect.gen(function* () {
+ const { transcript, settings, home } = yield* setup;
+ yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5)));
+
+ let ratesFetches = 0;
+ const service = yield* UsageService.make.pipe(
+ Effect.provide(
+ serviceLayers({
+ prefix: "usage-service-flight-test",
+ home,
+ settings,
+ onRatesFetch: () => {
+ ratesFetches += 1;
+ },
+ }),
+ ),
+ );
+
+ const [first, second] = yield* Effect.all(
+ [service.readSummary(WINDOW), service.readSummary(WINDOW)],
+ { concurrency: 2 },
+ );
+ assert.deepStrictEqual(first, second);
+ assert.strictEqual(ratesFetches, 1);
+
+ // A later request is fresh work again, not a stale cached answer.
+ yield* service.readSummary(WINDOW);
+ assert.strictEqual(ratesFetches, 2);
+ }).pipe(Effect.scoped),
+ );
+
+ it.live("does not orphan an in-flight scan when its first caller is interrupted", () =>
+ Effect.gen(function* () {
+ const { settings, home } = yield* setup;
+ const service = yield* UsageService.make.pipe(
+ Effect.provide(
+ serviceLayers({ prefix: "usage-service-interruption-test", home, settings }),
+ ),
+ );
+
+ let orphanedAt: number | undefined;
+ for (let interruptAt = 1; interruptAt <= 31; interruptAt += 1) {
+ const tasks: Array<() => void> = [];
+ const dispatcher: Scheduler.SchedulerDispatcher = {
+ scheduleTask: (task) => tasks.push(task),
+ flush: () => {
+ let task: (() => void) | undefined;
+ while ((task = tasks.shift()) !== undefined) task();
+ },
+ };
+
+ let requestFiber: Fiber.Fiber<unknown, unknown> | undefined;
+ let requestChecks = 0;
+ const scheduler: Scheduler.Scheduler = {
+ executionMode: "async",
+ makeDispatcher: () => dispatcher,
+ shouldYield: (fiber) => {
+ if (fiber !== requestFiber) return false;
+ requestChecks += 1;
+ if (requestChecks !== interruptAt) return false;
+ fiber.interruptUnsafe();
+ return true;
+ },
+ };
+
+ // Each candidate needs a distinct key because the broken case leaves
+ // its entry in the service's private in-flight map. The invalid window
+ // keeps the real scan synchronous once its detached fiber starts.
+ const input: UsageSummaryInput = {
+ ...WINDOW,
+ sinceDay: UsageDay.make("2026-09-01"),
+ untilDay: UsageDay.make(`2026-08-${String(interruptAt).padStart(2, "0")}`),
+ };
+ const first = yield* service
+ .readSummary(input)
+ .pipe(
+ Effect.exit,
+ Effect.provideService(Scheduler.Scheduler, scheduler),
+ Effect.forkChild,
+ );
+ requestFiber = first;
+ yield* Effect.yieldNow;
+ dispatcher.flush();
+
+ const second = yield* service.readSummary(input).pipe(
+ Effect.match({
+ onFailure: (error) => error.reason,
+ onSuccess: () => "success" as const,
+ }),
+ Effect.provideService(Scheduler.Scheduler, scheduler),
+ Effect.forkChild,
+ );
+ yield* Effect.yieldNow;
+ dispatcher.flush();
+ const secondExit = second.pollUnsafe();
+ if (secondExit === undefined) {
+ second.interruptUnsafe();
+ orphanedAt = interruptAt;
+ break;
+ }
+ if (Exit.isFailure(secondExit)) {
+ assert.fail("the matching request fiber was interrupted");
+ }
+ assert.strictEqual(secondExit.value, "invalidWindow");
+ }
+
+ assert.isUndefined(
+ orphanedAt,
+ `interruption left the next matching request pending at scheduler check ${orphanedAt}`,
+ );
+ }).pipe(Effect.scoped),
+ );
+});
diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts
index 224662e9dca..16a7478d954 100644
--- a/apps/server/src/usage/UsageService.ts
+++ b/apps/server/src/usage/UsageService.ts
@@ -7,7 +7,8 @@
*
* Transcripts are append-only, so parsed records are memoised per file by
* `(size, mtime)`. A cold 30-day scan of ~1.4 GB lands around 2-3 seconds; warm
- * scans only reparse files that changed.
+ * scans only reparse files that changed, and a file that merely grew resumes
+ * from its cached parse position so only the appended bytes are read.
*
* @module UsageService
*/
@@ -26,6 +27,7 @@ import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -272,7 +274,14 @@ export const make = Effect.gen(function* () {
);
});
- /** Parses one transcript, reusing the cached result when it is unchanged. */
+ /**
+ * Parses one transcript, reusing the cached result when it is unchanged.
+ *
+ * A file that only grew re-parses from the cached position, so an actively
+ * written multi-hundred-megabyte rollout costs its appended bytes per scan
+ * rather than a full re-read. The reader verifies the position's guard bytes
+ * and silently restarts from byte 0 when they no longer match.
+ */
const readFileRecords = (
filePath: string,
size: number,
@@ -289,23 +298,85 @@ export const make = Effect.gen(function* () {
cached.mtimeMs === mtimeMs &&
cached.provider === provider
) {
- return cached.records;
+ return cached.tailRecords.length === 0
+ ? cached.records
+ : [...cached.records, ...cached.tailRecords];
}
- const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, provider));
+ // Only a strictly grown file may resume. Same size with a new mtime, or
+ // a shrunken file, means rewritten content; re-parse it whole.
+ const resumeFrom =
+ cached !== undefined && cached.provider === provider && size > cached.size
+ ? cached.position
+ : undefined;
+
+ const parsed = yield* Effect.promise(() =>
+ readTranscriptRecords(filePath, provider, resumeFrom),
+ );
// A read failure is not an empty transcript: caching it under this
// (size, mtime) would silently drop the file's usage until it changes.
if (parsed === null) return [];
- // Stored already de-duplicated within the file, which is 99% of all
- // duplicates. The aggregator still runs the cross-file dedupe pass.
- const records = dedupeWithinFile(parsed);
- fileCache.set(filePath, { size, mtimeMs, provider, records });
+ // Stored already de-duplicated within the file, which is 99% of all
+ // duplicates. The aggregator still runs the cross-file dedupe pass. One
+ // seen set spans the cached base, the new lines, and the tail so a
+ // resumed parse dedupes exactly like a full one.
+ const base = parsed.resumed && cached !== undefined ? cached.records : [];
+ const seen = new Set<string>();
+ const records = dedupeWithinFile([...base, ...parsed.records], seen);
+ const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);
+
+ fileCache.set(filePath, {
+ size,
+ mtimeMs,
+ provider,
+ records,
+ tailRecords,
+ position: parsed.position,
+ });
cacheDirty = true;
- return records;
+ return tailRecords.length === 0 ? records : [...records, ...tailRecords];
});
- const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
+ /** One provider directory's walk and parse, before rates are involved. */
+ interface ScannedDir {
+ readonly provider: UsageProviderKind;
+ readonly dir: string;
+ readonly volumeId: string;
+ /** Parsed records per file, or `null` when the directory does not exist. */
+ readonly files:
+ | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
+ | null;
+ }
+
+ const collectDirs = Effect.fn("UsageService.collectDirs")(function* (windowStartMs: number) {
+ // The home resolvers ask for `Path` themselves; satisfy them from the
+ // instance we already hold so the scan stays context-free.
+ const dirs = yield* resolveTranscriptDirs().pipe(Effect.provideService(Path.Path, path));
+ const scanned: ScannedDir[] = [];
+ for (const { provider, dir, fileName } of dirs) {
+ const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
+ const exists = yield* fileSystem
+ .exists(dir)
+ .pipe(Effect.catchCause(() => Effect.succeed(false)));
+ if (!exists) {
+ scanned.push({ provider, dir, volumeId, files: null });
+ continue;
+ }
+ const files = yield* Effect.promise(() =>
+ listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
+ );
+ const parsedFiles: { path: string; records: readonly UsageRecord[] }[] = [];
+ for (const file of files) {
+ const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);
+ parsedFiles.push({ path: file.path, records });
+ }
+ scanned.push({ provider, dir, volumeId, files: parsedFiles });
+ }
+ return scanned;
+ });
+
+ const scanSummary = Effect.fn("UsageService.scanSummary")(function* (input: UsageSummaryInput) {
if (input.sinceDay > input.untilDay) {
return yield* new UsageReadError({
reason: "invalidWindow",
@@ -338,13 +409,9 @@ export const make = Effect.gen(function* () {
}
const startedAtMs = yield* Clock.currentTimeMillis;
- yield* ensureRates();
yield* ensureScanCacheLoaded;
const hostId = NodeOS.hostname();
- // The home resolvers ask for `Path` themselves; satisfy them from the
- // instance we already hold so `readSummary` stays context-free.
- const dirs = yield* resolveTranscriptDirs().pipe(Effect.provideService(Path.Path, path));
const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
if (Option.isNone(windowStart)) {
return yield* new UsageReadError({
@@ -355,6 +422,13 @@ export const make = Effect.gen(function* () {
const windowStartMs =
(hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
+ // Pricing only matters once records are aggregated, so the rate table
+ // loads while transcripts stream instead of gating them: a cold rates
+ // fetch on a slow network no longer delays the scan by its own timeout.
+ const [, scannedDirs] = yield* Effect.all([ensureRates(), collectDirs(windowStartMs)], {
+ concurrency: 2,
+ });
+
const aggregator = new UsageAggregator({
timeZone: input.timeZone,
sinceDay: input.sinceDay,
@@ -368,13 +442,8 @@ export const make = Effect.gen(function* () {
const livePaths = new Set<string>();
const walkedRoots: string[] = [];
- for (const { provider, dir, fileName } of dirs) {
- const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
- const exists = yield* fileSystem
- .exists(dir)
- .pipe(Effect.catchCause(() => Effect.succeed(false)));
-
- if (!exists) {
+ for (const { provider, dir, volumeId, files } of scannedDirs) {
+ if (files === null) {
sources.push({
fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
status: "missing",
@@ -388,9 +457,6 @@ export const make = Effect.gen(function* () {
}
walkedRoots.push(dir);
- const files = yield* Effect.promise(() =>
- listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
- );
let scannedFiles = 0;
let skippedFiles = 0;
// Distinct per directory. Buckets carry per-cell session counts, but a
@@ -399,13 +465,12 @@ export const make = Effect.gen(function* () {
for (const file of files) {
livePaths.add(file.path);
- const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);
- if (records.length === 0) {
+ if (file.records.length === 0) {
skippedFiles += 1;
continue;
}
scannedFiles += 1;
- for (const record of records) {
+ for (const record of file.records) {
// Only sessions that contributed in-window count: the mtime slack
// admits boundary files whose records fall outside the range.
if (aggregator.add(record) && record.sessionId.length > 0) {
@@ -459,6 +524,52 @@ export const make = Effect.gen(function* () {
} satisfies UsageSummary;
});
+ /**
+ * In-flight scans by window, so concurrent identical requests (the usage
+ * page open on two clients at once) share one scan instead of racing over
+ * the same corpus twice.
+ */
+ const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
+
+ const scanKey = (input: UsageSummaryInput): string =>
+ JSON.stringify([
+ input.timeZone,
+ input.sinceDay,
+ input.untilDay,
+ input.resolution ?? "day",
+ input.sinceTime ?? null,
+ input.untilTime ?? null,
+ ]);
+
+ const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
+ const key = scanKey(input);
+ const deferred = yield* Effect.uninterruptible(
+ Effect.gen(function* () {
+ const existing = inflightScans.get(key);
+ if (existing !== undefined) return existing;
+
+ // Enrollment and detached-fiber creation must be atomic. Otherwise a
+ // canceled first caller can leave a Deferred with no scan to finish it.
+ const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
+ inflightScans.set(key, created);
+ // Detached so one departing client cannot tear the scan out from under
+ // the fibers awaiting it; a finished scan warms the cache either way.
+ yield* scanSummary(input).pipe(
+ Effect.onExit((exit) =>
+ Effect.sync(() => inflightScans.delete(key)).pipe(
+ Effect.andThen(Deferred.done(created, exit)),
+ ),
+ ),
+ Effect.forkDetach,
+ );
+ return created;
+ }),
+ );
+ // Waiting stays interruptible. The detached scan continues for other
+ // callers and still warms the cache if this caller leaves.
+ return yield* Deferred.await(deferred);
+ });
+
return { readSummary } as const;
});
diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts
index 8c6faa88a26..fdb0aabafa4 100644
--- a/apps/server/src/usage/usageScanCache.test.ts
+++ b/apps/server/src/usage/usageScanCache.test.ts
@@ -5,6 +5,7 @@ import {
dedupeWithinFile,
encodeScanCache,
pruneScanCache,
+ type CachedFile,
type ScanCache,
} from "./usageScanCache.ts";
import type { UsageRecord } from "./usageTranscripts.ts";
@@ -28,10 +29,27 @@ function record(overrides: Partial<UsageRecord> = {}): UsageRecord {
};
}
+function position(overrides: Partial<CachedFile["position"]> = {}): CachedFile["position"] {
+ return {
+ resumeOffset: 120,
+ guardLength: 64,
+ guardHash: 0xdeadbeef,
+ codexState: null,
+ ...overrides,
+ };
+}
+
function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][]): ScanCache {
const cache: ScanCache = new Map();
for (const [path, mtimeMs, records] of entries) {
- cache.set(path, { size: records.length * 10, mtimeMs, provider: "claude", records });
+ cache.set(path, {
+ size: records.length * 10,
+ mtimeMs,
+ provider: "claude",
+ records,
+ tailRecords: [],
+ position: position(),
+ });
}
return cache;
}
@@ -49,14 +67,67 @@ describe("scan cache round trip", () => {
records: [
record({ provider: "grok", model: "grok-4.5-build", dedupeKey: "s:p:grok-4.5-build" }),
],
+ tailRecords: [record({ provider: "grok", model: "grok-4.5-build", dedupeKey: null })],
+ position: position({ resumeOffset: 30, guardLength: 30, guardHash: 123 }),
+ });
+ original.set("/codex.jsonl", {
+ size: 80,
+ mtimeMs: 400,
+ provider: "codex",
+ records: [record({ provider: "codex", model: "gpt-5.2-codex", dedupeKey: null })],
+ tailRecords: [],
+ position: position({
+ codexState: {
+ model: "gpt-5.2-codex",
+ sessionId: "session-c",
+ lastUsageSignature: '{"input_tokens":1}',
+ sawSessionMeta: true,
+ suppressingForkCopies: false,
+ forkCopyAnchorMs: 0,
+ },
+ }),
});
const restored = decodeScanCache(JSON.parse(JSON.stringify(encodeScanCache(original))));
- expect(restored.size).toBe(3);
+ expect(restored.size).toBe(4);
expect(restored.get("/a.jsonl")).toEqual(original.get("/a.jsonl"));
expect(restored.get("/b.jsonl")).toEqual(original.get("/b.jsonl"));
expect(restored.get("/grok.jsonl")).toEqual(original.get("/grok.jsonl"));
+ expect(restored.get("/codex.jsonl")).toEqual(original.get("/codex.jsonl"));
+ });
+
+ it("drops an entry whose persisted parse state is corrupt", () => {
+ // Resuming with a bad reducer state would attach appended usage to the
+ // wrong model or replay fork-copied history; that entry must cold parse.
+ const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
+ const poisoned = {
+ ...encoded,
+ files: {
+ "/a.jsonl": { ...encoded.files["/a.jsonl"]!, cs: { model: 42 } },
+ },
+ };
+
+ expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
+ });
+
+ it("drops an entry whose guard length is outside the supported range", () => {
+ // The guard length sizes a Buffer in the reader; a bogus value would make
+ // every parse of that file fail and silently drop its usage.
+ const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
+ const poisoned = {
+ ...encoded,
+ files: { "/a.jsonl": { ...encoded.files["/a.jsonl"]!, gl: 1e20 } },
+ };
+
+ expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
+ });
+
+ it("rejects a document from the previous cache version", () => {
+ const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
+ const previous = { ...encoded, version: 2 };
+
+ expect(decodeScanCache(JSON.parse(JSON.stringify(previous))).size).toBe(0);
});
it("interns repeated model and session strings", () => {
diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts
index bca97152c1d..102058a07d3 100644
--- a/apps/server/src/usage/usageScanCache.ts
+++ b/apps/server/src/usage/usageScanCache.ts
@@ -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) {
diff --git a/apps/server/src/usage/usageTranscriptReader.test.ts b/apps/server/src/usage/usageTranscriptReader.test.ts
new file mode 100644
index 00000000000..5feb68b2ff5
--- /dev/null
+++ b/apps/server/src/usage/usageTranscriptReader.test.ts
@@ -0,0 +1,210 @@
+// @effect-diagnostics nodeBuiltinImport:off - resume coverage writes, appends
+// to, and truncates real transcript files byte-exactly, mirroring the reader's
+// own deliberate node:fs usage.
+import * as NodeFSP from "node:fs/promises";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+
+import { afterEach, assert, beforeEach, describe, it } from "@effect/vitest";
+
+import { readTranscriptRecords } from "./usageTranscriptReader.ts";
+
+let dir: string;
+
+beforeEach(async () => {
+ dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "usage-reader-test-"));
+});
+
+afterEach(async () => {
+ await NodeFSP.rm(dir, { recursive: true, force: true });
+});
+
+function claudeLine(id: number, outputTokens: number): string {
+ return `${JSON.stringify({
+ type: "assistant",
+ timestamp: "2026-08-01T10:00:00Z",
+ requestId: `req_${id}`,
+ sessionId: "session-1",
+ message: {
+ id: `msg_${id}`,
+ model: "claude-fable-5",
+ usage: { input_tokens: 10, output_tokens: outputTokens },
+ },
+ })}\n`;
+}
+
+function codexMetaLine(): string {
+ return `${JSON.stringify({
+ type: "session_meta",
+ timestamp: "2026-08-01T10:00:00Z",
+ payload: { type: "session_meta", id: "codex-session-1" },
+ })}\n`;
+}
+
+function codexModelLine(model: string): string {
+ return `${JSON.stringify({
+ type: "turn_context",
+ timestamp: "2026-08-01T10:00:01Z",
+ payload: { type: "turn_context", model },
+ })}\n`;
+}
+
+function codexUsageLine(outputTokens: number, secondsOffset: number): string {
+ return `${JSON.stringify({
+ type: "event_msg",
+ timestamp: `2026-08-01T10:00:${String(secondsOffset).padStart(2, "0")}Z`,
+ payload: {
+ type: "token_count",
+ info: { last_token_usage: { input_tokens: 100, output_tokens: outputTokens } },
+ },
+ })}\n`;
+}
+
+describe("readTranscriptRecords resume", () => {
+ it("parses only appended lines when resuming a grown file", async () => {
+ const path = NodePath.join(dir, "claude.jsonl");
+ await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
+ const first = await readTranscriptRecords(path, "claude");
+ assert.isNotNull(first);
+ assert.strictEqual(first.records.length, 2);
+ assert.isFalse(first.resumed);
+
+ await NodeFSP.appendFile(path, claudeLine(3, 11));
+ const second = await readTranscriptRecords(path, "claude", first.position);
+ assert.isNotNull(second);
+ assert.isTrue(second.resumed);
+ assert.strictEqual(second.records.length, 1);
+ assert.strictEqual(second.records[0]?.totals.outputTokens, 11);
+
+ // The stitched result matches a from-scratch parse of the whole file.
+ const full = await readTranscriptRecords(path, "claude");
+ assert.isNotNull(full);
+ assert.deepStrictEqual([...first.records, ...second.records], [...full.records]);
+ });
+
+ it("carries the Codex reducer state across the resume boundary", async () => {
+ const path = NodePath.join(dir, "rollout.jsonl");
+ await NodeFSP.writeFile(path, codexMetaLine() + codexModelLine("gpt-5.2-codex"));
+ const first = await readTranscriptRecords(path, "codex");
+ assert.isNotNull(first);
+ assert.strictEqual(first.records.length, 0);
+
+ // The appended usage event has no turn_context or session_meta of its own;
+ // model and session must come from the state captured before the boundary.
+ await NodeFSP.appendFile(path, codexUsageLine(9, 5));
+ const second = await readTranscriptRecords(path, "codex", first.position);
+ assert.isNotNull(second);
+ assert.isTrue(second.resumed);
+ assert.strictEqual(second.records.length, 1);
+ assert.strictEqual(second.records[0]?.model, "gpt-5.2-codex");
+ assert.strictEqual(second.records[0]?.sessionId, "codex-session-1");
+ });
+
+ it("suppresses a Codex duplicate usage event that straddles the boundary", async () => {
+ const path = NodePath.join(dir, "rollout.jsonl");
+ await NodeFSP.writeFile(
+ path,
+ codexMetaLine() + codexModelLine("gpt-5.2-codex") + codexUsageLine(9, 5),
+ );
+ const first = await readTranscriptRecords(path, "codex");
+ assert.isNotNull(first);
+ assert.strictEqual(first.records.length, 1);
+
+ // Codex re-emits an unchanged token_count on stream boundaries; the copy
+ // lands after the resume point and must still be dropped.
+ await NodeFSP.appendFile(path, codexUsageLine(9, 5) + codexUsageLine(21, 8));
+ const second = await readTranscriptRecords(path, "codex", first.position);
+ assert.isNotNull(second);
+ assert.isTrue(second.resumed);
+ assert.deepStrictEqual(
+ second.records.map((record) => record.totals.outputTokens),
+ [21],
+ );
+ });
+
+ it("defers an unterminated trailing line to tailRecords, then consumes it once terminated", async () => {
+ const path = NodePath.join(dir, "claude.jsonl");
+ const unterminated = claudeLine(2, 7).trimEnd();
+ await NodeFSP.writeFile(path, claudeLine(1, 5) + unterminated);
+ const first = await readTranscriptRecords(path, "claude");
+ assert.isNotNull(first);
+ assert.strictEqual(first.records.length, 1);
+ assert.strictEqual(first.tailRecords.length, 1);
+ assert.strictEqual(first.tailRecords[0]?.totals.outputTokens, 7);
+
+ // Completing the line and appending another re-reads from the resume
+ // point, so the once-tail record arrives exactly once as a line record.
+ await NodeFSP.appendFile(path, `\n${claudeLine(3, 11)}`);
+ const second = await readTranscriptRecords(path, "claude", first.position);
+ assert.isNotNull(second);
+ assert.isTrue(second.resumed);
+ assert.deepStrictEqual(
+ second.records.map((record) => record.totals.outputTokens),
+ [7, 11],
+ );
+ assert.strictEqual(second.tailRecords.length, 0);
+ });
+
+ it("re-parses from the start when the guard bytes no longer match", async () => {
+ const path = NodePath.join(dir, "claude.jsonl");
+ await NodeFSP.writeFile(path, claudeLine(1, 5));
+ const first = await readTranscriptRecords(path, "claude");
+ assert.isNotNull(first);
+
+ // Same path, larger size, different content: a replaced file, not growth.
+ await NodeFSP.writeFile(path, claudeLine(4, 13) + claudeLine(5, 17));
+ const second = await readTranscriptRecords(path, "claude", first.position);
+ assert.isNotNull(second);
+ assert.isFalse(second.resumed);
+ assert.deepStrictEqual(
+ second.records.map((record) => record.totals.outputTokens),
+ [13, 17],
+ );
+ });
+
+ it("re-parses from the start when the file shrank below the resume point", async () => {
+ const path = NodePath.join(dir, "claude.jsonl");
+ await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
+ const first = await readTranscriptRecords(path, "claude");
+ assert.isNotNull(first);
+
+ await NodeFSP.writeFile(path, claudeLine(3, 11));
+ const second = await readTranscriptRecords(path, "claude", first.position);
+ assert.isNotNull(second);
+ assert.isFalse(second.resumed);
+ assert.deepStrictEqual(
+ second.records.map((record) => record.totals.outputTokens),
+ [11],
+ );
+ });
+
+ it("parses a line larger than one stream chunk", async () => {
+ // Tool-heavy transcripts carry multi-megabyte single lines; they arrive
+ // split across many chunks and must reassemble into one record.
+ const path = NodePath.join(dir, "claude.jsonl");
+ const bigLine = `${JSON.stringify({
+ type: "assistant",
+ timestamp: "2026-08-01T10:00:00Z",
+ requestId: "req_big",
+ sessionId: "session-1",
+ padding: "x".repeat(512 * 1024),
+ message: {
+ id: "msg_big",
+ model: "claude-fable-5",
+ usage: { input_tokens: 10, output_tokens: 42 },
+ },
+ })}\n`;
+ await NodeFSP.writeFile(path, bigLine + claudeLine(2, 7));
+
+ const parsed = await readTranscriptRecords(path, "claude");
+ assert.isNotNull(parsed);
+ assert.deepStrictEqual(
+ parsed.records.map((record) => record.totals.outputTokens),
+ [42, 7],
+ );
+ });
+
+ it("returns null for an unreadable file", async () => {
+ assert.isNull(await readTranscriptRecords(NodePath.join(dir, "missing.jsonl"), "claude"));
+ });
+});
diff --git a/apps/server/src/usage/usageTranscriptReader.ts b/apps/server/src/usage/usageTranscriptReader.ts
index 33aef8fae25..9e5ab6e0c9e 100644
--- a/apps/server/src/usage/usageTranscriptReader.ts
+++ b/apps/server/src/usage/usageTranscriptReader.ts
@@ -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;
}
+ 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));
+ }
- if (!mightCarryUsage(line, provider)) continue;
- const record = parseClaudeLine(line);
- if (record !== null) records.push(record);
+ // 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;
}