Skip to content
TypeScript

perf(usage): cut warm usage scans from seconds to milliseconds on large histories (#15149)

Theo Browne71dbaf1f94b5
diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts
index 127679d0a44..62345d8472e 100644
--- a/apps/server/src/usage/UsageService.test.ts
+++ b/apps/server/src/usage/UsageService.test.ts
@@ -1,5 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off - the suite seeds and grows real
// transcript trees on disk, outside the service's Effect FileSystem.
+import * as NodeChildProcess from "node:child_process";
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
@@ -117,6 +118,41 @@ const serviceLayers = (input: {
),
);
+/** Outside `NARROW_WINDOW`, inside `WINDOW`. Seconds, as `utimes` takes them. */
+const BEFORE_NARROW_WINDOW = Date.parse("2026-08-01T10:00:00Z") / 1000;
+const NARROW_WINDOW: UsageSummaryInput = {
+ timeZone: "UTC",
+ sinceDay: UsageDay.make("2026-09-01"),
+ untilDay: UsageDay.make("2026-09-02"),
+};
+
+/**
+ * A FIFO named like a transcript. A scan's read of it waits in `open` until
+ * `openGate`, then fails at once, so a gate holds that scan's directory reads
+ * in flight. Each waiting gate holds one libuv pool thread; keep at most three.
+ */
+const makeGate = (path: string, lastWriteSeconds?: number) =>
+ Effect.promise(async () => {
+ NodeChildProcess.execFileSync("mkfifo", [path]);
+ if (lastWriteSeconds !== undefined) {
+ await NodeFSP.utimes(path, lastWriteSeconds, lastWriteSeconds);
+ }
+ });
+
+/**
+ * Returns once a scan has opened the gate. A scan opens every file of a
+ * directory at once, so it then holds the directory's transcripts open too.
+ */
+const openGate = (path: string) =>
+ Effect.promise(async () => (await NodeFSP.open(path, "w")).close());
+
+/** Replaces a file by rename, so a scan holding the old one keeps reading it. */
+const replaceFile = (path: string, content: string) =>
+ Effect.promise(async () => {
+ await NodeFSP.writeFile(path + ".next", content);
+ await NodeFSP.rename(path + ".next", path);
+ });
+
function totalOutputTokens(summary: { buckets: readonly { totals: { outputTokens: number } }[] }) {
return summary.buckets.reduce((sum, bucket) => sum + bucket.totals.outputTokens, 0);
}
@@ -972,6 +1008,157 @@ describe("UsageService", () => {
}).pipe(Effect.scoped),
);
+ it.live("credits the same copy of a duplicate after its transcripts are deleted", () =>
+ Effect.gen(function* () {
+ const { transcript, settings, home } = yield* setup;
+ const dir = NodePath.dirname(transcript);
+ // The walk-first file is the original, padded so it finishes parsing
+ // after the small fork copy that repeats its record under a new session.
+ const [first = "", second = ""] = yield* Effect.promise(async () => {
+ await NodeFSP.writeFile(NodePath.join(dir, "a.jsonl"), "");
+ await NodeFSP.writeFile(NodePath.join(dir, "b.jsonl"), "");
+ return (await NodeFSP.readdir(dir)).map((name) => NodePath.join(dir, name));
+ });
+ const forked = (line: string) => line.replace('"session-1"', '"session-2"');
+ yield* Effect.promise(async () => {
+ await NodeFSP.writeFile(
+ first,
+ claudeLine(1, 5).replace(
+ '"message":',
+ '"padding":' + encodeUnknownJsonString("x".repeat(9 * 1024 * 1024)) + ',"message":',
+ ),
+ );
+ await NodeFSP.writeFile(second, forked(claudeLine(1, 5)) + forked(claudeLine(2, 7)));
+ });
+ yield* Effect.gen(function* () {
+ const service = yield* UsageService.make;
+ const live = yield* service.readSummary(WINDOW);
+ assert.strictEqual(live.buckets[0]?.sessions, 2);
+
+ yield* Effect.promise(() => Promise.all([NodeFSP.rm(first), NodeFSP.rm(second)]));
+ const saved = yield* service.readSummary(WINDOW);
+ assert.deepStrictEqual(saved.buckets, live.buckets);
+ assert.deepStrictEqual(saved.sources, live.sources);
+ const restored = yield* (yield* UsageService.make).readSummary(WINDOW);
+ assert.deepStrictEqual(restored.buckets, live.buckets);
+ }).pipe(
+ Effect.provide(serviceLayers({ prefix: "usage-service-copy-order-test", home, settings })),
+ );
+ }).pipe(Effect.scoped),
+ );
+
+ it.live.skipIf(HostProcessPlatform.defaultValue() === "win32")(
+ "keeps a newer cached read when a slower scan of another window finishes later",
+ () =>
+ Effect.gen(function* () {
+ const { transcript, settings, home } = yield* setup;
+ const dir = NodePath.dirname(transcript);
+ const probe = NodePath.join(dir, "probe.jsonl");
+ const hold = NodePath.join(dir, "hold.jsonl");
+ yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5)));
+ yield* makeGate(probe, BEFORE_NARROW_WINDOW);
+ yield* makeGate(hold, BEFORE_NARROW_WINDOW);
+ yield* Effect.gen(function* () {
+ const service = yield* UsageService.make;
+ const wide = yield* service.readSummary(WINDOW).pipe(Effect.forkChild);
+ yield* openGate(probe);
+ yield* replaceFile(transcript, claudeLine(1, 5) + claudeLine(2, 7));
+ // The narrow scan caches the newer read while the wide one waits.
+ yield* service.readSummary(NARROW_WINDOW);
+ yield* openGate(hold);
+ yield* Fiber.join(wide);
+
+ yield* Effect.promise(() =>
+ Promise.all([transcript, probe, hold].map((path) => NodeFSP.rm(path))),
+ );
+ assert.strictEqual(totalOutputTokens(yield* service.readSummary(WINDOW)), 12);
+ }).pipe(
+ Effect.provide(
+ serviceLayers({ prefix: "usage-service-stale-read-test", home, settings }),
+ ),
+ );
+ }).pipe(Effect.scoped),
+ );
+
+ it.live.skipIf(HostProcessPlatform.defaultValue() === "win32")(
+ "keeps the later read when a scan that read earlier finishes first",
+ () =>
+ Effect.gen(function* () {
+ const { transcript, settings, home } = yield* setup;
+ const dir = NodePath.dirname(transcript);
+ const gate = (name: string) => NodePath.join(dir, `${name}.jsonl`);
+ const wideProbe = gate("wide-probe");
+ const wideHold = gate("wide-hold");
+ const narrowProbe = gate("narrow-probe");
+ const narrowHold = gate("narrow-hold");
+ yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5)));
+ yield* makeGate(wideProbe, BEFORE_NARROW_WINDOW);
+ yield* makeGate(wideHold, BEFORE_NARROW_WINDOW);
+ yield* Effect.gen(function* () {
+ const service = yield* UsageService.make;
+ const wide = yield* service.readSummary(WINDOW).pipe(Effect.forkChild);
+ yield* openGate(wideProbe);
+ yield* replaceFile(transcript, claudeLine(1, 5) + claudeLine(2, 7));
+ // Made after the wide scan's walk, so only the narrow scan waits on them.
+ yield* makeGate(narrowProbe);
+ yield* makeGate(narrowHold);
+ const narrow = yield* service.readSummary(NARROW_WINDOW).pipe(Effect.forkChild);
+ yield* openGate(narrowProbe);
+ // Both scans started from an empty cache entry; the earlier read lands first.
+ yield* openGate(wideHold);
+ yield* Fiber.join(wide);
+ yield* openGate(narrowHold);
+ yield* Fiber.join(narrow);
+
+ yield* Effect.promise(() =>
+ Promise.all(
+ [transcript, wideProbe, wideHold, narrowProbe, narrowHold].map((path) =>
+ NodeFSP.rm(path),
+ ),
+ ),
+ );
+ assert.strictEqual(totalOutputTokens(yield* service.readSummary(WINDOW)), 12);
+ }).pipe(
+ Effect.provide(serviceLayers({ prefix: "usage-service-late-read-test", home, settings })),
+ );
+ }).pipe(Effect.scoped),
+ );
+
+ it.live("reports saved usage of a removed directory only for windows it reaches", () =>
+ Effect.gen(function* () {
+ const { transcript, settings, home } = yield* setup;
+ yield* Effect.promise(async () => {
+ await NodeFSP.writeFile(transcript, claudeLine(1, 5));
+ const lastWrite = Date.parse("2026-08-01T10:00:00Z") / 1000;
+ await NodeFSP.utimes(transcript, lastWrite, lastWrite);
+ });
+ const service = yield* UsageService.make.pipe(
+ Effect.provide(
+ serviceLayers({ prefix: "usage-service-saved-window-test", home, settings }),
+ ),
+ );
+ const first = yield* service.readSummary(WINDOW);
+ yield* Effect.promise(() =>
+ NodeFSP.rm(NodePath.join(home, "claude", "projects"), { recursive: true }),
+ );
+
+ const reached = yield* service.readSummary(WINDOW);
+ assert.deepStrictEqual(reached.buckets, first.buckets);
+ assert.strictEqual(reached.sources[0]?.status, "ok");
+
+ // A missing source cannot claim this directory from another environment
+ // that still reads it, so it adds nothing to a window after its last write.
+ const later = yield* service.readSummary({
+ timeZone: "UTC",
+ sinceDay: UsageDay.make("2026-08-10"),
+ untilDay: UsageDay.make("2026-08-12"),
+ });
+ assert.deepStrictEqual(later.buckets, []);
+ assert.strictEqual(later.sources[0]?.status, "missing");
+ assert.strictEqual(later.sources[0]?.scannedFiles, 0);
+ }).pipe(Effect.scoped),
+ );
+
it.live("does not share an in-flight scan after custom prices change", () =>
Effect.gen(function* () {
const { transcript, settings, home } = yield* setup;
diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts
index 026641ae4d0..dc3121fc002 100644
--- a/apps/server/src/usage/UsageService.ts
+++ b/apps/server/src/usage/UsageService.ts
@@ -63,10 +63,11 @@ import {
import {
decodeScanCache,
dedupeWithinFile,
- encodeScanCache,
LEGACY_SCAN_CACHE_FILE_NAME,
+ makeScanCacheWriter,
pruneScanCache,
SCAN_CACHE_FILE_NAME,
+ type CachedFile,
type ScanCache,
} from "./usageScanCache.ts";
import type { UsageRecord } from "./usageTranscripts.ts";
@@ -90,6 +91,9 @@ const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
/** Longest window the UI offers, plus slack. Older entries are pruned. */
const CACHE_RETENTION_DAYS = 90;
+/** Transcripts parsed at once. More gains little once the disk stays busy. */
+const TRANSCRIPT_READ_CONCURRENCY = 4;
+
const decodeCodexSettings = Schema.decodeOption(CodexSettings);
const decodeClaudeSettings = Schema.decodeOption(ClaudeSettings);
@@ -108,9 +112,37 @@ const encodeRatesCache = Schema.encodeEffect(
/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */
const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);
const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
-const encodeScanCacheFile = Schema.encodeEffect(ScanCacheJson);
const encodeUsageRecordKey = Schema.encodeSync(ScanCacheJson);
const CachedSource = Schema.Struct({ dir: Schema.String, volumeId: Schema.String });
+
+/** Whether `a` read a later state of its file than `b`. Transcripts only grow. */
+function isLaterRead(a: CachedFile, b: CachedFile): boolean {
+ return a.mtimeMs > b.mtimeMs || (a.mtimeMs === b.mtimeMs && a.size > b.size);
+}
+
+/**
+ * Codex sessions with records in more than one file, such as a rollout that
+ * moved after it was read. Only these need cross-file dedupe keys: within one
+ * file the occurrence count already keeps every key unique, so keying the rest
+ * would only build and hash a string for each of their records.
+ */
+function sharedCodexSessions(
+ files: readonly { readonly records: readonly UsageRecord[] }[],
+): ReadonlySet<string> {
+ const firstFile = new Map<string, number>();
+ const shared = new Set<string>();
+ for (const [index, file] of files.entries()) {
+ let previous = "";
+ for (const { provider, sessionId } of file.records) {
+ if (provider !== "codex" || sessionId === previous || sessionId.length === 0) continue;
+ previous = sessionId;
+ const first = firstFile.get(sessionId);
+ if (first === undefined) firstFile.set(sessionId, index);
+ else if (first !== index) shared.add(sessionId);
+ }
+ }
+ return shared;
+}
const decodeCachedSources = Schema.decodeUnknownOption(
Schema.Struct({ sources: Schema.Record(Schema.String, CachedSource) }),
);
@@ -386,20 +418,28 @@ export const make = Effect.gen(function* () {
}),
);
+ const writeScanCache = makeScanCacheWriter();
+ // Scans with different windows can finish together; two writes interleaved
+ // in one file would corrupt it.
+ const persistLock = yield* Semaphore.make(1);
+
const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () {
if (!cacheDirty) return;
- // Cleared only after the write lands, so a failed persist is retried on
- // the next scan instead of leaving disk permanently stale.
- yield* encodeScanCacheFile({
- ...encodeScanCache(fileCache),
- sources: Object.fromEntries(sourceCache),
- }).pipe(
+ // Cleared before encoding, so a scan that changes the cache while this
+ // write is in flight marks it dirty again. A failed write restores the
+ // flag, so the next scan retries instead of leaving disk stale.
+ cacheDirty = false;
+ yield* Effect.sync(() =>
+ writeScanCache(fileCache, { sources: Object.fromEntries(sourceCache) }),
+ ).pipe(
Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)),
- Effect.map(() => {
- cacheDirty = false;
- }),
// A cache we cannot write is a slower next start, not a failed read.
- Effect.ignoreCause,
+ Effect.catchCause(() =>
+ Effect.sync(() => {
+ cacheDirty = true;
+ }),
+ ),
+ persistLock.withPermit,
);
});
@@ -410,13 +450,22 @@ export const make = Effect.gen(function* () {
* 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.
+ *
+ * A fresh parse comes back as `update` for the caller to cache, with the
+ * entry it was built from. Reads run concurrently, and the caller stores
+ * updates in walk order rather than completion order: saved records of
+ * deleted transcripts aggregate in cache order, where the first copy of a
+ * duplicate wins.
*/
const readFileRecords = (
filePath: string,
size: number,
mtimeMs: number,
provider: UsageProviderKind,
- ): Effect.Effect<readonly UsageRecord[]> =>
+ ): Effect.Effect<{
+ readonly records: readonly UsageRecord[];
+ readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
+ }> =>
Effect.gen(function* () {
const cached = fileCache.get(filePath);
// Provider is part of the identity: if both providers were ever pointed
@@ -427,9 +476,12 @@ export const make = Effect.gen(function* () {
cached.mtimeMs === mtimeMs &&
cached.provider === provider
) {
- return cached.tailRecords.length === 0
- ? cached.records
- : [...cached.records, ...cached.tailRecords];
+ return {
+ records:
+ cached.tailRecords.length === 0
+ ? cached.records
+ : [...cached.records, ...cached.tailRecords],
+ };
}
// Only a strictly grown file may resume. Same size with a new mtime, or
@@ -445,7 +497,9 @@ export const make = Effect.gen(function* () {
// 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 cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [];
+ return {
+ records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
+ };
// Stored already de-duplicated within the file, which is 99% of all
// duplicates. The aggregator still runs the cross-file dedupe pass. One
@@ -456,16 +510,13 @@ export const make = Effect.gen(function* () {
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 tailRecords.length === 0 ? records : [...records, ...tailRecords];
+ return {
+ records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
+ update: {
+ entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position },
+ replaces: cached,
+ },
+ };
});
/** One provider directory's walk and parse, before rates are involved. */
@@ -505,11 +556,32 @@ export const make = Effect.gen(function* () {
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 });
- }
+ // A cold parse waits on disk reads, so a few files in flight read
+ // close to twice as fast. Results keep walk order.
+ const read = yield* Effect.forEach(
+ files,
+ (file) =>
+ readFileRecords(file.path, file.size, file.mtimeMs, provider).pipe(
+ Effect.map((result) => ({ path: file.path, ...result })),
+ ),
+ { concurrency: TRANSCRIPT_READ_CONCURRENCY },
+ );
+ const parsedFiles = read.map(({ path, records, update }) => {
+ if (update === undefined) return { path, records };
+ // A scan of another window may have cached its own read of this file
+ // meanwhile. Then keep whichever read saw the later file, so a slower
+ // scan never replaces newer usage with older.
+ const current = fileCache.get(path);
+ if (
+ current === update.replaces ||
+ current === undefined ||
+ !isLaterRead(current, update.entry)
+ ) {
+ fileCache.set(path, update.entry);
+ cacheDirty = true;
+ }
+ return { path, records };
+ });
scanned.push({ provider, dir, volumeId, files: parsedFiles });
}
@@ -753,37 +825,39 @@ export const make = Effect.gen(function* () {
const sources: UsageSource[] = [];
- for (const {
- provider,
- dir,
- volumeId,
- files,
- status,
- message,
- action,
- hostId: sourceHostId,
- } of scannedDirs) {
+ // Cleanup may remove transcripts, but the usage we already saved still
+ // contributes to its source through the normal aggregation and dedupe
+ // path. Like the walk, skip files last written before the window: they
+ // cannot hold records inside it.
+ const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs);
+ const filesByDir = scannedDirs.map(({ provider, dir, files }) => {
const retainedFiles = [...(files ?? [])];
const livePaths = new Set(retainedFiles.map((file) => file.path));
- // Cleanup may remove transcripts, but the usage we already saved still
- // contributes to this source. Keep the normal aggregation and dedupe path.
for (const [filePath, entry] of fileCache) {
if (
entry.provider !== provider ||
- entry.mtimeMs < retentionCutoffMs ||
+ entry.mtimeMs < retainedSinceMs ||
livePaths.has(filePath) ||
!isWithinDirectory(filePath, dir)
)
continue;
retainedFiles.push({ path: filePath, records: [...entry.records, ...entry.tailRecords] });
}
+ return retainedFiles;
+ });
+ const sharedSessions = sharedCodexSessions(filesByDir.flat());
+
+ for (const [
+ index,
+ { provider, dir, volumeId, files, status, message, action, hostId: sourceHostId },
+ ] of scannedDirs.entries()) {
let scannedFiles = 0;
let skippedFiles = 0;
// Distinct per directory. Buckets carry per-cell session counts, but a
// session spans days and models, so clients total this figure instead.
const sessionIds = new Set<string>();
- for (const file of retainedFiles) {
+ for (const file of filesByDir[index] ?? []) {
if (file.records.length === 0) {
skippedFiles += 1;
continue;
@@ -792,9 +866,10 @@ export const make = Effect.gen(function* () {
const codexEventOccurrences = new Map<string, number>();
for (const record of file.records) {
let usageRecord = record;
- if (record.provider === "codex" && record.sessionId.length > 0) {
+ if (record.provider === "codex" && sharedSessions.has(record.sessionId)) {
// Match moved rollout copies without collapsing repeated equal events
// within one rollout (timestamps can have only second precision).
+ // Only sessions seen in several files can have a copy to match.
const key = encodeUsageRecordKey([
record.provider,
record.sessionId,
diff --git a/apps/server/src/usage/usageAggregation.test.ts b/apps/server/src/usage/usageAggregation.test.ts
index ab260d3398b..9fea9cd9664 100644
--- a/apps/server/src/usage/usageAggregation.test.ts
+++ b/apps/server/src/usage/usageAggregation.test.ts
@@ -128,6 +128,41 @@ describe("UsageAggregator", () => {
expect(losAngeles.buckets[0]?.day).toBe("2026-08-06");
});
+ it("finds the day at a quarter-hour zone's midnight across interleaved buckets", () => {
+ // Kathmandu is UTC+5:45, so its midnight falls at 18:15 UTC.
+ const result = aggregate(
+ [
+ record({ timestampMs: Date.parse("2026-08-01T18:14:59.999Z") }),
+ record({ timestampMs: Date.parse("2026-08-01T18:15:00.000Z") }),
+ record({ timestampMs: Date.parse("2026-08-01T18:15:00.000Z"), model: "claude-opus-5" }),
+ record({ timestampMs: Date.parse("2026-08-01T18:16:00.000Z") }),
+ ],
+ "Asia/Kathmandu",
+ );
+
+ expect(result.buckets.map((bucket) => [bucket.day, bucket.model, bucket.records])).toEqual([
+ ["2026-08-01", "claude-fable-5", 1],
+ ["2026-08-02", "claude-fable-5", 2],
+ ["2026-08-02", "claude-opus-5", 1],
+ ]);
+ });
+
+ it("finds the day at a fixed offset's midnight between quarter hours", () => {
+ // At +00:01, midnight falls at 23:59 UTC.
+ const result = aggregate(
+ [
+ record({ timestampMs: Date.parse("2026-08-01T23:58:59.999Z") }),
+ record({ timestampMs: Date.parse("2026-08-01T23:59:00.000Z") }),
+ ],
+ "+00:01",
+ );
+
+ expect(result.buckets.map((bucket) => [bucket.day, bucket.records])).toEqual([
+ ["2026-08-01", 1],
+ ["2026-08-02", 1],
+ ]);
+ });
+
it("splits an hourly request into fixed buckets anchored to its exact start", () => {
const result = aggregate(
[
diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.ts
index 040c258075d..0652ca4b7dc 100644
--- a/apps/server/src/usage/usageAggregation.ts
+++ b/apps/server/src/usage/usageAggregation.ts
@@ -20,7 +20,7 @@ import type {
UsageTokenTotals,
} from "@t3tools/contracts";
-import { addTotals, EMPTY_TOTALS, type UsageRecord } from "./usageTranscripts.ts";
+import { EMPTY_TOTALS, type UsageRecord } from "./usageTranscripts.ts";
import { cacheSavingsUsd, priceUsage, type RateTable } from "./usagePricing.ts";
/**
@@ -47,13 +47,30 @@ function makeDayFormatter(timeZone: string): (timestampMs: number) => string {
day: "2-digit",
});
}
- return (timestampMs) => format.format(new Date(timestampMs));
+ // Formatting once per quarter-hour slot keeps `Intl` (about 2µs a call) off
+ // the per-record path. A slot whose two ends fall on one day lies wholly in
+ // that day. Named zones put midnight on a quarter hour, so their slots never
+ // split; a fixed offset such as `+00:01` can, and records in a split slot are
+ // formatted exactly. `null` marks a split slot.
+ const days = new Map<number, string | null>();
+ return (timestampMs) => {
+ const slot = Math.floor(timestampMs / QUARTER_HOUR_MS);
+ let day = days.get(slot);
+ if (day === undefined) {
+ const first = format.format(new Date(slot * QUARTER_HOUR_MS));
+ const last = format.format(new Date((slot + 1) * QUARTER_HOUR_MS - 1));
+ day = first === last ? first : null;
+ days.set(slot, day);
+ }
+ return day ?? format.format(new Date(timestampMs));
+ };
}
+const QUARTER_HOUR_MS = 15 * 60 * 1000;
const HOUR_MS = 60 * 60 * 1000;
interface MutableBucket {
- totals: UsageTokenTotals;
+ totals: { -readonly [K in keyof UsageTokenTotals]: number };
costUsd: number;
cacheSavingsUsd: number;
categoryCostUsd: UsageCategoryCost | null;
@@ -98,6 +115,14 @@ export class UsageAggregator {
readonly #toDay: (timestampMs: number) => string;
readonly #hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null;
readonly #options: AggregateOptions;
+ #lastBucket: {
+ readonly day: string;
+ readonly hourIndex: number;
+ readonly provider: string;
+ readonly model: string;
+ readonly source: string;
+ readonly bucket: MutableBucket;
+ } | null = null;
#duplicatesDropped = 0;
#outOfWindow = 0;
@@ -149,35 +174,20 @@ export class UsageAggregator {
return false;
}
- const hourStart =
+ const hourIndex =
this.#hourlyWindow === null
- ? ""
- : new Date(
- this.#hourlyWindow.sinceTimeMs +
- Math.floor((record.timestampMs - this.#hourlyWindow.sinceTimeMs) / HOUR_MS) * HOUR_MS,
- ).toISOString();
- const key = `${day}\u0000${hourStart}\u0000${record.provider}\u0000${record.model}\u0000${sourcePath ?? ""}`;
- let bucket = this.#buckets.get(key);
- if (bucket === undefined) {
- bucket = {
- totals: EMPTY_TOTALS,
- costUsd: 0,
- cacheSavingsUsd: 0,
- categoryCostUsd: null,
- fastCostUsd: 0,
- ultrafastCostUsd: 0,
- speedPremiumUsd: 0,
- records: 0,
- unpricedRecords: 0,
- providerReportedRecords: 0,
- sessions: new Set<string>(),
- };
- this.#buckets.set(key, bucket);
- }
+ ? -1
+ : Math.floor((record.timestampMs - this.#hourlyWindow.sinceTimeMs) / HOUR_MS);
+ const bucket = this.#bucketFor(day, hourIndex, record.provider, record.model, sourcePath ?? "");
const priced = priceUsage(this.#options.rates, record, this.#options.priceOverrides);
- bucket.totals = addTotals(bucket.totals, record.totals);
+ const totals = bucket.totals;
+ totals.uncachedInputTokens += record.totals.uncachedInputTokens;
+ totals.cachedInputTokens += record.totals.cachedInputTokens;
+ totals.cacheCreationTokens += record.totals.cacheCreationTokens;
+ totals.outputTokens += record.totals.outputTokens;
+ totals.reasoningTokens += record.totals.reasoningTokens;
bucket.costUsd += priced.costUsd;
if (priced.categoryCostUsd !== null) {
const sum = bucket.categoryCostUsd;
@@ -207,6 +217,54 @@ export class UsageAggregator {
return true;
}
+ /**
+ * Records arrive file by file in time order, so most land in the bucket the
+ * previous record used. Checking that first skips building and hashing a
+ * key string per record.
+ */
+ #bucketFor(
+ day: string,
+ hourIndex: number,
+ provider: string,
+ model: string,
+ source: string,
+ ): MutableBucket {
+ const last = this.#lastBucket;
+ if (
+ last !== null &&
+ last.day === day &&
+ last.hourIndex === hourIndex &&
+ last.provider === provider &&
+ last.model === model &&
+ last.source === source
+ ) {
+ return last.bucket;
+ }
+ const window = this.#hourlyWindow;
+ const hourStart =
+ window === null ? "" : new Date(window.sinceTimeMs + hourIndex * HOUR_MS).toISOString();
+ const key = `${day}\u0000${hourStart}\u0000${provider}\u0000${model}\u0000${source}`;
+ let bucket = this.#buckets.get(key);
+ if (bucket === undefined) {
+ bucket = {
+ totals: { ...EMPTY_TOTALS },
+ costUsd: 0,
+ cacheSavingsUsd: 0,
+ categoryCostUsd: null,
+ fastCostUsd: 0,
+ ultrafastCostUsd: 0,
+ speedPremiumUsd: 0,
+ records: 0,
+ unpricedRecords: 0,
+ providerReportedRecords: 0,
+ sessions: new Set<string>(),
+ };
+ this.#buckets.set(key, bucket);
+ }
+ this.#lastBucket = { day, hourIndex, provider, model, source, bucket };
+ return bucket;
+ }
+
finish(): AggregateResult {
const buckets: UsageBucket[] = [];
for (const [key, bucket] of this.#buckets) {
@@ -222,7 +280,7 @@ export class UsageAggregator {
provider: provider as UsageBucket["provider"],
model,
...(sourcePath === "" ? {} : { sourcePath }),
- totals: bucket.totals,
+ totals: { ...bucket.totals },
costUsd: bucket.costUsd,
cacheSavingsUsd: bucket.cacheSavingsUsd,
// Zero and unknown figures are omitted to keep payloads small.
diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts
index 51ef35d7a8a..0ec7ef8d622 100644
--- a/apps/server/src/usage/usagePricing.ts
+++ b/apps/server/src/usage/usagePricing.ts
@@ -235,7 +235,27 @@ const UNPRICEABLE_MODELS = new Set([
"fable",
]);
+/**
+ * Lookups per table, by raw model name. A scan prices every record twice
+ * against a few dozen models, and tables are never mutated once built.
+ */
+const resolvedRates = new WeakMap<RateTable, Map<string, ModelRate | null>>();
+
export function lookupRate(table: RateTable, model: string): ModelRate | null {
+ let resolved = resolvedRates.get(table);
+ if (resolved === undefined) {
+ resolved = new Map();
+ resolvedRates.set(table, resolved);
+ }
+ let rate = resolved.get(model);
+ if (rate === undefined) {
+ rate = resolveRate(table, model);
+ resolved.set(model, rate);
+ }
+ return rate;
+}
+
+function resolveRate(table: RateTable, model: string): ModelRate | null {
const key = stripVariantSuffix(normalizeRateKey(model));
const bareName = bareModelName(key);
if (bareName.length === 0 || UNPRICEABLE_MODELS.has(bareName)) return null;
diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts
index 82ff1e36dfc..b59768cf892 100644
--- a/apps/server/src/usage/usageScanCache.test.ts
+++ b/apps/server/src/usage/usageScanCache.test.ts
@@ -4,6 +4,7 @@ import {
decodeScanCache,
dedupeWithinFile,
encodeScanCache,
+ makeScanCacheWriter,
pruneScanCache,
type CachedFile,
type ScanCache,
@@ -149,6 +150,26 @@ describe("scan cache round trip", () => {
expect(decodeScanCache(JSON.parse(JSON.stringify(previous))).size).toBe(0);
});
+ it("rewrites only changed entries and still restores the whole cache", () => {
+ const write = makeScanCacheWriter();
+ const cache = cacheWith([
+ ["/a.jsonl", 100, [record()]],
+ ["/b.jsonl", 200, [record({ sessionId: "session-b" })]],
+ ]);
+ const sources = { "claude\u0000/projects": { dir: "/projects", volumeId: "1:2" } };
+ expect(decodeScanCache(JSON.parse(write(cache, { sources })))).toEqual(cache);
+
+ // The replacement adds intern entries; /a's memoised indexes must hold.
+ cache.set("/b.jsonl", {
+ ...cache.get("/b.jsonl")!,
+ size: 30,
+ records: [record({ sessionId: "session-c", model: "claude-opus-5-5", dedupeKey: "msg_3:" })],
+ });
+ const document = JSON.parse(write(cache, { sources }));
+ expect(decodeScanCache(document)).toEqual(cache);
+ expect(document.sources).toEqual(sources);
+ });
+
it("interns repeated model and session strings", () => {
const encoded = encodeScanCache(
cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" }), record()]]]),
diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts
index 3c6826a6798..04e7ab4ce98 100644
--- a/apps/server/src/usage/usageScanCache.ts
+++ b/apps/server/src/usage/usageScanCache.ts
@@ -103,26 +103,32 @@ interface SerializedCache {
readonly files: Readonly<Record<string, SerializedFile>>;
}
-/** Serialises the cache, interning the repeated model and session strings. */
-export function encodeScanCache(cache: ScanCache): SerializedCache {
- const models: string[] = [];
- const sessions: string[] = [];
- const modelIndex = new Map<string, number>();
- const sessionIndex = new Map<string, number>();
+/** Model and session strings, each stored once and referenced by index. */
+interface InternTables {
+ readonly models: string[];
+ readonly sessions: string[];
+ readonly modelIndex: Map<string, number>;
+ readonly sessionIndex: Map<string, number>;
+}
- const intern = (table: string[], index: Map<string, number>, value: string): number => {
- const existing = index.get(value);
- if (existing !== undefined) return existing;
- const next = table.length;
- table.push(value);
- index.set(value, next);
- return next;
- };
+function makeInternTables(): InternTables {
+ return { models: [], sessions: [], modelIndex: new Map(), sessionIndex: new Map() };
+}
+
+function intern(table: string[], index: Map<string, number>, value: string): number {
+ const existing = index.get(value);
+ if (existing !== undefined) return existing;
+ const next = table.length;
+ table.push(value);
+ index.set(value, next);
+ return next;
+}
+function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile {
const serializeRecord = (record: UsageRecord): SerializedRecord => [
record.timestampMs,
- intern(models, modelIndex, record.model),
- intern(sessions, sessionIndex, record.sessionId),
+ intern(tables.models, tables.modelIndex, record.model),
+ intern(tables.sessions, tables.sessionIndex, record.sessionId),
record.totals.uncachedInputTokens,
record.totals.cachedInputTokens,
record.totals.cacheCreationTokens,
@@ -132,23 +138,68 @@ export function encodeScanCache(cache: ScanCache): SerializedCache {
record.reportedCostUsd,
SPEEDS.indexOf(record.speed),
];
+ return {
+ s: entry.size,
+ m: entry.mtimeMs,
+ p: entry.provider,
+ 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,
+ };
+}
+/** Serialises the cache, interning the repeated model and session strings. */
+export function encodeScanCache(cache: ScanCache): SerializedCache {
+ const tables = makeInternTables();
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(serializeRecord),
- t: entry.tailRecords.map(serializeRecord),
- o: entry.position.resumeOffset,
- gl: entry.position.guardLength,
- gh: entry.position.guardHash,
- cs: entry.position.codexState,
- };
- }
+ for (const [path, entry] of cache) files[path] = serializeFile(entry, tables);
+ return {
+ version: USAGE_SCAN_CACHE_VERSION,
+ models: tables.models,
+ sessions: tables.sessions,
+ files,
+ };
+}
- return { version: USAGE_SCAN_CACHE_VERSION, models, sessions, files };
+/**
+ * Returns a function that serialises the cache to JSON text, re-encoding only
+ * the entries that changed since its last call. Call it once per persist.
+ *
+ * Writes the same document as `encodeScanCache`. Most entries never change
+ * between scans, and encoding all of them made each persist cost close to a
+ * second on a large cache. Entries are replaced, never mutated, when their file
+ * changes, so an entry's JSON is memoised by identity. The intern tables only
+ * grow, so a memoised entry's indexes stay valid; a pruned entry can leave an
+ * unused string behind until the next process start.
+ */
+export function makeScanCacheWriter(): (
+ cache: ScanCache,
+ extra: Readonly<Record<string, unknown>>,
+) => string {
+ const tables = makeInternTables();
+ const fragments = new WeakMap<CachedFile, string>();
+ return (cache, extra) => {
+ const files: string[] = [];
+ for (const [path, entry] of cache) {
+ let fragment = fragments.get(entry);
+ if (fragment === undefined) {
+ fragment = JSON.stringify(serializeFile(entry, tables));
+ fragments.set(entry, fragment);
+ }
+ files.push(`${JSON.stringify(path)}:${fragment}`);
+ }
+ // Encoded after the files, which may have added to the intern tables.
+ const head = JSON.stringify({
+ ...extra,
+ version: USAGE_SCAN_CACHE_VERSION,
+ models: tables.models,
+ sessions: tables.sessions,
+ });
+ return `${head.slice(0, -1)},"files":{${files.join(",")}}}`;
+ };
}
function isRecordArray(value: unknown): value is readonly unknown[] {
diff --git a/apps/server/src/usage/usageTranscriptReader.ts b/apps/server/src/usage/usageTranscriptReader.ts
index 4d170237568..bca22468a95 100644
--- a/apps/server/src/usage/usageTranscriptReader.ts
+++ b/apps/server/src/usage/usageTranscriptReader.ts
@@ -85,6 +85,8 @@ export const GUARD_LENGTH = 64;
// readers; it never discards a record because of its size.
const STREAMING_THRESHOLD_BYTES = 8 * 1024 * 1024;
const NEWLINE = 0x0a;
+/** `stat` calls one transcript walk keeps in flight. The libuv pool has 4 threads. */
+const STAT_CONCURRENCY = 32;
const CARRIAGE_RETURN = 0x0d;
type SelectedFields = { readonly [key: string]: true | SelectedFields };
@@ -156,15 +158,19 @@ function fnv1a(buffer: Buffer): number {
* `fileName` restricts the walk to a single basename (Grok's `updates.jsonl`).
* Grok sessions also ship multi-megabyte `chat_history` and `events` logs that
* never carry usage, so the basename filter keeps a cold scan off those files.
+ *
+ * Directories are listed depth-first, one at a time, then the candidates are
+ * stat'd by a fixed pool of workers: a warm scan stats thousands of files, and
+ * one at a time each waits its own trip through the thread pool. Results keep
+ * `readdir` order, which the aggregator's first-seen dedupe relies on.
*/
export async function listTranscriptFiles(
root: string,
sinceMs: number,
options?: { readonly fileName?: string },
): Promise<readonly TranscriptFile[]> {
- const found: TranscriptFile[] = [];
const fileName = options?.fileName;
-
+ const candidates: string[] = [];
const walk = async (dir: string): Promise<void> => {
let entries;
try {
@@ -174,28 +180,33 @@ export async function listTranscriptFiles(
}
for (const entry of entries) {
const child = NodePath.join(dir, entry.name);
- if (entry.isDirectory()) {
- await walk(child);
- continue;
- }
- if (fileName !== undefined) {
- if (entry.name !== fileName) continue;
- } else if (!entry.name.endsWith(".jsonl")) {
- continue;
+ if (entry.isDirectory()) await walk(child);
+ else if (fileName !== undefined ? entry.name === fileName : entry.name.endsWith(".jsonl")) {
+ candidates.push(child);
}
+ }
+ };
+ await walk(root);
+
+ const found: Array<TranscriptFile | undefined> = Array.from({ length: candidates.length });
+ // Each worker pulls the next candidate from one shared iterator.
+ const queue = candidates.entries();
+ const statQueued = async (): Promise<void> => {
+ for (const [index, path] of queue) {
try {
- const stats = await NodeFSP.stat(child);
+ const stats = await NodeFSP.stat(path);
if (stats.mtimeMs >= sinceMs) {
- found.push({ path: child, size: stats.size, mtimeMs: stats.mtimeMs });
+ found[index] = { path, size: stats.size, mtimeMs: stats.mtimeMs };
}
} catch {
// Vanished between readdir and stat.
}
}
};
-
- await walk(root);
- return found;
+ await Promise.all(
+ Array.from({ length: Math.min(STAT_CONCURRENCY, candidates.length) }, statQueued),
+ );
+ return found.filter((file) => file !== undefined);
}
/**
diff --git a/apps/server/src/usage/usageTranscripts.ts b/apps/server/src/usage/usageTranscripts.ts
index eb32e664f43..451f8a726b3 100644
--- a/apps/server/src/usage/usageTranscripts.ts
+++ b/apps/server/src/usage/usageTranscripts.ts
@@ -54,16 +54,6 @@ function parseTimestampMs(value: unknown): number | null {
return Number.isNaN(parsed) ? null : parsed;
}
-export function addTotals(a: UsageTokenTotals, b: UsageTokenTotals): UsageTokenTotals {
- return {
- uncachedInputTokens: a.uncachedInputTokens + b.uncachedInputTokens,
- cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,
- cacheCreationTokens: a.cacheCreationTokens + b.cacheCreationTokens,
- outputTokens: a.outputTokens + b.outputTokens,
- reasoningTokens: a.reasoningTokens + b.reasoningTokens,
- };
-}
-
export function totalTokens(totals: UsageTokenTotals): number {
// reasoningTokens is a subset of outputTokens and must not be added again.
return (