Skip to content
TypeScript

fix(usage): Codex Fast and Ultrafast now cost what they bill (#15101)

Theo Browne56914128c1ff
diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts
index 29fcecdc234..127679d0a44 100644
--- a/apps/server/src/usage/UsageService.test.ts
+++ b/apps/server/src/usage/UsageService.test.ts
@@ -34,6 +34,7 @@ import * as UsageService from "./UsageService.ts";
const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
+const decodeUnknownJsonString = Schema.decodeSync(Schema.fromJsonString(Schema.Unknown));
function claudeLine(id: number, outputTokens: number, model = "claude-fable-5"): string {
return `${JSON.stringify({
@@ -788,6 +789,98 @@ describe("UsageService", () => {
}).pipe(Effect.scoped),
);
+ it.live(
+ "upgrades a v4 cache: reprices live Codex tiers, keeps deleted rollouts, leaves v4 intact",
+ () =>
+ Effect.gen(function* () {
+ const { home, settings } = yield* setup;
+ const sessions = NodePath.join(home, "codex", "sessions");
+ const rollout = (sessionId: string, outputTokens: number) =>
+ [
+ { type: "session_meta", payload: { id: sessionId } },
+ { type: "turn_context", payload: { model: "gpt-6-astra" } },
+ {
+ type: "event_msg",
+ payload: {
+ type: "thread_settings_applied",
+ thread_settings: { service_tier: "ultrafast" },
+ },
+ },
+ {
+ type: "event_msg",
+ timestamp: "2026-08-01T10:00:00Z",
+ payload: {
+ type: "token_count",
+ info: { last_token_usage: { input_tokens: 0, output_tokens: outputTokens } },
+ },
+ },
+ ]
+ .map((line) => encodeUnknownJsonString(line))
+ .join("\n") + "\n";
+ const live = NodePath.join(sessions, "live.jsonl");
+ const deleted = NodePath.join(sessions, "deleted.jsonl");
+ yield* Effect.promise(async () => {
+ await NodeFSP.mkdir(sessions, { recursive: true });
+ await NodeFSP.writeFile(live, rollout("live", 10));
+ await NodeFSP.writeFile(deleted, rollout("deleted", 20));
+ });
+
+ 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");
+ yield* (yield* UsageService.make).readSummary(WINDOW);
+
+ // Rewrite the cache as a v4 server left it: every Codex record at
+ // speed 0 (standard), and no tier in the reducer state.
+ const legacy = yield* Effect.promise(async () => {
+ const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as {
+ files: Record<string, { r: unknown[][]; cs: { speed?: unknown } }>;
+ };
+ for (const file of Object.values(document.files)) {
+ file.r = file.r.map((row) => [...row.slice(0, 10), 0]);
+ delete file.cs.speed;
+ }
+ const text = encodeUnknownJsonString({ ...document, version: 4 });
+ await NodeFSP.writeFile(legacyPath, text);
+ await NodeFSP.rm(cachePath);
+ await NodeFSP.rm(deleted);
+ return text;
+ });
+
+ const summary = yield* (yield* UsageService.make).readSummary(WINDOW);
+ // The live rollout re-parses at the ultrafast rate (10 x 6); the
+ // deleted one keeps its saved v4 usage at the standard rate (20 x 1).
+ assert.strictEqual(totalOutputTokens(summary), 30);
+ assert.strictEqual(
+ summary.buckets.reduce((sum, bucket) => sum + bucket.costUsd, 0),
+ 80,
+ );
+ // A v4 server sharing this state directory still finds its own cache.
+ assert.strictEqual(
+ yield* Effect.promise(() => NodeFSP.readFile(legacyPath, "utf8")),
+ legacy,
+ );
+ }).pipe(
+ Effect.provide(
+ serviceLayers({
+ prefix: "usage-service-v4-upgrade-test",
+ home,
+ settings,
+ ratesDocument: {
+ "gpt-6-astra": {
+ input_cost_per_token: 0,
+ output_cost_per_token: 1,
+ input_cost_per_token_ultrafast: 0,
+ output_cost_per_token_ultrafast: 6,
+ },
+ },
+ }),
+ ),
+ );
+ }).pipe(Effect.scoped),
+ );
+
it.live("preserves saved tokens, costs and sessions after transcript cleanup and restart", () =>
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 a3b07d64d71..026641ae4d0 100644
--- a/apps/server/src/usage/UsageService.ts
+++ b/apps/server/src/usage/UsageService.ts
@@ -64,7 +64,9 @@ import {
decodeScanCache,
dedupeWithinFile,
encodeScanCache,
+ LEGACY_SCAN_CACHE_FILE_NAME,
pruneScanCache,
+ SCAN_CACHE_FILE_NAME,
type ScanCache,
} from "./usageScanCache.ts";
import type { UsageRecord } from "./usageTranscripts.ts";
@@ -168,7 +170,8 @@ export const make = Effect.gen(function* () {
};
const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
- const scanCachePath = path.join(config.stateDir, "usage-scan-cache.json");
+ const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME);
+ const legacyScanCachePath = path.join(config.stateDir, LEGACY_SCAN_CACHE_FILE_NAME);
let rates: RateTable = new Map();
let ratesFetchedAtMs: number | null = null;
let ratesStatus: UsagePricing["status"] = "unavailable";
@@ -362,10 +365,17 @@ export const make = Effect.gen(function* () {
*/
const ensureScanCacheLoaded = yield* Effect.cached(
Effect.gen(function* () {
- const document = yield* fileSystem.readFileString(scanCachePath).pipe(
- Effect.flatMap((raw) => decodeScanCacheFile(raw)),
- Effect.catchCause(() => Effect.succeed(null)),
- );
+ const readDocument = (filePath: string) =>
+ fileSystem.readFileString(filePath).pipe(
+ Effect.flatMap((raw) => decodeScanCacheFile(raw)),
+ Effect.catchCause(() => Effect.succeed(null)),
+ );
+ let document = yield* readDocument(scanCachePath);
+ if (document === null) {
+ document = yield* readDocument(legacyScanCachePath);
+ // Write the migrated cache to its own file on the next scan.
+ cacheDirty = document !== null;
+ }
if (document === null) return;
for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);
const sources = decodeCachedSources(document);
diff --git a/apps/server/src/usage/antigravityUsageReader.ts b/apps/server/src/usage/antigravityUsageReader.ts
index 54c00b804b7..34a88114f42 100644
--- a/apps/server/src/usage/antigravityUsageReader.ts
+++ b/apps/server/src/usage/antigravityUsageReader.ts
@@ -240,7 +240,7 @@ async function readDatabase(path: string, fallbackTimestamp: number): Promise<Us
"antigravity-unknown",
totals,
reportedCostUsd: null,
- fast: false,
+ speed: "standard",
dedupeKey: keys[0] ?? `antigravity:${sessionId}:${source}:${index}:${usageIndex}`,
};
records.push({
diff --git a/apps/server/src/usage/cursorUsageReader.ts b/apps/server/src/usage/cursorUsageReader.ts
index 31fae24c3cf..0931718cea6 100644
--- a/apps/server/src/usage/cursorUsageReader.ts
+++ b/apps/server/src/usage/cursorUsageReader.ts
@@ -253,7 +253,7 @@ export async function readCursorAccountUsage(
sessionId,
totals,
reportedCostUsd,
- fast: false,
+ speed: "standard",
dedupeKey: `cursor-account:${accountKey}:${key}:${occurrence}`,
});
}
diff --git a/apps/server/src/usage/opencodeUsageReader.ts b/apps/server/src/usage/opencodeUsageReader.ts
index 45d6ef33a58..d4414ac7b9a 100644
--- a/apps/server/src/usage/opencodeUsageReader.ts
+++ b/apps/server/src/usage/opencodeUsageReader.ts
@@ -64,7 +64,7 @@ function parseOpenCodeMessage(
// OpenCode writes zero for models without a known rate, including paid
// subscription models. Let the shared price table estimate those records.
reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) && cost > 0 ? cost : null,
- fast: false,
+ speed: "standard",
dedupeKey: id ? `opencode:${id}` : null,
};
}
diff --git a/apps/server/src/usage/usageAggregation.test.ts b/apps/server/src/usage/usageAggregation.test.ts
index 75435de08ff..7ae0712c12b 100644
--- a/apps/server/src/usage/usageAggregation.test.ts
+++ b/apps/server/src/usage/usageAggregation.test.ts
@@ -12,7 +12,8 @@ const rates: RateTable = new Map([
outputCostPerToken: 5e-5,
cacheReadCostPerToken: 1e-6,
cacheCreationCostPerToken: 1.25e-5,
- fastMultiplier: 1,
+ fast: null,
+ ultrafast: null,
},
],
]);
@@ -32,7 +33,7 @@ function record(overrides: Partial<UsageRecord> = {}): UsageRecord {
reasoningTokens: 0,
},
reportedCostUsd: null,
- fast: false,
+ speed: "standard",
dedupeKey: null,
...overrides,
};
diff --git a/apps/server/src/usage/usagePricing.test.ts b/apps/server/src/usage/usagePricing.test.ts
index db4f68c2cb4..badd50a4901 100644
--- a/apps/server/src/usage/usagePricing.test.ts
+++ b/apps/server/src/usage/usagePricing.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "@effect/vitest";
import { cursorRateModel } from "./cursorUsageReader.ts";
+import type { UsageSpeed } from "./usageTranscripts.ts";
import {
cacheSavingsUsd,
createOverrideRateTable,
@@ -23,11 +24,15 @@ describe("usage pricing", () => {
outputTokens: 1_000_000,
reasoningTokens: 500_000,
};
- const record = (model: string, reportedCostUsd: number | null = null, fast = false) => ({
+ const record = (
+ model: string,
+ reportedCostUsd: number | null = null,
+ speed: UsageSpeed = "standard",
+ ) => ({
model,
totals,
reportedCostUsd,
- fast,
+ speed,
});
it("uses custom token rates ahead of public and provider-reported costs", () => {
@@ -117,20 +122,46 @@ describe("usage pricing", () => {
const overrides = createOverrideRateTable({
"claude-opus-5-5": { inputCostPerMillionTokens: 4, outputCostPerMillionTokens: 20 },
});
- const cost = (model: string, fast: boolean, custom?: typeof overrides) =>
- priceUsage(table, record(model, null, fast), custom).costUsd;
+ const cost = (model: string, speed: UsageSpeed, custom?: typeof overrides) =>
+ priceUsage(table, record(model, null, speed), custom).costUsd;
- expect(cost("claude-opus-5-5", true)).toBeCloseTo(2 * cost("claude-opus-5-5", false));
- expect(cacheSavingsUsd(table, record("claude-opus-5-5", null, true))).toBeCloseTo(
+ expect(cost("claude-opus-5-5", "fast")).toBeCloseTo(2 * cost("claude-opus-5-5", "standard"));
+ expect(cacheSavingsUsd(table, record("claude-opus-5-5", null, "fast"))).toBeCloseTo(
2 * cacheSavingsUsd(table, record("claude-opus-5-5")),
);
// No published fast tier, and custom prices, both stay at the standard rate.
- expect(cost("claude-fable-5-1", true)).toBe(cost("claude-fable-5-1", false));
- expect(cost("claude-opus-5-5", true, overrides)).toBe(
- cost("claude-opus-5-5", false, overrides),
+ expect(cost("claude-fable-5-1", "fast")).toBe(cost("claude-fable-5-1", "standard"));
+ expect(cost("claude-opus-5-5", "fast", overrides)).toBe(
+ cost("claude-opus-5-5", "standard", overrides),
);
});
+ it("prices Codex priority and ultrafast requests at their published tier rates", () => {
+ const table = parseRateTable({
+ "gpt-6-astra": {
+ ...rate(1e-5, 1e-6),
+ input_cost_per_token_priority: 2e-5,
+ output_cost_per_token_priority: 1e-4,
+ cache_read_input_token_cost_priority: 2e-6,
+ input_cost_per_token_ultrafast: 6e-5,
+ output_cost_per_token_ultrafast: 3e-4,
+ // No ultrafast cache rate: keeps the standard 10:1 input-to-cache ratio.
+ },
+ "gpt-6-sol": rate(2e-6, 2e-7),
+ });
+ const cost = (model: string, speed: UsageSpeed) =>
+ priceUsage(table, record(model, null, speed)).costUsd;
+ const standard = cost("gpt-6-astra", "standard");
+
+ expect(cost("gpt-6-astra", "fast")).toBeCloseTo(2 * standard);
+ expect(cost("gpt-6-astra", "ultrafast")).toBeCloseTo(6 * standard);
+ expect(cacheSavingsUsd(table, record("gpt-6-astra", null, "ultrafast"))).toBeCloseTo(
+ 6 * cacheSavingsUsd(table, record("gpt-6-astra")),
+ );
+ // A tier the model does not publish bills at the standard rate.
+ expect(cost("gpt-6-sol", "ultrafast")).toBe(cost("gpt-6-sol", "standard"));
+ });
+
it("keeps the canonical Fable rate separate from DeepInfra in either order", () => {
const canonical = ["claude-fable-5", rate(1e-5, 1e-6)] as const;
const deepInfra = ["deepinfra/anthropic/claude-fable-5", rate(1e-5)] as const;
diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts
index 78f6cf2c5cd..63190eebbf3 100644
--- a/apps/server/src/usage/usagePricing.ts
+++ b/apps/server/src/usage/usagePricing.ts
@@ -9,33 +9,39 @@
*/
import type { UsageCostSource, UsageModelPriceOverride } from "@t3tools/contracts";
-import type { UsageRecord } from "./usageTranscripts.ts";
+import type { UsageRecord, UsageSpeed } from "./usageTranscripts.ts";
-/**
- * The subset of a LiteLLM entry we price against. All values are USD per token.
- *
- * LiteLLM also publishes tiered variants (`*_above_272k_tokens`, `*_flex`,
- * `*_priority`, `*_batches`). We deliberately price at the base tier: the
- * transcripts don't record which tier served a request, so anything else would
- * be a guess dressed up as precision.
- */
-export interface ModelRate {
+/** Token rates for one billing speed. All values are USD per token. */
+export interface TokenRates {
readonly inputCostPerToken: number;
readonly outputCostPerToken: number;
readonly cacheReadCostPerToken: number;
readonly cacheCreationCostPerToken: number;
+}
+
+/**
+ * The subset of a LiteLLM entry we price against: standard rates, plus rates
+ * for each faster speed the model publishes. A request at a speed with no
+ * published rates bills at the standard rates.
+ *
+ * LiteLLM also publishes `*_above_272k_tokens`, `*_flex`, and `*_batches`
+ * variants. Transcripts don't record those, so we don't price them.
+ */
+export interface ModelRate extends TokenRates {
/**
- * Multiple of the rates above billed for a fast-mode request, from LiteLLM's
- * `provider_specific_entry.fast`. `1` when the model publishes no fast tier.
+ * From LiteLLM's `provider_specific_entry.fast` multiple (Claude fast mode),
+ * or else its `*_priority` rates (Codex `priority`).
*/
- readonly fastMultiplier: number;
+ readonly fast: TokenRates | null;
+ /** From LiteLLM's `*_ultrafast` rates (Codex `ultrafast`). */
+ readonly ultrafast: TokenRates | null;
}
export type RateTable = ReadonlyMap<string, ModelRate>;
/**
* Custom IDs keep their case, provider prefix, and variant suffix. Custom rates
- * apply as entered, fast-mode requests included.
+ * apply as entered, at every speed.
*/
export function createOverrideRateTable(
overrides: Readonly<Record<string, UsageModelPriceOverride>>,
@@ -50,31 +56,68 @@ export function createOverrideRateTable(
(prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
cacheCreationCostPerToken:
(prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
- fastMultiplier: 1,
+ fast: null,
+ ultrafast: null,
},
]),
);
}
-/** Raw shape of one LiteLLM entry, narrowed to the fields we read. */
-interface LiteLlmEntry {
- readonly input_cost_per_token?: unknown;
- readonly output_cost_per_token?: unknown;
- readonly cache_read_input_token_cost?: unknown;
- readonly cache_creation_input_token_cost?: unknown;
- readonly provider_specific_entry?: unknown;
-}
+/** One raw LiteLLM entry. Field names carry a tier suffix, e.g. `_priority`. */
+type LiteLlmEntry = Readonly<Record<string, unknown>>;
function finiteNumber(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
+/**
+ * Reads one rate set, `suffix` selecting a tier such as `_priority`. Returns
+ * `null` without both an input and an output rate.
+ *
+ * Anthropic bills cache reads at a discount and cache writes at a premium.
+ * When the standard tier omits them, cached input is priced as plain input
+ * rather than as free. A faster tier that omits them keeps the standard tier's
+ * cache-to-input ratio.
+ */
+function readTokenRates(
+ entry: LiteLlmEntry,
+ suffix: string,
+ standard?: TokenRates,
+): TokenRates | null {
+ const input = finiteNumber(entry[`input_cost_per_token${suffix}`]);
+ const output = finiteNumber(entry[`output_cost_per_token${suffix}`]);
+ if (input === null || output === null) return null;
+ const cacheRate = (name: string, field: "cacheReadCostPerToken" | "cacheCreationCostPerToken") =>
+ finiteNumber(entry[`${name}${suffix}`]) ??
+ (standard !== undefined && standard.inputCostPerToken > 0
+ ? (standard[field] / standard.inputCostPerToken) * input
+ : input);
+ return {
+ inputCostPerToken: input,
+ outputCostPerToken: output,
+ cacheReadCostPerToken: cacheRate("cache_read_input_token_cost", "cacheReadCostPerToken"),
+ cacheCreationCostPerToken: cacheRate(
+ "cache_creation_input_token_cost",
+ "cacheCreationCostPerToken",
+ ),
+ };
+}
+
+function scaleTokenRates(rates: TokenRates, multiple: number): TokenRates {
+ return {
+ inputCostPerToken: rates.inputCostPerToken * multiple,
+ outputCostPerToken: rates.outputCostPerToken * multiple,
+ cacheReadCostPerToken: rates.cacheReadCostPerToken * multiple,
+ cacheCreationCostPerToken: rates.cacheCreationCostPerToken * multiple,
+ };
+}
+
/** Reads `provider_specific_entry.fast`, e.g. `2` for Claude Opus 5.5. */
-function fastMultiplier(entry: LiteLlmEntry): number {
- const specific = entry.provider_specific_entry;
- if (typeof specific !== "object" || specific === null) return 1;
+function fastMultiplier(entry: LiteLlmEntry): number | null {
+ const specific = entry["provider_specific_entry"];
+ if (typeof specific !== "object" || specific === null) return null;
const fast = finiteNumber((specific as Record<string, unknown>)["fast"]);
- return fast !== null && fast > 0 ? fast : 1;
+ return fast !== null && fast > 0 ? fast : null;
}
/**
@@ -94,21 +137,19 @@ export function parseRateTable(document: unknown): RateTable {
for (const [name, raw] of Object.entries(document as Record<string, unknown>)) {
if (typeof raw !== "object" || raw === null) continue;
const entry = raw as LiteLlmEntry;
- const input = finiteNumber(entry.input_cost_per_token);
- const output = finiteNumber(entry.output_cost_per_token);
- if (input === null || output === null) continue;
+ const standard = readTokenRates(entry, "");
+ if (standard === null) continue;
const key = normalizeRateKey(name);
if (key.length === 0) continue;
+ const multiple = fastMultiplier(entry);
table.set(key, {
- inputCostPerToken: input,
- outputCostPerToken: output,
- // Anthropic bills cache reads at a discount and cache writes at a
- // premium. When a model omits them, cached input is priced as plain
- // input rather than as free.
- cacheReadCostPerToken: finiteNumber(entry.cache_read_input_token_cost) ?? input,
- cacheCreationCostPerToken: finiteNumber(entry.cache_creation_input_token_cost) ?? input,
- fastMultiplier: fastMultiplier(entry),
+ ...standard,
+ fast:
+ multiple === null
+ ? readTokenRates(entry, "_priority", standard)
+ : scaleTokenRates(standard, multiple),
+ ultrafast: readTokenRates(entry, "_ultrafast", standard),
});
}
@@ -131,16 +172,29 @@ export function parseRateTable(document: unknown): RateTable {
return table;
}
-function sameRate(a: ModelRate, b: ModelRate): boolean {
+function sameTokenRates(a: TokenRates | null, b: TokenRates | null): boolean {
+ if (a === null || b === null) return a === b;
return (
a.inputCostPerToken === b.inputCostPerToken &&
a.outputCostPerToken === b.outputCostPerToken &&
a.cacheReadCostPerToken === b.cacheReadCostPerToken &&
- a.cacheCreationCostPerToken === b.cacheCreationCostPerToken &&
- a.fastMultiplier === b.fastMultiplier
+ a.cacheCreationCostPerToken === b.cacheCreationCostPerToken
);
}
+function sameRate(a: ModelRate, b: ModelRate): boolean {
+ return (
+ sameTokenRates(a, b) &&
+ sameTokenRates(a.fast, b.fast) &&
+ sameTokenRates(a.ultrafast, b.ultrafast)
+ );
+}
+
+/** The rates a request at `speed` bills at. */
+function ratesAt(rate: ModelRate, speed: UsageSpeed): TokenRates {
+ return (speed === "standard" ? null : rate[speed]) ?? rate;
+}
+
function normalizeRateKey(model: string): string {
return model.trim().toLowerCase();
}
@@ -186,7 +240,7 @@ export function lookupRate(table: RateTable, model: string): ModelRate | null {
/** The parts of a transcript record that decide its price. */
export type PricedRecord = Pick<
UsageRecord,
- "model" | "rateModel" | "totals" | "fast" | "reportedCostUsd"
+ "model" | "rateModel" | "totals" | "speed" | "reportedCostUsd"
>;
export interface PricedUsage {
@@ -214,14 +268,13 @@ export function priceUsage(
const rate = override ?? lookupRate(table, record.rateModel ?? model);
if (rate === null) return { costUsd: 0, costSource: "unpriced" };
- const standardCostUsd =
- totals.uncachedInputTokens * rate.inputCostPerToken +
- totals.cachedInputTokens * rate.cacheReadCostPerToken +
- totals.cacheCreationTokens * rate.cacheCreationCostPerToken +
- totals.outputTokens * rate.outputCostPerToken;
-
+ const rates = ratesAt(rate, record.speed);
return {
- costUsd: standardCostUsd * (record.fast ? rate.fastMultiplier : 1),
+ costUsd:
+ totals.uncachedInputTokens * rates.inputCostPerToken +
+ totals.cachedInputTokens * rates.cacheReadCostPerToken +
+ totals.cacheCreationTokens * rates.cacheCreationCostPerToken +
+ totals.outputTokens * rates.outputCostPerToken,
costSource: "modelPriced",
};
}
@@ -238,9 +291,6 @@ export function cacheSavingsUsd(
const rate =
overrides?.get(record.model.trim()) ?? lookupRate(table, record.rateModel ?? record.model);
if (rate === null) return 0;
- return (
- record.totals.cachedInputTokens *
- (rate.inputCostPerToken - rate.cacheReadCostPerToken) *
- (record.fast ? rate.fastMultiplier : 1)
- );
+ const rates = ratesAt(rate, record.speed);
+ return record.totals.cachedInputTokens * (rates.inputCostPerToken - rates.cacheReadCostPerToken);
}
diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts
index 6455b1eb777..82ff1e36dfc 100644
--- a/apps/server/src/usage/usageScanCache.test.ts
+++ b/apps/server/src/usage/usageScanCache.test.ts
@@ -24,7 +24,7 @@ function record(overrides: Partial<UsageRecord> = {}): UsageRecord {
reasoningTokens: 0,
},
reportedCostUsd: null,
- fast: false,
+ speed: "standard",
dedupeKey: "msg_1:",
...overrides,
};
@@ -61,7 +61,7 @@ describe("scan cache round trip", () => {
[
"/a.jsonl",
100,
- [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5-5", fast: true })],
+ [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5-5", speed: "fast" })],
],
["/b.jsonl", 200, [record({ sessionId: "session-b", reportedCostUsd: 1.5 })]],
]);
@@ -79,11 +79,14 @@ describe("scan cache round trip", () => {
size: 80,
mtimeMs: 400,
provider: "codex",
- records: [record({ provider: "codex", model: "gpt-5.2-codex", dedupeKey: null })],
+ records: [
+ record({ provider: "codex", model: "gpt-6-astra", dedupeKey: null, speed: "ultrafast" }),
+ ],
tailRecords: [],
position: position({
codexState: {
- model: "gpt-5.2-codex",
+ model: "gpt-6-astra",
+ speed: "ultrafast",
sessionId: "session-c",
lastUsageSignature: '{"input_tokens":1}',
sawSessionMeta: true,
@@ -128,8 +131,8 @@ describe("scan cache round trip", () => {
expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
});
- it("drops an entry whose fast flag is not 0 or 1", () => {
- const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record({ fast: true })]]]));
+ it("drops an entry whose speed is not a known index", () => {
+ const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record({ speed: "fast" })]]]));
const row = encoded.files["/a.jsonl"]!.r[0]!;
const poisoned = {
...encoded,
@@ -139,7 +142,7 @@ describe("scan cache round trip", () => {
expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).has("/a.jsonl")).toBe(false);
});
- it("rejects a document from the previous cache version", () => {
+ it("rejects a document from before records carried a speed", () => {
const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
const previous = { ...encoded, version: 3 };
diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts
index 79cca5cff8e..3c6826a6798 100644
--- a/apps/server/src/usage/usageScanCache.ts
+++ b/apps/server/src/usage/usageScanCache.ts
@@ -17,14 +17,33 @@
import type { UsageProviderKind } from "@t3tools/contracts";
import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts";
-import type { CodexScanState, UsageRecord } from "./usageTranscripts.ts";
+import type { CodexScanState, UsageRecord, UsageSpeed } from "./usageTranscripts.ts";
// v2: Codex fork-copy suppression changed what a file parses to, so v1
// entries would keep serving double-counted records forever.
// v3: entries carry the parse position and reducer state so a grown file
// re-parses only its appended bytes instead of starting over.
// v4: records carry Claude fast mode, which v3 rows never captured.
-const USAGE_SCAN_CACHE_VERSION = 4 as const;
+// v5: Codex records carry their service tier. v4 rows store speed the same
+// way, so v4 entries still load; see `decodeScanCache` for v4 Codex entries.
+const USAGE_SCAN_CACHE_VERSION = 5 as const;
+const SPEED_COMPATIBLE_SINCE_VERSION = 4;
+
+/**
+ * Each cache version writes its own file in the state directory. An older
+ * server sharing that directory cannot read a newer cache and would replace
+ * it, dropping saved usage for deleted transcripts. Separate files keep both.
+ * A v5 server reads the legacy (v4) file once, when its own file is missing.
+ */
+export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v5.json";
+export const LEGACY_SCAN_CACHE_FILE_NAME = "usage-scan-cache.json";
+
+/** Serialised as the index into this list. */
+const SPEEDS: readonly UsageSpeed[] = ["standard", "fast", "ultrafast"];
+
+function isSpeed(value: unknown): value is UsageSpeed {
+ return SPEEDS.some((speed) => speed === value);
+}
export interface CachedFile {
readonly size: number;
@@ -59,7 +78,7 @@ type SerializedRecord = readonly [
reasoningTokens: number,
dedupeKey: string | null,
reportedCostUsd: number | null,
- fast: 0 | 1,
+ speed: number,
];
interface SerializedFile {
@@ -111,7 +130,7 @@ export function encodeScanCache(cache: ScanCache): SerializedCache {
record.totals.reasoningTokens,
record.dedupeKey,
record.reportedCostUsd,
- record.fast ? 1 : 0,
+ SPEEDS.indexOf(record.speed),
];
const files: Record<string, SerializedFile> = {};
@@ -147,7 +166,14 @@ export function decodeScanCache(document: unknown): ScanCache {
if (typeof document !== "object" || document === null) return cache;
const root = document as Partial<SerializedCache>;
- if (root.version !== USAGE_SCAN_CACHE_VERSION) return cache;
+ const version = root.version;
+ if (
+ typeof version !== "number" ||
+ version < SPEED_COMPATIBLE_SINCE_VERSION ||
+ version > USAGE_SCAN_CACHE_VERSION
+ ) {
+ return cache;
+ }
if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;
if (typeof root.files !== "object" || root.files === null) return cache;
@@ -180,8 +206,9 @@ export function decodeScanCache(document: unknown): ScanCache {
reasoning,
dedupeKey,
reportedCostUsd,
- fast,
+ speedIndex,
] = row as SerializedRecord;
+ const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined;
const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
if (
@@ -193,7 +220,7 @@ export function decodeScanCache(document: unknown): ScanCache {
!Number.isFinite(cacheCreation) ||
!Number.isFinite(output) ||
!Number.isFinite(reasoning) ||
- (fast !== 0 && fast !== 1)
+ speed === undefined
) {
return null;
}
@@ -211,7 +238,7 @@ export function decodeScanCache(document: unknown): ScanCache {
reasoningTokens: reasoning,
},
reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null,
- fast: fast === 1,
+ speed,
dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null,
});
}
@@ -242,7 +269,11 @@ export function decodeScanCache(document: unknown): ScanCache {
) {
continue;
}
- const codexState = decodeCodexState(entry.cs);
+ // v4 Codex records 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.
+ const legacyCodex = entry.p === "codex" && version < USAGE_SCAN_CACHE_VERSION;
+ const codexState = legacyCodex ? null : decodeCodexState(entry.cs);
if (codexState === undefined) continue;
const provider: UsageProviderKind = entry.p;
@@ -251,17 +282,14 @@ export function decodeScanCache(document: unknown): ScanCache {
if (records === null || tailRecords === null) continue;
cache.set(path, {
- size: entry.s,
+ size: legacyCodex ? -1 : entry.s,
mtimeMs: entry.m,
provider,
records,
tailRecords,
- position: {
- resumeOffset: entry.o,
- guardLength: entry.gl,
- guardHash: entry.gh,
- codexState,
- },
+ position: legacyCodex
+ ? { resumeOffset: 0, guardLength: 0, guardHash: 0, codexState: null }
+ : { resumeOffset: entry.o, guardLength: entry.gl, guardHash: entry.gh, codexState },
});
}
@@ -279,6 +307,7 @@ function decodeCodexState(value: unknown): CodexScanState | null | undefined {
const state = value as Partial<CodexScanState>;
if (
typeof state.model !== "string" ||
+ !isSpeed(state.speed) ||
typeof state.sessionId !== "string" ||
(state.lastUsageSignature !== null && typeof state.lastUsageSignature !== "string") ||
typeof state.sawSessionMeta !== "boolean" ||
@@ -290,6 +319,7 @@ function decodeCodexState(value: unknown): CodexScanState | null | undefined {
}
return {
model: state.model,
+ speed: state.speed,
sessionId: state.sessionId,
lastUsageSignature: state.lastUsageSignature ?? null,
sawSessionMeta: state.sawSessionMeta,
diff --git a/apps/server/src/usage/usageTranscriptReader.test.ts b/apps/server/src/usage/usageTranscriptReader.test.ts
index 6c95a36df19..e55c01ad491 100644
--- a/apps/server/src/usage/usageTranscriptReader.test.ts
+++ b/apps/server/src/usage/usageTranscriptReader.test.ts
@@ -76,6 +76,14 @@ function codexModelLine(model: string): string {
})}\n`;
}
+function codexTierLine(serviceTier: string): string {
+ return `${JSON.stringify({
+ type: "event_msg",
+ timestamp: "2026-08-01T10:00:01Z",
+ payload: { type: "thread_settings_applied", thread_settings: { service_tier: serviceTier } },
+ })}\n`;
+}
+
function codexUsageLine(outputTokens: number, secondsOffset: number): string {
return `${JSON.stringify({
type: "event_msg",
@@ -111,19 +119,24 @@ describe("readTranscriptRecords resume", () => {
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"));
+ await NodeFSP.writeFile(
+ path,
+ codexMetaLine() + codexModelLine("gpt-5.2-codex") + codexTierLine("ultrafast"),
+ );
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.
+ // The appended usage event has no turn_context, thread settings, or
+ // session_meta of its own; model, tier, 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]?.speed, "ultrafast");
assert.strictEqual(second.records[0]?.sessionId, "codex-session-1");
});
diff --git a/apps/server/src/usage/usageTranscriptReader.ts b/apps/server/src/usage/usageTranscriptReader.ts
index faa68699077..4d170237568 100644
--- a/apps/server/src/usage/usageTranscriptReader.ts
+++ b/apps/server/src/usage/usageTranscriptReader.ts
@@ -108,6 +108,7 @@ const USAGE_FIELDS: Record<"claude" | "codex" | "grok", SelectedFields> = {
id: true,
session_id: true,
model: true,
+ thread_settings: { service_tier: true },
forked_from_id: true,
source: { subagent: { thread_spawn: { parent_thread_id: true } } },
info: { last_token_usage: true },
@@ -245,9 +246,10 @@ async function guardMatches(
* 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.
+ * Codex carries the active model on `turn_context` lines and the service tier
+ * on `thread_settings_applied` lines. Neither holds usage of its own, but both
+ * still have to pass through the reducer to keep attribution and pricing
+ * correct.
*/
export async function readTranscriptRecords(
filePath: string,
@@ -283,6 +285,7 @@ export async function readTranscriptRecords(
if (
!mightCarryUsage(line, provider) &&
!line.includes('"turn_context"') &&
+ !line.includes('"thread_settings_applied"') &&
!line.includes('"session_meta"')
) {
return;
diff --git a/apps/server/src/usage/usageTranscriptStreaming.test.ts b/apps/server/src/usage/usageTranscriptStreaming.test.ts
index 2187fd4aa43..fd23593e552 100644
--- a/apps/server/src/usage/usageTranscriptStreaming.test.ts
+++ b/apps/server/src/usage/usageTranscriptStreaming.test.ts
@@ -122,7 +122,7 @@ describe("large usage records", () => {
reasoningTokens: 0,
},
reportedCostUsd: 0.25,
- fast: true,
+ speed: "fast",
dedupeKey: "m1:r-m1",
},
]);
diff --git a/apps/server/src/usage/usageTranscripts.test.ts b/apps/server/src/usage/usageTranscripts.test.ts
index ace3b7d18cf..8d668a13982 100644
--- a/apps/server/src/usage/usageTranscripts.test.ts
+++ b/apps/server/src/usage/usageTranscripts.test.ts
@@ -53,15 +53,15 @@ describe("parseClaudeLine", () => {
reasoningTokens: 0,
});
expect(record?.dedupeKey).toBe("msg_1:");
- expect(record?.fast).toBe(false);
+ expect(record?.speed).toBe("standard");
});
it("marks fast-mode requests", () => {
const line = (speed: string) =>
parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text", speed }));
- expect(line("fast")?.fast).toBe(true);
- expect(line("standard")?.fast).toBe(false);
+ expect(line("fast")?.speed).toBe("fast");
+ expect(line("standard")?.speed).toBe("standard");
});
it("gives every content block of one message the same dedupe key", () => {
@@ -148,6 +148,27 @@ describe("parseCodexLine", () => {
expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull();
});
+ it("carries the service tier from the latest thread settings", () => {
+ const settings = (thread_settings: Record<string, unknown>) =>
+ JSON.stringify({
+ type: "event_msg",
+ timestamp: "2026-08-01T05:17:42.000Z",
+ payload: { type: "thread_settings_applied", thread_settings },
+ });
+ const state = initialCodexScanState();
+ parseCodexLine(turnContext, state);
+ const speedAfter = (line: string, output: number) => {
+ parseCodexLine(line, state);
+ return parseCodexLine(tokenCount(100, 0, output, 0), state)?.speed;
+ };
+
+ expect(parseCodexLine(tokenCount(100, 0, 1, 0), state)?.speed).toBe("standard");
+ expect(speedAfter(settings({ service_tier: "ultrafast" }), 2)).toBe("ultrafast");
+ expect(speedAfter(settings({ service_tier: "priority" }), 3)).toBe("fast");
+ // Codex omits the field when no tier was requested.
+ expect(speedAfter(settings({ model: "gpt-6-astra" }), 4)).toBe("standard");
+ });
+
// A forked/subagent rollout opens with the parent's history copied in and
// every line re-stamped to the fork instant, then the ancestors' session
// metas. Counting those again multiplied usage ~1.85x on real data (#5758).
diff --git a/apps/server/src/usage/usageTranscripts.ts b/apps/server/src/usage/usageTranscripts.ts
index c3903ef4719..eb32e664f43 100644
--- a/apps/server/src/usage/usageTranscripts.ts
+++ b/apps/server/src/usage/usageTranscripts.ts
@@ -8,6 +8,13 @@
*/
import type { UsageProviderKind, UsageTokenTotals } from "@t3tools/contracts";
+/**
+ * Billing speed of a request. Faster speeds bill at a model-specific premium.
+ * Claude fast mode and Codex `priority` are `fast`; Codex `ultrafast` is its
+ * own, more expensive tier.
+ */
+export type UsageSpeed = "standard" | "fast" | "ultrafast";
+
export interface UsageRecord {
readonly provider: UsageProviderKind;
readonly timestampMs: number;
@@ -20,11 +27,8 @@ export interface UsageRecord {
readonly sessionId: string;
readonly totals: UsageTokenTotals;
readonly reportedCostUsd: number | null;
- /**
- * Whether the request ran in fast mode, which bills at a model-specific
- * multiple of the standard rate. Only Claude Code records this.
- */
- readonly fast: boolean;
+ /** Only Claude Code and Codex record a speed; other providers are `standard`. */
+ readonly speed: UsageSpeed;
/**
* Key for cross-file de-duplication, or `null` when the record is inherently
* unique and needs no dedup.
@@ -159,7 +163,7 @@ export function parseClaudeRecord(parsed: unknown): UsageRecord | null {
reasoningTokens: 0,
},
reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null,
- fast: usageRecord["speed"] === "fast",
+ speed: usageRecord["speed"] === "fast" ? "fast" : "standard",
dedupeKey,
};
}
@@ -171,12 +175,14 @@ export function parseClaudeRecord(parsed: unknown): UsageRecord | null {
/**
* Rolling state for a single Codex rollout file.
*
- * Codex `token_count` events carry no model, so the model is carried forward
- * from the most recent `turn_context`. Sessions that switch models mid-run
- * attribute correctly from the switch onward.
+ * 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`. Sessions that switch either
+ * mid-run attribute correctly from the switch onward.
*/
export interface CodexScanState {
model: string;
+ speed: UsageSpeed;
sessionId: string;
lastUsageSignature: string | null;
sawSessionMeta: boolean;
@@ -188,6 +194,7 @@ export interface CodexScanState {
export function initialCodexScanState(): CodexScanState {
return {
model: "",
+ speed: "standard",
sessionId: "",
lastUsageSignature: null,
sawSessionMeta: false,
@@ -265,6 +272,14 @@ export function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageR
return null;
}
+ if (payloadType === "thread_settings_applied") {
+ const settings = payloadRecord["thread_settings"];
+ if (typeof settings === "object" && settings !== null) {
+ state.speed = codexSpeed((settings as Record<string, unknown>)["service_tier"]);
+ }
+ return null;
+ }
+
if (payloadType !== "token_count") return null;
const info = payloadRecord["info"];
@@ -323,13 +338,24 @@ export function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageR
totals,
// Codex does not report cost in the rollout.
reportedCostUsd: null,
- fast: false,
+ speed: state.speed,
// Events surviving the fork-copy suppression above are unique to this
// rollout, so they need no global dedup.
dedupeKey: null,
};
}
+/**
+ * Maps a Codex `service_tier` to its billing speed. Codex omits the field when
+ * no tier was requested, which bills as standard, as do `default` and
+ * `standard`. `fast` is accepted as an alias of `priority`.
+ */
+function codexSpeed(serviceTier: unknown): UsageSpeed {
+ if (serviceTier === "priority" || serviceTier === "fast") return "fast";
+ if (serviceTier === "ultrafast") return "ultrafast";
+ return "standard";
+}
+
/* -------------------------------------------------------------------------- */
/* Grok Build */
/* -------------------------------------------------------------------------- */
@@ -457,7 +483,7 @@ export function parseGrokRecord(parsed: unknown): readonly UsageRecord[] {
sessionId,
totals: grokTotalsToUsage(topLevel),
reportedCostUsd: grokCostTicksToUsd(topLevel.costUsdTicks),
- fast: false,
+ speed: "standard",
// No prompt id means we cannot tell two same-second updates apart.
dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:grok`,
},
@@ -504,7 +530,7 @@ export function parseGrokRecord(parsed: unknown): readonly UsageRecord[] {
sessionId,
totals,
reportedCostUsd,
- fast: false,
+ speed: "standard",
dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:${entry.model}`,
});
}