TypeScript
fix(usage): count compressed Codex rollouts (#25453)
maria3121c19a1b68
diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.tsindex 33f2332dbd4..9600f0a45ad 100644--- a/apps/server/src/usage/UsageService.test.ts+++ b/apps/server/src/usage/UsageService.test.ts@@ -5,6 +5,7 @@ import * as NodeFSP from "node:fs/promises";import * as NodeOS from "node:os";import * as NodePath from "node:path";import * as NodeSqlite from "node:sqlite";+import * as NodeZlib from "node:zlib";import { assert, describe, it } from "@effect/vitest";import { vi } from "vite-plus/test";@@ -467,6 +468,73 @@ describe("Codex usage history", () => {});describe("UsageService", () => {+ it.live("counts compressed Codex rollouts across refresh, rewrites, and cache restarts", () =>+ Effect.gen(function* () {+ const { home, settings } = yield* setup;+ const sessions = NodePath.join(home, "codex", "sessions");+ const compressedPath = NodePath.join(sessions, "compressed.jsonl.zst");+ const usage = (output_tokens: number, timestamp = "2026-08-01T10:00:00Z") =>+ encodeUnknownJsonString({+ type: "event_msg",+ timestamp,+ payload: {+ type: "token_count",+ info: { last_token_usage: { input_tokens: 10, output_tokens } },+ },+ }) + "\n";+ const rollout = (id: string, output: number) =>+ [+ { type: "session_meta", payload: { id } },+ { type: "turn_context", payload: { model: "gpt-6-astra" } },+ ]+ .map((line) => encodeUnknownJsonString(line))+ .join("\n") ++ "\n" ++ usage(output);+ const compressed = rollout("compressed-session", 23);+ yield* Effect.promise(async () => {+ await NodeFSP.mkdir(sessions, { recursive: true });+ await NodeFSP.writeFile(+ NodePath.join(sessions, "plain.jsonl"),+ rollout("plain-session", 17),+ );+ await NodeFSP.writeFile(compressedPath, NodeZlib.zstdCompressSync(compressed));+ });+ yield* Effect.gen(function* () {+ const service = yield* UsageService.make;+ const first = yield* service.readSummary(WINDOW);+ assert.strictEqual(totalOutputTokens(first), 40);+ assert.strictEqual(+ first.sources.find((source) => source.fingerprint.provider === "codex")?.distinctSessions,+ 2,+ );+ assert.deepStrictEqual((yield* service.readSummary(WINDOW)).buckets, first.buckets);+ yield* service.awaitPersisted;+ // The same rollout may remain in a plain file while compression finishes.+ yield* Effect.promise(() =>+ NodeFSP.writeFile(NodePath.join(sessions, "copy.jsonl"), compressed),+ );+ assert.strictEqual(totalOutputTokens(yield* service.readSummary(WINDOW)), 40);+ yield* Effect.promise(() =>+ NodeFSP.writeFile(+ compressedPath,+ NodeZlib.zstdCompressSync(compressed + usage(31, "2026-08-01T10:00:05Z")),+ ),+ );+ const rewritten = yield* service.readSummary(WINDOW);+ assert.strictEqual(totalOutputTokens(rewritten), 71);+ assert.deepStrictEqual((yield* service.readSummary(WINDOW)).buckets, rewritten.buckets);+ yield* service.awaitPersisted;+ const restarted = yield* UsageService.make;+ assert.deepStrictEqual((yield* restarted.readSummary(WINDOW)).buckets, rewritten.buckets);+ yield* restarted.awaitPersisted;+ }).pipe(+ Effect.scoped,+ Effect.provide(layerService({ prefix: "usage-compressed-codex", home, settings })),+ );+ }).pipe(Effect.scoped),+ );+it.live("keeps the first host identity across recreation and explicit override removal", () =>Effect.gen(function* () {const { transcript, settings, home } = yield* setup;diff --git a/apps/server/src/usage/usageTranscriptReader.test.ts b/apps/server/src/usage/usageTranscriptReader.test.tsindex e7fa7067916..f2b4fb43b48 100644--- a/apps/server/src/usage/usageTranscriptReader.test.ts+++ b/apps/server/src/usage/usageTranscriptReader.test.ts@@ -4,13 +4,18 @@import * as NodeFSP from "node:fs/promises";import * as NodeOS from "node:os";import * as NodePath from "node:path";+import * as NodeZlib from "node:zlib";import { afterEach, assert, beforeEach, describe, it } from "@effect/vitest";import type { TranscriptUsageFormat } from "@t3tools/provider-core/server/usage";import * as Schema from "effect/Schema";import { TEST_FORMATS } from "./usageTestFormats.ts";-import { readTranscriptRecords, transcriptLineGate } from "./usageTranscriptReader.ts";+import {+ listTranscriptFiles,+ readTranscriptRecords,+ transcriptLineGate,+} from "./usageTranscriptReader.ts";let dir: string;@@ -71,6 +76,103 @@ function codexUsageLine(outputTokens: number, secondsOffset: number): string {})}\n`;}+describe("compressed transcripts", () => {+ it("discovers nested plain and zstd JSONL files within the requested window", async () => {+ const nested = NodePath.join(dir, "nested");+ await NodeFSP.mkdir(nested);+ const plain = NodePath.join(dir, "active.jsonl");+ const compressed = NodePath.join(nested, "archived.jsonl.zst");+ const old = NodePath.join(nested, "old.jsonl.zst");+ await NodeFSP.writeFile(plain, claudeLine(1, 5));+ await NodeFSP.writeFile(compressed, NodeZlib.zstdCompressSync(claudeLine(2, 7)));+ await NodeFSP.writeFile(old, NodeZlib.zstdCompressSync(claudeLine(3, 11)));+ await NodeFSP.writeFile(NodePath.join(nested, "unrelated.zst"), "ignored");+ await NodeFSP.writeFile(NodePath.join(nested, "partial.jsonl.zst.tmp"), "ignored");+ await NodeFSP.utimes(old, 1, 1);++ const listed = await listTranscriptFiles(dir, Date.parse("2026-01-01T00:00:00Z"));+ assert.deepStrictEqual(+ listed.files.map((file) => file.path).sort(),+ [plain, compressed].sort(),+ );+ assert.strictEqual(listed.failedPaths, 0);+ assert.isAbove(listed.files.find((file) => file.path === compressed)?.size ?? 0, 0);+ });++ it.each([+ { parser: "native", streamingThresholdBytes: undefined },+ { parser: "projected", streamingThresholdBytes: 1024 },+ ])(+ "matches plain Codex records and unfinished tails through long lines ($parser)",+ async ({ streamingThresholdBytes }) => {+ const plain = NodePath.join(dir, "rollout.jsonl");+ const compressed = plain + ".zst";+ const large = codexUsageLine(9, 5).replace(+ '"payload":',+ '"padding":' + JSON.stringify("日本語 é".repeat(128 * 1024)) + ',"payload":',+ );+ const content =+ codexMetaLine() ++ codexModelLine("gpt-6-astra") ++ codexTierLine("ultrafast") ++ large ++ codexUsageLine(13, 6).replace('"output_tokens":13', '"output_tokens":"invalid"') ++ codexUsageLine(21, 8).trimEnd();+ await NodeFSP.writeFile(plain, content);+ await NodeFSP.writeFile(compressed, NodeZlib.zstdCompressSync(content));++ const options =+ streamingThresholdBytes === undefined ? undefined : { streamingThresholdBytes };+ const expected = await readTranscriptRecords(plain, TEST_FORMATS.codex, undefined, options);+ const actual = await readTranscriptRecords(+ compressed,+ TEST_FORMATS.codex,+ undefined,+ options,+ );+ assert.isNotNull(expected);+ assert.isNotNull(actual);+ assert.strictEqual(expected.records.length, 1);+ assert.strictEqual(expected.tailRecords.length, 1);+ assert.deepStrictEqual(actual.records, expected.records);+ assert.deepStrictEqual(actual.tailRecords, expected.tailRecords);+ assert.strictEqual(expected.malformedRecords, 1);+ assert.strictEqual(actual.malformedRecords, expected.malformedRecords);+ assert.strictEqual(actual.records[0]?.speed, "ultrafast");+ assert.isFalse(actual.resumed);+ assert.strictEqual(actual.position.resumeOffset, 0);+ },+ );++ it("ignores a prior resume position and rereads compressed rollouts from their start", async () => {+ const plain = NodePath.join(dir, "rollout.jsonl");+ const content = codexMetaLine() + codexModelLine("gpt-6-astra") + codexUsageLine(9, 5);+ await NodeFSP.writeFile(plain, content);+ const first = await readTranscriptRecords(plain, TEST_FORMATS.codex);+ assert.isNotNull(first);++ const compressed = plain + ".zst";+ await NodeFSP.writeFile(compressed, NodeZlib.zstdCompressSync(content + codexUsageLine(21, 8)));+ const actual = await readTranscriptRecords(compressed, TEST_FORMATS.codex, first.position);+ assert.isNotNull(actual);+ assert.isFalse(actual.resumed);+ assert.deepStrictEqual(+ actual.records.map((record) => record.totals.outputTokens),+ [9, 21],+ );+ const repeated = await readTranscriptRecords(compressed, TEST_FORMATS.codex, actual.position);+ assert.isNotNull(repeated);+ assert.isFalse(repeated.resumed);+ assert.deepStrictEqual(repeated.records, actual.records);+ });++ it("returns null for zstd decoder errors rather than caching an empty parse", async () => {+ const path = NodePath.join(dir, "corrupt.jsonl.zst");+ await NodeFSP.writeFile(path, "not a zstd frame");+ assert.isNull(await readTranscriptRecords(path, TEST_FORMATS.claude));+ });+});+describe("readTranscriptRecords resume", () => {it.each([{ mode: "buffered", streamingThresholdBytes: Infinity },diff --git a/apps/server/src/usage/usageTranscriptReader.ts b/apps/server/src/usage/usageTranscriptReader.tsindex 4f131f310f4..38b80d36c86 100644--- a/apps/server/src/usage/usageTranscriptReader.ts+++ b/apps/server/src/usage/usageTranscriptReader.ts@@ -3,6 +3,7 @@import * as NodeFSP from "node:fs/promises";import * as NodePath from "node:path";import * as NodeStringDecoder from "node:string_decoder";+import * as NodeZlib from "node:zlib";import type {SelectedFields,@@ -85,7 +86,11 @@ export async function listTranscriptFiles(for (const entry of entries) {const child = NodePath.join(dir, entry.name);if (entry.isDirectory()) await walk(child);- else if (fileName !== undefined ? entry.name === fileName : entry.name.endsWith(".jsonl")) {+ else if (+ fileName !== undefined+ ? entry.name === fileName+ : entry.name.endsWith(".jsonl") || entry.name.endsWith(".jsonl.zst")+ ) {candidates.push(child);}}@@ -162,6 +167,7 @@ export async function readTranscriptRecords<State>(options?: { readonly streamingThresholdBytes?: number },): Promise<TranscriptParseResult | null> {const streamingThresholdBytes = options?.streamingThresholdBytes ?? STREAMING_THRESHOLD_BYTES;+ const compressed = filePath.endsWith(".jsonl.zst");let handle: NodeFSP.FileHandle;try {handle = await NodeFSP.open(filePath, "r");@@ -181,6 +187,7 @@ export async function readTranscriptRecords<State>(? Option.none(): decodeState(resumeFrom.state);if (+ !compressed &&resumeFrom !== undefined &&resumeFrom.resumeOffset > 0 &&(codec === undefined || Option.isSome(savedState)) &&@@ -247,11 +254,14 @@ export async function readTranscriptRecords<State>(streaming = undefined;decoder = undefined;};- const stream = handle.createReadStream({+ const input = handle.createReadStream({start,- autoClose: false,+ autoClose: compressed,highWaterMark: 256 * 1024,- }) as AsyncIterable<Buffer>;+ });+ // Compressed snapshots cache a full parse; decoded byte offsets cannot+ // resume the compressed input.+ const stream = compressed ? input.compose(NodeZlib.createZstdDecompress()) : input;for await (const chunk of stream) {let lineStart = 0;while (lineStart < chunk.length) {@@ -279,7 +289,7 @@ export async function readTranscriptRecords<State>(decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState));finish(tailState, tailRecords);- const guardLength = Math.min(GUARD_LENGTH, resumeOffset);+ const guardLength = compressed ? 0 : Math.min(GUARD_LENGTH, resumeOffset);let guardHash = 0;if (guardLength > 0) {const window = Buffer.alloc(guardLength);@@ -292,7 +302,7 @@ export async function readTranscriptRecords<State>(tailRecords,malformedRecords: format.readMalformedRecords?.(tailState) ?? 0,position: {- resumeOffset,+ resumeOffset: compressed ? 0 : resumeOffset,guardLength,guardHash,state: encodedState,