Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test: require an upstream context overflow to read as context_length_exceeded (#731)
Alfredo Lopeza68429f00abb
diff --git a/codex-llm-proxy/test/codexTransport.conformance.test.ts b/codex-llm-proxy/test/codexTransport.conformance.test.tsindex d8e8dc04a..319e29784 100644--- a/codex-llm-proxy/test/codexTransport.conformance.test.ts+++ b/codex-llm-proxy/test/codexTransport.conformance.test.ts@@ -12,6 +12,12 @@ import type { RedeemAttemptSuccess } from '../src/controlApiClient.js'import { CODEX_COMPLETIONS_ORIGIN } from '../src/originPolicy.js'import { ToolNameMap } from '../src/toolNameMap.js'import { eventaskUpdateTool, optionalMcpTools, webSearchTool } from './fixtures/optionalMcpTools.js'+import {+ UPSTREAM_CONTEXT_ERROR_EVENT,+ UPSTREAM_CONTEXT_FAILED_EVENT,+ UPSTREAM_CONTEXT_OVERFLOW_FRAMES,+ sseFrame,+} from './fixtures/upstreamContextOverflow.js'const REQUEST = {schemaVersion: 'codex-completion-request.v1' as const,@@ -336,6 +342,75 @@ describe('streamCodexCompletion', () => {expect(emitted).toEqual([])})++ // #731 — an upstream context-window refusal is a property of this request.+ // The transport keeps the upstream code so the Host does not retry it as an+ // outage. Each event carries the code in a different place; either is enough.+ function failingStream(frames: string[], attempt: string) {+ const finalize = vi.fn(async () => ({+ providerAttemptId: attempt,+ outcome: 'error' as const,+ duplicate: false,+ }))+ const fetchFn = vi.fn(async (_url: FetchInput, _init?: RequestInit) => sseResponse(frames))+ const pending = streamCodexCompletion({+ executionTicket: `ticket-${attempt}`,+ requestHash: REQUEST_HASH,+ request: REQUEST,+ ticket: {+ jti: `jti-${attempt}`,+ hostRef: 'research-host',+ model: REQUEST.model,+ requestHash: REQUEST_HASH,+ providerAttemptId: attempt,+ },+ redeem: vi.fn(async () => redeemSuccess()),+ finalize,+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ })+ return { pending, finalize, fetchFn }+ }++ it.each([+ { events: 'the recorded error + response.failed pair', frames: UPSTREAM_CONTEXT_OVERFLOW_FRAMES },+ { events: 'the error event alone', frames: [sseFrame(UPSTREAM_CONTEXT_ERROR_EVENT)] },+ { events: 'the response.failed event alone', frames: [sseFrame(UPSTREAM_CONTEXT_FAILED_EVENT)] },+ ])('T-R7-2a maps $events to context_length_exceeded', async ({ frames }) => {+ const { pending, finalize, fetchFn } = failingStream(frames, 'att-context')+ await expect(pending).rejects.toMatchObject({+ name: 'CodexTransportError',+ code: 'context_length_exceeded',+ })+ // Witness: the upstream stream was fetched and the attempt finalized as an error.+ expect(fetchFn).toHaveBeenCalledTimes(1)+ expect(finalize).toHaveBeenCalledWith(+ expect.objectContaining({ receipt: expect.objectContaining({ outcome: 'error' }) })+ )+ })++ // Controls: only `context_length_exceeded` is forwarded. A failure without a+ // code, or with any other upstream code, stays a provider outage, so an+ // upstream string never becomes a Host-visible code by itself.+ it.each([+ { events: 'response.failed without an error code', event: { type: 'response.failed' } },+ {+ events: 'response.failed with another upstream code',+ event: { type: 'response.failed', response: { error: { code: 'server_error' } } },+ },+ {+ events: 'an error event with another upstream code',+ event: { type: 'error', error: { code: 'rate_limit_exceeded' } },+ },+ ])('T-R7-2b keeps $events as provider_unavailable', async ({ event }) => {+ const { pending, fetchFn } = failingStream([sseFrame(event)], 'att-other')+ await expect(pending).rejects.toMatchObject({+ name: 'CodexTransportError',+ code: 'provider_unavailable',+ message: 'upstream response failed',+ })+ expect(fetchFn).toHaveBeenCalledTimes(1)+ })it.each([256, 257])('validates the complete %s-call response before emitting executable calls',async count => {diff --git a/codex-llm-proxy/test/fixtures/upstreamContextOverflow.ts b/codex-llm-proxy/test/fixtures/upstreamContextOverflow.tsnew file mode 100644index 000000000..fd877847d--- /dev/null+++ b/codex-llm-proxy/test/fixtures/upstreamContextOverflow.ts@@ -0,0 +1,27 @@+// The two SSE events the Codex upstream sends when a request exceeds the+// model's context window. Recorded on 2026-09-23 with `codex exec` 0.154.0+// against `gpt-5.6-luna` over HTTPS (1,040,000 CJK characters of input); the+// trace was filtered to these events, so no message text or account data is+// kept. #731: the proxy used to discard the code and answer 503.+export const UPSTREAM_CONTEXT_ERROR_EVENT = {+ type: 'error',+ error: {+ type: 'invalid_request_error',+ code: 'context_length_exceeded',+ param: 'input',+ },+}++export const UPSTREAM_CONTEXT_FAILED_EVENT = {+ type: 'response.failed',+ response: { status: 'failed', error: { code: 'context_length_exceeded' } },+}++export function sseFrame(event: unknown): string {+ return `data: ${JSON.stringify(event)}\n\n`+}++export const UPSTREAM_CONTEXT_OVERFLOW_FRAMES = [+ sseFrame(UPSTREAM_CONTEXT_ERROR_EVENT),+ sseFrame(UPSTREAM_CONTEXT_FAILED_EVENT),+]diff --git a/codex-llm-proxy/test/server.security.test.ts b/codex-llm-proxy/test/server.security.test.tsindex a6050f5ad..869b6b3a7 100644--- a/codex-llm-proxy/test/server.security.test.ts+++ b/codex-llm-proxy/test/server.security.test.ts@@ -19,6 +19,7 @@ import {import { logger } from '../src/logger.js'import { CODEX_COMPLETIONS_ORIGIN } from '../src/originPolicy.js'import { createProxyApps } from '../src/server.js'+import { UPSTREAM_CONTEXT_OVERFLOW_FRAMES } from './fixtures/upstreamContextOverflow.js'const { privateKey, publicKey } = generateKeyPairSync('rsa', {modulusLength: 2048,@@ -545,7 +546,11 @@ describe('codex-llm-proxy attempt telemetry', () => {return { client, receipts }}- function upstream(textDeltas: number, calls: number): typeof fetch {+ function upstream(+ textDeltas: number,+ calls: number,+ terminal: string[] = ['data: {"type":"response.completed"}\n\n']+ ): typeof fetch {const frames: string[] = []for (let index = 0; index < textDeltas; index += 1) {frames.push(@@ -560,7 +565,7 @@ describe('codex-llm-proxy attempt telemetry', () => {})}\n\n`)}- frames.push('data: {"type":"response.completed"}\n\n')+ frames.push(...terminal)return (async () =>new Response(frames.join(''), {status: 200,@@ -591,14 +596,15 @@ describe('codex-llm-proxy attempt telemetry', () => {textDeltas: number,calls: number,tamper?: (raw: Record<string, unknown>) => void,- deniedCode?: string+ deniedCode?: string,+ terminal?: string[]) {const info = vi.spyOn(logger, 'info')const warn = vi.spyOn(logger, 'warn')const { client, receipts } = grantingClient()const apps = createProxyApps(config({ maxBodyBytes: 65_536 }), {controlApiClient: deniedCode ? denyingClient(deniedCode) : client,- fetchFn: upstream(textDeltas, calls),+ fetchFn: upstream(textDeltas, calls, terminal),lookup,})try {@@ -663,6 +669,56 @@ describe('codex-llm-proxy attempt telemetry', () => {expectNoForbiddenKeys(lines[0]!)})+ // #731 — the recorded upstream context-window refusal reaches the Host as a+ // 400 `context_length_exceeded` (the upstream's own status class), not as a+ // retryable 503 `provider_unavailable`.+ it('(h) T-R7-2c answers 400 context_length_exceeded for the upstream context overflow', async () => {+ const { res, receipts, lines, metricsText } = await run(+ 'att-context-http',+ 0,+ 0,+ undefined,+ undefined,+ UPSTREAM_CONTEXT_OVERFLOW_FRAMES+ )+ expect(res.status).toBe(400)+ expect(res.headers['content-type']).toMatch(/^application\/json/)+ expect(res.body).toEqual({ error: 'context_length_exceeded' })+ expect(receipts).toEqual([expect.objectContaining({ outcome: 'error' })])+ expect(lines).toHaveLength(1)+ expect(lines[0]).toMatchObject({+ providerAttemptId: 'att-context-http',+ outcome: 'failed',+ code: 'context_length_exceeded',+ deliveredAs: 'http_status',+ httpStatus: 400,+ })+ expectNoForbiddenKeys(lines[0]!)+ expect(failureCount(metricsText, 'context_length_exceeded')).toBe(1)+ expect(failureCount(metricsText, 'provider_unavailable')).toBe(0)+ })++ it('(i) T-R7-2c sends an SSE context_length_exceeded frame when text was already streamed', async () => {+ const { res, lines } = await run(+ 'att-context-sse',+ 1,+ 0,+ undefined,+ undefined,+ UPSTREAM_CONTEXT_OVERFLOW_FRAMES+ )+ expect(res.status).toBe(200)+ expect(res.text).toContain('data: {"type":"text","text":"t0"}')+ expect(res.text).toContain('data: {"type":"error","code":"context_length_exceeded"}')+ expect(lines).toHaveLength(1)+ expect(lines[0]).toMatchObject({+ outcome: 'failed',+ code: 'context_length_exceeded',+ deliveredAs: 'sse_error',+ textChunks: 1,+ })+ })+it('(d) logs an invalid request without the caller-supplied parse message', async () => {const secretField = 'sk-live-0123456789abcdef'const { res, lines } = await run('att-invalid', 0, 0, raw => {diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex b040aaaa4..9333d1607 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.401",+ "version": "0.1.402","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.401",+ "version": "0.1.402","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 41fba7d06..5f975bdd1 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.401",+ "version": "0.1.402","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/llm/__tests__/codexLlmProxyClient.test.ts b/mcp-host/src/llm/__tests__/codexLlmProxyClient.test.tsindex ac07c7ec7..3606849c4 100644--- a/mcp-host/src/llm/__tests__/codexLlmProxyClient.test.ts+++ b/mcp-host/src/llm/__tests__/codexLlmProxyClient.test.ts@@ -147,6 +147,64 @@ describe('CodexLlmProxyClient', () => {expect(classifyFailoverClass(classified.code, classified.retryable)).toBeNull()})+ // #731 — the upstream refuses a request over the model's context window with+ // `context_length_exceeded`. The proxy forwards that code as a 400 before any+ // frame, or as an SSE error frame after one. Retrying the same conversation+ // cannot succeed, so it must not read as a transient outage.+ it.each([+ {+ path: '400 JSON body before streaming',+ response: {+ ok: false,+ status: 400,+ json: async () => ({ error: 'context_length_exceeded' }),+ },+ message: 'proxy stream failed with 400 (context_length_exceeded)',+ },+ {+ path: 'SSE error frame after a text frame',+ response: {+ ok: true,+ body: sse([+ { type: 'text', text: 'partial' },+ { type: 'error', code: 'context_length_exceeded' },+ ]),+ },+ message: 'proxy stream failed with context_length_exceeded',+ },+ ])(+ 'T-R7-2d classifies the upstream context_length_exceeded from the $path as ContextLengthExceeded',+ async ({ response, message }) => {+ const fetchFn = vi.fn().mockResolvedValue(response)+ const client = new CodexLlmProxyClient({+ runtimeUrl: resolveCodexProxyRuntimeUrl(+ 'http://codex-llm-proxy.control-plane.svc.cluster.local:8080'+ ),+ readPlatformJwt: () => 'platform-jwt',+ fetchFn: fetchFn as unknown as typeof fetch,+ })+ const err = await client+ .stream({ executionTicket: 'ticket-123456', requestHash: 'a'.repeat(64), request: {} })+ .then(+ () => undefined,+ (e: unknown) => e+ )+ expect(fetchFn).toHaveBeenCalledTimes(1)+ expect(err).toBeInstanceOf(CodexProxyError)+ expect(err).toMatchObject({ code: 'context_length_exceeded', message })++ const classified = new CodexSubscriptionProvider('gpt-5.3-codex', {} as never).classifyError(+ err+ )+ expect(classified).toMatchObject({+ code: LlmErrorCode.ContextLengthExceeded,+ retryable: false,+ providerCode: 'context_length_exceeded',+ })+ expect(classifyFailoverClass(classified.code, classified.retryable)).toBeNull()+ }+ )+it('refuses a runtime URL that is not absolute', () => {expect(() =>