Skip to content
TypeScript

fix(usage): reconcile Codex request and cumulative counters (#21863)

Julius Marminge38b8c204a6a5
diff --git a/apps/server/src/provider/Drivers/codexUsage.test.ts b/apps/server/src/provider/Drivers/codexUsage.test.ts
index 4136aba3f36..f60c3938948 100644
--- a/apps/server/src/provider/Drivers/codexUsage.test.ts
+++ b/apps/server/src/provider/Drivers/codexUsage.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "@effect/vitest";
-import { initialCodexScanState, parseCodexLine } from "./codexUsage.ts";
+import { codexUsageFormat, initialCodexScanState, parseCodexLine } from "./codexUsage.ts";
describe("parseCodexLine", () => {
const sessionMeta = JSON.stringify({
@@ -30,6 +30,23 @@ describe("parseCodexLine", () => {
},
},
});
+ const counters = (input: number, output: number) => ({
+ input_tokens: input,
+ cached_input_tokens: 0,
+ cache_write_input_tokens: 0,
+ output_tokens: output,
+ reasoning_output_tokens: 0,
+ total_tokens: input + output,
+ });
+ const counted = (last: unknown, total?: unknown, extra = {}) =>
+ JSON.stringify({
+ type: "event_msg",
+ timestamp: "2026-08-01T05:17:49.919Z",
+ payload: {
+ type: "token_count",
+ info: { last_token_usage: last, total_token_usage: total, ...extra },
+ },
+ });
it("attributes usage to the model from the preceding turn context", () => {
const state = initialCodexScanState();
@@ -60,11 +77,158 @@ describe("parseCodexLine", () => {
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
});
- it("does not let a pre-model event poison the duplicate signature", () => {
+ it("does not consume counters before the model and timestamp are valid", () => {
const state = initialCodexScanState();
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
parseCodexLine(turnContext, state);
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull();
+
+ const cumulativeState = initialCodexScanState();
+ const line = counted(counters(100, 20), counters(100, 20));
+ expect(parseCodexLine(line, cumulativeState)).toBeNull();
+ parseCodexLine(turnContext, cumulativeState);
+ expect(
+ parseCodexLine(line.replace("2026-08-01T05:17:49.919Z", "invalid"), cumulativeState),
+ ).toBeNull();
+ expect(parseCodexLine(line, cumulativeState)?.totals.outputTokens).toBe(20);
+ expect(codexUsageFormat.readMalformedRecords?.(cumulativeState)).toBe(0);
+ });
+
+ it("ignores stale changed requests but counts equal requests when totals advance across contexts", () => {
+ const state = initialCodexScanState();
+ parseCodexLine(turnContext, state);
+ const request = counters(100, 20);
+ expect(parseCodexLine(counted(request, request), state)?.totals.outputTokens).toBe(20);
+ expect(parseCodexLine(counted(counters(20, 5), request), state)).toBeNull();
+ expect(
+ parseCodexLine(
+ counted({ ...counters(0, 0), total_tokens: 20330 }, request, {
+ model_context_window: 258400,
+ }),
+ state,
+ ),
+ ).toBeNull();
+ expect(parseCodexLine(counted(request, counters(200, 40)), state)?.totals.outputTokens).toBe(
+ 20,
+ );
+
+ for (const [index, tier] of ["priority", "ultrafast"].entries()) {
+ parseCodexLine(
+ JSON.stringify({ type: "turn_context", payload: { model: "gpt-6-astra" } }),
+ state,
+ );
+ parseCodexLine(
+ JSON.stringify({
+ type: "event_msg",
+ payload: { type: "thread_settings_applied", thread_settings: { service_tier: tier } },
+ }),
+ state,
+ );
+ const record = parseCodexLine(
+ counted(request, counters(100 * (index + 3), 20 * (index + 3))),
+ state,
+ );
+ expect(record).toMatchObject({
+ model: "gpt-6-astra",
+ speed: tier === "priority" ? "fast" : "ultrafast",
+ totals: { uncachedInputTokens: 100, outputTokens: 20 },
+ });
+ }
+ expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
+ });
+
+ it.each([false, true])(
+ "does not rebill legacy requests or drop the next cumulative delta (initial cumulative=%s)",
+ (initialCumulative) => {
+ const state = initialCodexScanState();
+ parseCodexLine(turnContext, state);
+ const first = counters(100, 20);
+ expect(
+ parseCodexLine(counted(first, initialCumulative ? first : undefined), state)?.totals
+ .outputTokens,
+ ).toBe(20);
+ expect(parseCodexLine(counted(first), state)).toBeNull();
+ expect(parseCodexLine(counted(counters(20, 5)), state)?.totals.outputTokens).toBe(5);
+ expect(parseCodexLine(counted(counters(20, 5), counters(120, 25)), state)).toBeNull();
+ expect(
+ parseCodexLine(counted(counters(10, 2), counters(130, 27)), state)?.totals.outputTokens,
+ ).toBe(2);
+ expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
+ },
+ );
+
+ it("checks every cumulative component and recovers using an inconsistent pair's valid baseline", () => {
+ const request = {
+ ...counters(100, 20),
+ cached_input_tokens: 30,
+ cache_write_input_tokens: 10,
+ reasoning_output_tokens: 5,
+ };
+ const fields = Object.keys(request) as (keyof typeof request)[];
+ for (const field of fields) {
+ const state = initialCodexScanState();
+ parseCodexLine(turnContext, state);
+ expect(parseCodexLine(counted(request, request), state)?.totals).toEqual({
+ uncachedInputTokens: 60,
+ cachedInputTokens: 30,
+ cacheCreationTokens: 10,
+ outputTokens: 20,
+ reasoningTokens: 5,
+ });
+ const total = { ...request };
+ for (const key of fields) total[key] *= 2;
+ total[field] += 1;
+ if (field === "input_tokens" || field === "output_tokens") total.total_tokens += 1;
+ expect(parseCodexLine(counted(request, total), state), field).toBeNull();
+ expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1);
+ for (const key of fields) total[key] += request[key];
+ expect(parseCodexLine(counted(request, total), state)?.totals.outputTokens, field).toBe(20);
+ expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1);
+ }
+ });
+
+ it.each(["request", "cumulative"])("skips malformed %s counters and recovers", (malformed) => {
+ const state = initialCodexScanState();
+ parseCodexLine(turnContext, state);
+ const request = counters(100, 20);
+ parseCodexLine(counted(request, request), state);
+ expect(
+ parseCodexLine(
+ counted(
+ malformed === "request" ? { ...request, cached_input_tokens: -1 } : request,
+ malformed === "cumulative"
+ ? { ...counters(200, 40), output_tokens: "40" }
+ : counters(200, 40),
+ ),
+ state,
+ ),
+ ).toBeNull();
+ expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1);
+ expect(
+ parseCodexLine(
+ counted(request, malformed === "request" ? counters(300, 60) : counters(200, 40)),
+ state,
+ )?.totals.outputTokens,
+ ).toBe(20);
+ expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1);
+ });
+
+ it("does not bill a context-window estimate or lose the following real request", () => {
+ const state = initialCodexScanState();
+ parseCodexLine(turnContext, state);
+ parseCodexLine(counted(counters(100, 20), counters(100, 20)), state);
+ const estimate = { ...counters(0, 0), total_tokens: 1000 };
+ expect(
+ parseCodexLine(
+ counted({ ...estimate, total_tokens: 880 }, estimate, { model_context_window: 1000 }),
+ state,
+ ),
+ ).toBeNull();
+ expect(
+ parseCodexLine(counted(counters(10, 2), { ...counters(10, 2), total_tokens: 1012 }), state)
+ ?.totals.outputTokens,
+ ).toBe(2);
+ expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
});
it("carries the service tier from the latest thread settings", () => {
@@ -139,24 +303,32 @@ describe("parseCodexLine", () => {
parseCodexLine(stamped(forkInstant, turnContext), state);
expect(
- parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
+ parseCodexLine(
+ stamped("2026-08-01T05:00:00.001Z", counted(counters(100, 10), counters(100, 10))),
+ state,
+ ),
).toBeNull();
expect(
- parseCodexLine(stamped("2026-08-01T05:00:00.002Z", tokenCount(200, 0, 20, 0)), state),
+ parseCodexLine(
+ stamped("2026-08-01T05:00:00.002Z", counted(counters(200, 20), counters(300, 30))),
+ state,
+ ),
).toBeNull();
const real = parseCodexLine(
- stamped("2026-08-01T05:00:06.000Z", tokenCount(300, 0, 30, 0)),
+ stamped("2026-08-01T05:00:06.000Z", counted(counters(200, 20), counters(500, 50))),
state,
);
expect(real).not.toBeNull();
- expect(real?.totals.outputTokens).toBe(30);
+ expect(real?.sessionId).toBe("child");
+ expect(real?.totals.outputTokens).toBe(20);
const next = parseCodexLine(
- stamped("2026-08-01T05:00:06.100Z", tokenCount(400, 0, 40, 0)),
+ stamped("2026-08-01T05:00:06.100Z", counted(counters(400, 40), counters(900, 90))),
state,
);
expect(next).not.toBeNull();
+ expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
});
it("recognizes subagent spawns without forked_from_id", () => {
diff --git a/apps/server/src/provider/Drivers/codexUsage.ts b/apps/server/src/provider/Drivers/codexUsage.ts
index b737f19a6c8..2cff9eaa0a0 100644
--- a/apps/server/src/provider/Drivers/codexUsage.ts
+++ b/apps/server/src/provider/Drivers/codexUsage.ts
@@ -5,7 +5,6 @@ import * as Schema from "effect/Schema";
import {
parseTimestampMs,
- tokenCount,
totalTokens,
type ProviderUsageReader,
type TranscriptUsageFormat,
@@ -16,6 +15,51 @@ import type { UsageTokenTotals } from "@t3tools/contracts";
import { resolveCodexHomeLayout } from "./CodexHomeLayout.ts";
+const TokenCount = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
+const CodexTokenUsage = Schema.Struct({
+ input_tokens: TokenCount,
+ cached_input_tokens: TokenCount,
+ cache_write_input_tokens: TokenCount,
+ output_tokens: TokenCount,
+ reasoning_output_tokens: TokenCount,
+ total_tokens: TokenCount,
+}).check(
+ Schema.makeFilter(
+ (usage) =>
+ usage.cached_input_tokens + usage.cache_write_input_tokens <= usage.input_tokens &&
+ usage.reasoning_output_tokens <= usage.output_tokens &&
+ usage.total_tokens >= usage.input_tokens + usage.output_tokens,
+ ),
+);
+type CodexTokenUsage = typeof CodexTokenUsage.Type;
+const isCodexTokenUsage = Schema.is(CodexTokenUsage);
+const CODEX_USAGE_FIELDS = Object.keys(CodexTokenUsage.fields) as (keyof CodexTokenUsage)[];
+
+function readCodexTokenUsage(value: unknown): CodexTokenUsage | null {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
+ const raw = value as Record<string, unknown>;
+ const input = raw["input_tokens"];
+ const output = raw["output_tokens"];
+ if (typeof input !== "number" || typeof output !== "number") return null;
+ const usage = {
+ input_tokens: input,
+ cached_input_tokens: raw["cached_input_tokens"] === undefined ? 0 : raw["cached_input_tokens"],
+ cache_write_input_tokens:
+ raw["cache_write_input_tokens"] === undefined ? 0 : raw["cache_write_input_tokens"],
+ output_tokens: output,
+ reasoning_output_tokens:
+ raw["reasoning_output_tokens"] === undefined ? 0 : raw["reasoning_output_tokens"],
+ total_tokens: raw["total_tokens"] === undefined ? input + output : raw["total_tokens"],
+ };
+ return isCodexTokenUsage(usage) ? usage : null;
+}
+
+function advanceCodexUsage(previous: CodexTokenUsage | null, last: CodexTokenUsage) {
+ return readCodexTokenUsage(
+ Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, (previous?.[key] ?? 0) + last[key]])),
+ );
+}
+
/**
* Codex `token_count` events carry no model or service tier, so both are carried forward: the model
* from the most recent `turn_context`, the tier from the most recent `thread_settings_applied`.
@@ -25,6 +69,8 @@ export const CodexScanState = Schema.Struct({
speed: Schema.mutableKey(Schema.Literals(["standard", "fast", "ultrafast"])),
sessionId: Schema.mutableKey(Schema.String),
lastUsageSignature: Schema.mutableKey(Schema.NullOr(Schema.String)),
+ lastCumulativeUsage: Schema.mutableKey(Schema.NullOr(CodexTokenUsage)),
+ malformedRecords: Schema.mutableKey(TokenCount),
sawSessionMeta: Schema.mutableKey(Schema.Boolean),
suppressingForkCopies: Schema.mutableKey(Schema.Boolean),
forkCopyAnchorMs: Schema.mutableKey(Schema.Finite),
@@ -37,6 +83,8 @@ export function initialCodexScanState(): CodexScanState {
speed: "standard",
sessionId: "",
lastUsageSignature: null,
+ lastCumulativeUsage: null,
+ malformedRecords: 0,
sawSessionMeta: false,
suppressingForkCopies: false,
forkCopyAnchorMs: 0,
@@ -63,8 +111,8 @@ function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
}
/**
- * Deltas come from `last_token_usage`. Summing those across a session reconciles with the session's
- * final `total_token_usage`, provided consecutive duplicate events are dropped, which this does.
+ * Cumulative counters validate request deltas. Older events without cumulative counters use
+ * normalized consecutive-request deduplication.
*/
export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null {
let parsed: unknown;
@@ -118,45 +166,98 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord |
const info = payloadRecord["info"];
if (typeof info !== "object" || info === null) return null;
- const last = (info as Record<string, unknown>)["last_token_usage"];
- if (typeof last !== "object" || last === null) return null;
- const lastRecord = last as Record<string, unknown>;
-
- // Only an event that is otherwise eligible may consume the duplicate
- // signature. A token_count arriving before its turn_context (no model yet)
- // must not poison it, or the re-emitted copy after the model is known would
- // be skipped as a duplicate and those tokens never counted.
+ const infoRecord = info as Record<string, unknown>;
+
+ // Codex may re-emit these counters after the model or timestamp becomes available.
const timestampMs = parseTimestampMs(record["timestamp"]);
- if (timestampMs === null) return null;
- if (state.model.length === 0) return null;
+ if (timestampMs === null || state.model.length === 0) return null;
- // Codex re-emits an unchanged token_count on some stream boundaries. Summing
- // those would double count, so identical consecutive payloads are skipped.
- const signature = JSON.stringify(lastRecord);
- if (signature === state.lastUsageSignature) return null;
- state.lastUsageSignature = signature;
+ const last = readCodexTokenUsage(infoRecord["last_token_usage"]);
+ const rawCumulative = infoRecord["total_token_usage"];
+ const hasCumulative = rawCumulative !== undefined && rawCumulative !== null;
+ const cumulative = hasCumulative ? readCodexTokenUsage(rawCumulative) : null;
if (state.suppressingForkCopies) {
if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
state.forkCopyAnchorMs = timestampMs;
+ // Copied history is already billed in the parent, but establishes the child's baseline.
+ const signature = last === null ? null : JSON.stringify(last);
+ if (cumulative !== null) state.lastCumulativeUsage = cumulative;
+ else if (!hasCumulative && last !== null && signature !== state.lastUsageSignature) {
+ state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, last);
+ }
+ state.lastUsageSignature = signature;
return null;
}
state.suppressingForkCopies = false;
+ state.lastUsageSignature = null;
+ }
+
+ const previous = state.lastCumulativeUsage;
+ // A valid snapshot remains the next baseline even when its paired request is malformed.
+ if (cumulative !== null) state.lastCumulativeUsage = cumulative;
+ if (last === null || (hasCumulative && cumulative === null)) {
+ state.malformedRecords += 1;
+ return null;
+ }
+
+ // fill_to_context_window uses zero components and synthetic totals, then offsets future totals.
+ if (
+ cumulative !== null &&
+ last.input_tokens + last.output_tokens === 0 &&
+ cumulative.input_tokens + cumulative.output_tokens === 0 &&
+ cumulative.total_tokens === infoRecord["model_context_window"]
+ ) {
+ state.lastUsageSignature = null;
+ return null;
}
- const inputTokens = tokenCount(lastRecord["input_tokens"]);
- const cachedInputTokens = tokenCount(lastRecord["cached_input_tokens"]);
- const cacheCreationTokens = tokenCount(lastRecord["cache_write_input_tokens"]);
- const outputTokens = tokenCount(lastRecord["output_tokens"]);
+ if (
+ cumulative !== null &&
+ previous !== null &&
+ CODEX_USAGE_FIELDS.every((key) => cumulative[key] === previous[key])
+ ) {
+ return null;
+ }
+
+ if (last.total_tokens !== last.input_tokens + last.output_tokens) {
+ state.malformedRecords += 1;
+ return null;
+ }
+
+ const signature = JSON.stringify(last);
+ if (cumulative !== null) {
+ if (
+ !CODEX_USAGE_FIELDS.every((key) => cumulative[key] - (previous?.[key] ?? 0) === last[key])
+ ) {
+ state.malformedRecords += 1;
+ return null;
+ }
+ } else {
+ if (signature === state.lastUsageSignature) return null;
+ // Advance expected totals for billed legacy requests so a cumulative re-emission is stale.
+ const advanced = advanceCodexUsage(previous, last);
+ if (advanced === null) {
+ state.malformedRecords += 1;
+ return null;
+ }
+ state.lastCumulativeUsage = advanced;
+ }
+ state.lastUsageSignature = signature;
+
+ const inputTokens = last.input_tokens;
+ const cachedInputTokens = last.cached_input_tokens;
+ const cacheCreationTokens = last.cache_write_input_tokens;
+ const outputTokens = last.output_tokens;
const totals: UsageTokenTotals = {
// Codex reports `input_tokens` inclusive of the cached portion.
- uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens - cacheCreationTokens),
+ uncachedInputTokens: inputTokens - cachedInputTokens - cacheCreationTokens,
cachedInputTokens,
cacheCreationTokens,
outputTokens,
// Reported inside output_tokens, surfaced separately for the token mix.
- reasoningTokens: Math.min(outputTokens, tokenCount(lastRecord["reasoning_output_tokens"])),
+ reasoningTokens: last.reasoning_output_tokens,
};
if (totalTokens(totals) === 0) return null;
@@ -198,7 +299,7 @@ export const codexUsageFormat: TranscriptUsageFormat<CodexScanState> = {
thread_settings: { service_tier: true },
forked_from_id: true,
source: { subagent: { thread_spawn: { parent_thread_id: true } } },
- info: { last_token_usage: true },
+ info: { last_token_usage: true, total_token_usage: true, model_context_window: true },
},
},
// `turn_context`, `thread_settings_applied` and `session_meta` lines hold no
@@ -207,6 +308,7 @@ export const codexUsageFormat: TranscriptUsageFormat<CodexScanState> = {
parseLine: (line, state) => orEmpty(parseCodexLine(line, state)),
parseProjected: (projected, state) => orEmpty(parseCodexRecord(projected, state)),
state: { initial: initialCodexScanState, schema: CodexScanState },
+ readMalformedRecords: (state) => state.malformedRecords,
// A rollout that moved after it was read leaves a copy in both places.
sharedSessionsAcrossFiles: true,
};
diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts
index a4b0a8b30cf..f211251adce 100644
--- a/apps/server/src/usage/UsageService.test.ts
+++ b/apps/server/src/usage/UsageService.test.ts
@@ -7,6 +7,7 @@ import * as NodePath from "node:path";
import * as NodeSqlite from "node:sqlite";
import { assert, describe, it } from "@effect/vitest";
+import { vi } from "vite-plus/test";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { mergeUsage } from "@t3tools/shared/usageMerge";
@@ -16,6 +17,7 @@ import {
ProviderInstanceId,
UsageDay,
type UsageSource,
+ type UsageSummary,
type UsageSummaryInput,
} from "@t3tools/contracts";
import * as Duration from "effect/Duration";
@@ -43,7 +45,9 @@ import * as AntigravityUsage from "../provider/Drivers/AntigravityUsage.ts";
import * as ProviderHostLive from "../provider/ProviderHostLive.ts";
import { totalTokens, type UsageRecord } from "@t3tools/provider-core/server/usage";
import * as UsageService from "./UsageService.ts";
-import { encodeScanCache } from "./usageScanCache.ts";
+import { encodeScanCache, SCAN_CACHE_FILE_NAME } from "./usageScanCache.ts";
+
+vi.mock("node:fs/promises", { spy: true });
const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
@@ -1528,6 +1532,129 @@ describe("UsageService", () => {
}).pipe(Effect.scoped),
);
+ it.live(
+ "retains Codex reconciliation and partial coverage through persisted restart, append and repair",
+ () =>
+ Effect.gen(function* () {
+ const { home, settings } = yield* setup;
+ const dir = NodePath.join(home, "codex", "sessions");
+ const transcript = NodePath.join(dir, "rollout.jsonl");
+ const usage = (input: number, output: number) => ({
+ input_tokens: input,
+ output_tokens: output,
+ total_tokens: input + output,
+ });
+ const counted = (input: number, output: number, totalInput: number, totalOutput: number) =>
+ encodeUnknownJsonString({
+ type: "event_msg",
+ timestamp: "2026-08-01T10:00:00Z",
+ payload: {
+ type: "token_count",
+ info: {
+ last_token_usage: usage(input, output),
+ total_token_usage: usage(totalInput, totalOutput),
+ },
+ },
+ });
+ const tier = (service_tier: string) =>
+ encodeUnknownJsonString({
+ type: "event_msg",
+ payload: { type: "thread_settings_applied", thread_settings: { service_tier } },
+ });
+ const bad = counted(10, 2, 130, 28);
+ // Cross the reader's projection threshold so cumulative fields must survive selection.
+ const stale = counted(20, 5, 100, 20).replace(
+ '"payload":',
+ '"padding":' + encodeUnknownJsonString("x".repeat(9 * 1024 * 1024)) + ',"payload":',
+ );
+ let content = [
+ encodeUnknownJsonString({ type: "turn_context", payload: { model: "gpt-6-astra" } }),
+ counted(100, 20, 100, 20),
+ stale,
+ tier("priority"),
+ bad,
+ ].join("\n");
+ yield* Effect.promise(async () => {
+ await NodeFSP.mkdir(dir, { recursive: true });
+ await NodeFSP.writeFile(transcript, content);
+ });
+ yield* Effect.gen(function* () {
+ const verify = (
+ summary: UsageSummary,
+ output: number,
+ cost: number,
+ malformed: number,
+ ) => {
+ assert.strictEqual(totalOutputTokens(summary), output);
+ assert.strictEqual(
+ summary.buckets.reduce((sum, bucket) => sum + bucket.costUsd, 0),
+ cost,
+ );
+ const source = summary.sources.find(
+ (source) => source.fingerprint.provider === "codex",
+ );
+ assert.strictEqual(source?.status, malformed === 0 ? "ok" : "partial");
+ assert.strictEqual(source?.malformedRecords, malformed);
+ if (malformed > 0) assert.match(source?.message ?? "", /1 malformed or inconsistent/);
+ else assert.notMatch(source?.message ?? "", /malformed|inconsistent/);
+ };
+ const open = vi.spyOn(NodeFSP, "open");
+ open.mockClear();
+ yield* Effect.addFinalizer(() => Effect.sync(() => open.mockRestore()));
+ const first = yield* UsageService.make;
+ const cold = yield* first.readSummary(WINDOW);
+ assert.isTrue(open.mock.calls.some(([path]) => path === transcript));
+ verify(cold, 20, 20, 1);
+ yield* first.awaitPersisted;
+ const restarted = yield* UsageService.make;
+ open.mockClear();
+ verify(yield* first.readSummary(WINDOW), 20, 20, 1);
+ verify(yield* restarted.readSummary(WINDOW), 20, 20, 1);
+ assert.isFalse(open.mock.calls.some(([path]) => path === transcript));
+ open.mockRestore();
+
+ const append = "\n" + counted(10, 2, 140, 30) + "\n";
+ content += append;
+ yield* Effect.promise(() => NodeFSP.appendFile(transcript, append));
+ verify(yield* restarted.readSummary(WINDOW), 22, 24, 1);
+ yield* restarted.awaitPersisted;
+ const resumed = yield* UsageService.make;
+ verify(yield* resumed.readSummary(WINDOW), 22, 24, 1);
+ const next = tier("ultrafast") + "\n" + counted(10, 2, 150, 32) + "\n";
+ content += next;
+ yield* Effect.promise(() => NodeFSP.appendFile(transcript, next));
+ verify(yield* resumed.readSummary(WINDOW), 24, 36, 1);
+
+ const repaired = content.replace(bad, counted(30, 8, 130, 28));
+ assert.strictEqual(Buffer.byteLength(repaired), Buffer.byteLength(content));
+ yield* Effect.promise(async () => {
+ const stat = await NodeFSP.stat(transcript);
+ await NodeFSP.writeFile(transcript, repaired);
+ await NodeFSP.utimes(transcript, stat.atime, stat.mtimeMs / 1000 + 1);
+ });
+ verify(yield* resumed.readSummary(WINDOW), 32, 52, 0);
+ }).pipe(
+ Effect.provide(
+ layerService({
+ prefix: "usage-codex-reconciliation",
+ home,
+ settings,
+ ratesDocument: {
+ "gpt-6-astra": {
+ input_cost_per_token: 0,
+ output_cost_per_token: 1,
+ input_cost_per_token_priority: 0,
+ output_cost_per_token_priority: 2,
+ input_cost_per_token_ultrafast: 0,
+ output_cost_per_token_ultrafast: 6,
+ },
+ },
+ }),
+ ),
+ );
+ }).pipe(Effect.scoped),
+ );
+
it.live(
"keeps large-record totals and costs exact through append, dedupe, restart and cleanup",
() =>
@@ -1583,9 +1710,9 @@ describe("UsageService", () => {
}).pipe(Effect.scoped),
);
- it.live(
- "upgrades a v4 cache: reprices live Codex tiers, keeps deleted rollouts, leaves v4 intact",
- () =>
+ it.live.each([4, 5])(
+ "upgrades a v%s cache: reparses live Codex usage, keeps deleted rollouts and the old file",
+ (version) =>
Effect.gen(function* () {
const { home, settings } = yield* setup;
const sessions = NodePath.join(home, "codex", "sessions");
@@ -1621,33 +1748,46 @@ describe("UsageService", () => {
yield* Effect.gen(function* () {
const { stateDir } = yield* ServerConfig.ServerConfig;
- const cachePath = NodePath.join(stateDir, "usage-scan-cache-v5.json");
- const legacyPath = NodePath.join(stateDir, "usage-scan-cache.json");
+ const cachePath = NodePath.join(stateDir, SCAN_CACHE_FILE_NAME);
+ const legacyPath = NodePath.join(
+ stateDir,
+ version === 4 ? "usage-scan-cache.json" : "usage-scan-cache-v5.json",
+ );
const first = yield* UsageService.make;
yield* first.readSummary(WINDOW);
yield* first.awaitPersisted;
const legacy = yield* Effect.promise(async () => {
const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as {
- files: Record<string, { r: unknown[][]; cs: { speed?: unknown } }>;
+ files: Record<string, { r: unknown[][]; cs: Record<string, unknown> }>;
};
- for (const file of Object.values(document.files)) {
- file.r = file.r.map((row) => [...row.slice(0, 10), 0]);
- delete file.cs.speed;
+ for (const [path, file] of Object.entries(document.files)) {
+ file.r = file.r.map((row) => [
+ ...row.slice(0, 6),
+ path === live ? 99 : row[6],
+ ...row.slice(7, 10),
+ version === 4 ? 0 : 1,
+ ]);
+ if (version === 4) delete file.cs.speed;
+ delete file.cs.lastCumulativeUsage;
+ delete file.cs.malformedRecords;
}
- const text = encodeUnknownJsonString({ ...document, version: 4 });
- await NodeFSP.writeFile(legacyPath, text);
+ const text = encodeUnknownJsonString({ ...document, version });
await NodeFSP.rm(cachePath);
+ await NodeFSP.writeFile(legacyPath, text);
await NodeFSP.rm(deleted);
return text;
});
- const summary = yield* (yield* UsageService.make).readSummary(WINDOW);
+ const upgraded = yield* UsageService.make;
+ const summary = yield* upgraded.readSummary(WINDOW);
assert.strictEqual(totalOutputTokens(summary), 30);
assert.strictEqual(
summary.buckets.reduce((sum, bucket) => sum + bucket.costUsd, 0),
- 80,
+ 60 + 20 * (version === 4 ? 1 : 2),
);
+ yield* upgraded.awaitPersisted;
+ assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v6.json");
assert.strictEqual(
yield* Effect.promise(() => NodeFSP.readFile(legacyPath, "utf8")),
legacy,
@@ -1655,13 +1795,15 @@ describe("UsageService", () => {
}).pipe(
Effect.provide(
layerService({
- prefix: "usage-service-v4-upgrade-test",
+ prefix: "usage-service-cache-upgrade-test",
home,
settings,
ratesDocument: {
"gpt-6-astra": {
input_cost_per_token: 0,
output_cost_per_token: 1,
+ input_cost_per_token_priority: 0,
+ output_cost_per_token_priority: 2,
input_cost_per_token_ultrafast: 0,
output_cost_per_token_ultrafast: 6,
},
@@ -1911,7 +2053,7 @@ describe("UsageService", () => {
yield* Effect.promise(async () => {
await NodeFSP.mkdir(stateDir, { recursive: true });
await NodeFSP.writeFile(
- NodePath.join(stateDir, "usage-scan-cache-v5.json"),
+ NodePath.join(stateDir, SCAN_CACHE_FILE_NAME),
encodeUnknownJsonString(cache),
);
});
diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts
index b17d5cb3064..f24fa0949fa 100644
--- a/apps/server/src/usage/UsageService.ts
+++ b/apps/server/src/usage/UsageService.ts
@@ -50,7 +50,7 @@ import {
import {
decodeScanCache,
dedupeWithinFile,
- LEGACY_SCAN_CACHE_FILE_NAME,
+ LEGACY_SCAN_CACHE_FILE_NAMES,
makeScanCacheWriter,
pruneScanCache,
SCAN_CACHE_FILE_NAME,
@@ -204,7 +204,6 @@ export const make = Effect.gen(function* () {
const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME);
- const legacyScanCachePath = path.join(config.stateDir, LEGACY_SCAN_CACHE_FILE_NAME);
const writeCacheFile = (filePath: string, contents: string) =>
writeFileStringAtomically({ filePath, contents }).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
@@ -392,8 +391,9 @@ export const make = Effect.gen(function* () {
Effect.catchCause(() => Effect.succeed(null)),
);
let document = yield* readDocument(scanCachePath);
- if (document === null) {
- document = yield* readDocument(legacyScanCachePath);
+ for (const fileName of LEGACY_SCAN_CACHE_FILE_NAMES) {
+ if (document !== null) break;
+ document = yield* readDocument(path.join(config.stateDir, fileName));
cacheDirty = document !== null;
}
if (document === null) return;
diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts
index e58293a02a6..ddacde80fda 100644
--- a/apps/server/src/usage/usageScanCache.test.ts
+++ b/apps/server/src/usage/usageScanCache.test.ts
@@ -12,6 +12,7 @@ import {
import type { UsageRecord } from "@t3tools/provider-core/server/usage";
import { TEST_FORMAT_MAP } from "./usageTestFormats.ts";
+import { initialCodexScanState } from "../provider/Drivers/codexUsage.ts";
function record(overrides: Partial<UsageRecord> = {}): UsageRecord {
return {
@@ -108,13 +109,12 @@ describe("scan cache round trip", () => {
tailRecords: [],
position: position({
state: {
+ ...initialCodexScanState(),
model: "gpt-6-astra",
speed: "ultrafast",
sessionId: "session-c",
lastUsageSignature: '{"input_tokens":1}',
sawSessionMeta: true,
- suppressingForkCopies: false,
- forkCopyAnchorMs: 0,
},
}),
});
@@ -142,14 +142,31 @@ describe("scan cache round trip", () => {
expect(restored).toEqual(original);
});
- it("defaults missing v5 diagnostic counts to zero without losing cached records", () => {
+ it("retains v5 history and stateless positions but invalidates obsolete Codex state", () => {
const original = cacheWith([["/gone.jsonl", 100, [record({ speed: "fast" })]]]);
+ original.set("/gone-codex.jsonl", {
+ ...original.get("/gone.jsonl")!,
+ provider: "codex",
+ records: [record({ provider: "codex", speed: "fast", dedupeKey: null })],
+ position: position({
+ state: {
+ model: "gpt-6-astra",
+ speed: "fast",
+ sessionId: "session-a",
+ lastUsageSignature: null,
+ sawSessionMeta: true,
+ suppressingForkCopies: false,
+ forkCopyAnchorMs: 0,
+ },
+ }),
+ });
const encoded = encodeScanCache(original);
const entry = encoded.files["/gone.jsonl"]!;
const legacy = {
...encoded,
version: 5,
files: {
+ ...encoded.files,
"/gone.jsonl": {
s: entry.s,
m: entry.m,
@@ -164,7 +181,13 @@ describe("scan cache round trip", () => {
},
};
- expect(decodeScanCache(JSON.parse(JSON.stringify(legacy)), TEST_FORMAT_MAP)).toEqual(original);
+ const restored = decodeScanCache(JSON.parse(JSON.stringify(legacy)), TEST_FORMAT_MAP);
+ expect(restored.get("/gone.jsonl")).toEqual(original.get("/gone.jsonl"));
+ expect(restored.get("/gone-codex.jsonl")).toEqual({
+ ...original.get("/gone-codex.jsonl"),
+ size: -1,
+ position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null },
+ });
});
it("drops an entry whose persisted parse state is corrupt", () => {
diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts
index 5d9df36a1d9..921158a38ab 100644
--- a/apps/server/src/usage/usageScanCache.ts
+++ b/apps/server/src/usage/usageScanCache.ts
@@ -9,7 +9,7 @@ import * as Schema from "effect/Schema";
import { CLAUDE_SYNTHETIC_MODEL } from "../provider/Drivers/claudeUsage.ts";
import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts";
-const USAGE_SCAN_CACHE_VERSION = 5 as const;
+const USAGE_SCAN_CACHE_VERSION = 6 as const;
const SPEED_COMPATIBLE_SINCE_VERSION = 4;
/**
@@ -17,8 +17,11 @@ const SPEED_COMPATIBLE_SINCE_VERSION = 4;
* replace it, dropping saved usage for deleted transcripts. Separate files keep
* both.
*/
-export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v5.json";
-export const LEGACY_SCAN_CACHE_FILE_NAME = "usage-scan-cache.json";
+export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v6.json";
+export const LEGACY_SCAN_CACHE_FILE_NAMES = [
+ "usage-scan-cache-v5.json",
+ "usage-scan-cache.json",
+] as const;
const SPEEDS: readonly UsageSpeed[] = ["standard", "fast", "ultrafast"];
@@ -295,10 +298,8 @@ export function decodeScanCache(
) {
continue;
}
- // v4 records of stateful formats (Codex) predate service tiers, so they
- // all priced as standard. Keep them, because the rollout may be gone, but
- // make a live rollout re-parse whole: no file has size -1, and a zero
- // position cannot resume.
+ // Older stateful reducers have different semantics. Keep their history for deleted rollouts,
+ // but force live files to re-parse: no file has size -1 and a zero position cannot resume.
const legacy = format.state !== undefined && version < USAGE_SCAN_CACHE_VERSION;
// A corrupt state disqualifies the entry: resuming with it would attach
// appended usage to the wrong model or replay fork-copied history.