Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(codex): keep Codex spend on a single finalize-owned ledger row

Alfredo Lopezf571cb4690e4
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 4e7e7446e..8c09ceb3b 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.517",
+ "version": "0.1.518",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.517",
+ "version": "0.1.518",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index f90191797..53787d300 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.517",
+ "version": "0.1.518",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/internal/usageEvents.ts b/control-api/src/routes/internal/usageEvents.ts
index 8cb775d23..abdb3b03f 100644
--- a/control-api/src/routes/internal/usageEvents.ts
+++ b/control-api/src/routes/internal/usageEvents.ts
@@ -267,15 +267,30 @@ export function createInternalUsageEventsRouter(): Router {
got: events.length,
})
}
- const violation = checkClaimBinding(events, req.mcpHostJwt!)
+ // Old mcp-host reporters still enqueue Codex. Proxy finalize owns that
+ // ledger row; drop reporter Codex here so request_id cannot fork.
+ const reporterEvents: unknown[] = []
+ let droppedCodex = 0
+ for (const event of events) {
+ if (
+ event &&
+ typeof event === 'object' &&
+ (event as { provider?: unknown }).provider === 'codex-subscription'
+ ) {
+ droppedCodex += 1
+ continue
+ }
+ reporterEvents.push(event)
+ }
+ const violation = checkClaimBinding(reporterEvents, req.mcpHostJwt!)
if (violation) {
return res.status(403).json({ error: 'claim_binding_mismatch', ...violation })
}
const transactionResult = await withTraceIngestTransaction(async db => {
- const workflowBinding = await checkWorkflowRunBinding(events, req.mcpHostJwt!, db)
+ const workflowBinding = await checkWorkflowRunBinding(reporterEvents, req.mcpHostJwt!, db)
if (workflowBinding.violation) return { violation: workflowBinding.violation }
- const ingest = await ingestUsageEventsInTransaction(events, db, {
+ const ingest = await ingestUsageEventsInTransaction(reporterEvents, db, {
recipeNamespace: req.mcpHostJwt!.recipeNamespace,
recipeName: req.mcpHostJwt!.recipeName,
})
@@ -285,7 +300,12 @@ export function createInternalUsageEventsRouter(): Router {
recipeName: req.mcpHostJwt!.recipeName,
hostRef: req.mcpHostJwt!.hostRefs[0],
})
- return { result: ingest.result }
+ return {
+ result: {
+ ...ingest.result,
+ rejected: ingest.result.rejected + droppedCodex,
+ },
+ }
})
if ('violation' in transactionResult) {
return res.status(403).json({
diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.ts
index aaf02ab94..8576c8209 100644
--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts
+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts
@@ -332,12 +332,11 @@ export async function authorizeLlmProviderAttempt(
host_ref: caller.hostRef,
context_ref: null,
team_id: null,
- user_id:
- typeof body.userId === 'string' && body.userId.trim() ? body.userId.trim() : claims.sub,
+ user_id: null,
provider: PROVIDER,
model: request.model,
llm_secret_name: null,
- source_kind: caller.callerKind === 'recipe' ? 'workflow' : 'channel',
+ source_kind: 'channel',
recipe_name: caller.recipeName,
cron_job_id: null,
task_ref: `${invocationId}:${attemptGeneration}:${providerAttemptIndex}`,
diff --git a/control-api/src/services/llmProviderAttemptFinalization.ts b/control-api/src/services/llmProviderAttemptFinalization.ts
index 617405784..470c9057d 100644
--- a/control-api/src/services/llmProviderAttemptFinalization.ts
+++ b/control-api/src/services/llmProviderAttemptFinalization.ts
@@ -1,14 +1,19 @@
-import { parseCodexAttemptReceiptV1 } from '@clerum/llm-provider-attempt-contract'
+import {
+ type CodexAttemptReceiptV1,
+ parseCodexAttemptReceiptV1,
+} from '@clerum/llm-provider-attempt-contract'
import { config } from '../config.js'
-import { withTransaction } from '../db.js'
+import { type DbClient, withTransaction } from '../db.js'
import { rootLogger } from '../observability/logger.js'
import { releaseReservation } from './budgets/reservations.js'
import { hashCodexAttemptReceipt } from './llmProviderAttemptReceipt.js'
import { opaqueAttemptReceipt } from './llmProviderAttemptRedemption.js'
import {
+ type LlmProviderAttemptRow,
loadLlmProviderAttempt,
markLlmProviderAttemptFinalized,
} from './llmProviderAttemptStore.js'
+import { ingestUsageEventsInTransaction } from './usageEvents.js'
const log = rootLogger.child({ module: 'llm-provider-attempt-finalization' })
@@ -104,6 +109,9 @@ export async function finalizeLlmProviderAttempt(
'provider attempt already has a different terminal outcome'
)
}
+ if (result === 'applied') {
+ await ingestCodexFinalizeLedgerRow(tx, attempt, receipt)
+ }
if (attempt.budgetReservationId && attempt.budgetReservationId !== 'unbudgeted') {
await releaseReservation(
{ reservationId: attempt.budgetReservationId, hostRef: attempt.hostRef },
@@ -126,3 +134,74 @@ export async function finalizeLlmProviderAttempt(
}
})
}
+
+function completeSuccessUsage(
+ usage: CodexAttemptReceiptV1['usage']
+): { inputTokens: number; outputTokens: number } | null {
+ const inputTokens = usage?.inputTokens
+ const outputTokens = usage?.outputTokens
+ if (
+ typeof inputTokens !== 'number' ||
+ typeof outputTokens !== 'number' ||
+ !Number.isInteger(inputTokens) ||
+ !Number.isInteger(outputTokens) ||
+ inputTokens < 0 ||
+ outputTokens < 0
+ ) {
+ return null
+ }
+ return { inputTokens, outputTokens }
+}
+
+function buildCodexFinalizeLedgerEvent(
+ attempt: LlmProviderAttemptRow,
+ usage: { inputTokens: number; outputTokens: number }
+): Record<string, unknown> {
+ return {
+ request_id: attempt.id,
+ ts: new Date().toISOString(),
+ run_id: null,
+ host_ref: attempt.hostRef,
+ context_ref: null,
+ team_id: null,
+ provider: attempt.provider,
+ model: attempt.model,
+ llm_secret_name: null,
+ source_kind: 'channel',
+ user_id: null,
+ sender: null,
+ channel_type: null,
+ recipe_name: attempt.recipeName ?? null,
+ cron_job_id: null,
+ task_id: null,
+ iteration: null,
+ input_tokens: usage.inputTokens,
+ output_tokens: usage.outputTokens,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ cache_tokens_reported: false,
+ prompt_bridge_metadata: null,
+ }
+}
+
+async function ingestCodexFinalizeLedgerRow(
+ tx: DbClient,
+ attempt: LlmProviderAttemptRow,
+ receipt: CodexAttemptReceiptV1
+): Promise<void> {
+ if (receipt.outcome !== 'success') return
+ const usage = completeSuccessUsage(receipt.usage)
+ if (!usage) return
+ const ingest = await ingestUsageEventsInTransaction(
+ [buildCodexFinalizeLedgerEvent(attempt, usage)],
+ tx,
+ undefined,
+ { origin: 'finalize' }
+ )
+ if (ingest.result.rejected !== 0 || ingest.result.accepted + ingest.result.duplicates !== 1) {
+ throw new LlmProviderAttemptFinalizeError(
+ 'invalid_receipt',
+ 'Codex usage could not be bound to a single ledger row'
+ )
+ }
+}
diff --git a/control-api/src/services/pluginWorkloadSdkFinalization.ts b/control-api/src/services/pluginWorkloadSdkFinalization.ts
index e15bb652f..6e82d5c89 100644
--- a/control-api/src/services/pluginWorkloadSdkFinalization.ts
+++ b/control-api/src/services/pluginWorkloadSdkFinalization.ts
@@ -345,7 +345,7 @@ export async function finalizePromptBridgeInTransaction(
[input.invocationId, expectedStatus, input.attemptGeneration]
)
- if (input.status === 'complete') {
+ if (input.status === 'complete' && input.target.provider !== 'codex-subscription') {
const usage = input.usage!
const event = {
request_id: input.providerAttemptId,
diff --git a/control-api/src/services/usageEvents.ts b/control-api/src/services/usageEvents.ts
index 39c57c17a..9734c6e52 100644
--- a/control-api/src/services/usageEvents.ts
+++ b/control-api/src/services/usageEvents.ts
@@ -179,7 +179,12 @@ function promptBridgeMetadata(value: unknown): LlmUsageEvent['prompt_bridge_meta
}
}
-export function validateUsageEvent(raw: unknown): LlmUsageEvent | null {
+export type UsageEventValidationOrigin = 'reporter' | 'finalize'
+
+export function validateUsageEvent(
+ raw: unknown,
+ options?: { origin?: UsageEventValidationOrigin }
+): LlmUsageEvent | null {
if (!raw || typeof raw !== 'object') return null
const r = raw as Record<string, unknown>
@@ -194,14 +199,20 @@ export function validateUsageEvent(raw: unknown): LlmUsageEvent | null {
const host_ref = typeof r.host_ref === 'string' ? r.host_ref.trim() : ''
if (!host_ref) return null
+ const origin = options?.origin === 'finalize' ? 'finalize' : 'reporter'
const provider = typeof r.provider === 'string' ? r.provider.trim() : ''
if (!provider) return null
+ // Codex spend belongs to proxy finalize. Reporter shapes (workflow, desktop,
+ // plugin_workload_sdk) must not open a second ledger row.
+ if (provider === 'codex-subscription' && origin !== 'finalize') return null
+ if (origin === 'finalize' && provider !== 'codex-subscription') return null
const model = typeof r.model === 'string' ? r.model.trim() : ''
if (!model) return null
const source_kind_raw = typeof r.source_kind === 'string' ? r.source_kind.trim() : ''
if (!SOURCE_KINDS.has(source_kind_raw)) return null
+ if (origin === 'finalize' && source_kind_raw !== 'channel') return null
const team_id = trimOrNull(r.team_id)
if (team_id && !isUsageTeamId(team_id)) return null
@@ -234,6 +245,7 @@ export function validateUsageEvent(raw: unknown): LlmUsageEvent | null {
const recipe_name = trimOrNull(r.recipe_name)
const llm_secret_name = trimOrNull(r.llm_secret_name)
+ if (origin === 'finalize' && llm_secret_name !== null) return null
const task_id = trimOrNull(r.task_id)
const run_id = trimOrNull(r.run_id)
if (run_id && !UUID_REGEX.test(run_id)) return null
@@ -499,12 +511,13 @@ export async function ingestUsageEvents(
export async function ingestUsageEventsInTransaction(
rawEvents: unknown[],
db: DbClient,
- binding?: UsageBindingContext
+ binding?: UsageBindingContext,
+ options?: { origin?: UsageEventValidationOrigin }
): Promise<UsageIngestTransactionResult> {
const total = rawEvents.length
let validated: LlmUsageEvent[] = []
for (const raw of rawEvents) {
- const ev = validateUsageEvent(raw)
+ const ev = validateUsageEvent(raw, options)
if (ev) validated.push(ev)
}
let rejected = total - validated.length
diff --git a/control-api/test/routes.usageEvents.test.ts b/control-api/test/routes.usageEvents.test.ts
index 67164a28b..c4e617469 100644
--- a/control-api/test/routes.usageEvents.test.ts
+++ b/control-api/test/routes.usageEvents.test.ts
@@ -168,6 +168,48 @@ describe('POST /api/v1/internal/usage/llm/events', () => {
expect(res.body).toEqual({ accepted: 0, duplicates: 1, rejected: 0 })
})
+ it('drops reporter Codex events so they cannot open a second ledger row', async () => {
+ mockPoolQuery.mockResolvedValue({ rows: [{ request_id: VALID_EVENT.request_id }], rowCount: 1 })
+ const app = createApp(new MockGateway('mcp-server') as never)
+ const res = await authedPost(app)
+ .send({
+ events: [
+ VALID_EVENT,
+ {
+ ...VALID_EVENT,
+ request_id: '66666666-6666-4666-8666-666666666666',
+ provider: 'codex-subscription',
+ llm_secret_name: null,
+ source_kind: 'channel',
+ },
+ ],
+ })
+ .expect(200)
+ expect(res.body).toEqual({ accepted: 1, duplicates: 0, rejected: 1 })
+ const insert = mockPoolQuery.mock.calls.find(
+ ([sql]: [string]) => typeof sql === 'string' && sql.includes('INSERT INTO usage_events')
+ )
+ expect(insert?.[1]).toEqual(expect.arrayContaining([VALID_EVENT.request_id, 'openai']))
+ expect(JSON.stringify(insert?.[1] ?? [])).not.toContain('codex-subscription')
+ })
+
+ it('rejects a Codex-only reporter batch without inserting', async () => {
+ const app = createApp(new MockGateway('mcp-server') as never)
+ const res = await authedPost(app)
+ .send({
+ events: [
+ {
+ ...VALID_EVENT,
+ provider: 'codex-subscription',
+ llm_secret_name: null,
+ },
+ ],
+ })
+ .expect(200)
+ expect(res.body).toEqual({ accepted: 0, duplicates: 0, rejected: 1 })
+ expect(mockPoolQuery).not.toHaveBeenCalled()
+ })
+
it('reports schema-rejected events separately', async () => {
mockPoolQuery.mockResolvedValue({ rows: [], rowCount: 0 })
const app = createApp(new MockGateway('mcp-server') as never)
diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
index 7baf4da25..95467547a 100644
--- a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
+++ b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
@@ -320,6 +320,53 @@ describe('authorizeLlmProviderAttempt', () => {
expect(resolveConnectionKey).toHaveBeenCalledWith('agent-c')
})
+ it('evaluates budget with a null user_id even when claims.sub is present', async () => {
+ const result = await authorizeLlmProviderAttempt(
+ claims({ sub: 'default/research-host' }),
+ body({ userId: 'default/research-host' }),
+ current
+ )
+ expect(result.executionTicket).toBe('ticket.jwt')
+ expect(current.evaluateBudget).toHaveBeenCalledWith(
+ expect.objectContaining({
+ user_id: null,
+ source_kind: 'channel',
+ host_ref: 'research-host',
+ }),
+ expect.anything(),
+ expect.anything(),
+ expect.anything()
+ )
+ const budgetInput = vi.mocked(current.evaluateBudget).mock.calls[0]?.[0] as {
+ user_id: unknown
+ }
+ expect(budgetInput.user_id).not.toBe('default/research-host')
+ })
+
+ it('uses source_kind=channel for recipe callers and never feeds claims.sub to the budget', async () => {
+ await authorizeLlmProviderAttempt(
+ claims({
+ sub: 'sandbox-recipes/research-host',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'research-host',
+ hostRefs: ['sandbox-recipes/research-host'],
+ }),
+ body(),
+ current
+ )
+ expect(current.evaluateBudget).toHaveBeenCalledWith(
+ expect.objectContaining({
+ user_id: null,
+ source_kind: 'channel',
+ host_ref: 'sandbox-recipes/research-host',
+ recipe_name: 'research-host',
+ }),
+ expect.anything(),
+ expect.anything(),
+ expect.anything()
+ )
+ })
+
it('is disabled when the feature flag is off', async () => {
await expect(
authorizeLlmProviderAttempt(claims(), body(), { ...current, enabled: false })
diff --git a/control-api/test/services.llmProviderAttemptFinalization.realPostgres.integration.test.ts b/control-api/test/services.llmProviderAttemptFinalization.realPostgres.integration.test.ts
index 3ae69065d..59e3a6bc3 100644
--- a/control-api/test/services.llmProviderAttemptFinalization.realPostgres.integration.test.ts
+++ b/control-api/test/services.llmProviderAttemptFinalization.realPostgres.integration.test.ts
@@ -15,6 +15,11 @@ import { insertLlmProviderAttempt } from '../src/services/llmProviderAttemptStor
import { issueRegisteredCodexExecutionTicket } from '../src/services/llmProviderAttemptTicket.js'
const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+if (process.env.CONTROL_API_REAL_PG_REQUIRED === '1' && !adminUrl) {
+ throw new Error(
+ 'REAL_PG_REQUIRED_BUT_UNAVAILABLE: CONTROL_API_REAL_PG_ADMIN_URL is required for Codex finalize ledger proof'
+ )
+}
const describeRealPostgres = adminUrl ? describe : describe.skip
const KEY = deriveOAuthEncryptionKey('ab'.repeat(32))
@@ -178,5 +183,94 @@ describeRealPostgres('Codex attempt finalization on real PostgreSQL', () => {
runTx
)
).rejects.toMatchObject({ code: 'conflict' })
+
+ const unknownLedger = await pool.query<{ count: number }>(
+ `SELECT COUNT(*)::int AS count FROM usage_events WHERE request_id = $1::uuid`,
+ [attempt.id]
+ )
+ expect(unknownLedger.rows[0]?.count).toBe(0)
+ })
+
+ it('writes exactly one usage_events row with a null user_id on success finalize', async () => {
+ const attempt = await insertLlmProviderAttempt(pool, {
+ callerKind: 'host',
+ hostRef: 'research-host',
+ invocationId: `invocation-${randomUUID()}`,
+ attemptGeneration: 1,
+ providerAttemptIndex: 1,
+ model: 'gpt-5.1',
+ requestHash: 'c'.repeat(64),
+ policyRevision: 1,
+ policyHash: 'd'.repeat(64),
+ budgetReservationId: 'unbudgeted',
+ connectionRevision: 1,
+ connectionId,
+ })
+ const issued = await issueRegisteredCodexExecutionTicket(pool, {
+ sub: 'host/research-host',
+ hostRef: attempt.hostRef,
+ invocationId: attempt.invocationId,
+ attemptGeneration: attempt.attemptGeneration,
+ providerAttemptId: attempt.id,
+ providerAttemptIndex: attempt.providerAttemptIndex,
+ model: attempt.model,
+ requestHash: attempt.requestHash,
+ policyRevision: attempt.policyRevision,
+ policyHash: attempt.policyHash,
+ budgetReservationId: attempt.budgetReservationId,
+ connectionRevision: attempt.connectionRevision,
+ })
+ await redeemLlmProviderAttempt(
+ {
+ executionTicket: issued.executionTicket,
+ requestHash: attempt.requestHash,
+ },
+ txDeps()
+ )
+ const attemptReceipt = opaqueAttemptReceipt({
+ jti: issued.claims.jti,
+ providerAttemptId: attempt.id,
+ requestHash: attempt.requestHash,
+ })
+ const receipt = {
+ schemaVersion: 'codex-attempt-receipt.v1' as const,
+ providerAttemptId: attempt.id,
+ requestHash: attempt.requestHash,
+ outcome: 'success' as const,
+ usage: { inputTokens: 12, outputTokens: 4 },
+ }
+
+ const first = await finalizeLlmProviderAttempt({ attemptReceipt, receipt }, runTx)
+ const repeat = await finalizeLlmProviderAttempt({ attemptReceipt, receipt }, runTx)
+ expect(first).toMatchObject({
+ providerAttemptId: attempt.id,
+ outcome: 'success',
+ duplicate: false,
+ })
+ expect(repeat.duplicate).toBe(true)
+
+ const ledger = await pool.query<{
+ count: number
+ user_id: string | null
+ source_kind: string
+ llm_secret_name: string | null
+ provider: string
+ }>(
+ `SELECT COUNT(*)::int AS count,
+ MIN(user_id::text) AS user_id,
+ MIN(source_kind) AS source_kind,
+ MIN(llm_secret_name) AS llm_secret_name,
+ MIN(provider) AS provider
+ FROM usage_events
+ WHERE request_id = $1::uuid`,
+ [attempt.id]
+ )
+ expect(ledger.rows[0]).toEqual({
+ count: 1,
+ user_id: null,
+ source_kind: 'channel',
+ llm_secret_name: null,
+ provider: 'codex-subscription',
+ })
})
})
diff --git a/control-api/test/services.llmProviderAttemptFinalization.test.ts b/control-api/test/services.llmProviderAttemptFinalization.test.ts
index 5fe8a99b0..042138cfe 100644
--- a/control-api/test/services.llmProviderAttemptFinalization.test.ts
+++ b/control-api/test/services.llmProviderAttemptFinalization.test.ts
@@ -1,11 +1,69 @@
-import { describe, expect, it } from 'vitest'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
import { config } from '../src/config.js'
import { finalizeLlmProviderAttempt } from '../src/services/llmProviderAttemptFinalization.js'
import { hashCodexAttemptReceipt } from '../src/services/llmProviderAttemptReceipt.js'
+import { opaqueAttemptReceipt } from '../src/services/llmProviderAttemptRedemption.js'
+
+const ingest = vi.hoisted(() => vi.fn())
+const loadAttempt = vi.hoisted(() => vi.fn())
+const markFinalized = vi.hoisted(() => vi.fn())
+
+vi.mock('../src/services/usageEvents.js', () => ({
+ ingestUsageEventsInTransaction: (...args: unknown[]) => ingest(...args),
+}))
+vi.mock('../src/services/llmProviderAttemptStore.js', async importOriginal => {
+ const actual = await importOriginal<typeof import('../src/services/llmProviderAttemptStore.js')>()
+ return {
+ ...actual,
+ loadLlmProviderAttempt: (...args: unknown[]) => loadAttempt(...args),
+ markLlmProviderAttemptFinalized: (...args: unknown[]) => markFinalized(...args),
+ }
+})
+
+const ATTEMPT_ID = '33333333-3333-4333-8333-333333333333'
+const REQUEST_HASH = 'b'.repeat(64)
+const JTI = 'jti-finalize'
+
+const attemptRow = {
+ id: ATTEMPT_ID,
+ callerKind: 'host' as const,
+ hostRef: 'research-host',
+ recipeName: null,
+ requestHash: REQUEST_HASH,
+ model: 'gpt-5.1',
+ provider: 'codex-subscription' as const,
+ budgetReservationId: 'unbudgeted',
+}
+
+const successReceipt = {
+ schemaVersion: 'codex-attempt-receipt.v1' as const,
+ providerAttemptId: ATTEMPT_ID,
+ requestHash: REQUEST_HASH,
+ outcome: 'success' as const,
+ usage: { inputTokens: 12, outputTokens: 4 },
+}
+
+function attemptReceipt(): string {
+ return opaqueAttemptReceipt({
+ jti: JTI,
+ providerAttemptId: ATTEMPT_ID,
+ requestHash: REQUEST_HASH,
+ })
+}
+
+function runTx(tx: { query: ReturnType<typeof vi.fn> }) {
+ return async <T>(work: (client: typeof tx) => Promise<T>): Promise<T> => work(tx)
+}
describe('finalizeLlmProviderAttempt', () => {
- it('rejects a malformed receipt without inventing usage', async () => {
+ beforeEach(() => {
config.codexSubscriptionEnabled = true
+ ingest.mockReset()
+ loadAttempt.mockReset()
+ markFinalized.mockReset()
+ })
+
+ it('rejects a malformed receipt without inventing usage', async () => {
await expect(
finalizeLlmProviderAttempt({
attemptReceipt: 'not-a-hash',
@@ -13,6 +71,7 @@ describe('finalizeLlmProviderAttempt', () => {
})
).rejects.toMatchObject({ code: 'invalid_receipt' })
expect(hashCodexAttemptReceipt).toBeTypeOf('function')
+ expect(ingest).not.toHaveBeenCalled()
})
it('is disabled when the flag is off', async () => {
@@ -22,11 +81,114 @@ describe('finalizeLlmProviderAttempt', () => {
attemptReceipt: 'a'.repeat(64),
receipt: {
schemaVersion: 'codex-attempt-receipt.v1',
- providerAttemptId: '33333333-3333-4333-8333-333333333333',
- requestHash: 'b'.repeat(64),
+ providerAttemptId: ATTEMPT_ID,
+ requestHash: REQUEST_HASH,
outcome: 'success',
},
})
).rejects.toMatchObject({ code: 'disabled' })
+ expect(ingest).not.toHaveBeenCalled()
+ })
+
+ it('ingests exactly one channel ledger row on first success finalize', async () => {
+ loadAttempt.mockResolvedValueOnce(attemptRow)
+ markFinalized.mockResolvedValueOnce('applied')
+ ingest.mockResolvedValueOnce({
+ result: { accepted: 1, duplicates: 0, rejected: 0 },
+ acceptedEvents: [{ request_id: ATTEMPT_ID }],
+ })
+ const tx = { query: vi.fn().mockResolvedValue({ rows: [{ jti: JTI }] }) }
+
+ const result = await finalizeLlmProviderAttempt(
+ { attemptReceipt: attemptReceipt(), receipt: successReceipt },
+ runTx(tx) as never
+ )
+
+ expect(result).toEqual({
+ providerAttemptId: ATTEMPT_ID,
+ outcome: 'success',
+ duplicate: false,
+ })
+ expect(ingest).toHaveBeenCalledTimes(1)
+ const [events, db, binding, options] = ingest.mock.calls[0] as unknown[]
+ expect(db).toBe(tx)
+ expect(binding).toBeUndefined()
+ expect(options).toEqual({ origin: 'finalize' })
+ expect(events).toEqual([
+ expect.objectContaining({
+ request_id: ATTEMPT_ID,
+ host_ref: 'research-host',
+ recipe_name: null,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ source_kind: 'channel',
+ user_id: null,
+ sender: null,
+ team_id: null,
+ context_ref: null,
+ llm_secret_name: null,
+ channel_type: null,
+ input_tokens: 12,
+ output_tokens: 4,
+ }),
+ ])
+ })
+
+ it('does not ingest on duplicate finalize', async () => {
+ loadAttempt.mockResolvedValueOnce(attemptRow)
+ markFinalized.mockResolvedValueOnce('duplicate')
+ const tx = { query: vi.fn().mockResolvedValue({ rows: [{ jti: JTI }] }) }
+
+ const result = await finalizeLlmProviderAttempt(
+ { attemptReceipt: attemptReceipt(), receipt: successReceipt },
+ runTx(tx) as never
+ )
+
+ expect(result.duplicate).toBe(true)
+ expect(ingest).not.toHaveBeenCalled()
+ })
+
+ it('does not ingest cancel, error, unknown, or success without both token counts', async () => {
+ const tx = { query: vi.fn().mockResolvedValue({ rows: [{ jti: JTI }] }) }
+ const cases = [
+ { outcome: 'canceled' as const },
+ { outcome: 'error' as const },
+ { outcome: 'unknown' as const },
+ { outcome: 'success' as const, usage: { inputTokens: 3 } },
+ ]
+ for (const extra of cases) {
+ loadAttempt.mockResolvedValueOnce(attemptRow)
+ markFinalized.mockResolvedValueOnce('applied')
+ await finalizeLlmProviderAttempt(
+ {
+ attemptReceipt: attemptReceipt(),
+ receipt: {
+ schemaVersion: 'codex-attempt-receipt.v1',
+ providerAttemptId: ATTEMPT_ID,
+ requestHash: REQUEST_HASH,
+ ...extra,
+ },
+ },
+ runTx(tx) as never
+ )
+ }
+ expect(ingest).not.toHaveBeenCalled()
+ })
+
+ it('rolls back when finalize ingest cannot bind a single ledger row', async () => {
+ loadAttempt.mockResolvedValueOnce(attemptRow)
+ markFinalized.mockResolvedValueOnce('applied')
+ ingest.mockResolvedValueOnce({
+ result: { accepted: 0, duplicates: 0, rejected: 1 },
+ acceptedEvents: [],
+ })
+ const tx = { query: vi.fn().mockResolvedValue({ rows: [{ jti: JTI }] }) }
+
+ await expect(
+ finalizeLlmProviderAttempt(
+ { attemptReceipt: attemptReceipt(), receipt: successReceipt },
+ runTx(tx) as never
+ )
+ ).rejects.toMatchObject({ code: 'invalid_receipt' })
})
})
diff --git a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
index 9efdfda6a..cabaea353 100644
--- a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
@@ -413,4 +413,77 @@ describe('Plugin Workload SDK promptBridge finalization', () => {
usageAccepted: false,
})
})
+
+ it('does not ingest Codex prompt-bridge usage because proxy finalize owns the ledger', async () => {
+ ingest.mockReset()
+ project.mockReset()
+ const db = dbWithRows(
+ [],
+ [],
+ {
+ id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ method: 'promptBridge',
+ status: 'in_progress',
+ attempt_generation: 1,
+ },
+ {
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ method: 'promptBridge',
+ status: 'in_progress',
+ },
+ {
+ id: IDS.providerAttempt,
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ attempt_index: 1,
+ target_ref: 'codex-primary',
+ host_ref: inputBase.hostRef,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credential_slot: 'codex-oauth',
+ status: 'in_progress',
+ },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 }
+ )
+
+ const result = await finalizePromptBridgeInTransaction(
+ {
+ ...inputBase,
+ target: {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credentialSlot: 'codex-oauth',
+ },
+ status: 'complete',
+ usage: {
+ llmSecretName: 'unused-codex-secret',
+ callerRef: 'scanner',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 12,
+ outputTokens: 7,
+ },
+ },
+ db as never
+ )
+
+ expect(result).toMatchObject({
+ status: 'complete',
+ outcome: 'exact',
+ usageAccepted: false,
+ })
+ expect(ingest).not.toHaveBeenCalled()
+ expect(project).not.toHaveBeenCalled()
+ })
})
diff --git a/control-api/test/services.usageEvents.test.ts b/control-api/test/services.usageEvents.test.ts
index 156605765..33677d999 100644
--- a/control-api/test/services.usageEvents.test.ts
+++ b/control-api/test/services.usageEvents.test.ts
@@ -201,6 +201,89 @@ describe('validateUsageEvent', () => {
).toBeNull()
})
+ it('rejects reporter Codex events in every reporter shape', () => {
+ expect(validateUsageEvent({ ...VALID_EVENT, provider: 'codex-subscription' })).toBeNull()
+ expect(
+ validateUsageEvent({
+ ...VALID_EVENT,
+ provider: 'codex-subscription',
+ source_kind: 'workflow',
+ run_id: '00000000-0000-4000-8000-000000000001',
+ recipe_name: 'e2e-recipe',
+ task_id: '00000000-0000-4000-8000-000000000001:e2e-recipe:2026-05-09T00:00:00.000Z',
+ llm_secret_name: 'openai-key',
+ })
+ ).toBeNull()
+ expect(
+ validateUsageEvent({
+ ...SDK_EVENT,
+ provider: 'codex-subscription',
+ })
+ ).toBeNull()
+ })
+
+ it('accepts finalize-origin Codex channel events with a null secret', () => {
+ const ev = validateUsageEvent(
+ {
+ request_id: '33333333-3333-4333-8333-333333333333',
+ ts: '2026-04-29T10:00:00.000Z',
+ run_id: null,
+ host_ref: 'research-host',
+ context_ref: null,
+ team_id: null,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ llm_secret_name: null,
+ source_kind: 'channel',
+ user_id: null,
+ sender: null,
+ channel_type: null,
+ recipe_name: null,
+ cron_job_id: null,
+ task_id: null,
+ iteration: null,
+ input_tokens: 12,
+ output_tokens: 4,
+ },
+ { origin: 'finalize' }
+ )
+ expect(ev).toMatchObject({
+ provider: 'codex-subscription',
+ source_kind: 'channel',
+ user_id: null,
+ llm_secret_name: null,
+ request_id: '33333333-3333-4333-8333-333333333333',
+ })
+ })
+
+ it('rejects finalize-origin Codex events that still carry a secret or a non-channel source', () => {
+ const base = {
+ request_id: '33333333-3333-4333-8333-333333333333',
+ ts: '2026-04-29T10:00:00.000Z',
+ run_id: null,
+ host_ref: 'research-host',
+ context_ref: null,
+ team_id: null,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ llm_secret_name: null,
+ source_kind: 'channel',
+ user_id: null,
+ sender: null,
+ channel_type: null,
+ recipe_name: null,
+ input_tokens: 12,
+ output_tokens: 4,
+ }
+ expect(
+ validateUsageEvent({ ...base, llm_secret_name: 'codex-secret' }, { origin: 'finalize' })
+ ).toBeNull()
+ expect(
+ validateUsageEvent({ ...base, source_kind: 'workflow' }, { origin: 'finalize' })
+ ).toBeNull()
+ expect(validateUsageEvent({ ...base, provider: 'openai' }, { origin: 'finalize' })).toBeNull()
+ })
+
it('accepts workflow promptBridge usage with the SDK channel marker', () => {
const workflowEvent = {
...VALID_EVENT,
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 42c30df1b..9674fa520 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.295",
+ "version": "0.1.296",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.295",
+ "version": "0.1.296",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 5a3c9292e..ce39a7318 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.295",
+ "version": "0.1.296",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/core/adapters/__tests__/llmPortAdapter.test.ts b/mcp-host/src/core/adapters/__tests__/llmPortAdapter.test.ts
index 8b3ab74ac..81850ffff 100644
--- a/mcp-host/src/core/adapters/__tests__/llmPortAdapter.test.ts
+++ b/mcp-host/src/core/adapters/__tests__/llmPortAdapter.test.ts
@@ -266,6 +266,48 @@ describe('LlmPortAdapter usage reporting', () => {
expect(typeof event.ts).toBe('string')
})
+ it('does not enqueue Codex usage because proxy finalize owns the ledger', async () => {
+ const enqueue = vi.fn()
+ const onUsageRecorded = vi.fn()
+ const reporter = { enqueue, drain: vi.fn(), stop: vi.fn(), bufferSize: vi.fn() }
+ const provider: SingleTurnProvider = {
+ completeSingleTurn: vi.fn(),
+ completeSingleTurnWithTools: vi.fn().mockResolvedValue({
+ content: null,
+ tool_calls: [],
+ usage: { input_tokens: 100, output_tokens: 50, total_tokens: 150 },
+ finish_reason: FinishReason.Stop,
+ }),
+ getProviderType: () => 'codex-subscription' as const,
+ classifyError: vi.fn(),
+ }
+ const adapter = new LlmPortAdapter(
+ provider,
+ 'gpt-5.1',
+ 'codex-subscription',
+ reporter as never,
+ {
+ host_ref: 'research-host',
+ context_ref: null,
+ llm_secret_name: null,
+ },
+ undefined,
+ undefined,
+ onUsageRecorded
+ )
+ await adapter.completeWithTools({
+ messages: [],
+ tools: [],
+ usageContext: {
+ source_kind: 'channel',
+ team_id: null,
+ user_id: null,
+ },
+ })
+ expect(onUsageRecorded).toHaveBeenCalled()
+ expect(enqueue).not.toHaveBeenCalled()
+ })
+
it('does not enqueue when usageContext is omitted', async () => {
const enqueue = vi.fn()
const reporter = { enqueue, drain: vi.fn(), stop: vi.fn(), bufferSize: vi.fn() }
diff --git a/mcp-host/src/core/adapters/llmPortAdapter.ts b/mcp-host/src/core/adapters/llmPortAdapter.ts
index a2ecc87bb..a86f26691 100644
--- a/mcp-host/src/core/adapters/llmPortAdapter.ts
+++ b/mcp-host/src/core/adapters/llmPortAdapter.ts
@@ -255,6 +255,7 @@ export class LlmPortAdapter implements LlmPort {
}
}
if (!this.usageReporter || !this.staticContext || !usageContext || !usage) return
+ if (this.providerName === 'codex-subscription') return
const event: LlmUsageEvent = {
request_id: requestId,
ts: new Date().toISOString(),
diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.test.ts b/mcp-host/src/pluginWorkloadSdk/server/index.test.ts
index 115826212..957874967 100644
--- a/mcp-host/src/pluginWorkloadSdk/server/index.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/server/index.test.ts
@@ -128,4 +128,48 @@ describe('PluginWorkloadSdk server usage attribution', () => {
expect(JSON.stringify(event)).not.toContain('credentialTicket')
expect(JSON.stringify(event)).not.toContain('secret-')
})
+
+ it('does not emit reporter usage for Codex subscription', () => {
+ expect(
+ buildPromptBridgeUsageEvent({
+ binding: {
+ hostRef: 'sandbox-recipes/risk-review',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'risk-review',
+ },
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ inputTokens: 10,
+ outputTokens: 5,
+ callerRef: 'worker',
+ metadata: {
+ workflowExecutionId: `${WORKFLOW_RUN_ID}:risk-review:2026-07-12T12:00:00.000Z`,
+ workflowRunId: WORKFLOW_RUN_ID,
+ llmSecretName: 'chatllm-api-keys',
+ },
+ })
+ ).toBeNull()
+ expect(
+ buildPromptBridgeUsageEvent({
+ binding: {
+ hostRef: 'plugin-workload-sdk/sandbox-app',
+ recipeNamespace: 'sandbox-apps',
+ recipeName: 'prompt-notify',
+ },
+ runtimeMode: 'sdk-only',
+ invocationId: '00000000-0000-4000-8000-000000000100',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ inputTokens: 10,
+ outputTokens: 5,
+ callerRef: 'backend-worker',
+ promptBridgeMetadata: {
+ targetRef: 'codex-primary',
+ credentialSlot: 'codex-oauth',
+ fallbackUsed: false,
+ attemptCount: 1,
+ },
+ })
+ ).toBeNull()
+ })
})
diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.ts b/mcp-host/src/pluginWorkloadSdk/server/index.ts
index 6794aecde..ef1159d2c 100644
--- a/mcp-host/src/pluginWorkloadSdk/server/index.ts
+++ b/mcp-host/src/pluginWorkloadSdk/server/index.ts
@@ -64,6 +64,7 @@ export function buildPromptBridgeUsageEvent(input: {
}
metadata?: Record<string, unknown>
}): LlmUsageEvent | null {
+ if (input.provider === 'codex-subscription') return null
// Explicit runtime mode is authoritative for recipe-bound hosts. The
// namespace fallback remains only for older non-recipe callers that do not
// yet inject the mode into their pod.
diff --git a/mcp-host/src/workflow/__tests__/workflowServiceUsageReporting.test.ts b/mcp-host/src/workflow/__tests__/workflowServiceUsageReporting.test.ts
index ea79de0ac..124a3ba75 100644
--- a/mcp-host/src/workflow/__tests__/workflowServiceUsageReporting.test.ts
+++ b/mcp-host/src/workflow/__tests__/workflowServiceUsageReporting.test.ts
@@ -276,7 +276,7 @@ describe('WorkflowService — UsageReporter integration', () => {
expect(enqueued).toHaveLength(0)
})
- it('reports Codex workflow usage without an llmSecretName', async () => {
+ it('does not enqueue Codex workflow usage because proxy finalize owns the ledger', async () => {
const llm = mockLlmProvider([{ content: 'final answer', tool_calls: null }])
llm.getProviderType = () => 'codex-subscription'
const { reporter, enqueued } = makeReporter()
@@ -297,12 +297,7 @@ describe('WorkflowService — UsageReporter integration', () => {
contextVars: { workflowExecutionId, workflowTeamId, workflowUserId },
})
expect(res.status).toBe('completed')
- expect(enqueued).toHaveLength(1)
- expect(enqueued[0]).toMatchObject({
- provider: 'codex-subscription',
- model: 'gpt-5.3-codex',
- llm_secret_name: null,
- })
+ expect(enqueued).toHaveLength(0)
})
it('does NOT enqueue when no reporter is wired (workflow mode without ingest)', async () => {
diff --git a/mcp-host/src/workflow/workflowService.ts b/mcp-host/src/workflow/workflowService.ts
index ab2fc650a..31c79f42d 100644
--- a/mcp-host/src/workflow/workflowService.ts
+++ b/mcp-host/src/workflow/workflowService.ts
@@ -569,6 +569,7 @@ export class WorkflowService {
input_tokens: usage?.input_tokens ?? 0,
output_tokens: usage?.output_tokens ?? 0,
}
+ if (served.provider === 'codex-subscription') return
this.usageReporter.enqueue(event)
}
diff --git a/scripts/tests/test-codex-subscription-t0.sh b/scripts/tests/test-codex-subscription-t0.sh
index 5c43ec9ab..23c30ee40 100755
--- a/scripts/tests/test-codex-subscription-t0.sh
+++ b/scripts/tests/test-codex-subscription-t0.sh
@@ -173,7 +173,10 @@ run_group "control-api" "control-api" \
"test/services.llmProviderAttemptAuthorizer.test.ts" \
"test/services.llmProviderAttemptTicket.test.ts" \
"test/services.llmProviderAttemptRedemption.test.ts" \
- "test/services.llmProviderAttemptFinalization.test.ts"
+ "test/services.llmProviderAttemptFinalization.test.ts" \
+ "test/services.usageEvents.test.ts" \
+ "test/services.pluginWorkloadSdkFinalization.test.ts" \
+ "test/routes.usageEvents.test.ts"
run_group "codex-llm-proxy" "codex-llm-proxy" \
"test/codexTransport.conformance.test.ts" \
@@ -189,7 +192,10 @@ run_group "mcp-host" "mcp-host" \
"src/llm/hostLlmBinding.test.ts" \
"src/config/configStore.test.ts" \
"src/llm/failover/__tests__/engine.test.ts" \
- "src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts"
+ "src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts" \
+ "src/workflow/__tests__/workflowServiceUsageReporting.test.ts" \
+ "src/pluginWorkloadSdk/server/index.test.ts" \
+ "src/core/adapters/__tests__/llmPortAdapter.test.ts"
run_group "host-context-controller" "host-context-controller" \
"src/codexExecutionProjection.test.ts" \