TypeScript
fix(server): resolve Codex usage tiers from initial run history (#21898)
Julius Marmingef4e3f250c6f1
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.tsindex 2b4981e04d1..10206ded383 100644--- a/apps/server/src/persistence/Migrations.ts+++ b/apps/server/src/persistence/Migrations.ts@@ -67,6 +67,7 @@ import Migration0061 from "./Migrations/061_PullRequestReviewGuides.ts";import Migration0062 from "./Migrations/062_ThreadFailureLookupIndex.ts";import Migration0063 from "./Migrations/063_DropUnusedV1Projections.ts";import Migration0064 from "./Migrations/064_CanonicalizeThreadPullRequestLinks.ts";+import Migration0065 from "./Migrations/065_CodexUsageNativeTurnIndex.ts";export const migrationEntries = [[1, "OrchestrationEvents", Migration0001],@@ -134,6 +135,7 @@ export const migrationEntries = [[62, "ThreadFailureLookupIndex", Migration0062],[63, "DropUnusedV1Projections", Migration0063],[64, "CanonicalizeThreadPullRequestLinks", Migration0064],+ [65, "CodexUsageNativeTurnIndex", Migration0065],] as const;export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);diff --git a/apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts b/apps/server/src/persistence/Migrations/055_OrchestrationV2.test.tsindex 447c365082f..3f9461779c7 100644--- a/apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts+++ b/apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts@@ -1,11 +1,13 @@import { assert, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";+import * as Schema from "effect/Schema";import * as SqlClient from "effect/sql/SqlClient";import { migrationEntries, runMigrations } from "../Migrations.ts";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";+const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));layer("055_OrchestrationV2", (it) => {@@ -13,7 +15,7 @@ layer("055_OrchestrationV2", (it) => {Effect.sync(() => {assert.deepStrictEqual(migrationEntries.map(([id]) => id),- Array.from({ length: 64 }, (_, index) => index + 1),+ Array.from({ length: 65 }, (_, index) => index + 1),);}),);@@ -36,6 +38,7 @@ layer("055_OrchestrationV2", (it) => {[62, "ThreadFailureLookupIndex"],[63, "DropUnusedV1Projections"],[64, "CanonicalizeThreadPullRequestLinks"],+ [65, "CodexUsageNativeTurnIndex"],]);assert.deepStrictEqual(yield* runMigrations(), []);@@ -66,6 +69,7 @@ layer("055_OrchestrationV2", (it) => {{ migration_id: 62, name: "ThreadFailureLookupIndex" },{ migration_id: 63, name: "DropUnusedV1Projections" },{ migration_id: 64, name: "CanonicalizeThreadPullRequestLinks" },+ { migration_id: 65, name: "CodexUsageNativeTurnIndex" },]);const tables = yield* sql<{ readonly name: string }>`@@ -140,3 +144,70 @@ layer("055_OrchestrationV2", (it) => {}),);});++it.effect("indexes batched Codex native turns without discarding duplicate candidates", () =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ yield* runMigrations({ toMigrationInclusive: 64 });+ for (const [id, driver, nativeId] of [+ ["match", "codex", "requested"],+ ["duplicate", "codex", "requested"],+ ["second", "codex", "requested-second"],+ ["other-provider", "claudeAgent", "requested"],+ ["unrelated", "codex", "unrelated"],+ ] as const) {+ yield* sql`INSERT INTO orchestration_v2_projection_run_attempts ${sql.insert({+ attempt_id: `attempt-${id}`,+ thread_id: `thread-${id}`,+ run_id: `run-${id}`,+ attempt_ordinal: 1,+ root_node_id: `node-${id}`,+ provider: driver,+ provider_thread_id: `provider-thread-${id}`,+ status: "completed",+ payload_json: "{}",+ })}`;+ yield* sql`INSERT INTO orchestration_v2_projection_provider_turns ${sql.insert({+ provider_turn_id: `turn-${id}`,+ thread_id: `thread-${id}`,+ provider_thread_id: `provider-thread-${id}`,+ node_id: `node-${id}`,+ run_attempt_id: `attempt-${id}`,+ ordinal: 1,+ status: "completed",+ payload_json: encodeJson({ nativeTurnRef: { driver, nativeId, strength: "strong" } }),+ })}`;+ }+ const lookup = sql<{ readonly provider_turn_id: string }>`+ SELECT turn.provider_turn_id+ FROM orchestration_v2_projection_provider_turns AS turn+ JOIN orchestration_v2_projection_run_attempts AS attempt+ ON attempt.attempt_id = turn.run_attempt_id+ AND attempt.thread_id = turn.thread_id+ AND attempt.provider_thread_id = turn.provider_thread_id+ WHERE json_extract(turn.payload_json, '$.nativeTurnRef.driver') = 'codex'+ AND json_extract(turn.payload_json, '$.nativeTurnRef.nativeId') IN (+ SELECT value FROM json_each(${encodeJson(["requested", "requested-second", "missing"])})+ )+ `;+ const before = (yield* lookup).map((row) => row.provider_turn_id).toSorted();+ assert.deepStrictEqual(before, ["turn-duplicate", "turn-match", "turn-second"]);+ yield* runMigrations();+ assert.deepStrictEqual((yield* lookup).map((row) => row.provider_turn_id).toSorted(), before);++ const [statement, parameters] = lookup.compile();+ const plan = yield* sql.unsafe<{ readonly detail: string }>(+ `EXPLAIN QUERY PLAN ${statement}`,+ parameters,+ );+ assert.isTrue(+ plan.some(({ detail }) =>+ /SEARCH turn USING INDEX orchestration_v2_provider_turns_codex_native_id_idx\b/.test(+ detail,+ ),+ ),+ plan.map(({ detail }) => detail).join("\n"),+ );+ assert.isFalse(plan.some(({ detail }) => /SCAN turn\b/.test(detail)));+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),+);diff --git a/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.ts b/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.tsindex 706cc02760e..cb9cc0aed2a 100644--- a/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.ts+++ b/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.ts@@ -123,7 +123,10 @@ layer("064_CanonicalizeThreadPullRequestLinks", (it) => {'user', ${v1Payload}, '{}', 1)`;- assert.deepEqual(yield* runMigrations(), [[64, "CanonicalizeThreadPullRequestLinks"]]);+ assert.deepEqual(yield* runMigrations(), [+ [64, "CanonicalizeThreadPullRequestLinks"],+ [65, "CodexUsageNativeTurnIndex"],+ ]);assert.deepEqual(yield* runMigrations(), []);const rows = yield* sql<{ readonly thread_id: string; readonly payload_json: string }>`SELECT thread_id, payload_json FROM orchestration_v2_projection_threadsdiff --git a/apps/server/src/persistence/Migrations/065_CodexUsageNativeTurnIndex.ts b/apps/server/src/persistence/Migrations/065_CodexUsageNativeTurnIndex.tsnew file mode 100644index 00000000000..48f372df1ee--- /dev/null+++ b/apps/server/src/persistence/Migrations/065_CodexUsageNativeTurnIndex.ts@@ -0,0 +1,14 @@+import * as Effect from "effect/Effect";+import * as SqlClient from "effect/sql/SqlClient";++export default Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;++ yield* sql`+ CREATE INDEX orchestration_v2_provider_turns_codex_native_id_idx+ ON orchestration_v2_projection_provider_turns (+ json_extract(payload_json, '$.nativeTurnRef.nativeId')+ )+ WHERE json_extract(payload_json, '$.nativeTurnRef.driver') = 'codex'+ `;+});diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.tsindex 802c5110490..dc1f48c9c40 100644--- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts+++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts@@ -44,6 +44,7 @@ describe("V2 preview upgrade", () => {[62, "ThreadFailureLookupIndex"],[63, "DropUnusedV1Projections"],[64, "CanonicalizeThreadPullRequestLinks"],+ [65, "CodexUsageNativeTurnIndex"],]);assert.deepStrictEqual(yield* runMigrations(), []);assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);@@ -131,6 +132,7 @@ describe("V2 preview upgrade", () => {[62, "ThreadFailureLookupIndex"],[63, "DropUnusedV1Projections"],[64, "CanonicalizeThreadPullRequestLinks"],+ [65, "CodexUsageNativeTurnIndex"],]);}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),);diff --git a/apps/server/src/usage/CodexUsageHistory.ts b/apps/server/src/usage/CodexUsageHistory.tsnew file mode 100644index 00000000000..dd3623c6539--- /dev/null+++ b/apps/server/src/usage/CodexUsageHistory.ts@@ -0,0 +1,118 @@+import { ModelSelection } from "@t3tools/contracts";+import type { UsageSpeed } from "@t3tools/provider-core/server/usage";+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Option from "effect/Option";+import * as Schema from "effect/Schema";+import * as SqlClient from "effect/sql/SqlClient";++import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts";++export class CodexUsageHistoryReadError extends Schema.TaggedError<CodexUsageHistoryReadError>()(+ "CodexUsageHistoryReadError",+ { cause: Schema.Defect() },+) {+ override get message(): string {+ return "Could not read historical Codex usage tiers.";+ }+}++const decodeSelection = Schema.decodeUnknownOption(Schema.fromJsonString(ModelSelection));+const encodeTurnIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));++export interface CodexUsageHistoryRequest {+ readonly sessionId: string;+ readonly nativeTurnId: string;+ readonly model: string;+}++export class CodexUsageHistory extends Context.Service<+ CodexUsageHistory,+ {+ readonly resolve: (+ requests: readonly CodexUsageHistoryRequest[],+ ) => Effect.Effect<+ ReadonlyMap<CodexUsageHistoryRequest, UsageSpeed>,+ CodexUsageHistoryReadError+ >;+ }+>()("t3/usage/CodexUsageHistory") {}++const make = Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ const resolve = Effect.fn("CodexUsageHistory.resolve")(function* (+ requests: readonly CodexUsageHistoryRequest[],+ ) {+ const resolved = new Map<CodexUsageHistoryRequest, UsageSpeed>();+ if (requests.length === 0) return resolved;+ const turnIdsJson = encodeTurnIds([+ ...new Set(requests.map((request) => request.nativeTurnId)),+ ]);++ // The first running event for this attempt precedes any steering changes+ // to the selection. A missing selection there must not fall through to a later event.+ const rows = yield* sql<{+ readonly native_thread_id: string | null;+ readonly native_turn_id: string;+ readonly selection_json: string | null;+ }>`+ SELECT json_extract(attempt.payload_json, '$.nativeThreadId') AS native_thread_id,+ json_extract(turn.payload_json, '$.nativeTurnRef.nativeId') AS native_turn_id,+ (+ SELECT json_extract(event.payload_json, '$.modelSelection')+ FROM orchestration_events AS event+ WHERE event.aggregate_kind = 'thread'+ AND event.application_event_version = 2+ AND event.stream_id = attempt.thread_id+ AND event.event_type = 'run.updated'+ AND json_extract(event.payload_json, '$.id') = attempt.run_id+ AND json_extract(event.payload_json, '$.activeAttemptId') = attempt.attempt_id+ AND json_extract(event.payload_json, '$.status') = 'running'+ ORDER BY event.sequence+ LIMIT 1+ ) AS selection_json+ FROM orchestration_v2_projection_provider_turns AS turn+ LEFT JOIN orchestration_v2_projection_run_attempts AS attempt+ ON attempt.attempt_id = turn.run_attempt_id+ AND attempt.thread_id = turn.thread_id+ AND attempt.provider_thread_id = turn.provider_thread_id+ WHERE json_extract(turn.payload_json, '$.nativeTurnRef.driver') = 'codex'+ AND json_extract(turn.payload_json, '$.nativeTurnRef.nativeId') IN (+ SELECT value FROM json_each(${turnIdsJson})+ )+ `.pipe(+ NodeSqliteClient.readOnly,+ Effect.mapError((cause) => new CodexUsageHistoryReadError({ cause })),+ );++ // Keep duplicates ambiguous even when an attempt is missing or its destination differs.+ const byTurn = new Map<string, (typeof rows)[number] | null>();+ for (const row of rows) {+ byTurn.set(row.native_turn_id, byTurn.has(row.native_turn_id) ? null : row);+ }+ for (const request of requests) {+ const match = byTurn.get(request.nativeTurnId);+ if (!match || match.native_thread_id !== request.sessionId) continue;+ const selection = decodeSelection(match.selection_json);+ if (Option.isNone(selection) || selection.value.model !== request.model) continue;+ if (+ selection.value.options?.some(+ (option) => option.id === "serviceTier" && typeof option.value !== "string",+ )+ )+ continue;+ const tier = getCodexServiceTierOptionValue(selection.value);+ if (tier === "fast" || tier === "priority") resolved.set(request, "fast");+ else if (tier === "ultrafast") resolved.set(request, "ultrafast");+ else if (tier === undefined || tier === "default" || tier === "standard") {+ resolved.set(request, "standard");+ }+ }+ return resolved;+ });+ return CodexUsageHistory.of({ resolve });+});++export const layer = Layer.effect(CodexUsageHistory, make);diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.tsindex f211251adce..c44d4d3221e 100644--- a/apps/server/src/usage/UsageService.test.ts+++ b/apps/server/src/usage/UsageService.test.ts@@ -32,10 +32,13 @@ import * as Layer from "effect/Layer";import * as Scheduler from "effect/Scheduler";import * as Schema from "effect/Schema";import * as TestClock from "effect/testing/TestClock";+import * as SqlClient from "effect/sql/SqlClient";import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";import * as ServerConfig from "../config.ts";import * as ServerSettings from "../serverSettings.ts";+import * as Sqlite from "../persistence/Sqlite.ts";+import * as CodexUsageHistory from "./CodexUsageHistory.ts";import * as CursorAccountReader from "@t3tools/provider-cursor/server/CursorAccountReader";import * as CursorKeychain from "@t3tools/provider-cursor/server/CursorKeychain";import * as CursorUsageAccounts from "@t3tools/provider-cursor/server/CursorUsageAccounts";@@ -266,6 +269,191 @@ function cursorSource(summary: { readonly sources: readonly UsageSource[] }) {return summary.sources.find((source) => source.fingerprint.provider === "cursor");}+const seedCodexHistory = (input: {+ id: string;+ nativeTurnId?: string;+ sessionId?: string;+ model?: string;+ options?: readonly { id: string; value: string | boolean }[];+}) =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ const { id } = input;+ const selection = {+ instanceId: "codex",+ model: input.model ?? "gpt-6-astra",+ options: input.options ?? [{ id: "serviceTier", value: "priority" }],+ };+ const run = {+ id: `run-${id}`,+ activeAttemptId: `attempt-${id}`,+ status: "running",+ modelSelection: selection,+ };+ yield* sql`INSERT INTO orchestration_v2_projection_run_attempts ${sql.insert({+ attempt_id: run.activeAttemptId,+ thread_id: `thread-${id}`,+ run_id: run.id,+ attempt_ordinal: 1,+ root_node_id: `node-${id}`,+ provider: "codex",+ provider_thread_id: `provider-thread-${id}`,+ provider_turn_id: `turn-${id}`,+ status: "completed",+ payload_json: encodeUnknownJsonString({ nativeThreadId: input.sessionId ?? "session" }),+ })}`;+ yield* sql`INSERT INTO orchestration_v2_projection_provider_turns ${sql.insert({+ provider_turn_id: `turn-${id}`,+ thread_id: `thread-${id}`,+ provider_thread_id: `provider-thread-${id}`,+ node_id: `node-${id}`,+ run_attempt_id: run.activeAttemptId,+ ordinal: 1,+ status: "completed",+ payload_json: encodeUnknownJsonString({+ nativeTurnRef: { driver: "codex", nativeId: input.nativeTurnId ?? id, strength: "strong" },+ }),+ })}`;+ const changedSelection = {+ ...selection,+ options: [{ id: "serviceTier", value: "ultrafast" }],+ };+ // These selections disagree so reading the current projection or the wrong event is visible.+ yield* sql`INSERT INTO orchestration_v2_projection_runs ${sql.insert({+ run_id: run.id,+ thread_id: `thread-${id}`,+ ordinal: 1,+ provider: "codex",+ provider_thread_id: `provider-thread-${id}`,+ status: "completed",+ requested_at: "2026-08-01T10:00:00Z",+ payload_json: encodeUnknownJsonString({+ ...run,+ status: "completed",+ modelSelection: { ...selection, options: [] },+ }),+ })}`;+ for (const [index, payload] of [+ { ...run, activeAttemptId: "earlier-attempt", modelSelection: changedSelection },+ { ...run, status: "queued", modelSelection: changedSelection },+ run,+ { ...run, modelSelection: changedSelection },+ ].entries()) {+ yield* sql`INSERT INTO orchestration_events ${sql.insert({+ event_id: `event-${id}-${index}`,+ aggregate_kind: "thread",+ stream_id: `thread-${id}`,+ stream_version: index + 1,+ event_type: "run.updated",+ occurred_at: "2026-08-01T10:00:00Z",+ actor_kind: "system",+ metadata_json: "{}",+ application_event_version: 2,+ payload_json: encodeUnknownJsonString(payload),+ })}`;+ }+ });++describe("Codex usage history", () => {+ const historyLayer = CodexUsageHistory.layer.pipe(Layer.provideMerge(Sqlite.layerMemory));+ const request = (nativeTurnId: string) => ({+ sessionId: "session",+ nativeTurnId,+ model: "gpt-6-astra",+ });++ it.effect("resolves a batch from each attempt's first running selection", () =>+ Effect.gen(function* () {+ yield* seedCodexHistory({ id: "fast" });+ yield* seedCodexHistory({+ id: "ultrafast",+ options: [{ id: "serviceTier", value: "ultrafast" }],+ });+ yield* seedCodexHistory({ id: "legacy-option", options: [{ id: "fastMode", value: true }] });+ yield* seedCodexHistory({ id: "standard", options: [] });+ const requests = ["fast", "ultrafast", "legacy-option", "standard", "fast"].map(request);+ const history = yield* CodexUsageHistory.CodexUsageHistory;+ const resolved = yield* history.resolve(requests);+ assert.strictEqual(resolved.size, requests.length);+ assert.deepStrictEqual(+ requests.map((item) => resolved.get(item)),+ ["fast", "ultrafast", "fast", "standard", "fast"],+ );+ }).pipe(Effect.provide(historyLayer)),+ );++ it.effect("leaves ambiguous, mismatched, and missing V2 evidence unresolved", () =>+ Effect.gen(function* () {+ for (const id of [+ "valid",+ "duplicate-model",+ "duplicate-session",+ "imported",+ "v1-event",+ "queued",+ "missing-selection",+ ]) {+ yield* seedCodexHistory({ id });+ }+ yield* seedCodexHistory({+ id: "second-model",+ nativeTurnId: "duplicate-model",+ model: "other-model",+ });+ yield* seedCodexHistory({+ id: "second-session",+ nativeTurnId: "duplicate-session",+ sessionId: "other-session",+ });+ yield* seedCodexHistory({ id: "wrong-model", model: "other-model" });+ yield* seedCodexHistory({ id: "wrong-session", sessionId: "other-session" });+ const sql = yield* SqlClient.SqlClient;+ yield* sql`UPDATE orchestration_v2_projection_provider_turns+ SET run_attempt_id = NULL WHERE provider_turn_id = 'turn-imported'`;+ yield* sql`DELETE FROM orchestration_v2_projection_run_attempts WHERE attempt_id = 'attempt-imported'`;+ yield* sql`UPDATE orchestration_events SET application_event_version = 1+ WHERE stream_id = 'thread-v1-event'`;+ yield* sql`UPDATE orchestration_events+ SET payload_json = json_set(payload_json, '$.status', 'queued')+ WHERE stream_id = 'thread-queued'`;+ yield* sql`UPDATE orchestration_events+ SET payload_json = json_remove(payload_json, '$.modelSelection')+ WHERE event_id = 'event-missing-selection-2'`;+ const requests = [+ "valid",+ "duplicate-model",+ "duplicate-session",+ "wrong-model",+ "wrong-session",+ "missing-turn",+ "imported",+ "v1-event",+ "queued",+ "missing-selection",+ ].map(request);+ const history = yield* CodexUsageHistory.CodexUsageHistory;+ const resolved = yield* history.resolve(requests);+ assert.deepStrictEqual([...resolved], [[requests[0], "fast"]]);+ }).pipe(Effect.provide(historyLayer)),+ );++ it.effect(+ "reports SQL failures through the typed channel and can resolve again after repair",+ () =>+ Effect.gen(function* () {+ yield* seedCodexHistory({ id: "retry" });+ const history = yield* CodexUsageHistory.CodexUsageHistory;+ const sql = yield* SqlClient.SqlClient;+ const input = request("retry");+ yield* sql`ALTER TABLE orchestration_events RENAME TO unavailable_events`;+ const error = yield* Effect.flip(history.resolve([input]));+ assert.instanceOf(error, CodexUsageHistory.CodexUsageHistoryReadError);+ yield* sql`ALTER TABLE unavailable_events RENAME TO orchestration_events`;+ assert.strictEqual((yield* history.resolve([input])).get(input), "fast");+ }).pipe(Effect.provide(historyLayer)),+ );+});+describe("UsageService", () => {it.live("reads Pi per-model usage and auxiliary costs once across forks and repeated entries",